Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Sources/ContextLensCore/ContextReport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,9 @@ public enum ContextReport {
return v == "middle" ? (h == "center" ? "center" : "\(h) side") : (h == "center" ? v : "\(v) \(h)")
}
private static func clean(_ s: String) -> String { s.replacingOccurrences(of: "\n", with: " ").replacingOccurrences(of: "\r", with: " ") }
private static func quote(_ s: String) -> String { "> " + s.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\n", with: "\n> ") }
private static func quote(_ s: String) -> String {
"> " + s.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\n> ")
}
/// The prompt a person pastes into a coding agent. A task, when given, leads, because it is the request.
public static func instruction(path: String, task: String? = nil) -> String {
let entry = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("context.md").path
Expand Down
27 changes: 25 additions & 2 deletions Sources/ContextLensImaging/ExportPlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ public struct ExportPlan: Sendable {
public let source: URL
public let options: ExportOptions
public let summary: ExportSummary
private let candidates: [Frame]
private let sourceDigests: [String: SHA256.Digest]

public static func prepare(_ original: Session, source: URL, options: ExportOptions = ExportOptions()) throws -> ExportPlan {
try original.validate()
Expand All @@ -19,12 +21,14 @@ public struct ExportPlan: Sendable {
let candidates = selected.filter { !options.annotatedOnly || annotatedIDs.contains($0.id) }
var fingerprints: [String: String] = [:]
var sizes: [String: Int64] = [:]
var sourceDigests: [String: SHA256.Digest] = [:]
for frame in candidates {
try Task.checkCancellation()
let url = try SessionStore.resolve(frame.imagePath, in: source)
let image = try Images.load(url)
let snapshot = try Images.snapshot(url), image = snapshot.image
guard image.width == frame.width, image.height == frame.height else { throw LensError.invalid("Image dimensions disagree with metadata for \(frame.id).") }
if options.excludeDuplicates && !options.annotatedOnly { fingerprints[frame.id] = try pixelFingerprint(image) }
sourceDigests[frame.id] = snapshot.digest
sizes[frame.id] = (try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.int64Value ?? 0
}
var included = candidates
Expand All @@ -47,7 +51,26 @@ public struct ExportPlan: Sendable {
unlabelledAnnotations: visible.filter { $0.instruction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }.count,
excludedUnannotated: selected.count-candidates.count, excludedDuplicates: candidates.count-included.count,
estimatedSourceBytes: included.reduce(0) { $0 + (sizes[$1.id] ?? 0) })
return ExportPlan(sourceSession: original, session: filtered, source: source, options: options, summary: summary)
return ExportPlan(sourceSession: original, session: filtered, source: source, options: options, summary: summary,
candidates: candidates, sourceDigests: sourceDigests)
}

/// Read and verify exactly the pixels that the exporter will render.
func image(for frame: Frame) throws -> CGImage {
let snapshot = try Images.snapshot(SessionStore.resolve(frame.imagePath, in: source))
guard snapshot.image.width == frame.width, snapshot.image.height == frame.height,
sourceDigests[frame.id] == snapshot.digest else {
throw LensError.invalid("Source image changed after export preparation for \(frame.id). Refresh Hand Off and try again.")
}
return snapshot.image
}
/// Duplicate omissions are decisions about source pixels too, even though no file is exported.
func verifyOmittedCandidates() throws {
let included = Set(session.frames.map(\.id))
for frame in candidates where !included.contains(frame.id) {
try Task.checkCancellation()
try autoreleasepool { _ = try image(for: frame) }
}
}

/// Hash decoded, dimensioned sRGB pixels. PNG compression/metadata never determine duplicates.
Expand Down
6 changes: 3 additions & 3 deletions Sources/ContextLensImaging/Exporter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ public enum Exporter {
log.debug("Export attempt ms=\(ms, privacy: .public) frames=\(plan.session.frames.count, privacy: .public)")
}
try Task.checkCancellation()
let session = plan.session, source = plan.source
let session = plan.session
try session.validate()
guard !FileManager.default.fileExists(atPath: destination.path) else { throw LensError.invalid("Export destination already exists. Choose a new folder.") }
let selected = session.frames.filter(\.selected)
guard !selected.isEmpty else { throw LensError.invalid("No frames match the export filters. Include unannotated frames or add an annotation.") }
try plan.verifyOmittedCandidates()
let stage = destination.deletingLastPathComponent().appendingPathComponent(".contextlens-\(UUID().uuidString)")
let fm = FileManager.default
try fm.createDirectory(at: stage, withIntermediateDirectories: true)
Expand All @@ -28,8 +29,7 @@ public enum Exporter {
for var frame in selected {
try Task.checkCancellation()
try autoreleasepool {
let image = try Images.load(SessionStore.resolve(frame.imagePath, in: source))
guard image.width == frame.width, image.height == frame.height else { throw LensError.invalid("Image dimensions disagree with metadata for \(frame.id).") }
let image = try plan.image(for: frame)
let annotations = session.annotations.filter { $0.frameID == frame.id }
let safeImage = try Images.render(image, annotations: annotations, overlays: false)
frame.imagePath = "frames/\(frame.id).png"
Expand Down
9 changes: 9 additions & 0 deletions Sources/ContextLensImaging/Images.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,20 @@ import CoreGraphics
import ImageIO
import UniformTypeIdentifiers
import ContextLensCore
import CryptoKit

public enum Images {
public static func load(_ url: URL) throws -> CGImage {
// Read through Foundation so file errors are reported directly before ImageIO decodes in memory.
let data = try Data(contentsOf: url, options: .mappedIfSafe)
return try decode(data, url: url)
}
/// The digest and decoded image describe the same read, never separate filesystem lookups.
static func snapshot(_ url: URL) throws -> (image: CGImage, digest: SHA256.Digest) {
let data = try Data(contentsOf: url)
return (try decode(data, url: url), SHA256.hash(data: data))
}
private static func decode(_ data: Data, url: URL) throws -> CGImage {
guard let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else {
throw LensError.invalid("Cannot decode image: \(url.lastPathComponent)")
}
Expand Down
13 changes: 13 additions & 0 deletions Tests/ContextLensCoreTests/HandoffReportTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import XCTest
@testable import ContextLensCore

final class HandoffReportTests: XCTestCase {
func testCarriageReturnInstructionsStayInsideUserQuote() throws {
var session = Session(id: "report")
session.frames = [Frame(id: "f", timestampMS: 0, name: "Fixture", imagePath: "f.png", width: 100, height: 100)]
_ = try session.addAnnotation(frameID: "f", kind: .rectangle, region: Region(x: 0, y: 0, width: 1, height: 1), instruction: "First request\r## Still user text\r\nLast line")
let markdown = ContextReport.markdown(session)
XCTAssertTrue(markdown.contains("> First request\n> ## Still user text\n> Last line"))
XCTAssertFalse(markdown.contains("\r"))
}
}
Loading
Loading