Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 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
6 changes: 3 additions & 3 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
6917 Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite.swift
6359 cmuxTests/SessionPersistenceTests.swift
6217 cmuxTests/GhosttyConfigTests.swift
6180 Sources/TabManager.swift
Expand Down Expand Up @@ -100,7 +100,7 @@
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
823 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,8 @@ 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 let projector: ChatTranscriptProjector
@ObservationIgnored private let pageSize: Int
@ObservationIgnored private let maxWindowCount: Int
Expand All @@ -93,6 +94,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 +106,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 +129,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 Down Expand Up @@ -178,11 +184,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 Down Expand Up @@ -384,6 +415,34 @@ 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 && descriptor.version != self.descriptor.version
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 {} 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
wakeBackoff()
applyDescriptorSnapshot(descriptor, allowsVersionReset: didChangeSource)
}

/// After a stream drop, fetches the newest page and merges anything the
/// window missed while disconnected.
private func resyncTail() async {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public struct ChatScreen: View {
private let accessoryShortcuts: [ChatAccessoryShortcut]
private let onOpenTerminal: () -> Void
private let providesOwnChrome: Bool
private let runsStoreTask: Bool

/// Creates the screen.
///
Expand All @@ -41,19 +42,24 @@ public struct ChatScreen: View {
/// Open-Terminal button. Pass `false` when embedded in a host that
/// supplies its own navigation chrome (the in-place workspace
/// toggle), so the two don't fight and drop the header.
/// - runsStoreTask: Whether this screen should run the conversation
/// subscription. Pass `false` when a parent keeps the store warm while
/// the chat UI is not mounted.
public init(
store: ChatConversationStore,
draft: Binding<String> = .constant(""),
accessoryLeadingShortcuts: [ChatAccessoryShortcut] = [],
accessoryShortcuts: [ChatAccessoryShortcut] = [],
providesOwnChrome: Bool = true,
runsStoreTask: Bool = true,
onOpenTerminal: @escaping () -> Void
) {
_store = State(initialValue: store)
_draft = draft
self.accessoryLeadingShortcuts = accessoryLeadingShortcuts
self.accessoryShortcuts = accessoryShortcuts
self.providesOwnChrome = providesOwnChrome
self.runsStoreTask = runsStoreTask
self.onOpenTerminal = onOpenTerminal
}

Expand All @@ -76,7 +82,10 @@ public struct ChatScreen: View {
providesOwnChrome: providesOwnChrome,
onOpenTerminal: onOpenTerminal
))
.task { await store.run() }
.task {
guard runsStoreTask else { return }
await store.run()
}
#if canImport(UIKit)
.onChange(of: store.rows.last?.id) { announceLatestAgentProse() }
.onChange(of: store.lastErrorDescription) { announceLastError() }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@ internal import CmuxMobileRPC
/// Agent-chat access for the shell store: surfaces sessions and a
/// conversation event source bound to the current Mac connection.
extension MobileShellComposite {
/// Cached chat-capable sessions for a workspace, from the last authoritative
/// pull or push-derived session list. Used by workspace detail views before
/// their per-view refresh task has reconnected.
public func cachedChatSessions(workspaceID: String) -> [ChatSessionDescriptor] {
chatSessionSnapshotsByWorkspaceID[workspaceID] ?? []
}

/// Replaces the cached chat-session snapshot for a workspace. Call only when
/// data came from an authoritative pull or from the live session event stream,
/// not when the transport is unavailable.
public func rememberChatSessions(
_ sessions: [ChatSessionDescriptor],
workspaceID: String
) {
chatSessionSnapshotsByWorkspaceID[workspaceID] = sessions
}

/// A chat event source over the current connection, or `nil` when not
/// connected. Construct one ``ChatConversationStore`` per opened
/// conversation from this.
Expand All @@ -22,6 +39,23 @@ extension MobileShellComposite {
return (try? await source.sessions(workspaceID: workspaceID)) ?? []
}

/// Returns whether a chat-session list failure means the connected Mac does
/// not support chat RPCs, rather than a transient transport failure.
public func chatSessionListFailureMeansUnsupported(_ error: any Error) -> Bool {
guard case let MobileShellConnectionError.rpcError(code, message) = error else {
return false
}
let normalizedCode = code?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if let normalizedCode,
["method_not_found", "not_found", "unknown_method", "unsupported_method"].contains(normalizedCode) {
return true
}
return normalizedMessage.contains("unknown method")
|| normalizedMessage.contains("method not found")
|| normalizedMessage.contains("unsupported method")
}
Comment on lines +44 to +57

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unreliable message-string fallback drives a correctness-critical classification

When the Mac returns an rpcError whose code does not match the known set, the function falls back to scanning the free-text message for substrings like "unknown method". Any localized, reformatted, or vendor-extended error message that happens to contain one of those phrases will be misclassified as "unsupported", causing refreshChatSessions to use .authoritative([]) — which clears the cached session list and allows applyChatModeFallback to exit chat mode. Conversely, a genuinely unsupported Mac without a matching message string is silently treated as a transient failure, preserving stale sessions and leaving a chat toggle that can never open a session.

The code-based branch (normalizedCode) is a reliable structured signal; it should be the only detection path. If the Mac omits an error code for unsupported methods, the right fix is to add one on the Mac side and remove the message fallback here rather than guess on opaque prose.


/// The connected RPC client, for chat use only.
private func chatRPCClient() -> MobileCoreRPCClient? {
guard connectionState == .connected else { return nil }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
public import CMUXMobileCore
public import CmuxAgentChat
internal import CmuxMobileDiagnostics
public import CmuxMobilePairedMac
public import CmuxMobileRPC
Expand Down Expand Up @@ -218,6 +219,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
/// Bumped on every ``workspaces`` mutation: a cheap "lists may have
/// changed" signal (e.g. for retrying a parked notification deep link).
public private(set) var workspaceTopologyVersion: UInt64 = 0
/// Last authoritative chat-session snapshots, keyed by the workspace row id the UI renders.
var chatSessionSnapshotsByWorkspaceID: [String: [ChatSessionDescriptor]] = [:]
/// The group sections the UI renders. A materialized derivation of
/// ``workspacesByMac`` (currently the foreground Mac's groups). Each group's
/// `isCollapsed` reflects this device's choice (see ``groupCollapseStore``),
Expand Down Expand Up @@ -600,6 +603,8 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
}
/// `remoteClient` narrowed for `MobileShellComposite+AgentChat.swift`.
var remoteClientForAgentChat: MobileCoreRPCClient? { remoteClient }
/// Identity token that changes when the paired Mac chat event source is rebuilt.
public var agentChatEventSourceIdentity: String { chatEventSourceGeneration.uuidString }
private var terminalEventListenerTask: Task<Void, Never>?
private var terminalEventListenerID: UUID?
/// Recovers the Mac's identity post-handshake for tickets that arrived
Expand Down Expand Up @@ -655,6 +660,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
private var createTerminalTaskID: UUID?
private var connectionGeneration: UUID
private var connectionAttemptGeneration: UUID
private var chatEventSourceGeneration: UUID
/// The per-Mac connection pool (P2 of the multi-Mac work), keyed by
/// `macDeviceID`. Today it tracks the single foreground connection; P3 adds
/// read-only connections to the user's other Macs so every connected Mac's
Expand Down Expand Up @@ -869,6 +875,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
self.createTerminalTaskID = nil
self.connectionGeneration = UUID()
self.connectionAttemptGeneration = UUID()
self.chatEventSourceGeneration = UUID()
self.reportedViewportSizesByTerminalKey = [:]
self.deliveredTerminalByteEndSeqBySurfaceID = [:]
self.pendingTerminalByteEndSeqBySurfaceID = [:]
Expand Down Expand Up @@ -954,6 +961,7 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
// store we are about to empty wholesale.
isLoadingDraft = true
terminalInputText = ""
chatSessionSnapshotsByWorkspaceID = [:]
// Enqueued on the FIFO draft pipeline so every save issued before this
// point is applied first and then wiped; a pending keystroke save can
// never land after the wipe and leak into the next account's session.
Expand Down Expand Up @@ -3620,7 +3628,18 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
private func dropStalePreviousForeground(_ previousKey: String) {
guard previousKey != foregroundMacKey,
secondaryMacSubscriptions[previousKey] == nil else { return }
let removedWorkspaceIDs = Set((workspacesByMac[previousKey]?.workspaces ?? []).flatMap { workspace in
let remoteID = workspace.remoteWorkspaceID ?? workspace.id
return [
workspace.id.rawValue,
remoteID.rawValue,
workspaceAggregation.rowID(macDeviceID: previousKey, workspaceID: remoteID).rawValue,
]
})
workspacesByMac[previousKey] = nil
for workspaceID in removedWorkspaceIDs {
chatSessionSnapshotsByWorkspaceID[workspaceID] = nil
}
}

/// Adopt a host-reported real device id as the foreground Mac's aggregate key.
Expand Down Expand Up @@ -4840,6 +4859,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
private func replaceRemoteClient(with newValue: MobileCoreRPCClient?) {
let previous = remoteClient
remoteClient = newValue
if newValue != nil, previous !== newValue {
chatEventSourceGeneration = UUID()
}
if let previous, previous !== newValue {
Task { await previous.disconnect() }
}
Expand Down
1 change: 1 addition & 0 deletions Packages/iOS/CmuxMobileShellUI/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ let package = Package(
name: "CmuxMobileShellUITests",
dependencies: [
"CmuxMobileShellUI",
"CmuxAgentChat",
"CmuxMobileShell",
"CmuxMobileWorkspace",
.product(name: "StackAuth", package: "stack-auth-swift-sdk-prerelease"),
Expand Down
Loading