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

FeatureToolModels.swift

1,074 lines38.3 KB

1import Foundation
2​
3public struct FeatureCapabilityUnavailable: LocalizedError, Sendable, Equatable {
4 public let capability: String
5​
6 public init(_ capability: String) {
7 self.capability = capability
8 }
9​
10 public var errorDescription: String? {
11 "\(capability) is not supported by this environment."
12 }
14​
15/// Optional rich-file capability. The base file contract is deliberately text-only,
16/// while native clients can resolve the existing signed workspace asset route for images.
17@MainActor
18public protocol FeatureWorkspaceAssetResolving: AnyObject {
19 func workspaceAssetURL(threadID: String, path: String) async throws -> URL
20 func mediaAssetURL(threadID: String, path: String) async throws -> URL
21 func mediaAsset(threadID: String, path: String) async throws -> ResolvedAssetURL
22 func nativeAppIconURL(threadID: String, app: ToolNativeAppReference) async throws -> URL
24​
25public extension FeatureWorkspaceAssetResolving {
26 func mediaAsset(threadID: String, path: String) async throws -> ResolvedAssetURL {
27 ResolvedAssetURL(
28 url: try await mediaAssetURL(threadID: threadID, path: path),
29 expiresAt: .distantFuture
30 )
31 }
32​
33 func nativeAppIconURL(threadID: String, app: ToolNativeAppReference) async throws -> URL {
34 throw FeatureCapabilityUnavailable("Native app icons")
35 }
36​
37 func mediaAssetURL(threadID: String, path: String) async throws -> URL {
38 try await workspaceAssetURL(threadID: threadID, path: path)
39 }
41​
42@MainActor
43public protocol FeatureFeedbackSubmitting: AnyObject {
44 func submitCodexFeedback(threadID: String, reason: String?) async throws -> String
46​
47public enum FeatureFileKind: String, Sendable, Codable {
48 case file
49 case directory
50 case symbolicLink
52​
53public struct FeatureFileEntry: Identifiable, Sendable, Equatable, Hashable, Codable {
54 public var id: String { path }
55 public let path: String
56 public var name: String
57 public var kind: FeatureFileKind
58 public var sizeBytes: Int?
59 public var isHidden: Bool
60 public var isIgnored: Bool
61​
62 public init(
63 path: String,
64 name: String,
65 kind: FeatureFileKind,
66 sizeBytes: Int? = nil,
67 isHidden: Bool = false,
68 isIgnored: Bool = false
69 ) {
70 self.path = path
71 self.name = name
72 self.kind = kind
73 self.sizeBytes = sizeBytes
74 self.isHidden = isHidden
75 self.isIgnored = isIgnored
76 }
77​
78 public init(from decoder: Decoder) throws {
79 let values = try decoder.container(keyedBy: CodingKeys.self)
80 path = try values.decode(String.self, forKey: .path)
81 name = try values.decode(String.self, forKey: .name)
82 kind = try values.decode(FeatureFileKind.self, forKey: .kind)
83 sizeBytes = try values.decodeIfPresent(Int.self, forKey: .sizeBytes)
84 isHidden = try values.decode(Bool.self, forKey: .isHidden)
85 isIgnored = try values.decodeIfPresent(Bool.self, forKey: .isIgnored) ?? false
86 }
88​
89public extension Array where Element == FeatureFileEntry {
90 func featureFiltered(by query: String, includesHidden: Bool) -> [FeatureFileEntry] {
91 let visible = includesHidden ? self : filter { !$0.isHidden }
92 let filtered: [FeatureFileEntry]
93 if query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
94 filtered = visible
95 } else {
96 filtered = visible.filter { $0.name.localizedCaseInsensitiveContains(query) }
97 }
98 return filtered.sorted {
99 if $0.kind == .directory, $1.kind != .directory { return true }
100 if $0.kind != .directory, $1.kind == .directory { return false }
101 return $0.name.localizedStandardCompare($1.name) == .orderedAscending
102 }
103 }
105​
106public struct FeatureFileContent: Sendable, Equatable, Codable {
107 public var path: String
108 public var text: String
109 public var language: String?
110 public var isTruncated: Bool
111 public var totalBytes: Int?
112​
113 public init(
114 path: String,
115 text: String,
116 language: String? = nil,
117 isTruncated: Bool = false,
118 totalBytes: Int? = nil
119 ) {
120 self.path = path
121 self.text = text
122 self.language = language
123 self.isTruncated = isTruncated
124 self.totalBytes = totalBytes
125 }
127​
128public enum FeatureFilePreviewKind: Sendable, Equatable {
129 case image
130 case pdf
131 case video
132 case document
133 case markdown
134 case source
135 case plainText
136​
137 public static func infer(path: String, language: String? = nil) -> Self {
138 let fileExtension = URL(fileURLWithPath: path).pathExtension.lowercased()
139 if imageExtensions.contains(fileExtension) { return .image }
140 if fileExtension == "pdf" { return .pdf }
141 if videoExtensions.contains(fileExtension) { return .video }
142 if documentExtensions.contains(fileExtension) { return .document }
143 if language?.lowercased() == "markdown" || ["md", "mdx"].contains(fileExtension) {
144 return .markdown
145 }
146 if language != nil || sourceExtensions.contains(fileExtension) { return .source }
147 return .plainText
148 }
149​
150 private static let imageExtensions: Set<String> = [
151 "avif", "gif", "ico", "jpeg", "jpg", "png", "webp",
152 ]
153​
154 private static let videoExtensions: Set<String> = [
155 "m4v", "mov", "mp4", "mpeg", "mpg", "webm",
156 ]
157​
158 private static let documentExtensions: Set<String> = [
159 "doc", "docx", "key", "numbers", "pages", "ppt", "pptx", "rtf", "xls", "xlsx",
160 ]
161​
162 private static let sourceExtensions: Set<String> = [
163 "c", "cc", "cpp", "cs", "css", "go", "h", "hpp", "html", "java", "js", "jsx",
164 "json", "kt", "kts", "m", "mm", "php", "py", "rb", "rs", "scss", "sh", "sql",
165 "swift", "toml", "ts", "tsx", "vue", "xml", "yaml", "yml", "zsh",
166 ]
168​
169public enum FeatureSourceTokenKind: String, Sendable, Equatable, Hashable, Codable {
170 case plain
171 case comment
172 case keyword
173 case literal
174 case number
175 case property
177​
178public struct FeatureSourceSpan: Sendable, Equatable, Hashable, Codable {
179 public var text: String
180 public var kind: FeatureSourceTokenKind
181​
182 public init(text: String, kind: FeatureSourceTokenKind) {
183 self.text = text
184 self.kind = kind
185 }
187​
188public struct FeatureSourceLine: Identifiable, Sendable, Equatable, Hashable, Codable {
189 public let id: Int
190 public var spans: [FeatureSourceSpan]
191​
192 public init(id: Int, spans: [FeatureSourceSpan]) {
193 self.id = id
194 self.spans = spans
195 }
196​
197 public var number: Int { id + 1 }
198 public var text: String { spans.map(\.text).joined() }
200​
201/// A bounded, language-aware lexer for file previews. It runs once when a file loads;
202/// SwiftUI receives immutable line plans and performs no regex or token work while scrolling.
203public enum FeatureSourceHighlighter {
204 public static func lines(text: String, language: String?) -> [FeatureSourceLine] {
205 let sourceLines = text.split(separator: "\n", omittingEmptySubsequences: false)
206 let highlightsContent = text.utf8.count <= 512 * 1_024
207 var isInsideBlockComment = false
208 return sourceLines.enumerated().map { index, line in
209 guard highlightsContent, line.utf8.count <= 32 * 1_024 else {
210 return FeatureSourceLine(
211 id: index,
212 spans: line.isEmpty
213 ? []
214 : [FeatureSourceSpan(text: String(line), kind: .plain)]
215 )
216 }
217 return FeatureSourceLine(
218 id: index,
219 spans: spans(
220 in: String(line),
221 language: language?.lowercased(),
222 isInsideBlockComment: &isInsideBlockComment
223 )
224 )
225 }
226 }
227​
228 private static func spans(
229 in line: String,
230 language: String?,
231 isInsideBlockComment: inout Bool
232 ) -> [FeatureSourceSpan] {
233 let characters = Array(line)
234 var output: [FeatureSourceSpan] = []
235 var index = 0
236 let lineComment = lineCommentMarker(for: language)
237 let supportsBlockComments = blockCommentLanguages.contains(language ?? "")
238 let keywords = keywords(for: language)
239​
240 func hasPrefix(_ prefix: [Character], at offset: Int) -> Bool {
241 guard offset + prefix.count <= characters.count else { return false }
242 return characters[offset ..< offset + prefix.count].elementsEqual(prefix)
243 }
244​
245 func append(_ range: Range<Int>, kind: FeatureSourceTokenKind) {
246 guard !range.isEmpty else { return }
247 let text = String(characters[range])
248 if output.last?.kind == kind {
249 output[output.count - 1].text += text
250 } else {
251 output.append(FeatureSourceSpan(text: text, kind: kind))
252 }
253 }
254​
255 while index < characters.count {
256 if isInsideBlockComment {
257 let start = index
258 while index < characters.count, !hasPrefix(["*", "/"], at: index) {
259 index += 1
260 }
261 if index < characters.count {
262 index += 2
263 isInsideBlockComment = false
264 }
265 append(start ..< index, kind: .comment)
266 continue
267 }
268​
269 if let lineComment, hasPrefix(Array(lineComment), at: index) {
270 append(index ..< characters.count, kind: .comment)
271 break
272 }
273​
274 if supportsBlockComments, hasPrefix(["/", "*"], at: index) {
275 let start = index
276 index += 2
277 while index < characters.count, !hasPrefix(["*", "/"], at: index) {
278 index += 1
279 }
280 if index < characters.count {
281 index += 2
282 } else {
283 isInsideBlockComment = true
284 }
285 append(start ..< index, kind: .comment)
286 continue
287 }
288​
289 if ["\"", "'", "`"].contains(characters[index]) {
290 let start = index
291 let delimiter = characters[index]
292 index += 1
293 var isEscaped = false
294 while index < characters.count {
295 let character = characters[index]
296 index += 1
297 if character == delimiter, !isEscaped { break }
298 isEscaped = character == "\\" && !isEscaped
299 if character != "\\" { isEscaped = false }
300 }
301 var next = index
302 while next < characters.count, characters[next].isWhitespace { next += 1 }
303 let kind: FeatureSourceTokenKind = next < characters.count
304 && characters[next] == ":"
305 && propertyLanguages.contains(language ?? "")
306 ? .property
307 : .literal
308 append(start ..< index, kind: kind)
309 continue
310 }
311​
312 if characters[index].isNumber {
313 let start = index
314 index += 1
315 while index < characters.count,
316 characters[index].isNumber
317 || [".", "_", "x", "X", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"].contains(characters[index]) {
318 index += 1
319 }
320 append(start ..< index, kind: .number)
321 continue
322 }
323​
324 if isIdentifierStart(characters[index]) {
325 let start = index
326 index += 1
327 while index < characters.count, isIdentifierBody(characters[index]) {
328 index += 1
329 }
330 let token = String(characters[start ..< index])
331 var next = index
332 while next < characters.count, characters[next].isWhitespace { next += 1 }
333 let kind: FeatureSourceTokenKind
334 if ["true", "false", "null", "nil", "undefined"].contains(token) {
335 kind = .literal
336 } else if keywords.contains(token) {
337 kind = .keyword
338 } else if next < characters.count,
339 characters[next] == ":",
340 propertyLanguages.contains(language ?? "") {
341 kind = .property
342 } else {
343 kind = .plain
344 }
345 append(start ..< index, kind: kind)
346 continue
347 }
348​
349 append(index ..< index + 1, kind: .plain)
350 index += 1
351 }
352 return output
353 }
354​
355 private static func lineCommentMarker(for language: String?) -> String? {
356 switch language {
357 case "plain": nil
358 case "python", "shell", "ruby", "yaml", "toml": "#"
359 case "sql": "--"
360 case "html", "xml", "css", "scss": nil
361 default: "//"
362 }
363 }
364​
365 private static func keywords(for language: String?) -> Set<String> {
366 switch language {
367 case "plain": []
368 case "swift": swiftKeywords
369 case "typescript", "javascript": javascriptKeywords
370 case "python": pythonKeywords
371 case "rust": rustKeywords
372 case "go": goKeywords
373 case "shell": shellKeywords
374 default: commonKeywords
375 }
376 }
377​
378 private static func isIdentifierStart(_ character: Character) -> Bool {
379 character == "_" || character == "$" || character.isLetter
380 }
381​
382 private static func isIdentifierBody(_ character: Character) -> Bool {
383 isIdentifierStart(character) || character.isNumber || character == "-"
384 }
385​
386 private static let propertyLanguages: Set<String> = ["json", "typescript", "javascript", "yaml"]
387 private static let blockCommentLanguages: Set<String> = [
388 "css", "go", "java", "javascript", "rust", "scss", "swift", "typescript",
389 ]
390 private static let commonKeywords: Set<String> = [
391 "class", "const", "else", "enum", "false", "for", "func", "function", "if", "import",
392 "let", "nil", "null", "private", "public", "return", "struct", "true", "var", "while",
393 ]
394 private static let swiftKeywords = commonKeywords.union([
395 "actor", "any", "associatedtype", "async", "await", "case", "defer", "extension", "guard",
396 "in", "init", "internal", "nonisolated", "opaque", "protocol", "self", "some", "switch",
397 "throws", "try", "typealias", "where",
398 ])
399 private static let javascriptKeywords = commonKeywords.union([
400 "as", "break", "case", "catch", "continue", "default", "export", "extends", "from", "interface",
401 "new", "of", "static", "throw", "type", "typeof", "undefined",
402 ])
403 private static let pythonKeywords = commonKeywords.union([
404 "and", "as", "assert", "async", "await", "def", "elif", "except", "finally", "from", "in",
405 "is", "lambda", "not", "or", "pass", "raise", "with", "yield",
406 ])
407 private static let rustKeywords = commonKeywords.union([
408 "as", "async", "await", "crate", "dyn", "impl", "in", "loop", "match", "mod", "move", "mut",
409 "ref", "self", "trait", "type", "unsafe", "use", "where",
410 ])
411 private static let goKeywords = commonKeywords.union([
412 "break", "case", "chan", "continue", "defer", "fallthrough", "go", "goto", "interface", "map",
413 "package", "range", "select", "type",
414 ])
415 private static let shellKeywords = commonKeywords.union([
416 "case", "do", "done", "elif", "esac", "export", "fi", "in", "then",
417 ])
419​
420public enum FeatureDiffLineKind: String, Sendable, Codable {
421 case context
422 case addition
423 case deletion
424 case hunk
426​
427public struct FeatureDiffLine: Identifiable, Sendable, Equatable, Hashable, Codable {
428 public let id: String
429 public var kind: FeatureDiffLineKind
430 public var oldLine: Int?
431 public var newLine: Int?
432 public var text: String
433 public var spans: [FeatureDiffTextSpan]?
434​
435 public init(
436 id: String,
437 kind: FeatureDiffLineKind,
438 oldLine: Int? = nil,
439 newLine: Int? = nil,
440 text: String,
441 spans: [FeatureDiffTextSpan]? = nil
442 ) {
443 self.id = id
444 self.kind = kind
445 self.oldLine = oldLine
446 self.newLine = newLine
447 self.text = text
448 self.spans = spans
449 }
451​
452public enum FeatureDiffTextSpanKind: String, Sendable, Equatable, Hashable, Codable {
453 case unchanged
454 case changed
456​
457public struct FeatureDiffTextSpan: Sendable, Equatable, Hashable, Codable {
458 public var text: String
459 public var kind: FeatureDiffTextSpanKind
460​
461 public init(text: String, kind: FeatureDiffTextSpanKind) {
462 self.text = text
463 self.kind = kind
464 }
466​
467public enum FeatureDiffWordHighlighter {
468 public static func spans(
469 old: String,
470 new: String
471 ) -> (old: [FeatureDiffTextSpan], new: [FeatureDiffTextSpan]) {
472 guard old != new else {
473 let unchanged = [FeatureDiffTextSpan(text: old, kind: .unchanged)]
474 return (unchanged, unchanged)
475 }
476 let oldTokens = tokens(in: old)
477 let newTokens = tokens(in: new)
478 guard !oldTokens.isEmpty, !newTokens.isEmpty,
479 oldTokens.count * newTokens.count <= 20_000 else {
480 return (changed(old), changed(new))
481 }
482​
483 var lengths = Array(
484 repeating: Array(repeating: 0, count: newTokens.count + 1),
485 count: oldTokens.count + 1
486 )
487 for oldIndex in oldTokens.indices.reversed() {
488 for newIndex in newTokens.indices.reversed() {
489 lengths[oldIndex][newIndex] = oldTokens[oldIndex] == newTokens[newIndex]
490 ? lengths[oldIndex + 1][newIndex + 1] + 1
491 : max(lengths[oldIndex + 1][newIndex], lengths[oldIndex][newIndex + 1])
492 }
493 }
494​
495 var oldMatches = Array(repeating: false, count: oldTokens.count)
496 var newMatches = Array(repeating: false, count: newTokens.count)
497 var oldIndex = 0
498 var newIndex = 0
499 while oldIndex < oldTokens.count, newIndex < newTokens.count {
500 if oldTokens[oldIndex] == newTokens[newIndex] {
501 oldMatches[oldIndex] = true
502 newMatches[newIndex] = true
503 oldIndex += 1
504 newIndex += 1
505 } else if lengths[oldIndex + 1][newIndex] >= lengths[oldIndex][newIndex + 1] {
506 oldIndex += 1
507 } else {
508 newIndex += 1
509 }
510 }
511​
512 return (
513 makeSpans(tokens: oldTokens, matches: oldMatches),
514 makeSpans(tokens: newTokens, matches: newMatches)
515 )
516 }
517​
518 private static func tokens(in text: String) -> [String] {
519 var output: [String] = []
520 var current = ""
521 var currentClass: TokenClass?
522 for character in text {
523 let tokenClass: TokenClass = if character.isWhitespace {
524 .whitespace
525 } else if character.isLetter || character.isNumber || character == "_" || character == "$" {
526 .word
527 } else {
528 .punctuation
529 }
530 if tokenClass == .punctuation {
531 if !current.isEmpty { output.append(current) }
532 output.append(String(character))
533 current = ""
534 currentClass = nil
535 } else if currentClass == tokenClass {
536 current.append(character)
537 } else {
538 if !current.isEmpty { output.append(current) }
539 current = String(character)
540 currentClass = tokenClass
541 }
542 }
543 if !current.isEmpty { output.append(current) }
544 return output
545 }
546​
547 private static func makeSpans(
548 tokens: [String],
549 matches: [Bool]
550 ) -> [FeatureDiffTextSpan] {
551 var output: [FeatureDiffTextSpan] = []
552 for (index, token) in tokens.enumerated() {
553 let isWhitespace = token.allSatisfy(\.isWhitespace)
554 let kind: FeatureDiffTextSpanKind = matches[index] || isWhitespace
555 ? .unchanged
556 : .changed
557 if output.last?.kind == kind {
558 output[output.count - 1].text += token
559 } else {
560 output.append(FeatureDiffTextSpan(text: token, kind: kind))
561 }
562 }
563 return output
564 }
565​
566 private static func changed(_ text: String) -> [FeatureDiffTextSpan] {
567 [FeatureDiffTextSpan(text: text, kind: .changed)]
568 }
569​
570 private enum TokenClass {
571 case whitespace
572 case word
573 case punctuation
574 }
576​
577public enum FeatureReviewLineSide: String, Sendable, Equatable, Hashable, Codable {
578 case old
579 case new
581​
582public struct FeatureReviewLineSelection: Sendable, Equatable, Hashable, Codable {
583 public var side: FeatureReviewLineSide
584 public var line: Int
585​
586 public init(side: FeatureReviewLineSide, line: Int) {
587 self.side = side
588 self.line = line
589 }
591​
592public struct FeatureReviewCommentDraft: Sendable, Equatable, Hashable {
593 public var filePath: String
594 public var line: FeatureReviewLineSelection?
595 public var body: String
596​
597 public init(filePath: String, line: FeatureReviewLineSelection? = nil, body: String) {
598 self.filePath = filePath
599 self.line = line
600 self.body = body
601 }
602​
603 public var prompt: String {
604 let location = line.map { " at \($0.side.rawValue) line \($0.line)" } ?? ""
605 return """
606 Address this review comment in `\(filePath)`\(location):
607​
608 \(body.trimmingCharacters(in: .whitespacesAndNewlines))
609​
610 Inspect the surrounding code, make the smallest correct change, and report what changed.
611 """
612 }
613​
614 public func submissionText(contextRecord: ComposerContextRecord) -> String {
615 let reference = ComposerContextReferences.format(contextRecord)
616 // The record has a smaller bound than a message. Keep the full comment
617 // in ordinary text when it does not fit instead of discarding instructions.
618 return body.utf16.count > 16_000
619 ? prompt + "\n\n" + reference
620 : "Address this review comment: " + reference
621 }
622​
623 public func contextRecord(lines: [FeatureDiffLine]) -> ComposerContextRecord {
624 let range = line.map { "\($0.side.rawValue) line \($0.line)" } ?? "File"
625 let selectedIndex = line.flatMap { selected in
626 lines.firstIndex {
627 selected.side == .new ? $0.newLine == selected.line : $0.oldLine == selected.line
628 }
629 } ?? 0
630 func formatted(_ index: Int) -> String {
631 let line = lines[index]
632 let prefix = switch line.kind {
633 case .addition: "+"
634 case .deletion: "-"
635 case .context: " "
636 case .hunk: ""
637 }
638 return prefix + line.text
639 }
640 // Build outward from the selected row so a large file never clips away
641 // the code the comment is about. Indices still refer to the full diff.
642 var lower = min(selectedIndex, max(0, lines.count - 1))
643 var upper = min(lines.count, lower + 1)
644 let selectedText = lines.isEmpty ? "" : ComposerContextReferences.boundedPrefix(formatted(lower), maximumUTF16: 32_000)
645 var remaining = 32_000 - selectedText.utf16.count
646 while remaining > 0, lower > 0 || upper < lines.count {
647 var added = false
648 if lower > 0, formatted(lower - 1).utf16.count + 1 <= remaining {
649 lower -= 1
650 remaining -= formatted(lower).utf16.count + 1
651 added = true
652 }
653 if upper < lines.count, formatted(upper).utf16.count + 1 <= remaining {
654 remaining -= formatted(upper).utf16.count + 1
655 upper += 1
656 added = true
657 }
658 if !added { break }
659 }
660 return ComposerContextRecord(label: "\(filePath) \(range)", payload: .reviewComment(.init(
661 sectionId: "working-tree", sectionTitle: "Working changes", filePath: filePath,
662 startIndex: selectedIndex, endIndex: selectedIndex,
663 rangeLabel: range, text: ComposerContextReferences.boundedPrefix(body, maximumUTF16: 16_000),
664 diff: (lower..<upper).map { $0 == selectedIndex ? selectedText : formatted($0) }.joined(separator: "\n"),
665 fenceLanguage: "diff", pullRequest: nil
666 )))
667 }
669​
670public enum FeatureReviewChangeKind: String, Sendable, Codable {
671 case added
672 case modified
673 case deleted
674 case renamed
675 case binary
677​
678public struct FeatureReviewFile: Identifiable, Sendable, Equatable, Hashable, Codable {
679 public var id: String { path }
680 public var path: String
681 public var previousPath: String?
682 public var change: FeatureReviewChangeKind
683 public var additions: Int
684 public var deletions: Int
685 public var lines: [FeatureDiffLine]
686 public var sourceKind: String?
687 public var sourceBaseReference: String?
688 public var sourceHeadReference: String?
689​
690 public init(
691 path: String,
692 previousPath: String? = nil,
693 change: FeatureReviewChangeKind,
694 additions: Int,
695 deletions: Int,
696 lines: [FeatureDiffLine] = [],
697 sourceKind: String? = nil,
698 sourceBaseReference: String? = nil,
699 sourceHeadReference: String? = nil
700 ) {
701 self.path = path
702 self.previousPath = previousPath
703 self.change = change
704 self.additions = additions
705 self.deletions = deletions
706 self.lines = lines
707 self.sourceKind = sourceKind
708 self.sourceBaseReference = sourceBaseReference
709 self.sourceHeadReference = sourceHeadReference
710 }
712​
713public struct FeatureReviewFileContents: Sendable, Equatable {
714 public var oldContents: String
715 public var newContents: String
716​
717 public init(oldContents: String, newContents: String) {
718 self.oldContents = oldContents
719 self.newContents = newContents
720 }
722​
723enum FeatureFullDiffHydrator {
724 static func lines(
725 for file: FeatureReviewFile,
726 contents: FeatureReviewFileContents
727 ) -> [FeatureDiffLine] {
728 let oldLines = contentLines(contents.oldContents)
729 let newLines = contentLines(contents.newContents)
730​
731 switch file.change {
732 case .added:
733 return wholeFileLines(newLines, kind: .addition, side: .new, path: file.path)
734 case .deleted:
735 return wholeFileLines(oldLines, kind: .deletion, side: .old, path: file.path)
736 case .renamed where file.additions == 0 && file.deletions == 0:
737 return newLines.enumerated().map { index, text in
738 FeatureDiffLine(
739 id: "full-\(file.path)-\(index + 1)",
740 kind: .context,
741 oldLine: index + 1,
742 newLine: index + 1,
743 text: text
744 )
745 }
746 case .modified, .renamed, .binary:
747 break
748 }
749​
750 let patchLines = file.lines.filter { $0.kind != .hunk }
751 guard !newLines.isEmpty else { return file.lines }
752 guard !patchLines.isEmpty else {
753 return newLines.enumerated().map { index, text in
754 FeatureDiffLine(
755 id: "full-\(file.path)-\(index + 1)",
756 kind: .context,
757 oldLine: oldLines.indices.contains(index) ? index + 1 : nil,
758 newLine: index + 1,
759 text: text
760 )
761 }
762 }
763​
764 let anchors = patchLines.compactMap { line -> (new: Int, offset: Int)? in
765 guard let oldLine = line.oldLine, let newLine = line.newLine else { return nil }
766 return (newLine, oldLine - newLine)
767 }
768 // Anchors ascend by new-line number; binary search keeps hydration
769 // linear instead of scanning every anchor per emitted context line.
770 func oldLine(for newLine: Int) -> Int? {
771 guard !anchors.isEmpty else { return nil }
772 var low = 0
773 var high = anchors.count
774 while low < high {
775 let mid = (low + high) / 2
776 if anchors[mid].new <= newLine {
777 low = mid + 1
778 } else {
779 high = mid
780 }
781 }
782 let anchor = low > 0 ? anchors[low - 1] : anchors[0]
783 return newLine + anchor.offset
784 }
785​
786 var output: [FeatureDiffLine] = []
787 var nextNewLine = 1
788 var precedingAnchorOffset: Int?
789 for (index, line) in patchLines.enumerated() {
790 if let newLine = line.newLine {
791 if nextNewLine < newLine {
792 for number in nextNewLine ..< newLine where newLines.indices.contains(number - 1) {
793 output.append(
794 FeatureDiffLine(
795 id: "full-\(file.path)-\(number)",
796 kind: .context,
797 oldLine: oldLine(for: number),
798 newLine: number,
799 text: newLines[number - 1]
800 )
801 )
802 }
803 }
804 output.append(line)
805 nextNewLine = max(nextNewLine, newLine + 1)
806 if let oldLine = line.oldLine {
807 precedingAnchorOffset = oldLine - newLine
808 }
809 } else {
810 let insertionLine: Int
811 if let oldLine = line.oldLine, let precedingAnchorOffset {
812 insertionLine = oldLine - precedingAnchorOffset
813 } else {
814 insertionLine = patchLines.dropFirst(index + 1).compactMap(\.newLine).first
815 ?? (newLines.count + 1)
816 }
817 if nextNewLine < insertionLine {
818 for number in nextNewLine ..< insertionLine
819 where newLines.indices.contains(number - 1) {
820 output.append(
821 FeatureDiffLine(
822 id: "full-\(file.path)-\(number)",
823 kind: .context,
824 oldLine: oldLine(for: number),
825 newLine: number,
826 text: newLines[number - 1]
827 )
828 )
829 }
830 nextNewLine = insertionLine
831 }
832 output.append(line)
833 }
834 }
835 if nextNewLine <= newLines.count {
836 for number in nextNewLine ... newLines.count {
837 output.append(
838 FeatureDiffLine(
839 id: "full-\(file.path)-\(number)",
840 kind: .context,
841 oldLine: oldLine(for: number),
842 newLine: number,
843 text: newLines[number - 1]
844 )
845 )
846 }
847 }
848 return output
849 }
850​
851 private enum Side: Equatable { case old, new }
852​
853 private static func wholeFileLines(
854 _ lines: [String],
855 kind: FeatureDiffLineKind,
856 side: Side,
857 path: String
858 ) -> [FeatureDiffLine] {
859 lines.enumerated().map { index, text in
860 let number = index + 1
861 return FeatureDiffLine(
862 id: "full-\(path)-\(number)",
863 kind: kind,
864 oldLine: side == .old ? number : nil,
865 newLine: side == .new ? number : nil,
866 text: text
867 )
868 }
869 }
870​
871 private static func contentLines(_ contents: String) -> [String] {
872 guard !contents.isEmpty else { return [] }
873 var lines = contents.components(separatedBy: "\n")
874 if lines.last?.isEmpty == true { lines.removeLast() }
875 return lines
876 }
878​
879public struct FeatureReview: Sendable, Equatable, Codable {
880 public var title: String
881 public var baseReference: String?
882 public var files: [FeatureReviewFile]
883 public var isTruncated: Bool
884​
885 public init(
886 title: String = "Working tree",
887 baseReference: String? = nil,
888 files: [FeatureReviewFile] = [],
889 isTruncated: Bool = false
890 ) {
891 self.title = title
892 self.baseReference = baseReference
893 self.files = files
894 self.isTruncated = isTruncated
895 }
896​
897 public var additions: Int { files.reduce(0) { $0 + $1.additions } }
898 public var deletions: Int { files.reduce(0) { $0 + $1.deletions } }
900​
901public enum FeatureSourceControlFileState: String, Sendable, Codable {
902 case added
903 case modified
904 case deleted
905 case renamed
906 case untracked
907 case conflicted
909​
910public struct FeatureSourceControlFile: Identifiable, Sendable, Equatable, Hashable, Codable {
911 public var id: String { path }
912 public var path: String
913 public var state: FeatureSourceControlFileState
914 public var isStaged: Bool
915​
916 public init(path: String, state: FeatureSourceControlFileState, isStaged: Bool) {
917 self.path = path
918 self.state = state
919 self.isStaged = isStaged
920 }
922​
923public struct FeaturePullRequest: Sendable, Equatable, Hashable, Codable {
924 public var number: Int
925 public var title: String
926 public var state: String
927 public var url: URL?
928 public var updatedAt: String?
929​
930 public init(
931 number: Int,
932 title: String,
933 state: String,
934 url: URL? = nil,
935 updatedAt: String? = nil
936 ) {
937 self.number = number
938 self.title = title
939 self.state = state
940 self.url = url
941 self.updatedAt = updatedAt
942 }
944​
945public enum FeatureSourceControlAction: String, CaseIterable, Sendable, Codable {
946 case commit
947 case push
948 case pull
949 case createPullRequest
950 case commitAndPush
951 case commitPushAndCreatePullRequest
953​
954public struct FeatureSourceControlStatus: Sendable, Equatable, Codable {
955 public var isRepository: Bool
956 public var branch: String?
957 public var upstream: String?
958 public var aheadCount: Int
959 public var behindCount: Int
960 /// `false` while the remote half of a streamed status is still pending, so
961 /// ahead/behind/pull-request fields are "not yet known" rather than zero.
962 public var isRemoteKnown: Bool
963 public var files: [FeatureSourceControlFile]
964 public var pullRequest: FeaturePullRequest?
965 public var isBusy: Bool
966​
967 public init(
968 isRepository: Bool = true,
969 branch: String? = nil,
970 upstream: String? = nil,
971 aheadCount: Int = 0,
972 behindCount: Int = 0,
973 isRemoteKnown: Bool = true,
974 files: [FeatureSourceControlFile] = [],
975 pullRequest: FeaturePullRequest? = nil,
976 isBusy: Bool = false
977 ) {
978 self.isRepository = isRepository
979 self.branch = branch
980 self.upstream = upstream
981 self.aheadCount = aheadCount
982 self.behindCount = behindCount
983 self.isRemoteKnown = isRemoteKnown
984 self.files = files
985 self.pullRequest = pullRequest
986 self.isBusy = isBusy
987 }
988​
989 public var availableActions: [FeatureSourceControlAction] {
990 guard isRepository, !isBusy else { return [] }
991 var actions: [FeatureSourceControlAction] = []
992 if !files.isEmpty {
993 actions.append(.commit)
994 actions.append(.commitAndPush)
995 if isRemoteKnown, pullRequest == nil {
996 actions.append(.commitPushAndCreatePullRequest)
997 }
998 }
999 if aheadCount > 0 { actions.append(.push) }
1000 if behindCount > 0 { actions.append(.pull) }
1001 // Withheld until the remote half lands: offering it against an unknown
1002 // remote can propose a second PR for a branch that already has one.
1003 if isRemoteKnown, pullRequest == nil { actions.append(.createPullRequest) }
1004 return actions
1007​
1008public enum FeatureTerminalState: String, Sendable, Codable {
1009 case stopped
1010 case starting
1011 case running
1012 case exited
1013 case failed
1015​
1016public struct FeatureTerminalSnapshot: Sendable, Equatable, Codable {
1017 public var threadID: String
1018 public var terminalID: String
1019 public var state: FeatureTerminalState
1020 public var title: String
1021 public var workingDirectory: String?
1022 public var buffer: String
1023 public var exitCode: Int?
1024 public var error: String?
1025 public var hasRunningSubprocess: Bool
1026 public var updatedAt: String?
1027 public var lifecycleVersion: Int
1028​
1029 public init(
1030 threadID: String,
1031 terminalID: String = "default",
1032 state: FeatureTerminalState = .stopped,
1033 title: String = "Terminal",
1034 workingDirectory: String? = nil,
1035 buffer: String = "",
1036 exitCode: Int? = nil,
1037 error: String? = nil,
1038 hasRunningSubprocess: Bool = false,
1039 updatedAt: String? = nil,
1040 lifecycleVersion: Int = 0
1041 ) {
1042 self.threadID = threadID
1043 self.terminalID = terminalID
1044 self.state = state
1045 self.title = title
1046 self.workingDirectory = workingDirectory
1047 self.buffer = buffer
1048 self.exitCode = exitCode
1049 self.error = error
1050 self.hasRunningSubprocess = hasRunningSubprocess
1051 self.updatedAt = updatedAt
1052 self.lifecycleVersion = lifecycleVersion
1054​
1055 private enum CodingKeys: String, CodingKey {
1056 case threadID, terminalID, state, title, workingDirectory, buffer
1057 case exitCode, error, hasRunningSubprocess, updatedAt, lifecycleVersion
1059​
1060 public init(from decoder: any Decoder) throws {
1061 let container = try decoder.container(keyedBy: CodingKeys.self)
1062 threadID = try container.decode(String.self, forKey: .threadID)
1063 terminalID = try container.decodeIfPresent(String.self, forKey: .terminalID) ?? "default"
1064 state = try container.decodeIfPresent(FeatureTerminalState.self, forKey: .state) ?? .stopped
1065 title = try container.decodeIfPresent(String.self, forKey: .title) ?? "Terminal"
1066 workingDirectory = try container.decodeIfPresent(String.self, forKey: .workingDirectory)
1067 buffer = try container.decodeIfPresent(String.self, forKey: .buffer) ?? ""
1068 exitCode = try container.decodeIfPresent(Int.self, forKey: .exitCode)
1069 error = try container.decodeIfPresent(String.self, forKey: .error)
1070 hasRunningSubprocess = try container.decodeIfPresent(Bool.self, forKey: .hasRunningSubprocess) ?? false
1071 updatedAt = try container.decodeIfPresent(String.self, forKey: .updatedAt)
1072 lifecycleVersion = try container.decodeIfPresent(Int.self, forKey: .lifecycleVersion) ?? 0