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

FeatureToolModels.swift

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