Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
6a9a45b
Keep mobile chat GUI cached during reconnect
azooz2003-bit Jun 29, 2026
deed98d
Stabilize mobile chat GUI toggle
azooz2003-bit Jun 29, 2026
80776fc
Reserve mobile chat toolbar slots
azooz2003-bit Jun 29, 2026
c903d7f
Stabilize mobile workspace top chrome
azooz2003-bit Jun 29, 2026
7647783
Revert "Stabilize mobile workspace top chrome"
azooz2003-bit Jun 29, 2026
ae96779
Merge remote-tracking branch 'origin/main' into feat-gui-cache-reconnect
azooz2003-bit Jun 29, 2026
d04fd04
Address chat cache review findings
azooz2003-bit Jun 29, 2026
98d2deb
Update Swift file length budget
azooz2003-bit Jun 29, 2026
7b6c129
Refresh chat source after reconnect
azooz2003-bit Jun 29, 2026
8bc77c6
Scope cached chat sessions by workspace
azooz2003-bit Jun 29, 2026
b1a88d0
Guard cached chat offline entry
azooz2003-bit Jun 29, 2026
ab4dafe
Prune scoped chat cache keys
azooz2003-bit Jun 29, 2026
6cdb66b
Wake chat store after source rebinding
azooz2003-bit Jun 29, 2026
75fbba8
Keep chat backoff wake structured
azooz2003-bit Jun 29, 2026
c97f40f
Address chat backoff policy checks
azooz2003-bit Jun 30, 2026
7714488
Bind chat cache to installed source
azooz2003-bit Jun 30, 2026
58b69e9
Restart chat session refresh on source swap
azooz2003-bit Jun 30, 2026
020ff85
Stop warm chat stream while backgrounded
azooz2003-bit Jun 30, 2026
e1d70f1
Prevent stale chat descriptor downgrades
azooz2003-bit Jun 30, 2026
ff0a90f
Preserve chat cache on transient seed failures
azooz2003-bit Jun 30, 2026
b185e49
Merge remote-tracking branch 'origin/main' into feat-gui-cache-reconnect
azooz2003-bit Jun 30, 2026
09fb2b7
Exit chat mode on authoritative session removal
azooz2003-bit Jun 30, 2026
167437a
Reset chat store state on source rebinding
azooz2003-bit Jun 30, 2026
51b17a7
Bound mobile chat cache retention
azooz2003-bit Jun 30, 2026
1aa5a33
Guard chat store source replacement races
azooz2003-bit Jun 30, 2026
5680f3f
Accept equal-version chat source descriptors
azooz2003-bit Jun 30, 2026
7d9712b
Prune chat snapshots for removed workspaces
azooz2003-bit Jun 30, 2026
d0d7e06
Declare shell chat test dependency
azooz2003-bit Jun 30, 2026
931e52c
Split chat source replacement test support
azooz2003-bit Jun 30, 2026
756f6ab
Treat unknown chat source identity as changed
azooz2003-bit Jun 30, 2026
7516c10
Ignore stale chat session refreshes
azooz2003-bit Jun 30, 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
8 changes: 4 additions & 4 deletions .github/swift-file-length-budget.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
8016 CLI/cmux_open.swift
7366 cmuxTests/WorkspaceUnitTests.swift
7218 cmuxTests/WorkspaceRemoteConnectionTests.swift
6895 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
6935 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
6359 cmuxTests/SessionPersistenceTests.swift
6217 cmuxTests/GhosttyConfigTests.swift
6180 Sources/TabManager.swift
Expand Down Expand Up @@ -92,15 +92,15 @@
1002 Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/PairedMacBackupTests.swift
953 cmuxTests/DockSocketLifecycleTests.swift
951 Sources/App/TerminalDirectoryOpenSupport.swift
948 Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatConversationStoreTests.swift
982 Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatConversationStoreTests.swift
948 Sources/App/ShortcutRoutingSupport.swift
947 Sources/TerminalNotificationPolicy.swift
945 Sources/SessionIndexRegisteredAgents.swift
937 Sources/Panels/BrowserPopupWindowController.swift
937 Sources/TextBoxMentionIndexStore.swift
928 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AppSection.swift
920 Sources/CommandPalette/CommandPaletteSettingsToggle.swift
914 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift
755 Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/WorkspaceDetailView.swift
905 Sources/CmuxSSHURLRequest.swift
899 Sources/Panels/MarkdownWebRenderer.swift
885 Sources/Panels/TerminalPanel.swift
Expand All @@ -124,7 +124,7 @@
773 Sources/App/MenuBarExtraController.swift
769 Packages/macOS/CmuxTerminal/Sources/CmuxTerminal/Surface/TerminalSurface+Input.swift
768 cmuxUITests/BrowserFixtureInteractionUITests.swift
764 Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift
864 Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift
762 Packages/iOS/CmuxMobileTransport/Sources/CmuxMobileTransport/CmxNetworkByteTransport.swift
761 Sources/Mobile/AgentChat/AgentChatSessionRegistry.swift
760 Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ public final class ChatConversationStore {
/// reproject below ignores them) for agent sessions.
@ObservationIgnored private var terminalBlocks: [Int: TerminalCommandBlock] = [:]
@ObservationIgnored private var terminalBlockOrder: [Int] = []
@ObservationIgnored private let source: any ChatEventSource
@ObservationIgnored private var source: any ChatEventSource
@ObservationIgnored private var sourceIdentity: String?
@ObservationIgnored private var sourceGeneration = 0
@ObservationIgnored private let projector: ChatTranscriptProjector
@ObservationIgnored private let pageSize: Int
@ObservationIgnored private let maxWindowCount: Int
Expand All @@ -93,6 +95,8 @@ public final class ChatConversationStore {
/// - Parameters:
/// - descriptor: The session to show.
/// - source: The conversation data seam.
/// - sourceIdentity: Optional producer identity used to accept version
/// resets only when the underlying source changes.
/// - lastReadSeq: Highest seq the user has already seen, used to place
/// the unread separator on first load; `nil` shows no separator.
/// - projector: Row projection policy (grouping interval, calendar).
Expand All @@ -103,16 +107,18 @@ public final class ChatConversationStore {
public init(
descriptor: ChatSessionDescriptor,
source: any ChatEventSource,
sourceIdentity: String? = nil,
lastReadSeq: Int? = nil,
projector: ChatTranscriptProjector = ChatTranscriptProjector(),
pageSize: Int = 100,
maxWindowCount: Int = 600,
now: @escaping @Sendable () -> Date = { Date() },
idleSleep: @escaping (Duration) async -> Void = { try? await Task.sleep(for: $0) }
idleSleep: @escaping @Sendable (Duration) async -> Void = { try? await ContinuousClock().sleep(for: $0) }
) {
self.descriptor = descriptor
self.agentState = descriptor.state
self.source = source
self.sourceIdentity = sourceIdentity
self.projector = projector
self.pageSize = pageSize
self.maxWindowCount = maxWindowCount
Expand All @@ -124,7 +130,8 @@ public final class ChatConversationStore {
@ObservationIgnored private let lastReadSeqAtActivation: Int?
/// Cancellable reconnect-backoff sleep; injectable for deterministic
/// tests.
@ObservationIgnored private let idleSleep: (Duration) async -> Void
@ObservationIgnored private let idleSleep: @Sendable (Duration) async -> Void
@ObservationIgnored private var backoffWakeContinuation: AsyncStream<Void>.Continuation?

/// Follows the live event stream until cancelled, loading history
/// inside each subscription so no event falls into a fetch/subscribe
Expand All @@ -136,19 +143,24 @@ public final class ChatConversationStore {
public func run() async {
var backoff: Duration = .zero
while !Task.isCancelled {
let runGeneration = sourceGeneration
// Subscribe FIRST: events emitted while the history fetch is in
// flight buffer in the stream and replay after the merge (the
// window dedups by message id), instead of being dropped.
let stream = await source.events(sessionID: descriptor.id)
guard runGeneration == sourceGeneration else { continue }
isConnected = true
let hadHistory = hasLoadedInitialHistory
await loadInitialHistoryIfNeeded()
await loadInitialHistoryIfNeeded(expectedGeneration: runGeneration)
guard runGeneration == sourceGeneration else { continue }
if hadHistory {
// Reconnect: merge whatever the window missed while down.
await resyncTail()
await resyncTail(expectedGeneration: runGeneration)
guard runGeneration == sourceGeneration else { continue }
}
let streamStartedAt = now()
for await event in stream {
guard runGeneration == sourceGeneration else { break }
apply(event)
// If the initial history fetch failed (e.g. the Mac couldn't
// read the transcript yet — a title-detected agent adopted
Expand All @@ -157,7 +169,8 @@ public final class ChatConversationStore {
// context loads instead of parking on the failure. No-ops once
// loaded; only re-runs while the fetch still throws.
if !hasLoadedInitialHistory {
await loadInitialHistoryIfNeeded()
await loadInitialHistoryIfNeeded(expectedGeneration: runGeneration)
guard runGeneration == sourceGeneration else { break }
}
// Flush queued sends inline once the agent goes idle —
// structured here in the async run loop rather than a
Expand All @@ -166,6 +179,7 @@ public final class ChatConversationStore {
await flushQueuedSends()
}
}
guard runGeneration == sourceGeneration else { continue }
isConnected = false
guard !Task.isCancelled else { return }
// Back off before resubscribing unless the stream was healthy
Expand All @@ -178,11 +192,36 @@ public final class ChatConversationStore {
backoff = .zero
} else {
backoff = min(max(backoff * 2, .milliseconds(500)), .seconds(16))
await waitForBackoffOrSourceReplacement(backoff)
}
}
}

private func waitForBackoffOrSourceReplacement(_ backoff: Duration) async {
let idleSleep = idleSleep
let wakeStream = AsyncStream<Void> { continuation in
wakeBackoff()
backoffWakeContinuation = continuation
}
await withTaskGroup(of: Void.self) { group in
group.addTask {
await idleSleep(backoff)
}
group.addTask {
for await _ in wakeStream { break }
}
await group.next()
wakeBackoff()
group.cancelAll()
}
}

private func wakeBackoff() {
backoffWakeContinuation?.yield(())
backoffWakeContinuation?.finish()
backoffWakeContinuation = nil
}

/// Fetches one older page and prepends it to the window.
public func loadOlder() async {
guard hasMoreHistory, !isLoadingOlder else { return }
Expand All @@ -196,12 +235,14 @@ public final class ChatConversationStore {
}
isLoadingOlder = true
defer { isLoadingOlder = false }
let generation = sourceGeneration
do {
let page = try await source.history(
sessionID: descriptor.id,
beforeSeq: oldestSeq,
limit: pageSize
)
guard generation == sourceGeneration else { return }
// Re-check the anchor: an append may have raced the fetch.
guard messages.first?.seq == oldestSeq else { return }
if page.messages.isEmpty {
Expand All @@ -217,6 +258,7 @@ public final class ChatConversationStore {
lastErrorDescription = nil
reproject()
} catch {
guard generation == sourceGeneration else { return }
lastErrorDescription = error.localizedDescription
}
}
Expand Down Expand Up @@ -331,8 +373,9 @@ public final class ChatConversationStore {

// MARK: - Event application

private func loadInitialHistoryIfNeeded() async {
private func loadInitialHistoryIfNeeded(expectedGeneration: Int? = nil) async {
guard !hasLoadedInitialHistory else { return }
let generation = expectedGeneration ?? sourceGeneration
// A fresh newest-page load re-anchors paging; truncated-at-head is only
// re-discovered if a later loadOlder hits the Mac cache head.
historyTruncatedAtHead = false
Expand All @@ -342,6 +385,7 @@ public final class ChatConversationStore {
beforeSeq: nil,
limit: pageSize
)
guard generation == sourceGeneration else { return }
if descriptor.kind == .terminal {
seedTerminalBlocks(page.terminalBlocks ?? [])
// Block paging isn't implemented yet, so never advertise more
Expand All @@ -361,6 +405,7 @@ public final class ChatConversationStore {
lastErrorDescription = nil
reproject()
} catch {
guard generation == sourceGeneration else { return }
// Only flag failure while the initial load is still pending: a
// racing duplicate fetch (retry button vs reconnect) that fails
// AFTER another succeeded must not strand a dead error UI.
Expand All @@ -384,9 +429,62 @@ public final class ChatConversationStore {
await loadInitialHistoryIfNeeded()
}

/// Reconciles a fresh session-list descriptor into this conversation cache.
public func applyDescriptorSnapshot(
_ descriptor: ChatSessionDescriptor,
allowsVersionReset: Bool = false
) {
guard descriptor.id == self.descriptor.id else { return }
let isUnversioned = descriptor.version == 0 && self.descriptor.version == 0
let isNewer = descriptor.version > self.descriptor.version
let isProducerReset = allowsVersionReset
guard isUnversioned || isNewer || isProducerReset else { return }
self.descriptor = descriptor
agentState = descriptor.state
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if case .idle = descriptor.state {
Task { await flushQueuedSends() }
} else {
didFlushThisIdleWindow = false
}
}

/// Rebinds this conversation to the current Mac transport after reconnect.
public func replaceSource(
_ source: any ChatEventSource,
descriptor: ChatSessionDescriptor,
sourceIdentity: String? = nil
) {
let didChangeSource = sourceIdentity == nil || sourceIdentity != self.sourceIdentity
self.source = source
self.sourceIdentity = sourceIdentity
if didChangeSource {
sourceGeneration += 1
resetTranscriptAnchorForSourceReplacement()
}
wakeBackoff()
applyDescriptorSnapshot(descriptor, allowsVersionReset: didChangeSource)
}

/// Clears transcript state that is anchored to the prior event producer.
private func resetTranscriptAnchorForSourceReplacement() {
messages = []
streamingMessage = nil
firstUnreadSeq = nil
terminalBlocks = [:]
terminalBlockOrder = []
pending.removeAll { $0.delivery == .delivered }
hasMoreHistory = false
historyTruncatedAtHead = false
initialLoadFailed = false
hasLoadedInitialHistory = false
isLoadingOlder = false
reproject()
}

/// After a stream drop, fetches the newest page and merges anything the
/// window missed while disconnected.
private func resyncTail() async {
private func resyncTail(expectedGeneration: Int? = nil) async {
let generation = expectedGeneration ?? sourceGeneration
// Re-deriving the window from the newest page resets paging; a later
// loadOlder re-discovers truncated-at-head if it still applies.
historyTruncatedAtHead = false
Expand All @@ -396,6 +494,7 @@ public final class ChatConversationStore {
beforeSeq: nil,
limit: pageSize
)
guard generation == sourceGeneration else { return }
if descriptor.kind == .terminal {
// Blocks are whole-value and keyed by id, so re-seeding from
// the authoritative page is idempotent.
Expand Down Expand Up @@ -458,6 +557,7 @@ public final class ChatConversationStore {
if didUpdate { reproject() }
lastErrorDescription = nil
} catch {
guard generation == sourceGeneration else { return }
lastErrorDescription = error.localizedDescription
}
}
Expand Down
Loading
Loading