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

FeatureModels.swift

1,407 lines47.8 KB

1import Foundation
2​
3public struct FeatureConnection: Sendable, Equatable, Codable {
4 public enum State: String, Sendable, Hashable, Codable {
5 case disconnected
6 case connecting
7 case connected
8 case reconnecting
9 /// The server rejected the saved credential (expired, revoked, or
10 /// restored onto a new device). Retrying cannot fix it; only pairing
11 /// again can.
12 case needsPairing
13 }
14​
15 public var state: State
16 public var environmentName: String?
17 public var endpoint: String?
18 public var detail: String?
19​
20 public init(
21 state: State = .disconnected,
22 environmentName: String? = nil,
23 endpoint: String? = nil,
24 detail: String? = nil
25 ) {
26 self.state = state
27 self.environmentName = environmentName
28 self.endpoint = endpoint
29 self.detail = detail
30 }
32​
33public struct FeatureEnvironment: Identifiable, Sendable, Equatable, Hashable, Codable {
34 public enum Source: String, Sendable, Equatable, Hashable, Codable {
35 case direct
36 case t3Connect
37 }
38​
39 public let id: String
40 public var name: String
41 public var endpoint: String
42 /// Internal stream-leader compatibility. Product routing must use the
43 /// project or thread environment instead.
44 public var isActive: Bool
45 public var isEnabled: Bool
46 public var source: Source
47 /// Reachability from the latest aggregate refresh. `nil` means the client
48 /// has not probed this saved environment yet.
49 public var connectionState: FeatureConnection.State?
50 public var connectionDetail: String?
51 public var machineIcon: String? = nil
52 public var canCustomizeIcon: Bool? = nil
53​
54 public var systemImage: String {
55 switch machineIcon {
56 case "cloud": "cloud"
57 case "desktop": "desktopcomputer"
58 case "laptop": "laptopcomputer"
59 case "mac-mini": "macmini"
60 case "mac-studio": "macstudio"
61 default: "server.rack"
62 }
63 }
64​
65 public init(
66 id: String,
67 name: String,
68 endpoint: String,
69 isActive: Bool = false,
70 isEnabled: Bool = true,
71 source: Source = .direct,
72 connectionState: FeatureConnection.State? = nil,
73 connectionDetail: String? = nil
74 ) {
75 self.id = id
76 self.name = name
77 self.endpoint = endpoint
78 self.isActive = isActive
79 self.isEnabled = isEnabled
80 self.source = source
81 self.connectionState = connectionState
82 self.connectionDetail = connectionDetail
83 }
84​
85 private enum CodingKeys: String, CodingKey {
86 case id
87 case name
88 case endpoint
89 case isActive
90 case isEnabled
91 case source
92 case connectionState
93 case connectionDetail
94 case machineIcon
95 case canCustomizeIcon
96 }
97​
98 public init(from decoder: any Decoder) throws {
99 let container = try decoder.container(keyedBy: CodingKeys.self)
100 id = try container.decode(String.self, forKey: .id)
101 name = try container.decode(String.self, forKey: .name)
102 endpoint = try container.decode(String.self, forKey: .endpoint)
103 isActive = try container.decodeIfPresent(Bool.self, forKey: .isActive) ?? false
104 isEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) ?? true
105 source = try container.decodeIfPresent(Source.self, forKey: .source) ?? .direct
106 connectionState = try container.decodeIfPresent(
107 FeatureConnection.State.self,
108 forKey: .connectionState
109 )
110 connectionDetail = try container.decodeIfPresent(String.self, forKey: .connectionDetail)
111 machineIcon = try container.decodeIfPresent(String.self, forKey: .machineIcon)
112 canCustomizeIcon = try container.decodeIfPresent(Bool.self, forKey: .canCustomizeIcon)
113 }
115​
116public struct FeatureRepositoryIdentity: Sendable, Equatable, Hashable, Codable {
117 public var canonicalKey: String
118 public var rootPath: String?
119 public var displayName: String?
120 public var name: String?
121​
122 public init(
123 canonicalKey: String,
124 rootPath: String? = nil,
125 displayName: String? = nil,
126 name: String? = nil
127 ) {
128 self.canonicalKey = canonicalKey
129 self.rootPath = rootPath
130 self.displayName = displayName
131 self.name = name
132 }
134​
135public struct FeatureProject: Identifiable, Sendable, Equatable, Hashable, Codable {
136 public let id: String
137 /// The environment-local identifier sent over the wire. Native aggregate
138 /// snapshots scope `id` by environment so cloned databases remain distinct.
139 public var wireID: String?
140 public var environmentID: String
141 public var name: String
142 public var path: String
143 public var threadCount: Int
144 public var defaultSelection: FeatureSelection?
145 public var repositoryIdentity: FeatureRepositoryIdentity?
146 public var createdAt: String?
147 public var updatedAt: String?
148 public var projectIcon: ProjectIconOverride? = nil
149 public var defaultWorkspaceMode: FeatureWorkspaceMode? = nil
150 public var newWorktreesStartFromOrigin: Bool? = nil
151 public var supportsProjectSettingsOverrides: Bool? = nil
152​
153 public init(
154 id: String,
155 wireID: String? = nil,
156 environmentID: String,
157 name: String,
158 path: String,
159 threadCount: Int = 0,
160 defaultSelection: FeatureSelection? = nil,
161 repositoryIdentity: FeatureRepositoryIdentity? = nil,
162 createdAt: String? = nil,
163 updatedAt: String? = nil
164 ) {
165 self.id = id
166 self.wireID = wireID
167 self.environmentID = environmentID
168 self.name = name
169 self.path = path
170 self.threadCount = threadCount
171 self.defaultSelection = defaultSelection
172 self.repositoryIdentity = repositoryIdentity
173 self.createdAt = createdAt
174 self.updatedAt = updatedAt
175 }
177​
178public enum FeatureThreadState: String, Sendable, Codable {
179 case idle
180 case queued
181 case working
182 case monitoring
183 case waitingForApproval
184 case waitingForInput
185 case failed
186 case completed
188​
189public enum FeatureRuntimeMode: String, CaseIterable, Sendable, Codable {
190 case approvalRequired
191 case autoAcceptEdits
192 case automatic
193 case fullAccess
194​
195 /// Mobile offers the two current modes. Legacy modes remain distinct so
196 /// existing threads keep their exact server permission.
197 public static let allCases: [FeatureRuntimeMode] = [.automatic, .fullAccess]
199​
200public enum FeatureInteractionMode: String, CaseIterable, Sendable, Codable {
201 case standard
202 case plan
203​
204 /// Plan remains decodable for existing server state, but is no longer a
205 /// mobile prompt choice.
206 public static let allCases: [FeatureInteractionMode] = [.standard]
207​
208 public var mobileNormalized: FeatureInteractionMode { .standard }
210​
211public enum FeatureThreadSettlementOverride: String, Sendable, Equatable, Hashable, Codable {
212 case settled
213 case active
215​
216public struct FeatureThreadSettlementFacts: Sendable, Equatable, Hashable, Codable {
217 public struct LatestTurn: Sendable, Equatable, Hashable, Codable {
218 public var requestedAt: Date?
219 public var startedAt: Date?
220 public var completedAt: Date?
221 public var requestedAtIsInvalid: Bool
222 public var startedAtIsInvalid: Bool
223 public var completedAtIsInvalid: Bool
224​
225 public init(
226 requestedAt: Date? = nil,
227 startedAt: Date? = nil,
228 completedAt: Date? = nil,
229 requestedAtIsInvalid: Bool = false,
230 startedAtIsInvalid: Bool = false,
231 completedAtIsInvalid: Bool = false
232 ) {
233 self.requestedAt = requestedAt
234 self.startedAt = startedAt
235 self.completedAt = completedAt
236 self.requestedAtIsInvalid = requestedAtIsInvalid
237 self.startedAtIsInvalid = startedAtIsInvalid
238 self.completedAtIsInvalid = completedAtIsInvalid
239 }
240 }
241​
242 public var settlementOverride: FeatureThreadSettlementOverride?
243 public var sessionStatus: String?
244 public var hasPendingApprovals: Bool
245 public var hasPendingUserInput: Bool
246 public var latestUserMessageAt: Date?
247 public var latestTurn: LatestTurn?
248​
249 public init(
250 settlementOverride: FeatureThreadSettlementOverride? = nil,
251 sessionStatus: String? = nil,
252 hasPendingApprovals: Bool = false,
253 hasPendingUserInput: Bool = false,
254 latestUserMessageAt: Date? = nil,
255 latestTurn: LatestTurn? = nil
256 ) {
257 self.settlementOverride = settlementOverride
258 self.sessionStatus = sessionStatus
259 self.hasPendingApprovals = hasPendingApprovals
260 self.hasPendingUserInput = hasPendingUserInput
261 self.latestUserMessageAt = latestUserMessageAt
262 self.latestTurn = latestTurn
263 }
265​
266public struct FeatureThread: Identifiable, Sendable, Equatable, Hashable, Codable {
267 public let id: String
268 /// The environment-local identifier sent over the wire.
269 public var wireID: String?
270 public var projectID: String
271 public var environmentID: String?
272 public var environmentName: String?
273 public var title: String
274 public var preview: String?
275 public var branch: String?
276 public var worktreePath: String?
277 public var linkedPullRequest: ThreadLinkedPullRequest?
278 public var pullRequests: [ThreadPullRequestLink]?
279 public var branchPullRequest: ThreadLinkedPullRequest?
280 public var createdAt: Date
281 public var updatedAt: Date
282 public var state: FeatureThreadState
283 public var providerID: String?
284 public var sessionProviderID: String?
285 public var providerName: String?
286 public var modelID: String?
287 public var modelOptions: [FeatureModelOptionSelection]
288 public var isArchived: Bool
289 public var isSettled: Bool
290 public var keepsActive: Bool
291 public var settledAt: Date?
292 public var unsettledAt: Date?
293 public var activeOrderKey: String?
294 public var lastActivityAt: Date?
295 public var snoozedUntil: Date?
296 public var snoozedAt: Date?
297 public var pinnedAt: Date?
298 /// User-arranged position in the pinned block. Shared with web and
299 /// React Native; keyless pins sort after keyed ones by creation date.
300 public var pinOrderKey: String?
301 public var supportsSettlement: Bool?
302 public var supportsSnooze: Bool?
303 public var supportsPinning: Bool?
304 public var supportsPinReorder: Bool?
305 public var supportsActiveReorder: Bool?
306 public var supportsTitleRegeneration: Bool?
307 public var supportsPullRequestLinking: Bool?
308 public var supportsMultiplePullRequests: Bool?
309 /// True while the server is generating a new title. Derived from the wire
310 /// snapshot only, the same way the web and React Native clients do it.
311 public var isRegeneratingTitle: Bool
312 public var attentionAt: Date?
313 public var workingStartedAt: Date?
314 public var latestTurnCompletedAt: Date?
315 public var settlementFacts: FeatureThreadSettlementFacts?
316 public var runtimeMode: FeatureRuntimeMode
317 public var interactionMode: FeatureInteractionMode
318​
319 public init(
320 id: String,
321 wireID: String? = nil,
322 projectID: String,
323 environmentID: String? = nil,
324 environmentName: String? = nil,
325 title: String,
326 preview: String? = nil,
327 branch: String? = nil,
328 worktreePath: String? = nil,
329 linkedPullRequest: ThreadLinkedPullRequest? = nil,
330 pullRequests: [ThreadPullRequestLink]? = nil,
331 branchPullRequest: ThreadLinkedPullRequest? = nil,
332 createdAt: Date = .now,
333 updatedAt: Date = .now,
334 state: FeatureThreadState = .idle,
335 providerID: String? = nil,
336 sessionProviderID: String? = nil,
337 providerName: String? = nil,
338 modelID: String? = nil,
339 modelOptions: [FeatureModelOptionSelection] = [],
340 isArchived: Bool = false,
341 isSettled: Bool = false,
342 keepsActive: Bool = false,
343 settledAt: Date? = nil,
344 unsettledAt: Date? = nil,
345 activeOrderKey: String? = nil,
346 lastActivityAt: Date? = nil,
347 snoozedUntil: Date? = nil,
348 snoozedAt: Date? = nil,
349 pinnedAt: Date? = nil,
350 pinOrderKey: String? = nil,
351 supportsSettlement: Bool? = nil,
352 supportsSnooze: Bool? = nil,
353 supportsPinning: Bool? = nil,
354 supportsPinReorder: Bool? = nil,
355 supportsActiveReorder: Bool? = nil,
356 supportsTitleRegeneration: Bool? = nil,
357 supportsPullRequestLinking: Bool? = nil,
358 supportsMultiplePullRequests: Bool? = nil,
359 isRegeneratingTitle: Bool = false,
360 attentionAt: Date? = nil,
361 workingStartedAt: Date? = nil,
362 latestTurnCompletedAt: Date? = nil,
363 settlementFacts: FeatureThreadSettlementFacts? = nil,
364 runtimeMode: FeatureRuntimeMode = .fullAccess,
365 interactionMode: FeatureInteractionMode = .standard
366 ) {
367 self.id = id
368 self.wireID = wireID
369 self.projectID = projectID
370 self.environmentID = environmentID
371 self.environmentName = environmentName
372 self.title = title
373 self.preview = preview
374 self.branch = branch
375 self.worktreePath = worktreePath
376 self.linkedPullRequest = linkedPullRequest
377 self.pullRequests = pullRequests
378 self.branchPullRequest = branchPullRequest
379 self.createdAt = createdAt
380 self.updatedAt = updatedAt
381 self.state = state
382 self.providerID = providerID
383 self.sessionProviderID = sessionProviderID
384 self.providerName = providerName
385 self.modelID = modelID
386 self.modelOptions = modelOptions
387 self.isArchived = isArchived
388 self.isSettled = isSettled
389 self.keepsActive = keepsActive
390 self.settledAt = settledAt
391 self.unsettledAt = unsettledAt
392 self.activeOrderKey = activeOrderKey
393 self.lastActivityAt = lastActivityAt
394 self.snoozedUntil = snoozedUntil
395 self.snoozedAt = snoozedAt
396 self.pinnedAt = pinnedAt
397 self.pinOrderKey = pinOrderKey
398 self.supportsSettlement = supportsSettlement
399 self.supportsSnooze = supportsSnooze
400 self.supportsPinning = supportsPinning
401 self.supportsPinReorder = supportsPinReorder
402 self.supportsActiveReorder = supportsActiveReorder
403 self.supportsTitleRegeneration = supportsTitleRegeneration
404 self.supportsPullRequestLinking = supportsPullRequestLinking
405 self.supportsMultiplePullRequests = supportsMultiplePullRequests
406 self.isRegeneratingTitle = isRegeneratingTitle
407 self.attentionAt = attentionAt
408 self.workingStartedAt = workingStartedAt
409 self.latestTurnCompletedAt = latestTurnCompletedAt
410 self.settlementFacts = settlementFacts
411 self.runtimeMode = runtimeMode
412 self.interactionMode = interactionMode
413 }
414​
415 public var effectivePullRequest: ThreadLinkedPullRequest? {
416 if let pullRequests, !pullRequests.isEmpty {
417 return ThreadPullRequests.current(pullRequests).map {
418 ThreadLinkedPullRequest(projectId: projectID, repository: $0.repository,
419 number: $0.number, url: $0.url)
420 }
421 }
422 return linkedPullRequest ?? branchPullRequest
423 }
424​
425 /// Missing capabilities mean unsupported. Existing states remain reversible
426 /// so older cached snapshots cannot trap a thread in its current state.
427 public var canTogglePin: Bool {
428 pinnedAt != nil || supportsPinning == true
429 }
430​
431 public var canToggleSettlement: Bool {
432 isSettled || supportsSettlement == true
433 }
434​
435 public var canToggleSnooze: Bool {
436 snoozedUntil != nil || supportsSnooze == true
437 }
438​
439 /// The server refuses to archive a thread with live work. Hide the action
440 /// on those rows instead of offering it and then reporting the refusal.
441 public var canArchive: Bool {
442 switch state {
443 case .queued, .working, .monitoring, .waitingForApproval, .waitingForInput:
444 false
445 case .idle, .completed, .failed:
446 true
447 }
448 }
449​
450 /// Mirrors the server's `thread.snooze` guard and client-runtime
451 /// `canSnooze`: a raised hand or a turn that is still being adopted blocks
452 /// snooze. The session lifecycle state on its own does not.
453 public func canSnoozeNow(at now: Date) -> Bool {
454 guard canToggleSnooze else { return false }
455 if state == .waitingForApproval || state == .waitingForInput { return false }
456 return !hasQueuedTurnStart(at: now)
457 }
458​
460​
461/// The thread-list section a drag reorder arranges. Pinned threads write
462/// `pinOrderKey`; active threads write `activeOrderKey`.
463public enum FeatureThreadOrderSection: String, Sendable, Equatable {
464 case pinned
465 case active
467​
468/// One `orderKey` write needed to realize a move. A move between keyed
469/// neighbors produces a single assignment on the moved thread; a move next to
470/// keyless threads rewrites the whole section (see ThreadOrderPlanner).
471public struct FeatureThreadOrderAssignment: Sendable, Equatable {
472 /// Feature-scoped thread id (`FeatureScopedID.thread`), so assignments can
473 /// span environments.
474 public let threadID: String
475 public let orderKey: String
476​
477 public init(threadID: String, orderKey: String) {
478 self.threadID = threadID
479 self.orderKey = orderKey
480 }
482​
483/// A spread rewrite that wrote some assignments before a later environment
484/// rejected its write. Callers apply `confirmed` — those rows are arranged on
485/// their servers — and surface `underlying` as the move's failure.
486public struct FeatureThreadMovePartialError: Error, Sendable {
487 public let confirmed: [FeatureThreadOrderAssignment]
488 public let underlying: Error
489​
490 public init(confirmed: [FeatureThreadOrderAssignment], underlying: Error) {
491 self.confirmed = confirmed
492 self.underlying = underlying
493 }
495​
496public enum FeatureMessageRole: String, Sendable, Codable {
497 case user
498 case assistant
499 case system
500 case tool
502​
503public enum FeatureMessageState: String, Sendable, Codable {
504 case queued
505 case streaming
506 case complete
507 case failed
509​
510public struct FeatureMessageAttachment: Identifiable, Sendable, Equatable, Hashable, Codable {
511 public var source: PastedTextAttachmentSource?
512 public let id: String
513 public var name: String
514 public var mimeType: String
515 public var sizeBytes: Int
516 public var url: URL?
517 /// Small local preview retained only while an optimistic message is replaced
518 /// by its server-backed attachment URL.
519 public var previewData: Data?
520​
521 public init(
522 id: String,
523 name: String,
524 mimeType: String,
525 sizeBytes: Int,
526 url: URL? = nil,
527 previewData: Data? = nil,
528 source: PastedTextAttachmentSource? = nil
529 ) {
530 self.id = id
531 self.name = name
532 self.mimeType = mimeType
533 self.sizeBytes = sizeBytes
534 self.url = url
535 self.previewData = previewData
536 self.source = source
537 }
539​
540public struct FeatureUploadAttachment: Sendable, Equatable {
541 public var source: PastedTextAttachmentSource?
542 public let id: UUID
543 private var inlineData: Data?
544 public var ownedFile: FeatureOwnedAttachmentFile?
545 public var name: String
546 public var mimeType: String
547 public var uploadedReference: FeatureUploadedAttachmentReference?
548​
549 public init(
550 id: UUID = UUID(),
551 data: Data,
552 name: String,
553 mimeType: String,
554 uploadedReference: FeatureUploadedAttachmentReference? = nil,
555 source: PastedTextAttachmentSource? = nil
556 ) {
557 self.id = id
558 inlineData = data
559 ownedFile = nil
560 self.name = name
561 self.mimeType = mimeType
562 self.uploadedReference = uploadedReference
563 self.source = source
564 }
565​
566 public init(
567 id: UUID = UUID(),
568 ownedFile: FeatureOwnedAttachmentFile,
569 name: String,
570 mimeType: String,
571 uploadedReference: FeatureUploadedAttachmentReference? = nil,
572 source: PastedTextAttachmentSource? = nil
573 ) {
574 self.id = id
575 inlineData = nil
576 self.ownedFile = ownedFile
577 self.name = name
578 self.mimeType = mimeType
579 self.uploadedReference = uploadedReference
580 self.source = source
581 }
582​
583 public init(_ draft: FeatureDraftAttachment) {
584 id = draft.id
585 inlineData = draft.ownedFile == nil ? draft.data : nil
586 ownedFile = draft.ownedFile
587 name = draft.filename
588 mimeType = draft.mimeType
589 uploadedReference = draft.uploadedReference
590 source = draft.source
591 }
592​
593 public var data: Data {
594 get { inlineData ?? Data() }
595 set {
596 inlineData = newValue
597 ownedFile = nil
598 }
599 }
600​
601 public var byteCount: Int {
602 inlineData?.count ?? ownedFile?.byteCount ?? 0
603 }
605​
606public struct FeatureMessage: Identifiable, Sendable, Equatable, Hashable, Codable {
607 public var context: OrchestrationMessageContext?
608 public let id: String
609 public var role: FeatureMessageRole
610 public var text: String
611 public var createdAt: Date
612 public var state: FeatureMessageState
613 public var toolName: String?
614 public var attachments: [FeatureMessageAttachment]
615 public var workLogImagePaths: [String]?
616 public var activeWorkLabel: String?
617 public var toolPresentation: ToolActivityPresentation? = nil
618​
619 public init(
620 id: String,
621 role: FeatureMessageRole,
622 text: String,
623 createdAt: Date = .now,
624 state: FeatureMessageState = .complete,
625 toolName: String? = nil,
626 attachments: [FeatureMessageAttachment] = [],
627 workLogImagePaths: [String]? = nil,
628 activeWorkLabel: String? = nil,
629 context: OrchestrationMessageContext? = nil
630 ) {
631 self.id = id
632 self.role = role
633 self.text = text
634 self.createdAt = createdAt
635 self.state = state
636 self.toolName = toolName
637 self.attachments = attachments
638 self.workLogImagePaths = workLogImagePaths
639 self.activeWorkLabel = activeWorkLabel
640 self.context = context
641 }
643​
644public enum FeatureApprovalKind: String, Sendable, Codable {
645 case command
646 case fileRead
647 case fileChange
648 case mcpElicitation
649 case patch
650 case other
652​
653public struct FeatureApprovalOption: Identifiable, Sendable, Equatable, Hashable, Codable {
654 public var id: FeatureApprovalDecision { decision }
655 public let decision: FeatureApprovalDecision
656 public let label: String
657​
658 public init(decision: FeatureApprovalDecision, label: String) {
659 self.decision = decision
660 self.label = label
661 }
663​
664public struct FeatureApproval: Identifiable, Sendable, Equatable, Hashable, Codable {
665 public let id: String
666 /// The provider request identifier sent over the wire.
667 public var wireID: String?
668 public var threadID: String
669 public var kind: FeatureApprovalKind
670 public var title: String
671 public var detail: String
672 public var appName: String?
673 public var options: [FeatureApprovalOption]?
674​
675 public init(
676 id: String,
677 wireID: String? = nil,
678 threadID: String,
679 kind: FeatureApprovalKind,
680 title: String,
681 detail: String,
682 appName: String? = nil,
683 options: [FeatureApprovalOption]? = nil
684 ) {
685 self.id = id
686 self.wireID = wireID
687 self.threadID = threadID
688 self.kind = kind
689 self.title = title
690 self.detail = detail
691 self.appName = appName
692 self.options = options
693 }
695​
696public struct FeatureInputOption: Sendable, Equatable, Hashable, Codable {
697 public var label: String
698 public var detail: String
699​
700 public init(label: String, detail: String) {
701 self.label = label
702 self.detail = detail
703 }
705​
706/// A provider answer is either free-form/single-select text or the selected
707/// labels for a multi-select question. Its Codable shape intentionally matches
708/// the provider wire contract: a JSON string or an array of JSON strings.
709public enum FeatureInputAnswer: Sendable, Equatable, Hashable, Codable {
710 case text(String)
711 case selections([String])
712​
713 public init(from decoder: any Decoder) throws {
714 let container = try decoder.singleValueContainer()
715 if let value = try? container.decode(String.self) {
716 self = .text(value)
717 } else {
718 self = try .selections(container.decode([String].self))
719 }
720 }
721​
722 public func encode(to encoder: any Encoder) throws {
723 var container = encoder.singleValueContainer()
724 switch self {
725 case let .text(value):
726 try container.encode(value)
727 case let .selections(values):
728 try container.encode(values)
729 }
730 }
732​
733extension FeatureInputAnswer {
734 var normalized: FeatureInputAnswer? {
735 switch self {
736 case let .text(value):
737 let normalized = value.trimmingCharacters(in: .whitespacesAndNewlines)
738 return normalized.isEmpty ? nil : .text(normalized)
739 case let .selections(values):
740 var seen: Set<String> = []
741 let normalized = values.compactMap { value -> String? in
742 let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
743 guard !trimmed.isEmpty, seen.insert(trimmed).inserted else { return nil }
744 return trimmed
745 }
746 return normalized.isEmpty ? nil : .selections(normalized)
747 }
748 }
749​
750 func togglingOption(_ label: String, allowsMultiple: Bool) -> FeatureInputAnswer {
751 guard allowsMultiple else { return .text(label) }
752​
753 let current: [String]
754 if case let .selections(values) = self {
755 current = values
756 } else {
757 current = []
758 }
759​
760 if current.contains(label) {
761 return .selections(current.filter { $0 != label })
762 }
763 return .selections(current + [label])
764 }
766​
767public struct FeatureInputQuestion: Identifiable, Sendable, Equatable, Hashable, Codable {
768 public let id: String
769 public var header: String
770 public var question: String
771 public var options: [FeatureInputOption]
772 public var allowsMultiple: Bool
773 public var allowCustomAnswer: Bool? = nil
774​
775 public var canWriteCustomAnswer: Bool { allowCustomAnswer != false }
776​
777 public init(
778 id: String,
779 header: String,
780 question: String,
781 options: [FeatureInputOption] = [],
782 allowsMultiple: Bool = false
783 ) {
784 self.id = id
785 self.header = header
786 self.question = question
787 self.options = options
788 self.allowsMultiple = allowsMultiple
789 }
791​
792public struct FeatureUserInput: Identifiable, Sendable, Equatable, Hashable, Codable {
793 public let id: String
794 /// The provider request identifier sent over the wire.
795 public var wireID: String?
796 public var threadID: String
797 public var questions: [FeatureInputQuestion]
798 /// Only message-based questions can close without a provider callback.
799 public var dismissible: Bool? = nil
800 public var supportsAttachments: Bool? = nil
801​
802 public var canDismiss: Bool { dismissible == true }
803​
804 public init(
805 id: String,
806 wireID: String? = nil,
807 threadID: String,
808 questions: [FeatureInputQuestion]
809 ) {
810 self.id = id
811 self.wireID = wireID
812 self.threadID = threadID
813 self.questions = questions
814 }
816​
817/// Stable UI identity for entities merged from independent environments.
818/// Length-prefixing avoids separator collisions without requiring IDs to be parsed.
819enum FeatureScopedID {
820 static func project(environmentID: String, wireID: String) -> String {
821 make(kind: "project", environmentID: environmentID, wireID: wireID)
822 }
823​
824 static func thread(environmentID: String, wireID: String) -> String {
825 make(kind: "thread", environmentID: environmentID, wireID: wireID)
826 }
827​
828 static func approval(environmentID: String, wireID: String) -> String {
829 make(kind: "approval", environmentID: environmentID, wireID: wireID)
830 }
831​
832 static func input(environmentID: String, wireID: String) -> String {
833 make(kind: "input", environmentID: environmentID, wireID: wireID)
834 }
835​
836 private static func make(kind: String, environmentID: String, wireID: String) -> String {
837 "\(kind):\(environmentID.utf8.count):\(environmentID)\(wireID)"
838 }
840​
841public struct FeatureThreadDetail: Sendable, Equatable, Codable {
842 public var thread: FeatureThread
843 public var messages: [FeatureMessage]
844 public var approvals: [FeatureApproval]
845 public var userInputs: [FeatureUserInput]
846 public var page: FeatureThreadPage?
847 public var activeSubagentCount: Int
848 public var backgroundWorkIsActive: Bool
849 public var isCompacting: Bool?
850​
851 public init(
852 thread: FeatureThread,
853 messages: [FeatureMessage] = [],
854 approvals: [FeatureApproval] = [],
855 userInputs: [FeatureUserInput] = [],
856 page: FeatureThreadPage? = nil,
857 activeSubagentCount: Int = 0,
858 backgroundWorkIsActive: Bool = false,
859 isCompacting: Bool = false
860 ) {
861 self.thread = thread
862 self.messages = messages
863 self.approvals = approvals
864 self.userInputs = userInputs
865 self.page = page
866 self.activeSubagentCount = activeSubagentCount
867 self.backgroundWorkIsActive = backgroundWorkIsActive
868 self.isCompacting = isCompacting
869 }
871​
872public struct FeatureThreadPage: Sendable, Equatable, Codable {
873 public var beforeCursor: String?
874 public var hasMore: Bool
875 public var isLoading: Bool
876​
877 public init(beforeCursor: String?, hasMore: Bool, isLoading: Bool = false) {
878 self.beforeCursor = beforeCursor
879 self.hasMore = hasMore
880 self.isLoading = isLoading
881 }
883​
884/// The small rendered-message delta produced by the native thread stream.
885/// Keeping this beside the authoritative detail lets recycled transcript rows
886/// update in proportion to an event instead of rescanning the full history.
887public struct FeatureDetailDelta: Sendable, Equatable {
888 public var changedMessages: [FeatureMessage]
889 public var appendedMessageIDs: [String]
890​
891 public init(
892 changedMessages: [FeatureMessage],
893 appendedMessageIDs: [String] = []
894 ) {
895 self.changedMessages = changedMessages
896 self.appendedMessageIDs = appendedMessageIDs
897 }
899​
900public struct FeatureModel: Identifiable, Sendable, Equatable, Hashable, Codable {
901 public let id: String
902 public var name: String
903 public var detail: String?
904 public var supportsImages: Bool
905 public var imageSupportIsUnknown: Bool? = nil
906 public var supportsReasoning: Bool
907 public var isDefault: Bool
908 public var isLegacy: Bool?
909 public var options: [FeatureModelOptionDescriptor]
910​
911 public init(
912 id: String,
913 name: String,
914 detail: String? = nil,
915 supportsImages: Bool = false,
916 supportsReasoning: Bool = false,
917 isDefault: Bool = false,
918 isLegacy: Bool? = nil,
919 options: [FeatureModelOptionDescriptor] = []
920 ) {
921 self.id = id
922 self.name = name
923 self.detail = detail
924 self.supportsImages = supportsImages
925 self.supportsReasoning = supportsReasoning
926 self.isDefault = isDefault
927 self.isLegacy = isLegacy
928 self.options = options
929 }
931​
932public enum FeatureModelOptionKind: String, Sendable, Equatable, Hashable, Codable {
933 case select
934 case boolean
936​
937public struct FeatureModelOptionChoice: Identifiable, Sendable, Equatable, Hashable, Codable {
938 public let id: String
939 public var label: String
940 public var detail: String?
941 public var isDefault: Bool
942​
943 public init(
944 id: String,
945 label: String,
946 detail: String? = nil,
947 isDefault: Bool = false
948 ) {
949 self.id = id
950 self.label = label
951 self.detail = detail
952 self.isDefault = isDefault
953 }
955​
956public struct FeatureModelOptionDescriptor: Identifiable, Sendable, Equatable, Hashable, Codable {
957 public let id: String
958 public var label: String
959 public var detail: String?
960 public var kind: FeatureModelOptionKind
961 public var choices: [FeatureModelOptionChoice]
962 public var defaultValue: FeatureModelOptionValue?
963 public var promptInjectedValues: [String]?
964​
965 public init(
966 id: String,
967 label: String,
968 detail: String? = nil,
969 kind: FeatureModelOptionKind,
970 choices: [FeatureModelOptionChoice] = [],
971 defaultValue: FeatureModelOptionValue? = nil,
972 promptInjectedValues: [String]? = nil
973 ) {
974 self.id = id
975 self.label = label
976 self.detail = detail
977 self.kind = kind
978 self.choices = choices
979 self.defaultValue = defaultValue
980 self.promptInjectedValues = promptInjectedValues
981 }
983​
984public enum FeatureModelOptionValue: Sendable, Equatable, Hashable, Codable {
985 case string(String)
986 case boolean(Bool)
987​
988 private enum CodingKeys: String, CodingKey {
989 case type
990 case value
991 }
992​
993 private enum ValueType: String, Codable {
994 case string
995 case boolean
996 }
997​
998 public init(from decoder: any Decoder) throws {
999 let container = try decoder.container(keyedBy: CodingKeys.self)
1000 switch try container.decode(ValueType.self, forKey: .type) {
1001 case .string:
1002 self = try .string(container.decode(String.self, forKey: .value))
1003 case .boolean:
1004 self = try .boolean(container.decode(Bool.self, forKey: .value))
1007​
1008 public func encode(to encoder: any Encoder) throws {
1009 var container = encoder.container(keyedBy: CodingKeys.self)
1010 switch self {
1011 case let .string(value):
1012 try container.encode(ValueType.string, forKey: .type)
1013 try container.encode(value, forKey: .value)
1014 case let .boolean(value):
1015 try container.encode(ValueType.boolean, forKey: .type)
1016 try container.encode(value, forKey: .value)
1020​
1021public struct FeatureModelOptionSelection: Identifiable, Sendable, Equatable, Hashable, Codable {
1022 public let id: String
1023 public var value: FeatureModelOptionValue
1024​
1025 public init(id: String, value: FeatureModelOptionValue) {
1026 self.id = id
1027 self.value = value
1030​
1031public struct FeatureProviderWorkspace: Sendable, Equatable, Hashable, Codable {
1032 public let cwd: String
1033 public let slashCommands: [FeatureProviderSlashCommand]
1034 public let skills: [FeatureProviderSkill]
1036​
1037public struct FeatureProvider: Identifiable, Sendable, Equatable, Hashable, Codable {
1038 public let id: String
1039 public var name: String
1040 public var isAvailable: Bool
1041 public var driver: String
1042 public var requiresNewThreadForModelChange: Bool
1043 public var models: [FeatureModel]
1044 public var slashCommands: [FeatureProviderSlashCommand]?
1045 public var skills: [FeatureProviderSkill]?
1046 public var workspaceSnapshots: [FeatureProviderWorkspace]? = nil
1047 public var setup: ProviderSetupCapabilities? = nil
1048 public var isEnabled: Bool? = nil
1049 public var isInstalled: Bool? = nil
1050 public var authStatus: String? = nil
1051 public var statusMessage: String? = nil
1052 public var accentColor: String? = nil
1053​
1054 func workspaceCatalog(cwd: String?) -> FeatureProviderWorkspace {
1055 if let cwd, let workspace = workspaceSnapshots?.first(where: { $0.cwd == cwd }) {
1056 return workspace
1058 // A catalog from another workspace must not leak into this composer.
1059 return FeatureProviderWorkspace(
1060 cwd: cwd ?? "",
1061 slashCommands: workspaceSnapshots == nil ? slashCommands ?? [] : [],
1062 skills: workspaceSnapshots == nil ? skills ?? [] : []
1065​
1066 public init(
1067 id: String,
1068 name: String,
1069 isAvailable: Bool = true,
1070 driver: String = "",
1071 requiresNewThreadForModelChange: Bool = false,
1072 models: [FeatureModel] = [],
1073 slashCommands: [FeatureProviderSlashCommand] = [],
1074 skills: [FeatureProviderSkill] = []
1075 ) {
1076 self.id = id
1077 self.name = name
1078 self.isAvailable = isAvailable
1079 self.driver = driver
1080 self.requiresNewThreadForModelChange = requiresNewThreadForModelChange
1081 self.models = models
1082 self.slashCommands = slashCommands
1083 self.skills = skills
1086​
1087public struct FeatureSelection: Sendable, Equatable, Hashable, Codable {
1088 public var providerID: String
1089 public var modelID: String
1090 public var options: [FeatureModelOptionSelection]
1091​
1092 public init(
1093 providerID: String,
1094 modelID: String,
1095 options: [FeatureModelOptionSelection] = []
1096 ) {
1097 self.providerID = providerID
1098 self.modelID = modelID
1099 self.options = options
1102​
1103public enum FeatureAppearance: String, CaseIterable, Sendable, Codable {
1104 case system
1105 case light
1106 case dark
1108​
1109public struct FeatureTextSizeAdjustment: Sendable, Equatable, Hashable, Codable {
1110 public static let range = -2...3
1111 public static let standard = FeatureTextSizeAdjustment(steps: 0)
1112​
1113 public let steps: Int
1114​
1115 public init(steps: Int) {
1116 self.steps = min(Self.range.upperBound, max(Self.range.lowerBound, steps))
1118​
1119 public init(from decoder: any Decoder) throws {
1120 try self.init(steps: decoder.singleValueContainer().decode(Int.self))
1122​
1123 public func encode(to encoder: any Encoder) throws {
1124 var container = encoder.singleValueContainer()
1125 try container.encode(steps)
1128​
1129public struct FeatureSettings: Sendable, Equatable, Codable {
1130 public var appearance: FeatureAppearance
1131 public var textSize: FeatureTextSizeAdjustment
1132 public var codeSize: FeatureTextSizeAdjustment
1133 public var hapticsEnabled: Bool
1134 public var notificationsEnabled: Bool
1135 public var liveActivitiesEnabled: Bool
1136 public var defaultSelection: FeatureSelection?
1137​
1138 public init(
1139 appearance: FeatureAppearance = .system,
1140 textSize: FeatureTextSizeAdjustment = .standard,
1141 codeSize: FeatureTextSizeAdjustment = .standard,
1142 hapticsEnabled: Bool = true,
1143 notificationsEnabled: Bool = true,
1144 liveActivitiesEnabled: Bool = true,
1145 defaultSelection: FeatureSelection? = nil
1146 ) {
1147 self.appearance = appearance
1148 self.textSize = textSize
1149 self.codeSize = codeSize
1150 self.hapticsEnabled = hapticsEnabled
1151 self.notificationsEnabled = notificationsEnabled
1152 self.liveActivitiesEnabled = liveActivitiesEnabled
1153 self.defaultSelection = defaultSelection
1155​
1156 private enum CodingKeys: String, CodingKey {
1157 case appearance
1158 case textSize
1159 case codeSize
1160 case hapticsEnabled
1161 case notificationsEnabled
1162 case liveActivitiesEnabled
1163 case defaultSelection
1165​
1166 public init(from decoder: any Decoder) throws {
1167 let container = try decoder.container(keyedBy: CodingKeys.self)
1168 appearance = try container.decodeIfPresent(
1169 FeatureAppearance.self,
1170 forKey: .appearance
1171 ) ?? .system
1172 textSize = try container.decodeIfPresent(
1173 FeatureTextSizeAdjustment.self,
1174 forKey: .textSize
1175 ) ?? .standard
1176 codeSize = try container.decodeIfPresent(
1177 FeatureTextSizeAdjustment.self,
1178 forKey: .codeSize
1179 ) ?? .standard
1180 hapticsEnabled = try container.decodeIfPresent(
1181 Bool.self,
1182 forKey: .hapticsEnabled
1183 ) ?? true
1184 notificationsEnabled = try container.decodeIfPresent(
1185 Bool.self,
1186 forKey: .notificationsEnabled
1187 ) ?? true
1188 liveActivitiesEnabled = try container.decodeIfPresent(
1189 Bool.self,
1190 forKey: .liveActivitiesEnabled
1191 ) ?? true
1192 defaultSelection = try container.decodeIfPresent(
1193 FeatureSelection.self,
1194 forKey: .defaultSelection
1197​
1198 public func encode(to encoder: any Encoder) throws {
1199 var container = encoder.container(keyedBy: CodingKeys.self)
1200 try container.encode(appearance, forKey: .appearance)
1201 try container.encode(textSize, forKey: .textSize)
1202 try container.encode(codeSize, forKey: .codeSize)
1203 try container.encode(hapticsEnabled, forKey: .hapticsEnabled)
1204 try container.encode(notificationsEnabled, forKey: .notificationsEnabled)
1205 try container.encode(liveActivitiesEnabled, forKey: .liveActivitiesEnabled)
1206 try container.encodeIfPresent(defaultSelection, forKey: .defaultSelection)
1209​
1210public struct FeatureProjectPreferences: Sendable {
1211 public let environment: ServerSettingsSnapshot
1212 public let effective: ServerSettingsSnapshot
1214​
1215public struct FeatureEnvironmentPreferences: Sendable, Equatable, Codable {
1216 public enum ProjectGroupingMode: String, Sendable, Equatable, Codable {
1217 case repository
1218 case repositoryPath = "repository_path"
1219 case separate
1221​
1222 public var defaultWorkspaceMode: FeatureWorkspaceMode
1223 public var newWorktreesStartFromOrigin: Bool
1224 public var projectGroupingMode: ProjectGroupingMode
1225 public var projectGroupingOverrides: [String: ProjectGroupingMode]
1226 public var automaticSettlement: FeatureAutomaticSettlementSettings?
1227 public var supportsImageUploads: Bool
1228 public var maxFileAttachmentBytes: Int?
1229 public var continueThreadsAfterServerUpdate: Bool?
1230​
1231 public init(
1232 defaultWorkspaceMode: FeatureWorkspaceMode = .local,
1233 newWorktreesStartFromOrigin: Bool = true,
1234 projectGroupingMode: ProjectGroupingMode = .repository,
1235 projectGroupingOverrides: [String: ProjectGroupingMode] = [:],
1236 automaticSettlement: FeatureAutomaticSettlementSettings? = nil,
1237 supportsImageUploads: Bool = false,
1238 maxFileAttachmentBytes: Int? = nil,
1239 continueThreadsAfterServerUpdate: Bool? = nil
1240 ) {
1241 self.defaultWorkspaceMode = defaultWorkspaceMode
1242 self.newWorktreesStartFromOrigin = newWorktreesStartFromOrigin
1243 self.projectGroupingMode = projectGroupingMode
1244 self.projectGroupingOverrides = projectGroupingOverrides
1245 self.automaticSettlement = automaticSettlement
1246 self.supportsImageUploads = supportsImageUploads
1247 self.maxFileAttachmentBytes = maxFileAttachmentBytes
1248 self.continueThreadsAfterServerUpdate = continueThreadsAfterServerUpdate
1250​
1251 private enum CodingKeys: String, CodingKey {
1252 case defaultWorkspaceMode
1253 case newWorktreesStartFromOrigin
1254 case projectGroupingMode
1255 case projectGroupingOverrides
1256 case automaticSettlement
1257 case supportsImageUploads
1258 case maxFileAttachmentBytes
1259 case continueThreadsAfterServerUpdate
1261​
1262 public init(from decoder: any Decoder) throws {
1263 let container = try decoder.container(keyedBy: CodingKeys.self)
1264 defaultWorkspaceMode = try container.decodeIfPresent(
1265 FeatureWorkspaceMode.self,
1266 forKey: .defaultWorkspaceMode
1267 ) ?? .local
1268 newWorktreesStartFromOrigin = try container.decodeIfPresent(
1269 Bool.self,
1270 forKey: .newWorktreesStartFromOrigin
1271 ) ?? true
1272 projectGroupingMode = try container.decodeIfPresent(
1273 ProjectGroupingMode.self,
1274 forKey: .projectGroupingMode
1275 ) ?? .repository
1276 supportsImageUploads = try container.decodeIfPresent(
1277 Bool.self,
1278 forKey: .supportsImageUploads
1279 ) ?? false
1280 maxFileAttachmentBytes = try container.decodeIfPresent(
1281 Int.self,
1282 forKey: .maxFileAttachmentBytes
1284 continueThreadsAfterServerUpdate = try container.decodeIfPresent(
1285 Bool.self,
1286 forKey: .continueThreadsAfterServerUpdate
1288 projectGroupingOverrides = try container.decodeIfPresent(
1289 [String: ProjectGroupingMode].self,
1290 forKey: .projectGroupingOverrides
1291 ) ?? [:]
1292 automaticSettlement = try container.decodeIfPresent(
1293 FeatureAutomaticSettlementSettings.self,
1294 forKey: .automaticSettlement
1297​
1298 public func encode(to encoder: any Encoder) throws {
1299 var container = encoder.container(keyedBy: CodingKeys.self)
1300 try container.encode(defaultWorkspaceMode, forKey: .defaultWorkspaceMode)
1301 try container.encode(newWorktreesStartFromOrigin, forKey: .newWorktreesStartFromOrigin)
1302 try container.encode(projectGroupingMode, forKey: .projectGroupingMode)
1303 try container.encode(projectGroupingOverrides, forKey: .projectGroupingOverrides)
1304 try container.encodeIfPresent(automaticSettlement, forKey: .automaticSettlement)
1305 try container.encode(supportsImageUploads, forKey: .supportsImageUploads)
1306 try container.encodeIfPresent(maxFileAttachmentBytes, forKey: .maxFileAttachmentBytes)
1307 try container.encodeIfPresent(continueThreadsAfterServerUpdate, forKey: .continueThreadsAfterServerUpdate)
1310​
1311public struct FeatureAutomaticSettlementSettings: Sendable, Equatable, Codable {
1312 public var onMerge: Bool
1313 public var afterDays: Double?
1314​
1315 public init(onMerge: Bool, afterDays: Double?) {
1316 self.onMerge = onMerge
1317 self.afterDays = afterDays
1320​
1321public enum FeatureAutomaticSettlementChange: Sendable, Equatable {
1322 case onMerge(Bool)
1323 case afterDays(Double?)
1325​
1326public struct FeatureSnapshot: Sendable, Equatable, Codable {
1327 public var connection: FeatureConnection
1328 public var environments: [FeatureEnvironment]
1329 public var projects: [FeatureProject]
1330 public var threads: [FeatureThread]
1331 public var providers: [FeatureProvider]
1332 /// Provider catalogues are environment-scoped. `providers` remains only
1333 /// for decoding older cached snapshots and must not drive product choices.
1334 public var providersByEnvironment: [String: [FeatureProvider]]?
1335 /// Server-authoritative new-thread defaults keyed by saved environment.
1336 public var preferencesByEnvironment: [String: FeatureEnvironmentPreferences]?
1337 public var settings: FeatureSettings
1338​
1339 public init(
1340 connection: FeatureConnection = .init(),
1341 environments: [FeatureEnvironment] = [],
1342 projects: [FeatureProject] = [],
1343 threads: [FeatureThread] = [],
1344 providers: [FeatureProvider] = [],
1345 providersByEnvironment: [String: [FeatureProvider]]? = nil,
1346 preferencesByEnvironment: [String: FeatureEnvironmentPreferences]? = nil,
1347 settings: FeatureSettings = .init()
1348 ) {
1349 self.connection = connection
1350 self.environments = environments
1351 self.projects = projects
1352 self.threads = threads
1353 self.providers = providers
1354 self.providersByEnvironment = providersByEnvironment
1355 self.preferencesByEnvironment = preferencesByEnvironment
1356 self.settings = settings
1359​
1360public enum FeatureApprovalDecision: String, Sendable, Codable {
1361 case allowOnce
1362 case allowForSession
1363 case allowAlways
1364 case deny
1365 case cancel
1366​
1367 init?(wireValue: String) {
1368 switch wireValue {
1369 case "accept": self = .allowOnce
1370 case "acceptForSession": self = .allowForSession
1371 case "acceptAlways": self = .allowAlways
1372 case "decline": self = .deny
1373 case "cancel": self = .cancel
1374 default: return nil
1377​
1378 var wireValue: String {
1379 switch self {
1380 case .allowOnce: "accept"
1381 case .allowForSession: "acceptForSession"
1382 case .allowAlways: "acceptAlways"
1383 case .deny: "decline"
1384 case .cancel: "cancel"
1388​
1389public enum FeatureThreadSyncState: Sendable, Equatable {
1390 case catchingUp
1391 case reconnecting
1392 case live
1393 case failed(String)
1395​
1396public enum FeatureEvent: Sendable {
1397 case snapshot(FeatureSnapshot)
1398 /// Active environment connection change. `environmentID` lets the model
1399 /// patch that environment's row without installing a whole snapshot.
1400 case connection(FeatureConnection, environmentID: String? = nil)
1401 case thread(FeatureThread)
1402 case threadRemoved(id: String)
1403 case detail(FeatureThreadDetail)
1404 case detailDelta(FeatureThreadDetail, FeatureDetailDelta)
1405 case threadSync(id: String, state: FeatureThreadSyncState?)
1406 case failure(String)