Skip to content
Closed
Show file tree
Hide file tree
Changes from 70 commits
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
4b5cbc1
test: cover staged mobile attachment delivery
azooz2003-bit Aug 10, 2026
2408b3f
test: pin attachment retry upload identity
azooz2003-bit Aug 10, 2026
469e8f9
test: preserve attachment operation across retry
azooz2003-bit Aug 10, 2026
5a438d0
feat: stream staged mobile attachments
azooz2003-bit Aug 10, 2026
12e9654
test: require atomic attachment cleanup and resolution
azooz2003-bit Aug 10, 2026
4c0857d
fix: make mobile attachment cleanup atomic
azooz2003-bit Aug 10, 2026
b4c0e75
test: allow empty staged terminal files
azooz2003-bit Aug 10, 2026
3ea1fdd
test: cover empty attachment finalization
azooz2003-bit Aug 10, 2026
17b2c0d
test: exercise staged attachment routing
azooz2003-bit Aug 10, 2026
f5d9075
feat: unify mobile attachment composer UI
azooz2003-bit Aug 10, 2026
dcb70bb
Merge remote-tracking branch 'origin/main' into feat-ios-attachment-ux
azooz2003-bit Aug 10, 2026
8a02ad9
fix: match mobile attachment card layout
azooz2003-bit Aug 10, 2026
6357405
fix: import mobile attachment store in chat
azooz2003-bit Aug 10, 2026
7d9943f
fix: scope attachment localization helper
azooz2003-bit Aug 10, 2026
5d0a761
fix: share mobile viewport report helper
azooz2003-bit Aug 10, 2026
b6a735d
fix: match localized string signature
azooz2003-bit Aug 10, 2026
aa80bca
test: avoid mutating attachment preview draft
azooz2003-bit Aug 10, 2026
9d8e991
test: cover attachment retry and admission failures
azooz2003-bit Aug 10, 2026
db2a608
fix: surface attachment admission failures
azooz2003-bit Aug 10, 2026
fb4f945
test: cover attachment ownership and protocol boundaries
azooz2003-bit Aug 10, 2026
e44c26d
test: reject attachment operation directory escapes
azooz2003-bit Aug 10, 2026
54d8fe4
test: cover immutable upload metadata fields
azooz2003-bit Aug 10, 2026
b1d8a27
fix: harden attachment lifecycle and errors
azooz2003-bit Aug 10, 2026
5e9d79a
fix: gate attachment picker postprocessing
azooz2003-bit Aug 10, 2026
59ace84
test: cover completed multi-chunk attachment retry
azooz2003-bit Aug 10, 2026
3df4956
fix: accept completed attachment retry receipts
azooz2003-bit Aug 10, 2026
3c0854f
test: validate staged attachment backing files
azooz2003-bit Aug 10, 2026
d974515
fix: validate staged attachment lifecycle
azooz2003-bit Aug 10, 2026
29fb279
test: separate paste and attachment failures
azooz2003-bit Aug 10, 2026
81801fc
fix: preserve terminal paste failures
azooz2003-bit Aug 10, 2026
376179f
test: preserve pending attachment read failures
azooz2003-bit Aug 10, 2026
238be3e
fix: preserve pending attachment read failures
azooz2003-bit Aug 10, 2026
fb52544
fix: report excess task photos
azooz2003-bit Aug 10, 2026
eb127fe
test: preserve exact task prompt fixture value
azooz2003-bit Aug 10, 2026
534be90
fix: enable attachment controls in UI fixture
azooz2003-bit Aug 10, 2026
d245491
test: dismiss task attachment menu by coordinate
azooz2003-bit Aug 10, 2026
813d9ec
test: require shared attachment card geometry
azooz2003-bit Aug 10, 2026
4f684ba
fix: unify attachment card geometry
azooz2003-bit Aug 10, 2026
7e5ea14
test: cover attachment UX across mobile composers
azooz2003-bit Aug 10, 2026
8041d6b
test: capture attachment surface evidence
azooz2003-bit Aug 10, 2026
0c323de
test: cover oversized and cancelled attachment staging
azooz2003-bit Aug 10, 2026
c2719aa
test: repeat attachment composer lifecycle
azooz2003-bit Aug 10, 2026
0c64edd
fix: exercise attachment UX in real composers
azooz2003-bit Aug 10, 2026
959bc49
test: capture attachment preview lifecycle
azooz2003-bit Aug 10, 2026
7738a9e
fix: make attachment image fixture distinctive
azooz2003-bit Aug 10, 2026
a3e0d86
fix: satisfy attachment layout conventions
azooz2003-bit Aug 10, 2026
db2defc
fix: instantiate attachment UI fixtures
azooz2003-bit Aug 10, 2026
9feaa95
test: stabilize attachment menu interactions
azooz2003-bit Aug 10, 2026
f927b5f
test: target attachment preview close action
azooz2003-bit Aug 10, 2026
72d51fb
fix: identify attachment preview close action
azooz2003-bit Aug 10, 2026
9cf11d8
test: scope Japanese attachment coverage
azooz2003-bit Aug 10, 2026
0705733
test: preserve attachment fixture drafts
azooz2003-bit Aug 10, 2026
fe83927
test: assert terminal attachment containment
azooz2003-bit Aug 10, 2026
89c4d2c
test: seed attachment lifecycle drafts
azooz2003-bit Aug 10, 2026
5936cdb
test: isolate attachment lifecycle focus
azooz2003-bit Aug 10, 2026
a11df01
test: bound attachment lifecycle interactions
azooz2003-bit Aug 10, 2026
3593f6e
test: keep attachment fixtures unfocused
azooz2003-bit Aug 10, 2026
417a41d
fix: disable task attachments at capacity
azooz2003-bit Aug 10, 2026
8358496
test: support remote Foundation overloads
azooz2003-bit Aug 10, 2026
8071def
perf: decode attachment images off main thread
azooz2003-bit Aug 10, 2026
580b440
test: cover attachment UX completion regressions
azooz2003-bit Aug 10, 2026
b010728
fix: complete iOS attachment UX
azooz2003-bit Aug 10, 2026
3272aa9
test: correct attachment budget fixtures
azooz2003-bit Aug 10, 2026
e1838cc
test: import attachment store owner
azooz2003-bit Aug 10, 2026
6dec5ee
Fix attachment preparation UI test handshake
azooz2003-bit Aug 10, 2026
22c143b
Fix native Quick Look UI assertion
azooz2003-bit Aug 10, 2026
0b15b56
Fix oriented attachment fixture metadata
azooz2003-bit Aug 10, 2026
2466567
Fix attachment test compiler diagnostics
azooz2003-bit Aug 10, 2026
34b7839
Normalize oriented preview size label
azooz2003-bit Aug 10, 2026
ab3159d
test: catch task composer toggle overflow
azooz2003-bit Aug 11, 2026
15a3b40
Fix accessibility layout toggle sizing
azooz2003-bit Aug 11, 2026
9238309
Fix layout toggle interaction shape
azooz2003-bit Aug 11, 2026
3619b43
test: catch landscape attachment card overflow
azooz2003-bit Aug 11, 2026
c8a4320
Fix attachment card interaction boundary
azooz2003-bit Aug 11, 2026
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
Original file line number Diff line number Diff line change
@@ -1,31 +1,98 @@
import Foundation

/// An attachment the user is sending with a prompt.
///
/// Carries the binary payload from the composer to the ``ChatEventSource``,
/// which delivers it to the host out-of-band (image paste RPC).
public struct ChatOutboundAttachment: Sendable, Equatable {
/// The encoded image format of ``data``.
public enum Kind: String, Sendable, Equatable {
case image
case file
}

public enum Format: String, Sendable, Equatable {
/// PNG-encoded image data.
case png
/// JPEG-encoded image data.
case jpeg
}

/// The encoded payload.
public let data: Data
/// The attachment's explicit storage representation.
public enum Payload: Sendable, Equatable {
case inMemoryImage(data: Data, format: Format)
case stagedFile(url: URL, byteCount: Int)
}

/// Stable idempotency identity retained by a pending row across retries.
public let uploadID: UUID
/// Stable operation shared by all attachments in one prompt.
public let operationID: UUID
public let payload: Payload
public let fileName: String
public let kind: Kind
/// Bounded preview bytes prepared before the attachment reaches a view.
public let thumbnailData: Data?
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

public var localFileURL: URL? {
guard case let .stagedFile(url, _) = payload else { return nil }
return url
}

/// The encoding of ``data``.
public let format: Format
public var byteCount: Int {
switch payload {
case let .inMemoryImage(data, _): data.count
case let .stagedFile(_, count): count
}
}

public init(
data: Data,
format: Format,
uploadID: UUID = UUID(),
operationID: UUID = UUID()
) {
self.uploadID = uploadID
self.operationID = operationID
self.payload = .inMemoryImage(data: data, format: format)
self.fileName = format == .png ? "attachment.png" : "attachment.jpg"
self.kind = .image
// Legacy callers have no bounded preview. Retaining `data` here would
// duplicate the full image payload in view-facing state.
self.thumbnailData = nil
}

public init(
localFileURL: URL,
byteCount: Int,
fileName: String,
kind: Kind,
thumbnailData: Data? = nil,
uploadID: UUID = UUID(),
operationID: UUID = UUID()
) {
self.uploadID = uploadID
self.operationID = operationID
self.payload = .stagedFile(url: localFileURL, byteCount: byteCount)
self.fileName = fileName
self.kind = kind
self.thumbnailData = thumbnailData
}

/// Creates an outbound attachment.
///
/// - Parameters:
/// - data: The encoded payload.
/// - format: The encoding of `data`.
public init(data: Data, format: Format) {
self.data = data
self.format = format
/// Returns the same payload and upload identity under a prompt-wide operation.
public func withOperationID(_ operationID: UUID) -> Self {
switch payload {
case let .inMemoryImage(data, format):
Self(
data: data,
format: format,
uploadID: uploadID,
operationID: operationID
)
case let .stagedFile(url, byteCount):
Self(
localFileURL: url,
byteCount: byteCount,
fileName: fileName,
kind: kind,
thumbnailData: thumbnailData,
uploadID: uploadID,
operationID: operationID
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public final class ChatConversationStore {
@ObservationIgnored private let pageSize: Int
@ObservationIgnored private let maxWindowCount: Int
@ObservationIgnored private let now: @Sendable () -> Date
@ObservationIgnored private let releaseStagedFileURLs: ([URL]) -> Void
@ObservationIgnored private var pendingCounter = 0
@ObservationIgnored private var isFlushingQueue = false
@ObservationIgnored private var endedByUnversionedRemoval = false
Expand All @@ -103,6 +104,8 @@ public final class ChatConversationStore {
/// - maxWindowCount: Cap on the in-memory message window; older
/// messages fall out and become pageable history again.
/// - now: Clock seam for tests; defaults to the wall clock.
/// - releaseStagedFileURLs: Releases app-owned files after their final
/// pending owner leaves the store.
public init(
descriptor: ChatSessionDescriptor,
source: any ChatEventSource,
Expand All @@ -112,7 +115,12 @@ public final class ChatConversationStore {
pageSize: Int = 100,
maxWindowCount: Int = 600,
now: @escaping @Sendable () -> Date = { Date() },
idleSleep: @escaping @Sendable (Duration) async -> Void = { try? await ContinuousClock().sleep(for: $0) }
idleSleep: @escaping @Sendable (Duration) async -> Void = { try? await ContinuousClock().sleep(for: $0) },
releaseStagedFileURLs: @escaping ([URL]) -> Void = { urls in
for url in urls {
try? FileManager.default.removeItem(at: url)
}
}
) {
self.descriptor = descriptor
self.agentState = descriptor.state
Expand All @@ -123,6 +131,7 @@ public final class ChatConversationStore {
self.maxWindowCount = maxWindowCount
self.now = now
self.idleSleep = idleSleep
self.releaseStagedFileURLs = releaseStagedFileURLs
self.lastReadSeqAtActivation = lastReadSeq
}

Expand Down Expand Up @@ -278,10 +287,12 @@ public final class ChatConversationStore {
// goes idle, so the message is delivered cleanly in turn order.
let queueWhileBusy: Bool
if case .working = agentState { queueWhileBusy = true } else { queueWhileBusy = false }
let operationID = UUID()
let normalizedAttachments = attachments.map { $0.withOperationID(operationID) }
let item = ChatPendingOutbound(
id: "local-\(pendingCounter)",
text: trimmed,
attachments: attachments,
attachments: normalizedAttachments,
createdAt: now(),
delivery: queueWhileBusy ? .queued : .sending
)
Expand Down Expand Up @@ -341,7 +352,10 @@ public final class ChatConversationStore {
///
/// - Parameter pendingID: The pending row to discard.
public func discard(pendingID: String) {
let removed = pending.filter { $0.id == pendingID }
guard !removed.isEmpty else { return }
pending.removeAll { $0.id == pendingID }
releaseStagedFiles(ownedBy: removed)
reproject()
}

Expand Down Expand Up @@ -471,7 +485,7 @@ public final class ChatConversationStore {
firstUnreadSeq = nil
terminalBlocks = [:]
terminalBlockOrder = []
pending.removeAll { $0.delivery == .delivered }
removePending { $0.delivery == .delivered }
hasMoreHistory = false
historyTruncatedAtHead = false
initialLoadFailed = false
Expand Down Expand Up @@ -638,7 +652,7 @@ public final class ChatConversationStore {
// permanently if the resync history fetch fails).
terminalBlocks = [:]
terminalBlockOrder = []
pending.removeAll { $0.delivery == .delivered }
removePending { $0.delivery == .delivered }
hasMoreHistory = false
// The new transcript re-anchors paging from scratch; a stale
// truncated-at-head flag would render the "earlier history is on
Expand Down Expand Up @@ -676,6 +690,7 @@ public final class ChatConversationStore {
private func reconcilePending(against newMessages: [ChatMessage], onReconciled: (ChatMessage) -> Void = { _ in }) {
guard !pending.isEmpty else { return }
var maxReconciledCounter: Int?
var removedPending: [ChatPendingOutbound] = []
for message in newMessages where message.role == .user {
let index: Int?
switch message.kind {
Expand Down Expand Up @@ -738,6 +753,7 @@ public final class ChatConversationStore {
}
if let index {
let removed = pending.remove(at: index)
removedPending.append(removed)
onReconciled(message)
if let counter = Self.pendingCounter(removed.id) {
maxReconciledCounter = max(maxReconciledCounter ?? counter, counter)
Expand All @@ -755,15 +771,21 @@ public final class ChatConversationStore {
// so they keep their own reconcile lifecycle. Only `.delivered` rows
// (RPC-confirmed) are swept; sending/queued/failed keep their state.
if let maxReconciledCounter {
pending.removeAll { item in
let stale = pending.filter { item in
guard item.delivery == .delivered,
item.attachmentCount == 0,
!item.text.isEmpty,
let counter = Self.pendingCounter(item.id),
counter < maxReconciledCounter else { return false }
return true
}
if !stale.isEmpty {
let staleIDs = Set(stale.map(\.id))
pending.removeAll { staleIDs.contains($0.id) }
removedPending.append(contentsOf: stale)
}
}
releaseStagedFiles(ownedBy: removedPending)
}

/// Parses the monotonic counter from a pending row id (`local-<n>`), used
Expand Down Expand Up @@ -804,16 +826,48 @@ public final class ChatConversationStore {
/// Failed pendings keep their retry row (`isReconcilable` is false).
private func reconcileTerminalPending(against blocks: [TerminalCommandBlock]) {
guard !pending.isEmpty else { return }
var removedPending: [ChatPendingOutbound] = []
for block in blocks {
let command = block.command.trimmingCharacters(in: .whitespacesAndNewlines)
guard !command.isEmpty else { continue }
if let index = pending.firstIndex(where: {
$0.isReconcilable
&& $0.text.trimmingCharacters(in: .whitespacesAndNewlines) == command
}) {
pending.remove(at: index)
let removed = pending.remove(at: index)
removedPending.append(removed)
}
}
releaseStagedFiles(ownedBy: removedPending)
}

/// Removes matching rows and releases file-backed payloads no remaining
/// pending row owns. Failed and queued rows retain their files for retry.
private func removePending(where shouldRemove: (ChatPendingOutbound) -> Bool) {
let removed = pending.filter(shouldRemove)
guard !removed.isEmpty else { return }
pending.removeAll(where: shouldRemove)
releaseStagedFiles(ownedBy: removed)
}

/// Releases staged payloads after their owning pending rows leave the store.
/// A shared URL stays alive until its last pending owner is removed.
private func releaseStagedFiles(ownedBy removed: [ChatPendingOutbound]) {
guard !removed.isEmpty else { return }
let retainedURLs = Set(pending.flatMap { item in
item.attachments.compactMap(\.localFileURL)
})
var seen = Set<URL>()
var releasedURLs: [URL] = []
for item in removed {
for url in item.attachments.compactMap(\.localFileURL)
where !retainedURLs.contains(url) && seen.insert(url).inserted {
releasedURLs.append(url)
}
}
if !releasedURLs.isEmpty {
releaseStagedFileURLs(releasedURLs)
}
}

/// Replaces the terminal block window from a history page (oldest first).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,35 @@ struct ChatConversationStoreSourceReplacementTests {

#expect(store.agentState == .idle)
}

@Test("source replacement releases delivered attachment files from the prior producer")
func sourceReplacementReleasesDeliveredStagedFiles() async throws {
let oldSource = FixtureChatEventSource()
let store = ChatConversationStore(
descriptor: Self.descriptor(),
source: oldSource,
sourceIdentity: "old",
now: { Self.baseTime }
)
let fileURL = FileManager.default.temporaryDirectory
.appendingPathComponent("source-replaced-chat-attachment-\(UUID()).txt")
try Data("old source".utf8).write(to: fileURL)
defer { try? FileManager.default.removeItem(at: fileURL) }

await store.send(text: "old prompt", attachments: [ChatOutboundAttachment(
localFileURL: fileURL,
byteCount: 10,
fileName: "old.txt",
kind: .file
)])
#expect(FileManager.default.fileExists(atPath: fileURL.path))

store.replaceSource(
FixtureChatEventSource(),
descriptor: Self.descriptor(),
sourceIdentity: "new"
)

#expect(!FileManager.default.fileExists(atPath: fileURL.path))
}
}
Loading
Loading