From 52d94ae0a5ded1bd1178408274db070268fe51d5 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 1 Aug 2026 07:53:31 -0700 Subject: [PATCH] feat(swift-ios): add rich workspace previews --- .../swift-ios/App/NativeWorkspaceMapper.swift | 43 +- .../Features/Files/FeatureFilesView.swift | 252 +++++++++- .../Features/Review/FeatureReviewView.swift | 226 ++++++++- .../Features/Shared/FeatureToolModels.swift | 453 +++++++++++++++++- .../FeatureTests/FeatureToolStateTests.swift | 110 +++++ 5 files changed, 1058 insertions(+), 26 deletions(-) diff --git a/apps/swift-ios/App/NativeWorkspaceMapper.swift b/apps/swift-ios/App/NativeWorkspaceMapper.swift index 900982a4fa..72bac5f096 100644 --- a/apps/swift-ios/App/NativeWorkspaceMapper.swift +++ b/apps/swift-ios/App/NativeWorkspaceMapper.swift @@ -43,11 +43,15 @@ enum NativeWorkspaceMapper { case "json": "json" case "md", "mdx": "markdown" case "css", "scss": "css" - case "html": "html" + case "html", "htm": "html" + case "xml", "svg": "xml" case "sh", "zsh", "bash": "shell" case "py": "python" case "rs": "rust" case "go": "go" + case "rb": "ruby" + case "sql": "sql" + case "toml": "toml" case "yml", "yaml": "yaml" default: nil } @@ -56,6 +60,7 @@ enum NativeWorkspaceMapper { static func review(_ preview: ReviewDiffPreview) -> FeatureReview { FeatureReview( title: "Working tree", + baseReference: preview.sources.compactMap(\.baseRef).first, files: preview.sources.flatMap(parseDiff), isTruncated: preview.sources.contains(where: \.truncated) ) @@ -183,7 +188,7 @@ enum NativeWorkspaceMapper { change: change, additions: additions, deletions: deletions, - lines: lines + lines: annotateChangedSpans(lines) ) ) } @@ -295,13 +300,45 @@ enum NativeWorkspaceMapper { change: .modified, additions: additions, deletions: deletions, - lines: lines + lines: annotateChangedSpans(lines) ), ] } return files } + /// Git presents replacements as adjacent deletion/addition blocks. Pairing those + /// lines here keeps the view dumb and makes word-level highlighting stable on scroll. + private static func annotateChangedSpans( + _ source: [FeatureDiffLine] + ) -> [FeatureDiffLine] { + var lines = source + var index = 0 + while index < lines.count { + guard lines[index].kind == .deletion || lines[index].kind == .addition else { + index += 1 + continue + } + let start = index + while index < lines.count, + lines[index].kind == .deletion || lines[index].kind == .addition { + index += 1 + } + let changedIndices = start ..< index + let deletions = changedIndices.filter { lines[$0].kind == .deletion } + let additions = changedIndices.filter { lines[$0].kind == .addition } + for (deletionIndex, additionIndex) in zip(deletions, additions) { + let spans = FeatureDiffWordHighlighter.spans( + old: lines[deletionIndex].text, + new: lines[additionIndex].text + ) + lines[deletionIndex].spans = spans.old + lines[additionIndex].spans = spans.new + } + } + return lines + } + private static func stripDiffPrefix(_ path: String) -> String { if path.hasPrefix("a/") || path.hasPrefix("b/") { return String(path.dropFirst(2)) diff --git a/apps/swift-ios/Features/Files/FeatureFilesView.swift b/apps/swift-ios/Features/Files/FeatureFilesView.swift index 43b56f0b4b..4ac6dab297 100644 --- a/apps/swift-ios/Features/Files/FeatureFilesView.swift +++ b/apps/swift-ios/Features/Files/FeatureFilesView.swift @@ -1,4 +1,6 @@ +import ImageIO import SwiftUI +import UIKit public struct FeatureFilesView: View { let client: any FeatureClient @@ -137,7 +139,12 @@ private struct FeatureFileRow: View { case .directory: "folder.fill" case .symbolicLink: "link" case .file: - entry.name.hasSuffix(".swift") ? "swift" : "doc.text" + switch FeatureFilePreviewKind.infer(path: entry.path) { + case .image: "photo" + case .markdown: "doc.richtext" + case .source: entry.name.hasSuffix(".swift") ? "swift" : "chevron.left.forwardslash.chevron.right" + case .plainText: "doc.text" + } } } } @@ -148,14 +155,24 @@ private struct FeatureFilePreviewView: View { let entry: FeatureFileEntry @State private var content: FeatureFileContent? + @State private var sourceLines: [FeatureSourceLine] = [] + @State private var image: UIImage? + @State private var assetURL: URL? @State private var errorMessage: String? @State private var isLoading = true + private var previewKind: FeatureFilePreviewKind { + FeatureFilePreviewKind.infer(path: entry.path, language: content?.language) + } + var body: some View { Group { - if isLoading, content == nil { + if isLoading, content == nil, image == nil { ProgressView("Loading file…") .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if let image { + FeatureZoomableImageView(image: image) + .background(Color.black) } else if let content { VStack(spacing: 0) { if content.isTruncated { @@ -167,12 +184,26 @@ private struct FeatureFilePreviewView: View { .padding(.vertical, 8) .background(Color.orange.opacity(0.09)) } - FeatureSourceTextView(text: content.text) + switch previewKind { + case .markdown: + ScrollView { + MarkdownMessageView(content.text) + .frame(maxWidth: T3Metrics.readingWidth, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 18) + .padding(.vertical, 16) + } + .scrollDismissesKeyboard(.interactively) + case .source, .plainText: + FeatureSourceTextView(lines: sourceLines) + case .image: + EmptyView() + } } } else { ContentUnavailableView( - "File unavailable", - systemImage: "doc.badge.ellipsis", + previewKind == .image ? "Image unavailable" : "File unavailable", + systemImage: previewKind == .image ? "photo.badge.exclamationmark" : "doc.badge.ellipsis", description: Text(errorMessage ?? "The file could not be read.") ) } @@ -181,7 +212,14 @@ private struct FeatureFilePreviewView: View { .navigationTitle(entry.name) .navigationBarTitleDisplayMode(.inline) .toolbar { - if let content { + if let assetURL { + ToolbarItem(placement: .topBarTrailing) { + ShareLink(item: assetURL) { + Image(systemName: "square.and.arrow.up") + } + .accessibilityLabel("Share image") + } + } else if let content { ToolbarItem(placement: .topBarTrailing) { ShareLink(item: content.text) { Image(systemName: "square.and.arrow.up") @@ -197,33 +235,86 @@ private struct FeatureFilePreviewView: View { isLoading = true defer { isLoading = false } do { - content = try await client.readFile(threadID: threadID, path: entry.path) + if previewKind == .image { + guard let resolver = client as? any FeatureWorkspaceAssetResolving else { + throw FeatureCapabilityUnavailable("Signed image previews") + } + let resolvedURL = try await resolver.workspaceAssetURL( + threadID: threadID, + path: entry.path + ) + let (data, response) = try await URLSession.shared.data(from: resolvedURL) + if let response = response as? HTTPURLResponse, + !(200 ... 299).contains(response.statusCode) { + throw FeatureImagePreviewError.httpStatus(response.statusCode) + } + guard data.count <= 64 * 1_024 * 1_024 else { + throw FeatureImagePreviewError.tooLarge + } + guard let decoded = await Task.detached(priority: .userInitiated, operation: { + FeatureImageDecoder.downsample(data, maxPixelSize: 4_096) + }).value else { + throw FeatureImagePreviewError.invalidImage + } + guard !Task.isCancelled else { return } + assetURL = resolvedURL + image = decoded + content = nil + sourceLines = [] + } else { + let loaded = try await client.readFile(threadID: threadID, path: entry.path) + let loadedKind = FeatureFilePreviewKind.infer( + path: entry.path, + language: loaded.language + ) + let lines: [FeatureSourceLine] + switch loadedKind { + case .source: + lines = await Task.detached(priority: .userInitiated) { + FeatureSourceHighlighter.lines( + text: loaded.text, + language: loaded.language + ) + }.value + case .plainText: + lines = await Task.detached(priority: .userInitiated) { + FeatureSourceHighlighter.lines(text: loaded.text, language: "plain") + }.value + case .markdown: + _ = await MarkdownRenderCache.shared.document( + for: MarkdownContentRevision(loaded.text) + ) + lines = [] + case .image: + lines = [] + } + guard !Task.isCancelled else { return } + content = loaded + sourceLines = lines + image = nil + assetURL = nil + } errorMessage = nil } catch { + guard !Task.isCancelled else { return } errorMessage = error.localizedDescription } } } private struct FeatureSourceTextView: View { - let text: String - - private var lines: [Substring] { - text.split(separator: "\n", omittingEmptySubsequences: false) - } + let lines: [FeatureSourceLine] var body: some View { ScrollView([.horizontal, .vertical]) { LazyVStack(alignment: .leading, spacing: 0) { - ForEach(Array(lines.enumerated()), id: \.offset) { index, line in + ForEach(lines) { line in HStack(alignment: .top, spacing: 10) { - Text("\(index + 1)") + Text("\(line.number)") .foregroundStyle(.tertiary) .frame(width: 44, alignment: .trailing) .accessibilityHidden(true) - Text(String(line).isEmpty ? " " : String(line)) - .foregroundStyle(.primary) - .textSelection(.enabled) + FeatureHighlightedSourceLine(line: line) } .font(T3Typography.code) .frame(minHeight: 22) @@ -231,8 +322,135 @@ private struct FeatureSourceTextView: View { } .padding(.vertical, 10) .padding(.trailing, 14) + .textSelection(.enabled) } .background(Color.black) .accessibilityLabel("Source file") } } + +private struct FeatureHighlightedSourceLine: View { + let line: FeatureSourceLine + + var body: some View { + renderedText + .fixedSize(horizontal: true, vertical: false) + } + + private var renderedText: Text { + guard !line.spans.isEmpty else { return Text(" ") } + return line.spans.reduce(Text("")) { output, span in + output + Text(verbatim: span.text).foregroundColor(color(for: span.kind)) + } + } + + private func color(for kind: FeatureSourceTokenKind) -> Color { + switch kind { + case .plain: T3Colors.textPrimary.opacity(0.92) + case .comment: T3Colors.textTertiary + case .keyword: Color(red: 0.78, green: 0.56, blue: 1) + case .literal: Color(red: 0.55, green: 0.78, blue: 1) + case .number: Color(red: 0.92, green: 0.67, blue: 0.42) + case .property: Color(red: 0.42, green: 0.82, blue: 0.76) + } + } +} + +private struct FeatureZoomableImageView: UIViewRepresentable { + let image: UIImage + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + func makeUIView(context: Context) -> UIScrollView { + let scrollView = UIScrollView() + scrollView.backgroundColor = .black + scrollView.delegate = context.coordinator + scrollView.minimumZoomScale = 1 + scrollView.maximumZoomScale = 6 + scrollView.bouncesZoom = true + scrollView.decelerationRate = .fast + + let imageView = context.coordinator.imageView + imageView.translatesAutoresizingMaskIntoConstraints = false + imageView.contentMode = .scaleAspectFit + imageView.isAccessibilityElement = true + imageView.accessibilityLabel = "Image preview" + scrollView.addSubview(imageView) + NSLayoutConstraint.activate([ + imageView.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor), + imageView.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor), + imageView.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor), + imageView.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor), + imageView.widthAnchor.constraint(equalTo: scrollView.frameLayoutGuide.widthAnchor), + imageView.heightAnchor.constraint(equalTo: scrollView.frameLayoutGuide.heightAnchor), + ]) + + let doubleTap = UITapGestureRecognizer( + target: context.coordinator, + action: #selector(Coordinator.toggleZoom(_:)) + ) + doubleTap.numberOfTapsRequired = 2 + scrollView.addGestureRecognizer(doubleTap) + context.coordinator.scrollView = scrollView + return scrollView + } + + func updateUIView(_ scrollView: UIScrollView, context: Context) { + if context.coordinator.imageView.image !== image { + context.coordinator.imageView.image = image + scrollView.setZoomScale(scrollView.minimumZoomScale, animated: false) + } + } + + final class Coordinator: NSObject, UIScrollViewDelegate { + let imageView = UIImageView() + weak var scrollView: UIScrollView? + + func viewForZooming(in scrollView: UIScrollView) -> UIView? { + imageView + } + + @objc func toggleZoom(_ recognizer: UITapGestureRecognizer) { + guard let scrollView else { return } + let scale = scrollView.zoomScale > scrollView.minimumZoomScale + ? scrollView.minimumZoomScale + : min(2.5, scrollView.maximumZoomScale) + scrollView.setZoomScale(scale, animated: true) + } + } +} + +private enum FeatureImageDecoder { + static func downsample(_ data: Data, maxPixelSize: CGFloat) -> UIImage? { + let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { + return nil + } + let options = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: maxPixelSize, + ] as CFDictionary + guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options) else { + return nil + } + return UIImage(cgImage: image) + } +} + +private enum FeatureImagePreviewError: LocalizedError { + case httpStatus(Int) + case invalidImage + case tooLarge + + var errorDescription: String? { + switch self { + case let .httpStatus(status): "The image server returned HTTP \(status)." + case .invalidImage: "The file is not a supported image." + case .tooLarge: "The image is larger than the 64 MB preview limit." + } + } +} diff --git a/apps/swift-ios/Features/Review/FeatureReviewView.swift b/apps/swift-ios/Features/Review/FeatureReviewView.swift index 1ec75073c9..68f97ca449 100644 --- a/apps/swift-ios/Features/Review/FeatureReviewView.swift +++ b/apps/swift-ios/Features/Review/FeatureReviewView.swift @@ -1,4 +1,5 @@ import SwiftUI +import UIKit public struct FeatureReviewView: View { let client: any FeatureClient @@ -80,7 +81,7 @@ public struct FeatureReviewView: View { } ForEach(review.files) { file in NavigationLink { - FeatureDiffView(file: file) + FeatureDiffView(client: client, threadID: threadID, file: file) } label: { FeatureReviewFileRow(file: file) } @@ -180,8 +181,17 @@ struct FeatureDiffStatsLabel: View { } private struct FeatureDiffView: View { + let client: any FeatureClient + let threadID: String let file: FeatureReviewFile + @State private var selectedLine: FeatureReviewLineSelection? + @State private var isCommenting = false + @State private var comment = "" + @State private var isSending = false + @State private var commentError: String? + @FocusState private var isCommentFocused: Bool + var body: some View { Group { if file.lines.isEmpty { @@ -194,7 +204,14 @@ private struct FeatureDiffView: View { ScrollView([.horizontal, .vertical]) { LazyVStack(alignment: .leading, spacing: 0) { ForEach(file.lines) { line in - FeatureDiffLineRow(line: line) + FeatureDiffLineRow( + line: line, + isSelected: selection(for: line) == selectedLine + ) { + guard let selection = selection(for: line) else { return } + selectedLine = selection + openCommentComposer() + } } } .padding(.vertical, 8) @@ -204,11 +221,175 @@ private struct FeatureDiffView: View { .background(Color.black) .navigationTitle(file.path.split(separator: "/").last.map(String.init) ?? file.path) .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button { + selectedLine = nil + openCommentComposer() + } label: { + Image(systemName: "text.bubble") + } + .accessibilityLabel("Add file review comment") + } + } + .safeAreaInset(edge: .bottom, spacing: 0) { + if isCommenting { + commentComposer + } + } + } + + private var commentComposer: some View { + VStack(alignment: .leading, spacing: 10) { + HStack(spacing: 8) { + VStack(alignment: .leading, spacing: 2) { + Text("REVIEW COMMENT") + .font(T3Typography.eyebrow) + .foregroundStyle(T3Colors.textTertiary) + Text(commentLocation) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.textSecondary) + .lineLimit(1) + } + Spacer(minLength: 8) + Button { + isCommenting = false + isCommentFocused = false + commentError = nil + } label: { + Image(systemName: "xmark") + .frame(width: T3Metrics.minimumTapTarget, height: T3Metrics.minimumTapTarget) + } + .buttonStyle(.plain) + .foregroundStyle(T3Colors.textSecondary) + .accessibilityLabel("Close review comment") + } + + TextField( + "What should change?", + text: $comment, + axis: .vertical + ) + .font(T3Typography.composer) + .lineLimit(2 ... 6) + .focused($isCommentFocused) + .padding(.horizontal, 12) + .padding(.vertical, 10) + .background(T3Colors.input) + .clipShape(RoundedRectangle(cornerRadius: 10)) + .overlay { + RoundedRectangle(cornerRadius: 10) + .stroke(T3Colors.border, lineWidth: 1) + } + + if let commentError { + Text(commentError) + .font(T3Typography.supporting) + .foregroundStyle(T3Colors.danger) + } + + HStack(spacing: 10) { + Button { + UIPasteboard.general.string = reviewDraft.prompt + } label: { + Label("Copy prompt", systemImage: "doc.on.doc") + .frame(maxWidth: .infinity, minHeight: 42) + } + .buttonStyle(.plain) + .foregroundStyle(T3Colors.textSecondary) + .background(T3Colors.surfaceRaised) + .clipShape(RoundedRectangle(cornerRadius: 9)) + .disabled(trimmedComment.isEmpty) + + Button { + sendComment() + } label: { + HStack(spacing: 7) { + if isSending { + ProgressView() + .controlSize(.small) + } else { + Image(systemName: "arrow.up") + } + Text("Send to agent") + } + .frame(maxWidth: .infinity, minHeight: 42) + } + .buttonStyle(.plain) + .foregroundStyle(.white) + .background(T3Colors.accent) + .clipShape(RoundedRectangle(cornerRadius: 9)) + .disabled(trimmedComment.isEmpty || isSending) + } + .font(T3Typography.control) + } + .padding(.horizontal, 14) + .padding(.top, 10) + .padding(.bottom, 8) + .background(T3Colors.surface) + .overlay(alignment: .top) { + Rectangle() + .fill(T3Colors.separator) + .frame(height: 1) + } + } + + private var trimmedComment: String { + comment.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var reviewDraft: FeatureReviewCommentDraft { + FeatureReviewCommentDraft(filePath: file.path, line: selectedLine, body: comment) + } + + private var commentLocation: String { + guard let selectedLine else { return file.path } + return "\(file.path) · \(selectedLine.side.rawValue) line \(selectedLine.line)" + } + + private func selection(for line: FeatureDiffLine) -> FeatureReviewLineSelection? { + if let newLine = line.newLine { + return FeatureReviewLineSelection(side: .new, line: newLine) + } + if let oldLine = line.oldLine { + return FeatureReviewLineSelection(side: .old, line: oldLine) + } + return nil + } + + private func openCommentComposer() { + isCommenting = true + commentError = nil + Task { @MainActor in + await Task.yield() + isCommentFocused = true + } + } + + private func sendComment() { + guard !trimmedComment.isEmpty, !isSending else { return } + let prompt = reviewDraft.prompt + isSending = true + commentError = nil + Task { + do { + try await client.sendMessage(threadID: threadID, text: prompt, selection: nil) + comment = "" + selectedLine = nil + isCommenting = false + isCommentFocused = false + } catch { + commentError = error.localizedDescription + } + isSending = false + } } } private struct FeatureDiffLineRow: View { let line: FeatureDiffLine + let isSelected: Bool + let select: () -> Void var body: some View { HStack(alignment: .top, spacing: 0) { @@ -222,8 +403,7 @@ private struct FeatureDiffLineRow: View { Text(prefix) .foregroundStyle(prefixColor) .frame(width: 18) - Text(line.text.isEmpty ? " " : line.text) - .foregroundStyle(.primary) + diffText .textSelection(.enabled) .padding(.trailing, 12) } @@ -231,7 +411,17 @@ private struct FeatureDiffLineRow: View { .font(T3Typography.code) .frame(minHeight: line.kind == .hunk ? 30 : 22, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading) - .background(background) + .background(isSelected ? T3Colors.accent.opacity(0.14) : background) + .overlay(alignment: .leading) { + if isSelected { + Rectangle() + .fill(T3Colors.accent) + .frame(width: 2) + } + } + .contentShape(Rectangle()) + .onTapGesture(perform: select) + .accessibilityAction(named: "Add review comment", select) } private func lineNumber(_ value: Int?) -> some View { @@ -258,6 +448,32 @@ private struct FeatureDiffLineRow: View { } } + @ViewBuilder + private var diffText: some View { + if let spans = line.spans, !spans.isEmpty { + HStack(spacing: 0) { + ForEach(spans.indices, id: \.self) { index in + let span = spans[index] + Text(verbatim: span.text.isEmpty ? " " : span.text) + .foregroundStyle(.primary) + .fontWeight(span.kind == .changed ? .semibold : .regular) + .background(span.kind == .changed ? changedSpanBackground : Color.clear) + } + } + } else { + Text(line.text.isEmpty ? " " : line.text) + .foregroundStyle(.primary) + } + } + + private var changedSpanBackground: Color { + switch line.kind { + case .addition: Color.green.opacity(0.28) + case .deletion: Color.red.opacity(0.28) + case .context, .hunk: Color.clear + } + } + private var background: Color { switch line.kind { case .addition: Color.green.opacity(0.11) diff --git a/apps/swift-ios/Features/Shared/FeatureToolModels.swift b/apps/swift-ios/Features/Shared/FeatureToolModels.swift index d014f4627c..c29f641754 100644 --- a/apps/swift-ios/Features/Shared/FeatureToolModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureToolModels.swift @@ -12,6 +12,13 @@ public struct FeatureCapabilityUnavailable: LocalizedError, Sendable, Equatable } } +/// Optional rich-file capability. The base file contract is deliberately text-only, +/// while native clients can resolve the existing signed workspace asset route for images. +@MainActor +public protocol FeatureWorkspaceAssetResolving: AnyObject { + func workspaceAssetURL(threadID: String, path: String) async throws -> URL +} + public enum FeatureFileKind: String, Sendable, Codable { case file case directory @@ -80,6 +87,284 @@ public struct FeatureFileContent: Sendable, Equatable, Codable { } } +public enum FeatureFilePreviewKind: Sendable, Equatable { + case image + case markdown + case source + case plainText + + public static func infer(path: String, language: String? = nil) -> Self { + let fileExtension = URL(fileURLWithPath: path).pathExtension.lowercased() + if imageExtensions.contains(fileExtension) { return .image } + if language?.lowercased() == "markdown" || ["md", "mdx"].contains(fileExtension) { + return .markdown + } + if language != nil || sourceExtensions.contains(fileExtension) { return .source } + return .plainText + } + + private static let imageExtensions: Set = [ + "avif", "gif", "ico", "jpeg", "jpg", "png", "webp", + ] + + private static let sourceExtensions: Set = [ + "c", "cc", "cpp", "cs", "css", "go", "h", "hpp", "html", "java", "js", "jsx", + "json", "kt", "kts", "m", "mm", "php", "py", "rb", "rs", "scss", "sh", "sql", + "swift", "toml", "ts", "tsx", "vue", "xml", "yaml", "yml", "zsh", + ] +} + +public enum FeatureSourceTokenKind: String, Sendable, Equatable, Hashable, Codable { + case plain + case comment + case keyword + case literal + case number + case property +} + +public struct FeatureSourceSpan: Sendable, Equatable, Hashable, Codable { + public var text: String + public var kind: FeatureSourceTokenKind + + public init(text: String, kind: FeatureSourceTokenKind) { + self.text = text + self.kind = kind + } +} + +public struct FeatureSourceLine: Identifiable, Sendable, Equatable, Hashable, Codable { + public let id: Int + public var spans: [FeatureSourceSpan] + + public init(id: Int, spans: [FeatureSourceSpan]) { + self.id = id + self.spans = spans + } + + public var number: Int { id + 1 } + public var text: String { spans.map(\.text).joined() } +} + +/// A bounded, language-aware lexer for file previews. It runs once when a file loads; +/// SwiftUI receives immutable line plans and performs no regex or token work while scrolling. +public enum FeatureSourceHighlighter { + public static func lines(text: String, language: String?) -> [FeatureSourceLine] { + let sourceLines = text.split(separator: "\n", omittingEmptySubsequences: false) + let highlightsContent = text.utf8.count <= 512 * 1_024 + var isInsideBlockComment = false + return sourceLines.enumerated().map { index, line in + guard highlightsContent, line.utf8.count <= 32 * 1_024 else { + return FeatureSourceLine( + id: index, + spans: line.isEmpty + ? [] + : [FeatureSourceSpan(text: String(line), kind: .plain)] + ) + } + return FeatureSourceLine( + id: index, + spans: spans( + in: String(line), + language: language?.lowercased(), + isInsideBlockComment: &isInsideBlockComment + ) + ) + } + } + + private static func spans( + in line: String, + language: String?, + isInsideBlockComment: inout Bool + ) -> [FeatureSourceSpan] { + let characters = Array(line) + var output: [FeatureSourceSpan] = [] + var index = 0 + let lineComment = lineCommentMarker(for: language) + let supportsBlockComments = blockCommentLanguages.contains(language ?? "") + let keywords = keywords(for: language) + + func hasPrefix(_ prefix: [Character], at offset: Int) -> Bool { + guard offset + prefix.count <= characters.count else { return false } + return characters[offset ..< offset + prefix.count].elementsEqual(prefix) + } + + func append(_ range: Range, kind: FeatureSourceTokenKind) { + guard !range.isEmpty else { return } + let text = String(characters[range]) + if output.last?.kind == kind { + output[output.count - 1].text += text + } else { + output.append(FeatureSourceSpan(text: text, kind: kind)) + } + } + + while index < characters.count { + if isInsideBlockComment { + let start = index + while index < characters.count, !hasPrefix(["*", "/"], at: index) { + index += 1 + } + if index < characters.count { + index += 2 + isInsideBlockComment = false + } + append(start ..< index, kind: .comment) + continue + } + + if let lineComment, hasPrefix(Array(lineComment), at: index) { + append(index ..< characters.count, kind: .comment) + break + } + + if supportsBlockComments, hasPrefix(["/", "*"], at: index) { + let start = index + index += 2 + while index < characters.count, !hasPrefix(["*", "/"], at: index) { + index += 1 + } + if index < characters.count { + index += 2 + } else { + isInsideBlockComment = true + } + append(start ..< index, kind: .comment) + continue + } + + if ["\"", "'", "`"].contains(characters[index]) { + let start = index + let delimiter = characters[index] + index += 1 + var isEscaped = false + while index < characters.count { + let character = characters[index] + index += 1 + if character == delimiter, !isEscaped { break } + isEscaped = character == "\\" && !isEscaped + if character != "\\" { isEscaped = false } + } + var next = index + while next < characters.count, characters[next].isWhitespace { next += 1 } + let kind: FeatureSourceTokenKind = next < characters.count + && characters[next] == ":" + && propertyLanguages.contains(language ?? "") + ? .property + : .literal + append(start ..< index, kind: kind) + continue + } + + if characters[index].isNumber { + let start = index + index += 1 + while index < characters.count, + characters[index].isNumber + || [".", "_", "x", "X", "a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"].contains(characters[index]) { + index += 1 + } + append(start ..< index, kind: .number) + continue + } + + if isIdentifierStart(characters[index]) { + let start = index + index += 1 + while index < characters.count, isIdentifierBody(characters[index]) { + index += 1 + } + let token = String(characters[start ..< index]) + var next = index + while next < characters.count, characters[next].isWhitespace { next += 1 } + let kind: FeatureSourceTokenKind + if ["true", "false", "null", "nil", "undefined"].contains(token) { + kind = .literal + } else if keywords.contains(token) { + kind = .keyword + } else if next < characters.count, + characters[next] == ":", + propertyLanguages.contains(language ?? "") { + kind = .property + } else { + kind = .plain + } + append(start ..< index, kind: kind) + continue + } + + append(index ..< index + 1, kind: .plain) + index += 1 + } + return output + } + + private static func lineCommentMarker(for language: String?) -> String? { + switch language { + case "plain": nil + case "python", "shell", "ruby", "yaml", "toml": "#" + case "sql": "--" + case "html", "xml", "css", "scss": nil + default: "//" + } + } + + private static func keywords(for language: String?) -> Set { + switch language { + case "plain": [] + case "swift": swiftKeywords + case "typescript", "javascript": javascriptKeywords + case "python": pythonKeywords + case "rust": rustKeywords + case "go": goKeywords + case "shell": shellKeywords + default: commonKeywords + } + } + + private static func isIdentifierStart(_ character: Character) -> Bool { + character == "_" || character == "$" || character.isLetter + } + + private static func isIdentifierBody(_ character: Character) -> Bool { + isIdentifierStart(character) || character.isNumber || character == "-" + } + + private static let propertyLanguages: Set = ["json", "typescript", "javascript", "yaml"] + private static let blockCommentLanguages: Set = [ + "css", "go", "java", "javascript", "rust", "scss", "swift", "typescript", + ] + private static let commonKeywords: Set = [ + "class", "const", "else", "enum", "false", "for", "func", "function", "if", "import", + "let", "nil", "null", "private", "public", "return", "struct", "true", "var", "while", + ] + private static let swiftKeywords = commonKeywords.union([ + "actor", "any", "associatedtype", "async", "await", "case", "defer", "extension", "guard", + "in", "init", "internal", "nonisolated", "opaque", "protocol", "self", "some", "switch", + "throws", "try", "typealias", "where", + ]) + private static let javascriptKeywords = commonKeywords.union([ + "as", "break", "case", "catch", "continue", "default", "export", "extends", "from", "interface", + "new", "of", "static", "throw", "type", "typeof", "undefined", + ]) + private static let pythonKeywords = commonKeywords.union([ + "and", "as", "assert", "async", "await", "def", "elif", "except", "finally", "from", "in", + "is", "lambda", "not", "or", "pass", "raise", "with", "yield", + ]) + private static let rustKeywords = commonKeywords.union([ + "as", "async", "await", "crate", "dyn", "impl", "in", "loop", "match", "mod", "move", "mut", + "ref", "self", "trait", "type", "unsafe", "use", "where", + ]) + private static let goKeywords = commonKeywords.union([ + "break", "case", "chan", "continue", "defer", "fallthrough", "go", "goto", "interface", "map", + "package", "range", "select", "type", + ]) + private static let shellKeywords = commonKeywords.union([ + "case", "do", "done", "elif", "esac", "export", "fi", "in", "then", + ]) +} + public enum FeatureDiffLineKind: String, Sendable, Codable { case context case addition @@ -93,19 +378,185 @@ public struct FeatureDiffLine: Identifiable, Sendable, Equatable, Hashable, Coda public var oldLine: Int? public var newLine: Int? public var text: String + public var spans: [FeatureDiffTextSpan]? public init( id: String, kind: FeatureDiffLineKind, oldLine: Int? = nil, newLine: Int? = nil, - text: String + text: String, + spans: [FeatureDiffTextSpan]? = nil ) { self.id = id self.kind = kind self.oldLine = oldLine self.newLine = newLine self.text = text + self.spans = spans + } +} + +public enum FeatureDiffTextSpanKind: String, Sendable, Equatable, Hashable, Codable { + case unchanged + case changed +} + +public struct FeatureDiffTextSpan: Sendable, Equatable, Hashable, Codable { + public var text: String + public var kind: FeatureDiffTextSpanKind + + public init(text: String, kind: FeatureDiffTextSpanKind) { + self.text = text + self.kind = kind + } +} + +public enum FeatureDiffWordHighlighter { + public static func spans( + old: String, + new: String + ) -> (old: [FeatureDiffTextSpan], new: [FeatureDiffTextSpan]) { + guard old != new else { + let unchanged = [FeatureDiffTextSpan(text: old, kind: .unchanged)] + return (unchanged, unchanged) + } + let oldTokens = tokens(in: old) + let newTokens = tokens(in: new) + guard !oldTokens.isEmpty, !newTokens.isEmpty, + oldTokens.count * newTokens.count <= 20_000 else { + return (changed(old), changed(new)) + } + + var lengths = Array( + repeating: Array(repeating: 0, count: newTokens.count + 1), + count: oldTokens.count + 1 + ) + for oldIndex in oldTokens.indices.reversed() { + for newIndex in newTokens.indices.reversed() { + lengths[oldIndex][newIndex] = oldTokens[oldIndex] == newTokens[newIndex] + ? lengths[oldIndex + 1][newIndex + 1] + 1 + : max(lengths[oldIndex + 1][newIndex], lengths[oldIndex][newIndex + 1]) + } + } + + var oldMatches = Array(repeating: false, count: oldTokens.count) + var newMatches = Array(repeating: false, count: newTokens.count) + var oldIndex = 0 + var newIndex = 0 + while oldIndex < oldTokens.count, newIndex < newTokens.count { + if oldTokens[oldIndex] == newTokens[newIndex] { + oldMatches[oldIndex] = true + newMatches[newIndex] = true + oldIndex += 1 + newIndex += 1 + } else if lengths[oldIndex + 1][newIndex] >= lengths[oldIndex][newIndex + 1] { + oldIndex += 1 + } else { + newIndex += 1 + } + } + + return ( + makeSpans(tokens: oldTokens, matches: oldMatches), + makeSpans(tokens: newTokens, matches: newMatches) + ) + } + + private static func tokens(in text: String) -> [String] { + var output: [String] = [] + var current = "" + var currentClass: TokenClass? + for character in text { + let tokenClass: TokenClass = if character.isWhitespace { + .whitespace + } else if character.isLetter || character.isNumber || character == "_" || character == "$" { + .word + } else { + .punctuation + } + if tokenClass == .punctuation { + if !current.isEmpty { output.append(current) } + output.append(String(character)) + current = "" + currentClass = nil + } else if currentClass == tokenClass { + current.append(character) + } else { + if !current.isEmpty { output.append(current) } + current = String(character) + currentClass = tokenClass + } + } + if !current.isEmpty { output.append(current) } + return output + } + + private static func makeSpans( + tokens: [String], + matches: [Bool] + ) -> [FeatureDiffTextSpan] { + var output: [FeatureDiffTextSpan] = [] + for (index, token) in tokens.enumerated() { + let isWhitespace = token.allSatisfy(\.isWhitespace) + let kind: FeatureDiffTextSpanKind = matches[index] || isWhitespace + ? .unchanged + : .changed + if output.last?.kind == kind { + output[output.count - 1].text += token + } else { + output.append(FeatureDiffTextSpan(text: token, kind: kind)) + } + } + return output + } + + private static func changed(_ text: String) -> [FeatureDiffTextSpan] { + [FeatureDiffTextSpan(text: text, kind: .changed)] + } + + private enum TokenClass { + case whitespace + case word + case punctuation + } +} + +public enum FeatureReviewLineSide: String, Sendable, Equatable, Hashable, Codable { + case old + case new +} + +public struct FeatureReviewLineSelection: Sendable, Equatable, Hashable, Codable { + public var side: FeatureReviewLineSide + public var line: Int + + public init(side: FeatureReviewLineSide, line: Int) { + self.side = side + self.line = line + } +} + +public struct FeatureReviewCommentDraft: Sendable, Equatable, Hashable { + public var filePath: String + public var line: FeatureReviewLineSelection? + public var body: String + + public init(filePath: String, line: FeatureReviewLineSelection? = nil, body: String) { + self.filePath = filePath + self.line = line + self.body = body + } + + public var prompt: String { + let location = line.map { " at \($0.side.rawValue) line \($0.line)" } ?? "" + return """ + Address this review comment in `\(filePath)`\(location): + + \(body.trimmingCharacters(in: .whitespacesAndNewlines)) + + Inspect the surrounding code, make the smallest correct change, and report what changed. + """ } } diff --git a/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift b/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift index 7df5a90ae5..b73b753406 100644 --- a/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift +++ b/apps/swift-ios/Tests/FeatureTests/FeatureToolStateTests.swift @@ -18,6 +18,55 @@ struct FeatureToolStateTests { #expect(entries.featureFiltered(by: "env", includesHidden: true).map(\.name) == [".env"]) } + @Test + func filePreviewKindUsesImageMarkdownAndSourceSemantics() { + #expect(FeatureFilePreviewKind.infer(path: "art/hero.webp") == .image) + #expect(FeatureFilePreviewKind.infer(path: "README.md") == .markdown) + #expect(FeatureFilePreviewKind.infer(path: "Package.swift") == .source) + #expect(FeatureFilePreviewKind.infer(path: "LICENSE") == .plainText) + #expect(FeatureFilePreviewKind.infer(path: "template", language: "html") == .source) + } + + @Test + func sourceHighlighterPreservesTextAndClassifiesStableSpans() { + let source = """ + let count = 42 // total + /* first + second */ return "done" + """ + let lines = FeatureSourceHighlighter.lines(text: source, language: "swift") + + #expect(lines.map(\.text).joined(separator: "\n") == source) + #expect(lines[0].spans.contains { $0.text == "let" && $0.kind == .keyword }) + #expect(lines[0].spans.contains { $0.text == "42" && $0.kind == .number }) + #expect(lines[0].spans.last?.kind == .comment) + #expect(lines[1].spans.allSatisfy { $0.kind == .comment }) + #expect(lines[2].spans.first?.kind == .comment) + #expect(lines[2].spans.contains { $0.text.contains("return") && $0.kind == .keyword }) + #expect(lines[2].spans.last?.kind == .literal) + } + + @Test + func sourceHighlighterRecognizesJSONProperties() { + let line = FeatureSourceHighlighter.lines( + text: #"{"enabled": true, "count": 3}"#, + language: "json" + )[0] + + #expect(line.spans.contains { $0.text == #""enabled""# && $0.kind == .property }) + #expect(line.spans.contains { $0.text == "true" && $0.kind == .literal }) + #expect(line.spans.contains { $0.text == "3" && $0.kind == .number }) + } + + @Test + func sourceHighlighterBoundsWorkForLargeMinifiedLines() { + let source = String(repeating: #"{"value":42}"#, count: 3_000) + let line = FeatureSourceHighlighter.lines(text: source, language: "json")[0] + + #expect(line.text == source) + #expect(line.spans == [FeatureSourceSpan(text: source, kind: .plain)]) + } + @Test func reviewTotalsAggregateAcrossFiles() { let review = FeatureReview(files: [ @@ -29,6 +78,67 @@ struct FeatureToolStateTests { #expect(review.deletions == 1) } + @Test + func wordDiffHighlightsOnlyChangedTokens() { + let result = FeatureDiffWordHighlighter.spans( + old: "let color = blue", + new: "let color = green" + ) + + #expect(result.old.map(\.text).joined() == "let color = blue") + #expect(result.new.map(\.text).joined() == "let color = green") + #expect(result.old.filter { $0.kind == .changed }.map(\.text) == ["blue"]) + #expect(result.new.filter { $0.kind == .changed }.map(\.text) == ["green"]) + } + + @Test + func workspaceReviewMapperPairsReplacementLinesAndCarriesBaseReference() { + let preview = ReviewDiffPreview( + cwd: "/tmp/project", + generatedAt: "2026-08-01T00:00:00Z", + sources: [ + ReviewDiffSource( + id: "working-tree", + kind: "working-tree", + title: "Working tree", + baseRef: "main", + headRef: nil, + diff: """ + diff --git a/App.swift b/App.swift + --- a/App.swift + +++ b/App.swift + @@ -1,1 +1,1 @@ + -let color = blue + +let color = green + """, + diffHash: "hash", + truncated: false + ), + ] + ) + + let review = NativeWorkspaceMapper.review(preview) + let deletion = review.files[0].lines.first { $0.kind == .deletion } + let addition = review.files[0].lines.first { $0.kind == .addition } + + #expect(review.baseReference == "main") + #expect(deletion?.spans?.filter { $0.kind == .changed }.map(\.text) == ["blue"]) + #expect(addition?.spans?.filter { $0.kind == .changed }.map(\.text) == ["green"]) + } + + @Test + func reviewCommentPromptIncludesActionableFileAndLineContext() { + let draft = FeatureReviewCommentDraft( + filePath: "Sources/App.swift", + line: FeatureReviewLineSelection(side: .new, line: 42), + body: " Handle the nil case. " + ) + + #expect(draft.prompt.contains("`Sources/App.swift` at new line 42")) + #expect(draft.prompt.contains("Handle the nil case.")) + #expect(!draft.prompt.contains(" Handle the nil case. ")) + } + @Test func sourceControlActionsReflectRepositoryState() { let clean = FeatureSourceControlStatus(branch: "main")