From c7c0060933c5f7de04fdfb9449aa29c3a1d45ac0 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Mon, 16 Nov 2026 12:25:43 +0800 Subject: [PATCH 01/13] Keep a test store's host mirror out of the simulator's Keychain A HostStore handed its own directory isolated hosts.json but still mirrored every added host into the simulator's real synchronizable Keychain. The app adopted them on its next launch: the test simulators had accumulated 100 and 86 box / devbox hosts, and a deck screenshot showed NO SIGNAL tiles instead of the seeded host. The mirror is now a value, HostRecordMirror. The app's store uses the Keychain; a store with an injected directory gets a private in-memory mirror, and a test that reads back what a store mirrored passes its own. One test still touches the real Keychain, with a payload that cannot decode as a host, so even a killed run cannot add one. The shipped app is unchanged. A simulator that already accumulated hosts is cleared with `xcrun simctl keychain reset` and one launch; the recipe is in docs/agents/sync-and-widgets.md. --- Multiplex/Services/HostStore.swift | 72 ++++++++++++++++++-- MultiplexTests/CustomAgentCommandTests.swift | 8 ++- MultiplexTests/HostSyncTests.swift | 72 +++++++++++++++++++- docs/agents/sync-and-widgets.md | 17 +++++ 4 files changed, 158 insertions(+), 11 deletions(-) diff --git a/Multiplex/Services/HostStore.swift b/Multiplex/Services/HostStore.swift index 5584ce33..dd7e41a8 100644 --- a/Multiplex/Services/HostStore.swift +++ b/Multiplex/Services/HostStore.swift @@ -4,6 +4,62 @@ import Observation import notify #endif +/// Where a store keeps the cross-device copy of each host record. +/// +/// The app's store mirrors into the synchronizable Keychain. A store handed +/// its own directory is a persistence test boundary, and the mirror has to +/// be inside that boundary too: for as long as it was not, every test that +/// added a host to a temp-directory store also wrote that host into the +/// simulator's REAL Keychain, and the app adopted the lot on its next launch +/// (a hundred `box` / `devbox` hosts on the test simulator, found +/// 2026-11-16). So an isolated store gets a mirror of its own by default. +struct HostRecordMirror: Sendable { + var set: @Sendable (_ record: Data, _ hostID: UUID) -> Bool + var records: @Sendable () -> [Data] + var delete: @Sendable (_ hostID: UUID) -> Void + + /// The synchronizable Keychain — what every device of the user's reads. + static let keychain = HostRecordMirror( + set: { KeychainStore.setHostRecord($0, for: $1) }, + records: { + KeychainStore.migrateDeviceOnlyItems() + return KeychainStore.hostRecords() + }, + delete: { KeychainStore.deleteHostRecord(for: $0) } + ) + + /// A mirror that lives and dies with the value: same contract, nothing + /// outside the process. Each call makes a separate one. + static func inMemory() -> HostRecordMirror { + let storage = Storage() + return HostRecordMirror( + set: { storage.set($0, for: $1) }, + records: { storage.all() }, + delete: { storage.remove($0) } + ) + } + + /// `records` is read off the main actor (`refreshFromCloud`), so the box + /// takes a lock rather than trusting its callers' isolation. + private final class Storage: @unchecked Sendable { + private let lock = NSLock() + private var records: [UUID: Data] = [:] + + func set(_ record: Data, for id: UUID) -> Bool { + lock.withLock { records[id] = record } + return true + } + + func all() -> [Data] { + lock.withLock { Array(records.values) } + } + + func remove(_ id: UUID) { + lock.withLock { records[id] = nil } + } + } +} + /// Hosts persisted as JSON in Application Support — a local cache of the /// cross-device truth. Secrets and a mirrored copy of each host record live /// in the Keychain as synchronizable items, so iCloud Keychain moves both to @@ -17,6 +73,7 @@ final class HostStore { private let fileURL: URL private let persistsDevicePreferences: Bool + private let mirror: HostRecordMirror /// Host IDs this device has confirmed in the Keychain mirror. Lets the /// merge tell "new local host, publish it" apart from "a peer deleted @@ -36,13 +93,18 @@ final class HostStore { private static let recentSessionsKey = "MultiplexRecentSessions" private var isRefreshingFromCloud = false + /// `mirror` defaults to the Keychain for the app's own store and to a + /// private in-memory mirror for a store with an injected directory — + /// see `HostRecordMirror`. Pass one to read back what a store mirrored. init( directory overrideDirectory: URL? = nil, - knownMirroredIDs: Set? = nil + knownMirroredIDs: Set? = nil, + mirror: HostRecordMirror? = nil ) { let dir = overrideDirectory ?? FileManager.default .urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent("Multiplex", isDirectory: true) + self.mirror = mirror ?? (overrideDirectory == nil ? .keychain : .inMemory()) persistsDevicePreferences = overrideDirectory == nil try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) fileURL = dir.appendingPathComponent("hosts.json") @@ -86,7 +148,7 @@ final class HostStore { hosts.removeAll { $0.id == host.id } KeychainStore.delete(for: host.id) SSHKeyPassphraseSession.forget(for: host.id) - KeychainStore.deleteHostRecord(for: host.id) + mirror.delete(host.id) mirroredIDs.remove(host.id) persistMirroredIDs() sessionOrders.removeValue(forKey: host.id) @@ -289,9 +351,9 @@ final class HostStore { isRefreshingFromCloud = true defer { isRefreshingFromCloud = false } + let mirror = self.mirror let records = await Task.detached(priority: .utility) { - KeychainStore.migrateDeviceOnlyItems() - return KeychainStore.hostRecords() + mirror.records() }.value syncWithCloud(records: records) } @@ -377,7 +439,7 @@ final class HostStore { private func push(_ host: Host) -> Bool { guard let record = try? JSONEncoder().encode(host) else { return false } - return KeychainStore.setHostRecord(record, for: host.id) + return mirror.set(record, host.id) } private func persistMirroredIDs() { diff --git a/MultiplexTests/CustomAgentCommandTests.swift b/MultiplexTests/CustomAgentCommandTests.swift index 2b484d67..44350279 100644 --- a/MultiplexTests/CustomAgentCommandTests.swift +++ b/MultiplexTests/CustomAgentCommandTests.swift @@ -347,11 +347,13 @@ final class CustomAgentCommandTests: XCTestCase { hostname: "sync.example.com", username: "dev" ) - defer { KeychainStore.deleteHostRecord(for: host.id) } let hostsURL = directory.appendingPathComponent("hosts.json") try JSONEncoder().encode([host]).write(to: hostsURL) - let store = HostStore(directory: directory, knownMirroredIDs: []) + // A mirror of the test's own: the write must reach the mirror, and + // must not reach the simulator's real Keychain. + let mirror = HostRecordMirror.inMemory() + let store = HostStore(directory: directory, knownMirroredIDs: [], mirror: mirror) let custom = CustomAgentCommand( content: "review from every device", autoSubmit: false @@ -372,7 +374,7 @@ final class CustomAgentCommandTests: XCTestCase { [custom] ) - let mirrored = KeychainStore.hostRecords() + let mirrored = mirror.records() .compactMap { try? JSONDecoder().decode(Host.self, from: $0) } .first { $0.id == host.id } let mirroredHost = try XCTUnwrap(mirrored) diff --git a/MultiplexTests/HostSyncTests.swift b/MultiplexTests/HostSyncTests.swift index eb79cb60..eb4c861c 100644 --- a/MultiplexTests/HostSyncTests.swift +++ b/MultiplexTests/HostSyncTests.swift @@ -259,11 +259,13 @@ final class HostSyncTests: XCTestCase { defer { try? FileManager.default.removeItem(at: directory) } let seeded = host("enable-test") - defer { KeychainStore.deleteHostRecord(for: seeded.id) } let hostsURL = directory.appendingPathComponent("hosts.json") try JSONEncoder().encode([seeded]).write(to: hostsURL) - let store = HostStore(directory: directory, knownMirroredIDs: []) + // A mirror of the test's own: the write must reach the mirror, and + // must not reach the simulator's real Keychain. + let mirror = HostRecordMirror.inMemory() + let store = HostStore(directory: directory, knownMirroredIDs: [], mirror: mirror) store.setEnabled(false, for: seeded.id) XCTAssertEqual(store.hosts.map(\.isEnabled), [false]) @@ -274,7 +276,7 @@ final class HostSyncTests: XCTestCase { ) XCTAssertFalse(localHosts[0].isEnabled) - let mirrored = KeychainStore.hostRecords() + let mirrored = mirror.records() .compactMap { try? JSONDecoder().decode(Host.self, from: $0) } .first { $0.id == seeded.id } let mirroredHost = try XCTUnwrap(mirrored) @@ -300,4 +302,68 @@ final class HostSyncTests: XCTestCase { XCTAssertEqual(decoded.moshServerPath, "/opt/homebrew/bin/mosh-server") XCTAssertEqual(decoded.moshPorts, "60000:61000") } + + // MARK: The mirror is inside the test boundary + + /// A store with an injected directory used to isolate `hosts.json` and + /// still mirror every host into the simulator's real Keychain — which + /// the app then adopted, a few more hosts per test run. + @MainActor + func testAStoreWithItsOwnDirectoryNeverWritesTheRealKeychain() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("HostSyncTests-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + let store = HostStore(directory: directory, knownMirroredIDs: []) + let added = host("isolated") + store.add(added) + store.setEnabled(false, for: added.id) + + let leaked = KeychainStore.hostRecords() + .compactMap { try? JSONDecoder().decode(Host.self, from: $0) } + .contains { $0.id == added.id } + XCTAssertFalse(leaked, "an isolated store reached the real Keychain mirror") + } + + @MainActor + func testTwoIsolatedStoresDoNotShareAMirror() async throws { + func makeStore() -> (HostStore, URL) { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("HostSyncTests-\(UUID().uuidString)", isDirectory: true) + return (HostStore(directory: directory, knownMirroredIDs: []), directory) + } + let (first, firstDirectory) = makeStore() + let (second, secondDirectory) = makeStore() + defer { + try? FileManager.default.removeItem(at: firstDirectory) + try? FileManager.default.removeItem(at: secondDirectory) + } + first.add(host("only-here")) + // The second store's refresh reads ITS mirror: nothing to adopt. + await second.refreshFromCloud() + XCTAssertTrue(second.hosts.isEmpty) + // And the first reads its own write back. + await first.refreshFromCloud() + XCTAssertEqual(first.hosts.map(\.name), ["only-here"]) + } + + /// The one test that touches the real Keychain, so the mirror's SecItem + /// queries stay covered. Its payload is deliberately NOT a host record: + /// the app decodes mirror records as `Host` and skips what does not + /// parse, so even a run killed before the cleanup cannot add a host. + @MainActor + func testTheKeychainMirrorRoundTripsARecord() throws { + let id = UUID() + let payload = Data("multiplex-test-not-a-host-\(id.uuidString)".utf8) + let mirror = HostRecordMirror.keychain + defer { mirror.delete(id) } + + try XCTSkipUnless( + mirror.set(payload, id), "this runner has no usable Keychain") + XCTAssertTrue(mirror.records().contains(payload)) + XCTAssertThrowsError(try JSONDecoder().decode(Host.self, from: payload)) + + mirror.delete(id) + XCTAssertFalse(mirror.records().contains(payload)) + } } diff --git a/docs/agents/sync-and-widgets.md b/docs/agents/sync-and-widgets.md index 8aa73002..552639d3 100644 --- a/docs/agents/sync-and-widgets.md +++ b/docs/agents/sync-and-widgets.md @@ -12,6 +12,23 @@ Load-bearing decisions split from AGENTS.md. distinguishes "new local → publish" from "peer deleted → drop". No change notification exists — deck and terminal roots re-merge on scenePhase `.active`. + - ⚠ **A test store's mirror is inside its test boundary** + (`HostRecordMirror`). `HostStore(directory:)` isolated `hosts.json` + for years while still mirroring every added host into the simulator's + REAL Keychain; the app adopted them on its next launch, and by + 2026-11-16 the test simulators held 100 and 86 `box` / `devbox` hosts + (which is also why a deck screenshot showed NO SIGNAL tiles instead of + the seeded host). An injected directory now defaults to a private + in-memory mirror; a test that needs to read what a store mirrored + passes its own `.inMemory()`. Exactly one test touches the real + Keychain (`testTheKeychainMirrorRoundTripsARecord`), with a payload + that is deliberately not a decodable `Host`, so even a killed run + cannot add one. To clear a simulator that already accumulated hosts: + `xcrun simctl keychain reset`, then launch once — the merge + reads "mirrored here, gone from the cloud" as a peer's delete and + drops them (`simctl uninstall` alone does not: the mirror re-adopts). + Secrets a test saves through Add Host still land in the Keychain as + orphaned items; they are per-host-id and never become hosts. - **Widgets/Shortcuts add no background execution and must stay that way**: they declare no background mode of their own and must not grow one (the app's single `fetch` mode belongs to the agent-alert refresh — From 4f313db96a45f514207cf2d0e46649e798351a06 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Mon, 16 Nov 2026 12:25:49 +0800 Subject: [PATCH 02/13] Show, attach, and create Rex sessions as a third backend Rex (superlogical.com/rex) sessions on a host appear on the deck beside its tmux and herdr ones: one tile per session, its windows on the spine, its terminal blocks as panes, the fronted block's screen as the miniature. The rail offers + REX when discovery finds sessions, and Host Settings lists REX under Backends. Programs that report status through OSC 7501 drive RUNNING and NEEDS YOU directly. Rex ships no terminal client, so a Rex tab is a third transport beside the SSH PTY and mosh. RexSession speaks the server's own WebSocket protocol (WebSocketCodec, RexWire) through `rex __internal dial-stdio` on a PTY-less SSH channel: the screen, colors, cursor and scrollback are restored on attach, and a link lost to suspension re-attaches on return. One tab is one terminal. The tab's REX key lists the session's terminals and switches to another; Open Terminal in the tile menu opens one as its own tab. A window's split layout is not drawn. New Session's Runs on bar, a Rex tab's + TAB, and an external `action=agent&backend=rex` create a Rex session in one exec (`rex do -e --args `). What the user typed travels as JSON arguments, never as script text. The label is settled against the live list, and the setup script and launch line ride `initial_input`. Multiplex never starts a Rex server: every invocation carries REX_AUTOSTART=0, and a create with no server running says so and makes nothing. Because the default backend must answer on an idle host, Rex is never a host's default (`canBeDefault`); the record demotes it to a secondary on every path that could set it. Measured against Rex 0.1.0-preview.19 (API revision 14). The decisions and the measurements behind them are in docs/agents/backends-and-probe.md. --- AGENTS.md | 7 +- Multiplex/Design/Chassis.swift | 17 +- Multiplex/Design/GlassPrototype.swift | 8 + Multiplex/Design/Theme.swift | 8 + Multiplex/Localizable.xcstrings | 460 +++++++++ Multiplex/Models/Host.swift | 127 ++- Multiplex/Models/HostGuide.swift | 36 + Multiplex/Models/RexWire.swift | 525 ++++++++++ Multiplex/Models/ShortcutPanelContent.swift | 37 + Multiplex/Models/TerminalRoute.swift | 110 ++- Multiplex/Models/WebSocketCodec.swift | 281 ++++++ Multiplex/Services/AttentionCenter.swift | 5 +- Multiplex/Services/BackendDiscovery.swift | 14 + Multiplex/Services/ConnectionHub.swift | 150 ++- Multiplex/Services/ExternalActionRouter.swift | 50 +- Multiplex/Services/FileViewerController.swift | 8 + Multiplex/Services/RexProbe.swift | 912 ++++++++++++++++++ Multiplex/Services/RexSession.swift | 843 ++++++++++++++++ Multiplex/Services/SSHConnection.swift | 163 ++++ .../Services/TerminalSessionController.swift | 159 ++- Multiplex/Services/WidgetStatePublisher.swift | 9 +- Multiplex/Views/Deck/AddHostSheet.swift | 21 +- Multiplex/Views/Deck/BindPane.swift | 14 +- Multiplex/Views/Deck/FleetWall.swift | 128 ++- Multiplex/Views/Settings/FAQView.swift | 3 +- Multiplex/Views/Terminal/TerminalKeyBar.swift | 6 +- .../Views/Terminal/TerminalPaneUIKit.swift | 2 +- .../Views/Terminal/TerminalWindowUIKit.swift | 15 +- Multiplex/Views/Terminal/UMDBarUIKit.swift | 12 +- .../Fixtures/rex-probe-preview19.txt | 131 +++ .../rex-terminal-stream-preview19.bin | Bin 0 -> 2322 bytes MultiplexTests/RexProbeTests.swift | 804 +++++++++++++++ MultiplexTests/RexSessionTests.swift | 682 +++++++++++++ MultiplexTests/RexWireTests.swift | 490 ++++++++++ docs/agents/architecture.md | 13 +- docs/agents/backends-and-probe.md | 322 ++++++- docs/agents/e2e-headless.md | 11 +- docs/store-metadata.md | 15 + fastlane/testflight-whats-new.txt | 13 + 39 files changed, 6477 insertions(+), 134 deletions(-) create mode 100644 Multiplex/Models/RexWire.swift create mode 100644 Multiplex/Models/WebSocketCodec.swift create mode 100644 Multiplex/Services/RexProbe.swift create mode 100644 Multiplex/Services/RexSession.swift create mode 100644 MultiplexTests/Fixtures/rex-probe-preview19.txt create mode 100644 MultiplexTests/Fixtures/rex-terminal-stream-preview19.bin create mode 100644 MultiplexTests/RexProbeTests.swift create mode 100644 MultiplexTests/RexSessionTests.swift create mode 100644 MultiplexTests/RexWireTests.swift diff --git a/AGENTS.md b/AGENTS.md index ab4bc6e6..ba28e8d3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,6 @@ Multiplex — a spatial SSH terminal built around remote **tmux** (with herdr -as an optional second backend); visionOS-first, iPadOS alongside. The deck is +as an optional second backend, and Rex sessions shown, attached and created); +visionOS-first, iPadOS alongside. The deck is a fleet-wide monitor wall: every host probes concurrently, every session renders as a live capture-pane tile, and each attach opens its own terminal window (a scene on visionOS / Stage Manager on iPad). Product tour: @@ -89,8 +90,8 @@ approaches. Don't re-litigate a recorded decision without new facts. and tab moves, keyboard avoidance, secret fields, held-backspace filler. - `links-and-viewers.md` — link/path confirmation, ⌗ viewport, ▤ file viewer. - `backends-and-probe.md` — tmux invocation facts, mixed tmux+herdr hosts, - the herdr adaptation, session creation (setup scripts, per-host tmux conf, - systemd-run), file attach/drop. + the herdr adaptation, the Rex adaptation (probe, attach, mint), session creation + (setup scripts, per-host tmux conf, systemd-run), file attach/drop. - `agent-helpers.md` — CLI-agent detection, helper chips, launch model override, keychain-locked tip, HISTORY/jump. - `lifecycle-and-attention.md` — disabled hosts, session resume, keep screen on, background diff --git a/Multiplex/Design/Chassis.swift b/Multiplex/Design/Chassis.swift index 49f5f395..d5e4d967 100644 --- a/Multiplex/Design/Chassis.swift +++ b/Multiplex/Design/Chassis.swift @@ -17,11 +17,20 @@ enum UIKitChassis { } /// `bezel` for a session tile, tinted when the tile has to say which /// multiplexer it came from. Only a MIXED host reaches the tinted branch - /// — see `TallyPalette.herdrBezel`. + /// — see `TallyPalette.herdrBezel`. tmux keeps the plain bezel: it is + /// the tile every other backend is told apart from. static func tileBezel(backend: Host.SessionBackend, tinted: Bool) -> UIColor { - guard tinted, backend == .herdr else { return bezel } - return GlassPrototype.enabled - ? GlassPrototype.herdrStrata : TallyPalette.herdrBezel + guard tinted else { return bezel } + switch backend { + case .tmux: + return bezel + case .herdr: + return GlassPrototype.enabled + ? GlassPrototype.herdrStrata : TallyPalette.herdrBezel + case .rex: + return GlassPrototype.enabled + ? GlassPrototype.rexStrata : TallyPalette.rexBezel + } } static var bezelHi: UIColor { GlassPrototype.enabled ? GlassPrototype.line : TallyPalette.bezelHi diff --git a/Multiplex/Design/GlassPrototype.swift b/Multiplex/Design/GlassPrototype.swift index 9f96d96c..7b87bb3b 100644 --- a/Multiplex/Design/GlassPrototype.swift +++ b/Multiplex/Design/GlassPrototype.swift @@ -83,6 +83,11 @@ enum GlassPrototype { static let herdrStrataMaterial = UIColor( red: 203 / 255, green: 166 / 255, blue: 247 / 255, alpha: 0.10 ) + /// The strata step in Rex's cool blue (`TallyPalette.rexBezel` carries + /// the rationale) — the same one-step lift as the mauve above. + static let rexStrataMaterial = UIColor( + red: 137 / 255, green: 196 / 255, blue: 255 / 255, alpha: 0.09 + ) /// Hairlines and resting borders (replaces `bezelHi`). static let lineMaterial = UIColor(white: 1, alpha: 0.11) /// Active borders (lit spine segment, active tab). Part of the frozen @@ -116,6 +121,9 @@ enum GlassPrototype { static let herdrStrata = material( herdrStrataMaterial, fallback: TallyPalette.herdrBezel ) + static let rexStrata = material( + rexStrataMaterial, fallback: TallyPalette.rexBezel + ) static let line = material(lineMaterial, fallback: TallyPalette.bezelHi) static let lineHi = material(lineHiMaterial, fallback: TallyPalette.bezelHi) static let screenGlass = material(screenGlassMaterial, fallback: TallyPalette.screen) diff --git a/Multiplex/Design/Theme.swift b/Multiplex/Design/Theme.swift index cc25f1db..7d3426bb 100644 --- a/Multiplex/Design/Theme.swift +++ b/Multiplex/Design/Theme.swift @@ -33,6 +33,14 @@ enum TallyPalette { /// which is also what pins the blue > red > green ordering that makes it /// violet rather than merely cool). static let herdrBezel = UIColor(light: 0xF6F0FF, dark: 0x2C2833) + /// `bezel` for a Rex tile, under the same gate and the same rule: a + /// different TINT at `bezel`'s own lightness (within 1/255 in both + /// polarities), never a raised tile. Rex publishes no palette to borrow, + /// so the hue is chosen for the one job it has — to be unmistakable + /// beside tmux's neutral bezel and herdr's mauve. A cool blue: blue over + /// green over red, where mauve runs blue over red over green + /// (`testTheRexWashMatchesBezelsLightnessAndIsNotMauve` pins both). + static let rexBezel = UIColor(light: 0xEAF4FF, dark: 0x1F2A33) static let tally = UIColor(light: 0xC13439, dark: 0xE5484D) static let caution = UIColor(light: 0x966618, dark: 0xE0A33E) diff --git a/Multiplex/Localizable.xcstrings b/Multiplex/Localizable.xcstrings index d845b829..74893e5e 100644 --- a/Multiplex/Localizable.xcstrings +++ b/Multiplex/Localizable.xcstrings @@ -193,6 +193,28 @@ } } }, + "%@ reported “%@” without the id needed to attach it. Try again after the next refresh." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ reported “%2$@” without the id needed to attach it. Try again after the next refresh." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@が報告した「%2$@」には、アタッチに必要なIDがありません。次の更新後にもう一度お試しください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ 回報的「%2$@」缺少連接所需的 ID。請在下次重新整理後再試一次。" + } + } + } + }, ", %lld times" : { "localizations" : { "ja" : { @@ -1648,6 +1670,374 @@ } } }, + "A Rex tile opens one terminal: the one its session is showing. New Rex sessions need Rex already running on the host, so Rex is never the default." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexタイルは、そのセッションが表示しているターミナルを1つ開きます。新しいRexセッションを作成するには、ホストでRexがすでに実行されている必要があるため、Rexが新規セッションのデフォルトの実行先になることはありません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 方塊會開啟一個終端機:也就是該工作階段目前顯示的那一個。主機上必須已有 Rex 在執行,才能建立新的 Rex 工作階段,因此 Rex 不會是新工作階段的預設後端。" + } + } + } + }, + "All of them are shown, each tile marked with the backend it came from. Every extra backend adds a probe of its own to each deck refresh." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "すべてが表示され、各タイルにはどのバックエンド由来かが示されます。バックエンドが1つ増えるごとに、Deckの更新のたびにプローブが1回増えます。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "全部都會顯示,每個方塊都標示它來自哪個後端。每多一個後端,Deck 每次重新整理就會多一次探測。" + } + } + } + }, + "Couldn't attach the Rex session. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexセッションにアタッチできませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法連接 Rex 工作階段。%@" + } + } + } + }, + "Couldn't Open Session" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "セッションを開けませんでした" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法開啟工作階段" + } + } + } + }, + "Couldn't reach the Rex server. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーに接続できませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法連上 Rex 伺服器。%@" + } + } + } + }, + "Open Terminal" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナルを開く" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "開啟終端機" + } + } + } + }, + "Package installs, ~/.local/bin, and the Rex app on a Mac are already on the probe's PATH." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "パッケージによるインストール、~/.local/bin、MacのRexアプリはすでにプローブのPATHに含まれています。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "套件安裝、~/.local/bin 與 Mac 上的 Rex App 已在偵測用的 PATH 上。" + } + } + } + }, + "rex answered with exit status %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "rexが終了ステータス%@を返しました" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "rex 以結束狀態 %@ 回應" + } + } + } + }, + "Rex closed the terminal stream: %@." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexがターミナルストリームを閉じました:%@。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 關閉了終端機串流:%@。" + } + } + } + }, + "terminal %lld" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナル%lld" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "終端機 %lld" + } + } + } + }, + "The connection to the Rex server ended." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーとの接続が終了しました。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "與 Rex 伺服器的連線已結束。" + } + } + } + }, + "The connection to the Rex server was lost." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーとの接続が失われました。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "與 Rex 伺服器的連線已中斷。" + } + } + } + }, + "The Rex server answered the stream handshake unreadably." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーからのストリームハンドシェイクの応答を読み取れませんでした。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器對串流交握的回應無法讀取。" + } + } + } + }, + "The Rex server closed the connection before answering." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーが応答する前に接続を閉じました。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器在回應前就關閉了連線。" + } + } + } + }, + "The Rex server did not answer in time." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーが時間内に応答しませんでした。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器未在時限內回應。" + } + } + } + }, + "The Rex server issued no usable stream ticket." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーが有効なストリームチケットを発行しませんでした。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器沒有發出可用的串流票證。" + } + } + } + }, + "The Rex server refused the connection (%@)." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーが接続を拒否しました(%@)。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器拒絕了連線(%@)。" + } + } + } + }, + "The Rex server refused the terminal stream: %@." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーがターミナルストリームを拒否しました:%@。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器拒絕了終端機串流:%@。" + } + } + } + }, + "The Rex server refused: %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexサーバーが拒否しました:%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 伺服器拒絕了要求:%@" + } + } + } + }, + "This Rex session has no terminal to open." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このRexセッションには開けるターミナルがありません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "這個 Rex 工作階段沒有可開啟的終端機。" + } + } + } + }, + "This Rex session no longer exists." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このRexセッションはもう存在しません。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "這個 Rex 工作階段已不存在。" + } + } + } + }, + "unreadable rex probe response" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "rexの応答を読み取れません" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法讀取的 rex 探測回應" + } + } + } + }, + "window %lld" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ウインドウ%lld" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "視窗 %lld" + } + } + } + }, "✳ AGENT HELPERS · PRO" : { "localizations" : { "ja" : { @@ -9450,6 +9840,28 @@ } } }, + "No %@ server is running on %@, and Multiplex doesn’t start one. Start %@ there, then try again." : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "No %1$@ server is running on %2$@, and Multiplex doesn’t start one. Start %3$@ there, then try again." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%2$@で%1$@サーバーが実行されておらず、Multiplexは起動しません。ホストで%3$@を起動してから、もう一度お試しください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%2$@ 上沒有執行中的 %1$@ 伺服器,而 Multiplex 不會代為啟動。請先在主機上啟動 %3$@,然後再試一次。" + } + } + } + }, "No answer from %@ after %lld seconds — check the address and port, and that the host is reachable from this network." : { "localizations" : { "en" : { @@ -13300,6 +13712,22 @@ } } }, + "Show Rex terminals" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexのターミナルを表示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "顯示 Rex 終端機" + } + } + } + }, "Show only changed files" : { "localizations" : { "ja" : { @@ -14365,6 +14793,22 @@ } } }, + "Switch Terminal" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナルを切り替え" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "切換終端機" + } + } + } + }, "Switch this host to the herdr backend" : { "localizations" : { "ja" : { @@ -14483,6 +14927,22 @@ } } }, + "terminal" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナル" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "終端機" + } + } + } + }, "Tab" : { "localizations" : { "ja" : { diff --git a/Multiplex/Models/Host.swift b/Multiplex/Models/Host.swift index a70df021..fa2185db 100644 --- a/Multiplex/Models/Host.swift +++ b/Multiplex/Models/Host.swift @@ -25,6 +25,31 @@ struct Host: Identifiable, Codable, Hashable { enum SessionBackend: String, Codable, CaseIterable { case tmux case herdr + /// Rex (superlogical.com/rex). Rex ships no terminal client — no + /// `rex attach`; its sessions are rendered by a native app speaking + /// the server's WebSocket API — so Multiplex is that client: the + /// deck shows a Rex session's tile (`RexProbe`), a tile attaches + /// one of its terminals as a tab (`RexSession`), and New Session + /// creates one (`RexProbe.mintCommand`). The one thing Rex cannot be + /// is a host's default — `canBeDefault`. + case rex + + /// Whether this backend can be a host's default + /// (`Host.sessionBackend`). The default answers every request that + /// names no backend — New Session, the Signal check, an external + /// action — and it has to answer on a host with nothing running: + /// tmux and herdr bring their own server up with the first + /// session. Multiplex never starts a Rex server (`RexProbe`), so a + /// Rex session can be created only while one is already running. + /// That is fine for a backend the user picks and wrong for the one + /// everything falls back to, so Rex is only ever a secondary + /// (`Host.sessionBackend`'s `didSet` enforces it). Its sessions are + /// still shown, attached, created and closed like any other's. + var canBeDefault: Bool { self != .rex } + + /// The backends a host's default can be — what the "New sessions + /// run on" bars and the Bind pane offer. + static let defaultCases = allCases.filter(\.canBeDefault) /// Whether the probe can state how many clients a session has. /// tmux answers `#{session_attached}`; herdr 0.7.5 / protocol 17 @@ -33,8 +58,10 @@ struct Host: Identifiable, Codable, Hashable { /// and the bundled API schema — only the socket-only /// `client.window_title` reply leaks a `no_foreground_client` /// reason, and no CLI verb reaches it), so its records carry - /// `clientCount == 0` whatever is really attached. - var reportsClientCount: Bool { self == .tmux } + /// `clientCount == 0` whatever is really attached. Rex answers + /// `client.list` per session; the probe counts the attached APP + /// clients (a Rex window showing the session), never its own CLI. + var reportsClientCount: Bool { self != .herdr } /// Whether a session is live right now — said only where it can be /// verified. tmux counts every client on the host. herdr can answer @@ -42,9 +69,15 @@ struct Host: Identifiable, Codable, Hashable { /// open terminal tab means. A shell on the host attached to the same /// herdr session therefore stays invisible; the tile understates /// rather than guesses, the same choice its missing client count and - /// session age already make. + /// session age already make. Rex counts its APP clients, and this + /// app attaches as kind `other` on purpose (`RexWire.hello`), so its + /// own open tab is counted separately. func isSessionLive(clientCount: Int, hasOpenTab: Bool) -> Bool { - reportsClientCount ? clientCount > 0 : hasOpenTab + switch self { + case .tmux: clientCount > 0 + case .herdr: hasOpenTab + case .rex: clientCount > 0 || hasOpenTab + } } /// The one reader of a backend written by a human or an automation — @@ -103,8 +136,27 @@ struct Host: Identifiable, Codable, Hashable { /// Promoting a backend to primary retires it as a secondary in the same /// write, so the record can never point at a backend it also lists as an /// extra — see `secondaryBackends`. + /// + /// The primary can always create a session. It is where New Session + /// lands, what the Signal check asks, and what every external action + /// defaults to — none of which a backend that needs its server started + /// by someone else (`SessionBackend.canBeDefault`) can promise. So a + /// write naming one keeps the old primary and shows the newcomer as a + /// secondary instead. Enforced here, like the rule above, so no mint + /// path has to ask whether its default can answer on an idle host. var sessionBackend: SessionBackend = .tmux { - didSet { secondaryBackends.remove(sessionBackend) } + didSet { + if !sessionBackend.canBeDefault { + let watched = sessionBackend + // Restore the primary FIRST: `secondaryBackends`' own + // observer strips whatever the primary is at that moment, + // and would strip the newcomer straight back out. Assigning + // inside this observer does not re-enter it. + sessionBackend = oldValue + secondaryBackends.insert(watched) + } + secondaryBackends.remove(sessionBackend) + } } /// Backends beyond `sessionBackend` whose sessions ALSO appear on this /// host's deck. Empty is the shipping default and the only state that @@ -124,12 +176,12 @@ struct Host: Identifiable, Codable, Hashable { /// probe, because the probe command itself is backend-shaped — the same /// reasoning that already puts `sessionBackend` there. /// - /// ⚠ A `Set` encodes in iteration order, which Swift seeds per process. - /// That is stable today only because two backends exist, so this holds - /// at most one element and has exactly one encoding — and `hosts.json` - /// is written with `.sortedKeys` precisely to stay byte-stable. Adding a - /// third backend must therefore also sort this on the way out, or every - /// launch will rewrite the file and the mirrored Keychain record. + /// ⚠ A `Set` encodes in iteration order, which Swift seeds per process, + /// and with three backends this can hold two — so it is sorted on the + /// way out (the `KeyedEncodingContainer` overload at the foot of this + /// file). `hosts.json` is written with `.sortedKeys` precisely to stay + /// byte-stable; an unsorted set would rewrite the file and the mirrored + /// Keychain record on every launch. /// /// The primary is never also a secondary — `monitoredBackends` would /// list it twice, and a stray copy makes `connectionModelConfiguration` @@ -221,27 +273,42 @@ struct Host: Identifiable, Codable, Hashable { private(set) var enabled: Set init(preferred: SessionBackend = .tmux, also secondaries: Set = []) { - self.preferred = preferred - enabled = secondaries.union([preferred]) + // The default can always be one (`Host.sessionBackend`'s rule): a + // backend that cannot, handed in as the default, stays checked + // and the first that can leads instead. + self.preferred = preferred.canBeDefault + ? preferred + : SessionBackend.defaultCases.first(where: secondaries.contains) ?? .tmux + enabled = secondaries.union([preferred, self.preferred]) } var secondaries: Set { enabled.subtracting([preferred]) } var isMixed: Bool { enabled.count > 1 } + /// The checked backends the default can be, in canonical order — + /// the "New sessions run on" bar's choices. Rex is checked without + /// ever appearing here. + var defaultChoices: [SessionBackend] { + SessionBackend.defaultCases.filter(enabled.contains) + } /// Check or uncheck backends. Unchecking the current default promotes - /// whatever remains, so the record can never point at a backend it no - /// longer shows; an empty set is refused rather than stored. + /// whatever remains that can be one, so the record can never point at a + /// backend it no longer shows. Refused rather than stored: an empty + /// set, and a set with nothing that can be the default — a host + /// showing only Rex would have none at all. mutating func setEnabled(_ backends: Set) { - guard !backends.isEmpty else { return } + guard backends.contains(where: \.canBeDefault) else { return } enabled = backends guard !backends.contains(preferred) else { return } - preferred = SessionBackend.allCases.first(where: backends.contains) ?? preferred + preferred = SessionBackend.defaultCases.first(where: backends.contains) ?? preferred } /// Move the default without changing what is checked — the old /// default stays on as a secondary. A backend that is not checked is - /// checked by being chosen. + /// checked by being chosen. Naming a backend that cannot be the + /// default changes nothing. mutating func setPreferred(_ backend: SessionBackend) { + guard backend.canBeDefault else { return } preferred = backend enabled.insert(backend) } @@ -341,16 +408,21 @@ extension Host { // Decode via the raw string so an unknown value — a record written // by a newer schema that grew a third backend — degrades to tmux // instead of throwing this host (and with it the whole list) away. - sessionBackend = (try container.decodeIfPresent(String.self, forKey: .sessionBackend)) + let primary = (try container.decodeIfPresent(String.self, forKey: .sessionBackend)) .flatMap(SessionBackend.init(rawValue:)) ?? .tmux + // Observers don't run during initialization, so the two record rules + // are repeated here: a primary that cannot be one degrades to tmux and + // stays on as a secondary, and the primary is never also a secondary. + sessionBackend = primary.canBeDefault ? primary : .tmux // Same rule, applied per element: a record from a schema with a - // third backend degrades by dropping that entry instead of throwing + // newer backend degrades by dropping that entry instead of throwing // the host away. An older build simply ignores the key and behaves // as it always did — the safe direction. secondaryBackends = Set( (try container.decodeIfPresent([String].self, forKey: .secondaryBackends) ?? []) .compactMap(SessionBackend.init(rawValue:)) - ).subtracting([sessionBackend]) + ).union(primary.canBeDefault ? [] : [primary]) + .subtracting([sessionBackend]) moshServerPath = try container.decodeIfPresent(String.self, forKey: .moshServerPath) moshPorts = try container.decodeIfPresent(String.self, forKey: .moshPorts) workingDirs = try container.decodeIfPresent([String].self, forKey: .workingDirs) ?? [] @@ -397,3 +469,16 @@ extension Host { connectionModelConfiguration == other.connectionModelConfiguration } } + +extension KeyedEncodingContainer { + /// A backend set always encodes sorted by raw value. `Set` iterates in + /// an order Swift seeds per process, so the synthesized encoder would + /// write `["herdr","rex"]` on one launch and `["rex","herdr"]` on the + /// next — rewriting `hosts.json` and the mirrored Keychain record for a + /// host nobody touched. Synthesized `encode(to:)` bodies resolve their + /// `encode(_:forKey:)` calls like any other code, so this more specific + /// overload is what `Host` picks up; decoding needs no counterpart. + mutating func encode(_ value: Set, forKey key: Key) throws { + try encode(value.map(\.rawValue).sorted(), forKey: key) + } +} diff --git a/Multiplex/Models/HostGuide.swift b/Multiplex/Models/HostGuide.swift index f4823923..750d522d 100644 --- a/Multiplex/Models/HostGuide.swift +++ b/Multiplex/Models/HostGuide.swift @@ -38,6 +38,10 @@ enum HostGuide { switch backend { case .tmux: tmuxInstall case .herdr: herdrInstall + // Rex is never the primary: no dead tile and no failed mint speaks + // for it, so there is no install road to hand over. (Its packages + // also come from a per-distribution repository, not one line.) + case .rex: [] } } @@ -64,6 +68,22 @@ enum HostGuide { localized: "or change this host’s backend in Host Settings.") } + /// A mint that failed because the backend's server isn't running and + /// Multiplex won't start it — Rex, whose server belongs to the Rex app + /// on the host (`RexProbe`). Says what to do there instead of sending + /// the user after the connection, which is fine. + static func serverNotRunningMessage( + _ backend: Host.SessionBackend, hostName: String + ) -> String { + // The product's name, not the binary's: this is about an app the + // user opens, where `backendMissingMessage` is about a command. + let name = backend == .rex ? "Rex" : backend.rawValue + return String(localized: """ + No \(name) server is running on \(hostName), and Multiplex doesn’t \ + start one. Start \(name) there, then try again. + """) + } + /// Why a default install needs no further host setup: both probes /// prepend these directories (`TmuxProbe.pathPrefix`, /// `HerdrProbe.pathPrefix`). Shared so the tile's INSTALL GUIDE and the @@ -78,9 +98,25 @@ enum HostGuide { Homebrew, ~/.local/bin, and ~/.cargo/bin installs are already on \ the probe's PATH. """) + case .rex: + String(localized: """ + Package installs, ~/.local/bin, and the Rex app on a Mac are \ + already on the probe's PATH. + """) } } + /// What showing Rex sessions means, said wherever they can be switched + /// on — the rail's offer confirmation and Host Settings' Backend detail + /// — so neither promises more than the app does: one terminal per tab, + /// and new sessions only where a Rex server is already running, which + /// is also why it is missing from the default's choices right below. + static let rexSessionsNote = String(localized: """ + A Rex tile opens one terminal: the one its session is showing. \ + New Rex sessions need Rex already running on the host, so Rex is \ + never the default. + """) + /// What opting a host into a SECOND backend costs — the measured fact /// behind asking at all rather than escalating silently (a full second /// probe is ~25 KB/tick for herdr against tmux's ~3.5 KB; see diff --git a/Multiplex/Models/RexWire.swift b/Multiplex/Models/RexWire.swift new file mode 100644 index 00000000..3cd3332a --- /dev/null +++ b/Multiplex/Models/RexWire.swift @@ -0,0 +1,525 @@ +import Foundation + +/// The Rex server's wire protocol, as far as attaching one terminal needs it: +/// the control connection's JSON messages, the data connection's binary +/// handshake, and the terminal stream. Pure — `RexSession` owns the sockets. +/// +/// Written against API revision 14 (Rex 0.1.0-preview.19, 2026-11-16). The +/// authority is the server's own `GET /llms.txt`, not the website docs; what +/// is restated here is what was also exercised against a live server: +/// - Both connections are WebSockets (`WebSocketCodec`): `/api/control` with +/// subprotocol `rex.control.v1`, every message one JSON object in a text +/// frame; `/api/data` with `rex.data.terminal.v1`, binary frames only. +/// - A client sends one `hello` within 5 seconds, then `request`s. The +/// server answers `welcome`, a `response` per request (matched by `id`), +/// and unsolicited `event`s. A newer server translates to the revision the +/// hello asked for, so pinning 14 is what keeps this parser's shapes true. +/// - `session.attach` joins a session; `data.connect` needs that attachment +/// and issues a one-use ticket (16 bytes as 22 base64url characters). +/// - A data connection opens with HELLO `0x01 + ticket`; the server answers +/// WELCOME (`0x81`, 32 bytes, ending in a 64-bit little-endian nonce that +/// is never zero) or REJECT (`0x82 + reason`). After that every binary +/// message is stream bytes; message boundaries mean nothing. +/// - Bytes flow server → client only. Typing is the control connection's +/// `com.superlogical.terminal.write`. +enum RexWire { + static let controlPath = "/api/control" + static let controlSubprotocol = "rex.control.v1" + static let dataPath = "/api/data" + static let terminalSubprotocol = "rex.data.terminal.v1" + static let apiRevision = 14 + static let terminalCreator = "com.superlogical.terminal" + + // MARK: - Control: outbound + + /// The first message on a control connection. Kept far under the + /// protocol's 512-byte ceiling for a hello. + /// + /// ⚠ The kind is `other`, deliberately NOT `app`. Rex's CLI and its + /// agent skill aim client actions (`rex do pane.split`, "switch my Mac + /// to this session") at "the app client when exactly one is connected"; + /// a second client calling itself an app would make every one of those + /// ambiguous for as long as a Multiplex tab is attached. It also keeps + /// this client out of the deck's own count of app clients, which is + /// what the LIVE lamp reads (`SessionBackend.isSessionLive`). + static func hello(clientVersion: String) -> Data { + json([ + "type": "hello", + "api_revision": apiRevision, + "client": [ + "kind": "other", + "platform": "ios", + "name": "Multiplex", + "version": clientVersion, + ], + ]) + } + + static func request(id: String, method: String, payload: [String: Any]?) -> Data { + var message: [String: Any] = ["type": "request", "id": id, "method": method] + if let payload { message["payload"] = payload } + return json(message) + } + + /// A block method call: the block's own arguments ride under `args`. + static func blockPayload( + sessionID: String, blockID: String, args: [String: Any] = [:] + ) -> [String: Any] { + ["session_id": sessionID, "block_id": blockID, "args": args] + } + + private static func json(_ object: [String: Any]) -> Data { + // Sorted keys so a request is byte-stable — for the tests, and for + // anyone reading a capture. + (try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys])) + ?? Data("{}".utf8) + } + + // MARK: - Control: inbound + + struct ServerError: Error, Equatable { + var code: String + var message: String + var status: Int + } + + enum Inbound { + case welcome(clientID: String?) + /// `payload` is the method's result as a JSON object (empty for a + /// result that is not an object). + case response(id: String, result: Result<[String: Any], ServerError>) + /// A session event unwrapped to its innermost type and fields. + case event(type: String, fields: [String: Any]) + /// A `type` this client does not know. The protocol says to skip it. + case unknown + } + + static func decodeInbound(_ text: Data) -> Inbound? { + guard let object = (try? JSONSerialization.jsonObject(with: text)) as? [String: Any], + let type = object["type"] as? String + else { return nil } + switch type { + case "welcome": + guard object["protocol"] as? String == controlSubprotocol else { return nil } + let client = object["client"] as? [String: Any] + return .welcome(clientID: client?["id"] as? String) + case "response": + guard let id = object["id"] as? String else { return nil } + if let error = object["error"] as? [String: Any] { + return .response(id: id, result: .failure(ServerError( + code: error["code"] as? String ?? "internal", + message: error["message"] as? String ?? "", + status: error["status"] as? Int ?? 500 + ))) + } + return .response( + id: id, result: .success(object["payload"] as? [String: Any] ?? [:])) + case "event": + guard let payload = object["payload"] as? [String: Any] else { return .unknown } + return unwrapEvent(payload) + default: + return .unknown + } + } + + /// A session event arrives wrapped in `session_event`; this client only + /// ever attaches to one session, so the wrapper carries nothing it needs. + private static func unwrapEvent(_ payload: [String: Any]) -> Inbound { + guard let type = payload["type"] as? String else { return .unknown } + let fields = payload["payload"] as? [String: Any] ?? [:] + if type == "session_event", let inner = fields["event"] as? [String: Any] { + return unwrapEvent(inner) + } + return .event(type: type, fields: fields) + } + + // MARK: - Session view → the block to attach + + /// One terminal block a session shows, in window (tab) order. + struct Block: Equatable, Sendable { + var id: String + var label: String + var windowID: String + var windowLabel: String + /// The window's place in tab order, counted from one. + var windowPosition: Int = 1 + /// The window's focused block. + var isFocused: Bool + /// In the session's active window. + var isFronted: Bool + } + + /// Every terminal block of a `session.view` (or the `view` inside a + /// `session.attach` result). Other block types are not terminals and + /// are left out. + static func terminalBlocks(inView view: [String: Any]) -> [Block] { + let activeWindow = view["active_window_id"] as? String + var blocks: [Block] = [] + for (offset, window) in (view["windows"] as? [[String: Any]] ?? []).enumerated() { + guard let windowID = window["window_id"] as? String else { continue } + let focused = window["focused_block_id"] as? String + for layer in window["layers"] as? [[String: Any]] ?? [] { + for block in layer["blocks"] as? [[String: Any]] ?? [] { + guard block["creator_name"] as? String == terminalCreator, + let id = block["block_id"] as? String + else { continue } + blocks.append(Block( + id: id, + label: block["label"] as? String ?? "", + windowID: windowID, + windowLabel: window["label"] as? String ?? "", + windowPosition: offset + 1, + isFocused: id == focused, + isFronted: windowID == activeWindow + )) + } + } + } + return blocks + } + + /// The block a fresh attach lands on: the one named, else the block the + /// session is fronting (active window, focused block), else the first + /// focused block, else the first terminal at all. nil means the session + /// has no terminal to show. + static func attachTarget(in blocks: [Block], preferring blockID: String?) -> Block? { + if let blockID, let named = blocks.first(where: { $0.id == blockID }) { return named } + return blocks.first { $0.isFronted && $0.isFocused } + ?? blocks.first(where: \.isFronted) + ?? blocks.first(where: \.isFocused) + ?? blocks.first + } + + // MARK: - Working directory + + /// Where a terminal's program is, out of a `com.superlogical.terminal + /// .process` result: the foreground process's directory — tmux's + /// `pane_current_path`, and while an agent runs there, the agent's own + /// — else the directory of the program the terminal started. The value + /// is respliced into a shell line and aimed at by SFTP, so only a clean + /// absolute path answers; nil is the $HOME fallback every backend has. + static func workingDirectory(inProcess result: [String: Any]) -> String? { + [result["foreground"], result["child"]] + .compactMap { ($0 as? [String: Any])?["cwd"] as? String } + .first(where: isSpliceablePath) + } + + private static func isSpliceablePath(_ path: String) -> Bool { + path.hasPrefix("/") && path.utf8.count <= 4096 + && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) + } + + // MARK: - Switch Terminal list + + /// The rows of a Rex tab's Switch Terminal list — every terminal of the + /// session, in window order, as the shortcut panel's shared choice + /// record. A row reads `window — terminal`; a window nobody named (an + /// empty label, or Rex's generated `Window `) is `window N`, + /// and a terminal whose label says nothing more than its window is the + /// window alone. `isActive` marks the one this tab is showing. + static func terminalChoices( + in blocks: [Block], showing blockID: String? + ) -> [TmuxWindowChoice] { + blocks.enumerated().map { offset, block in + let label = block.windowLabel.trimmingCharacters(in: .whitespaces) + let generated = "Window " + block.windowID.suffix(8) + let window = label.isEmpty || label == generated + ? String(localized: "window \(block.windowPosition)") + : label + let terminal = block.label.trimmingCharacters(in: .whitespaces) + let name = terminal.isEmpty || terminal.caseInsensitiveCompare(window) == .orderedSame + ? window + : "\(window) — \(terminal)" + return TmuxWindowChoice( + tmuxID: block.id, index: offset + 1, + isActive: block.id == blockID, name: name) + } + } + + // MARK: - Data connection handshake + + /// HELLO: `0x01`, then the ticket's 16 bytes. nil for a ticket that is + /// not 16 bytes of base64url — never send a guess. + static func dataHello(ticket: String) -> Data? { + var base64 = ticket + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) + guard let bytes = Data(base64Encoded: base64), bytes.count == 16 else { return nil } + return Data([0x01]) + bytes + } + + enum DataReply: Equatable { + /// `nonce` marks the server's own messages inside the stream. + case welcome(nonce: UInt64) + case reject(reason: UInt8) + } + + static func parseDataReply(_ message: Data) -> DataReply? { + let bytes = [UInt8](message) + switch bytes.first { + case 0x81: + guard bytes.count == 32 else { return nil } + var nonce: UInt64 = 0 + for index in (24..<32).reversed() { nonce = nonce << 8 | UInt64(bytes[index]) } + // Zero is never a valid nonce; accepting it would make every + // unmarked APC in the stream look like the server's. + return nonce == 0 ? nil : .welcome(nonce: nonce) + case 0x82: + guard bytes.count >= 2 else { return nil } + return .reject(reason: bytes[1]) + default: + return nil + } + } + + /// What a REJECT reason means, for the tab's ended line. + static func rejectDescription(_ reason: UInt8) -> String { + switch reason { + case 0x01: "the ticket was not accepted" + case 0x02: "another connection already has this terminal" + case 0x03: "the terminal is no longer available" + case 0x04: "the server is at its connection limit" + case 0x05: "the handshake was malformed or late" + case 0x06: "the server failed" + case 0x07: "the server expected a different subprotocol" + default: "reason \(reason)" + } + } +} + +/// Splits a Rex terminal stream into what the terminal emulator should draw +/// and what the server said about the terminal. +/// +/// The stream is: a snapshot of the terminal **in Ghostty's binary snapshot +/// format** (`GHOSTSNP…`), then everything the program writes, with the +/// server's own messages spliced in as `ESC _ rex1;; ESC \`. +/// +/// ⚠ The snapshot is why this type exists. SwiftTerm cannot read it — fed to +/// the emulator it is a page of garbage — so it is DROPPED, and the screen +/// is bootstrapped from `com.superlogical.terminal.format` instead +/// (`RexSession`). Its length is not stated anywhere, but the protocol +/// guarantees a `resize` message "comes right after the snapshot", so +/// everything before the first marker carrying the right nonce is snapshot. +/// The nonce is 64 random bits minted per stream, which is what makes +/// scanning binary for it sound. +/// +/// Pure and incremental: stream bytes arrive in arbitrary pieces. +struct RexTerminalStream { + enum Event: Equatable { + /// Program output, in order — what the emulator is fed. + case output(Data) + /// The terminal's size, and the client that owns it (nil for none). + case resize(cols: Int, rows: Int, owner: String?) + /// The terminal's program exited; no more output follows. + case childExited(code: Int) + } + + private let marker: Data + private static let terminator = Data([0x1B, 0x5C]) + /// A server message is a small JSON object. Past this, an unterminated + /// "message" is treated as program output rather than held forever. + private static let maxMessageBytes = 256 * 1024 + + private var pending = Data() + private var pastSnapshot = false + + init(nonce: UInt64) { + marker = Data([0x1B, 0x5F]) + Data("rex1;\(nonce);".utf8) + } + + /// Whether the snapshot has been passed — the moment the stream starts + /// carrying program output. + var isLive: Bool { pastSnapshot } + + mutating func consume(_ chunk: Data) -> [Event] { + pending.append(chunk) + var events: [Event] = [] + var output = Data() + + func flush() { + guard !output.isEmpty else { return } + events.append(.output(output)) + output = Data() + } + + while true { + guard let found = pending.range(of: marker) else { + // No marker yet. Everything is output (or snapshot) except a + // tail that could be the START of a marker split across two + // chunks — that waits for the next one. + let keep = Self.partialMarkerSuffix(of: pending, marker: marker) + let ready = pending.count - keep + if pastSnapshot { output.append(pending.prefix(ready)) } + pending = Data(pending.suffix(keep)) + break + } + if pastSnapshot { + output.append(pending[pending.startIndex.. Int { + let limit = min(data.count, marker.count - 1) + guard limit > 0 else { return 0 } + for length in stride(from: limit, through: 1, by: -1) + where data.suffix(length).elementsEqual(marker.prefix(length)) { + return length + } + return 0 + } + + private static func event(from json: Data) -> Event? { + guard let object = (try? JSONSerialization.jsonObject(with: json)) as? [String: Any], + let type = object["type"] as? String + else { return nil } + switch type { + case "resize": + guard let cols = object["cols"] as? Int, let rows = object["rows"] as? Int + else { return nil } + return .resize(cols: cols, rows: rows, owner: object["owner"] as? String) + case "child_exited": + return .childExited(code: object["exit_code"] as? Int ?? 0) + default: + // `theme` (the terminal's colors are the app's own theme here) + // and any type a newer server adds: skipped, as the protocol + // asks. + return nil + } + } +} + +/// Notices a program leaving the alternate screen in a run of terminal +/// output — `CSI ? 1049 l`, or its older spellings 1047 and 47, alone or +/// among other modes in one sequence. +/// +/// It exists for one case. While a full-screen program is up, Rex's `format` +/// renders only that program's screen: the shell history underneath is not +/// available to ask for. A tab attached at that moment therefore starts +/// with an empty primary screen, and when the program exits the emulator +/// switches back to it — a bare prompt where a terminal would show +/// everything from before. `RexSession` uses this to notice the exit and +/// fetch the screen again, now that the server can render it. +/// +/// Pure and incremental: a sequence may be split across two chunks. +struct AlternateScreenExitWatch { + private var carry = Data() + private static let exitModes: Set = ["1049", "1047", "47"] + /// Far longer than any real mode-reset sequence; a longer "sequence" is + /// not one, and is dropped rather than carried forever. + private static let maxSequence = 64 + + /// True if `chunk` (continuing whatever came before) contains an + /// alternate-screen exit. + mutating func sawExit(in chunk: Data) -> Bool { + let bytes = [UInt8](carry + chunk) + carry = Data() + var found = false + var index = 0 + while index < bytes.count { + guard bytes[index] == 0x1B else { + index += 1 + continue + } + // `ESC [ ?` then parameters, then a final byte. + let prefix: [UInt8] = [0x1B, 0x5B, 0x3F] + let available = bytes.count - index + guard available >= prefix.count else { + if Array(bytes[index...]) == Array(prefix.prefix(available)) { + carry = Data(bytes[index...]) + } + break + } + guard Array(bytes[index..<(index + 3)]) == prefix else { + index += 1 + continue + } + var end = index + 3 + while end < bytes.count, + (0x30...0x39).contains(bytes[end]) || bytes[end] == 0x3B { + end += 1 + } + guard end < bytes.count else { + // Still arriving — keep it for the next chunk. + if bytes.count - index <= Self.maxSequence { carry = Data(bytes[index...]) } + break + } + if bytes[end] == 0x6C { // `l`: reset + let parameters = String(decoding: bytes[(index + 3).. String { + var data = carry + bytes + carry = Data() + // Hold back an incomplete trailing sequence (at most 3 bytes). + let tail = Self.incompleteTail(of: data) + if tail > 0 { + carry = Data(data.suffix(tail)) + data.removeLast(tail) + } + return String(decoding: data, as: UTF8.self) + } + + /// How many trailing bytes begin a multi-byte character that has not + /// finished arriving. + private static func incompleteTail(of data: Data) -> Int { + let bytes = [UInt8](data.suffix(3)) + for back in 1...3 where back <= bytes.count { + let byte = bytes[bytes.count - back] + if byte & 0xC0 == 0x80 { continue } // a continuation byte + let needed: Int + switch byte { + case 0xC0...0xDF: needed = 2 + case 0xE0...0xEF: needed = 3 + case 0xF0...0xF7: needed = 4 + default: return 0 // ASCII or invalid: nothing to wait for + } + return needed > back ? back : 0 + } + return 0 + } +} diff --git a/Multiplex/Models/ShortcutPanelContent.swift b/Multiplex/Models/ShortcutPanelContent.swift index 6a2b53bc..1f1084a9 100644 --- a/Multiplex/Models/ShortcutPanelContent.swift +++ b/Multiplex/Models/ShortcutPanelContent.swift @@ -125,13 +125,50 @@ struct ShortcutPanelContent: Equatable, Sendable { switchNoun: String(localized: "workspace") ) + /// Rex has no prefix-key client — Multiplex IS the client — so its panel + /// carries no shortcut rows at all. What it carries is the one thing a + /// Rex tab cannot otherwise do from inside itself: a tab shows ONE + /// terminal of its session, and this lists the others and switches the + /// tab to one in place (`RexSession.switchBlock`). The header's trailing + /// slot says so where the others state their prefix. + static let rex = ShortcutPanelContent( + headerTitle: "REX TERMINALS", + prefixLabel: "SWITCHES THIS TAB", + sections: [], + switchSectionTitle: String(localized: "Switch Terminal"), + switchSectionAccessibilityIdentifier: "rexTerminalSection", + switchChoiceAccessibilityPrefix: "rexTerminal.", + switchNoun: String(localized: "terminal") + ) + /// The panel for one terminal tab's backend; nil hides the chrome /// entirely (plain shells, viewports, the file viewer). static func content(for backend: Host.SessionBackend?) -> ShortcutPanelContent? { switch backend { case .tmux: .tmux case .herdr: .herdr + case .rex: .rex case nil: nil } } } + +extension Host.SessionBackend { + /// The face of the rail / bar key that opens this backend's panel. One + /// source for the three places that draw it. + var shortcutKeyCaption: String { + switch self { + case .tmux: "TMUX" + case .herdr: "HRDR" + case .rex: "REX" + } + } + + var shortcutKeyAccessibilityLabel: String { + switch self { + case .tmux: String(localized: "Show tmux shortcuts") + case .herdr: String(localized: "Show herdr shortcuts") + case .rex: String(localized: "Show Rex terminals") + } + } +} diff --git a/Multiplex/Models/TerminalRoute.swift b/Multiplex/Models/TerminalRoute.swift index ef3852f1..99c5528b 100644 --- a/Multiplex/Models/TerminalRoute.swift +++ b/Multiplex/Models/TerminalRoute.swift @@ -17,6 +17,19 @@ struct TerminalRoute: Codable, Hashable, Identifiable { /// presses too. A real terminal like `.attach`: restores across /// launches, resumes per `SessionResumePolicy`. case herdrAttach(sessionName: String) + /// Attach one terminal block of a Rex session. Unlike tmux and herdr + /// there is no client to run in a PTY: the tab speaks Rex's own + /// protocol (`RexSession`), so this mode has no remote command at + /// all. `sessionName` is the tile's display name — the identity the + /// deck and the tab strip match on — while `sessionID` is the only + /// thing the server can be asked for (a Rex label is not unique). + /// `block` names one terminal of the session (the tile menu's Open + /// Terminal rows); nil means the one the session is fronting, + /// decided at attach time, which is what a tile press opens. A real + /// terminal like `.attach`: restores across launches, resumes per + /// `SessionResumePolicy` — a named block that has since closed falls + /// back to the fronted one. + case rexAttach(sessionName: String, sessionID: String, block: RexBlockRef? = nil) /// The viewport — an inline browser tab, docked beside the sessions /// that produced its URL and moved with the same merge/split /// machinery. Not a terminal: no remote command, no tmux session, no @@ -37,15 +50,25 @@ struct TerminalRoute: Codable, Hashable, Identifiable { .create(sessionName: sessionName, directory: nil) } - /// The attach mode for one session — the tmux attach or the herdr - /// client. THE single place the app decides tmux-vs-herdr for a - /// tab, so no mint site can disagree. + /// The attach mode for one session — the tmux attach, the herdr + /// client, or a Rex terminal. THE single place the app decides + /// which, so no mint site can disagree. + /// + /// `sessionID` is the backend's own id for the session, where it has + /// one the attach needs. Rex does: a label is not unique, so a Rex + /// session can only be attached by id, and this is nil for a record + /// that carries no usable one (a caller holding only a name). static func attach( - backend: Host.SessionBackend, sessionName: String - ) -> Mode { + backend: Host.SessionBackend, sessionName: String, sessionID: String? = nil + ) -> Mode? { switch backend { - case .tmux: .attach(sessionName: sessionName) - case .herdr: .herdrAttach(sessionName: sessionName) + case .tmux: + return .attach(sessionName: sessionName) + case .herdr: + return .herdrAttach(sessionName: sessionName) + case .rex: + guard let sessionID, RexProbe.bakeableSessionID(sessionID) else { return nil } + return .rexAttach(sessionName: sessionName, sessionID: sessionID) } } @@ -55,14 +78,20 @@ struct TerminalRoute: Codable, Hashable, Identifiable { /// on a mixed host a bare name is ambiguous, and this is the /// documented tie-break, not a guess about which the user meant. static func attach(host: Host, sessionName: String) -> Mode { + // The primary is always tmux or herdr (`Host.sessionBackend`'s + // record rule), both of which attach by name, so the fallback is + // unreachable for a stored host; it exists so this stays total. attach(backend: host.sessionBackend, sessionName: sessionName) + ?? .attach(sessionName: sessionName) } /// A session RECORD knows its own backend. On a mixed host the tmux /// `main` and the herdr `main` are two tiles that attach two /// different ways, so this must never consult `host.sessionBackend`. - static func attach(host: Host, session: TmuxSession) -> Mode { - attach(backend: session.backend, sessionName: session.name) + static func attach(host: Host, session: TmuxSession) -> Mode? { + attach( + backend: session.backend, sessionName: session.name, + sessionID: session.tmuxID) } } @@ -82,7 +111,7 @@ struct TerminalRoute: Codable, Hashable, Identifiable { ) case .herdrAttach(let sessionName): return HerdrSessionLaunch.attachCommand(sessionName: sessionName, universalArguments: true) - case .shell, .viewport, .fileViewer: + case .shell, .rexAttach, .viewport, .fileViewer: return nil } } @@ -109,7 +138,8 @@ struct TerminalRoute: Codable, Hashable, Identifiable { // The attach line needs a shell (PATH export before the exec); // execvp gets that shell as its argv. return "sh -c \(HerdrSessionLaunch.attachCommand(sessionName: sessionName).shellQuoted)" - case .shell, .viewport, .fileViewer: + // A Rex tab never rides mosh: it has no PTY for mosh-server to run. + case .shell, .rexAttach, .viewport, .fileViewer: return nil } } @@ -118,6 +148,10 @@ struct TerminalRoute: Codable, Hashable, Identifiable { switch mode { case .attach(let name), .create(let name, _): name case .herdrAttach(let sessionName): sessionName + // A tab on a named terminal says which: two tabs of one session + // would otherwise wear the same label. + case .rexAttach(let sessionName, _, let block): + block.map { "\(sessionName) · \($0.label)" } ?? sessionName case .shell: "shell" case .viewport(let urlString): Self.viewportLabel(urlString) case .fileViewer(let path): Self.fileViewerLabel(path) @@ -132,11 +166,19 @@ struct TerminalRoute: Codable, Hashable, Identifiable { var sessionName: String? { switch mode { case .attach(let name), .create(let name, _): name - case .herdrAttach(let sessionName): sessionName + case .herdrAttach(let sessionName), .rexAttach(let sessionName, _, _): sessionName case .shell, .viewport, .fileViewer: nil } } + /// The Rex session this tab attaches, by the id the server knows it by, + /// and the terminal in it when one was named; nil for every other kind + /// of tab. Its presence is what selects the Rex transport over the PTY. + var rexTarget: (sessionID: String, blockID: String?)? { + guard case .rexAttach(_, let sessionID, let block) = mode else { return nil } + return (sessionID, block?.id) + } + /// The remote session namespace this route belongs to. Unlike /// `Host.sessionBackend`, this stays fixed for the lifetime of an open /// tab, so switching a host's deck backend can never make a restored tmux @@ -145,10 +187,19 @@ struct TerminalRoute: Codable, Hashable, Identifiable { switch mode { case .attach, .create: .tmux case .herdrAttach: .herdr + case .rexAttach: .rex case .shell, .viewport, .fileViewer: nil } } + /// The backend whose panel this tab carries — the rail's TMUX / HRDR / + /// REX key and the panel behind it (`ShortcutPanelContent.content`). + /// One accessor so the window bar and the pane rail cannot disagree; + /// the key's face is `SessionBackend.shortcutKeyCaption`, because a + /// two-way `herdr ? "HRDR" : "TMUX"` at each site once drew a TMUX key + /// on a Rex tab. + var shortcutBackend: Host.SessionBackend? { sessionBackend } + /// Complete multiplexer identity for control-plane work that outlives or /// sits beside this tab's interactive transport (for example a mosh tab /// summoning its independently connected file viewer). @@ -217,7 +268,7 @@ struct TerminalRoute: Codable, Hashable, Identifiable { var usesTmux: Bool { switch mode { case .attach, .create: true - case .herdrAttach, .shell, .viewport, .fileViewer: false + case .herdrAttach, .rexAttach, .shell, .viewport, .fileViewer: false } } @@ -275,6 +326,32 @@ enum RemoteCommandEnvironment { "PATH=\"$PATH:/opt/homebrew/bin:/usr/local/bin:$HOME/.local/bin\"; export PATH; " static let herdrPathPrefix = pathPrefix + "PATH=\"$PATH:$HOME/.cargo/bin\"; export PATH; " + /// Rex installs `rex` at `/usr/bin` (Linux/FreeBSD packages) or + /// `~/.local/bin` (its unprivileged install, already on `pathPrefix`). + /// On macOS the CLI is put on PATH only for terminals Rex itself opens — + /// an SSH exec never sees it — so its homes are named outright, read off + /// a live install (Rex Beta 0.1.0-preview.19, 2026-11-16): + /// - the server copy the app installs and runs, under Application + /// Support with a `Current` link — independent of where the app + /// bundle sits or what it is called, so it leads; + /// - the helper inside the app bundle, for a Mac where Rex is installed + /// but has not run yet. The Beta name was observed; the release name + /// is assumed to keep the layout. + /// A directory that does not exist costs a PATH lookup nothing. + static let rexPathPrefix = pathPrefix + + "PATH=\"$PATH" + + ":$HOME/Library/Application Support/com.superlogical.rex/RexServer" + + "/Versions/Current/Rex Server.app/Contents/MacOS" + + ":/Applications/Rex.app/Contents/Helpers/Rex Server.rex/Contents/MacOS" + + ":/Applications/Rex Beta.app/Contents/Helpers/Rex Server.rex/Contents/MacOS" + + "\"; export PATH; " +} + +/// One terminal block of a Rex session, as a tab remembers it: the id the +/// server is asked for, and the label the tab wears. +struct RexBlockRef: Codable, Hashable { + var id: String + var label: String } /// The PTY handoff for a full herdr client. Session actions that don't belong @@ -296,7 +373,10 @@ enum HerdrSessionLaunch { /// itself. A paste target is an interactive desktop shell, so no ssh wrapper, /// no PATH scaffolding, no `-u`: the user's own shell already has all three. enum SessionHandoff { - static func command(session: TmuxSession) -> String { + /// nil when the backend has no attach line to hand over: Rex has no + /// terminal client, so there is no command that opens its session in a + /// shell on the host. + static func command(session: TmuxSession) -> String? { switch session.backend { case .tmux: return "tmux attach-session -t \(plainWordOrQuoted(session.name))" @@ -304,6 +384,8 @@ enum SessionHandoff { let name = session.name.isEmpty ? HerdrSessionLaunch.primarySessionName : session.name return "herdr session attach \(plainWordOrQuoted(name))" + case .rex: + return nil } } diff --git a/Multiplex/Models/WebSocketCodec.swift b/Multiplex/Models/WebSocketCodec.swift new file mode 100644 index 00000000..c9876e55 --- /dev/null +++ b/Multiplex/Models/WebSocketCodec.swift @@ -0,0 +1,281 @@ +import CryptoKit +import Foundation + +/// A minimal RFC 6455 WebSocket client codec — the handshake and the frame +/// layer, with no socket of its own. Pure: bytes in, bytes and messages out. +/// +/// It exists because a Rex server speaks WebSocket on a Unix socket that the +/// app can only reach as a byte pipe through SSH (`SSHConnection.openPipe`), +/// which rules out `URLSessionWebSocketTask` and every other client that +/// wants to own the connection. Deliberately small: no extensions are +/// offered (the server works with or without `permessage-deflate`, and a +/// data connection is never compressed), so RSV bits are always a protocol +/// error, and the only payloads are whole messages. +enum WebSocketCodec { + enum Opcode: UInt8 { + case continuation = 0x0 + case text = 0x1 + case binary = 0x2 + case close = 0x8 + case ping = 0x9 + case pong = 0xA + + var isControl: Bool { rawValue >= 0x8 } + } + + /// One complete message, fragments already joined. + enum Message: Equatable { + case text(Data) + case binary(Data) + case ping(Data) + case pong(Data) + /// The peer is closing. `code` is nil when the frame carried none. + case close(code: UInt16?, reason: String) + } + + enum Failure: Error, Equatable { + /// The server answered the upgrade with something other than 101. + case upgradeRefused(status: Int, body: String) + case malformedUpgrade(String) + case protocolViolation(String) + /// A frame larger than this client will hold in memory. + case messageTooLarge(Int) + } + + /// Larger than the control connection's 1 MiB message limit and far + /// above a data connection's 64 KiB chunks; anything bigger is not a + /// peer this client was written for. + static let maxMessageBytes = 4 * 1024 * 1024 + + // MARK: - Handshake + + /// 16 random bytes, base64 — the `Sec-WebSocket-Key` of one handshake. + static func makeKey() -> String { + var bytes = [UInt8](repeating: 0, count: 16) + for index in bytes.indices { bytes[index] = UInt8.random(in: .min ... .max) } + return Data(bytes).base64EncodedString() + } + + static func upgradeRequest( + path: String, host: String, subprotocol: String, key: String + ) -> Data { + Data(""" + GET \(path) HTTP/1.1\r + Host: \(host)\r + Upgrade: websocket\r + Connection: Upgrade\r + Sec-WebSocket-Key: \(key)\r + Sec-WebSocket-Version: 13\r + Sec-WebSocket-Protocol: \(subprotocol)\r + \r + + """.utf8) + } + + /// The `Sec-WebSocket-Accept` a server must answer `key` with. + static func acceptValue(forKey key: String) -> String { + let magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + return Data(Insecure.SHA1.hash(data: Data((key + magic).utf8))) + .base64EncodedString() + } + + enum UpgradeReading: Equatable { + /// The response head has not fully arrived. + case incomplete + /// Upgraded. `remainder` is whatever followed the head in the same + /// read — already frame bytes. + case upgraded(remainder: Data) + } + + /// Reads the server's answer to `upgradeRequest`. The accept value and + /// the subprotocol are both checked: a peer that is not a WebSocket + /// server, or not the protocol asked for, must not be fed frames. + static func readUpgradeResponse( + _ buffer: Data, key: String, subprotocol: String + ) throws -> UpgradeReading { + let terminator = Data("\r\n\r\n".utf8) + guard let end = buffer.range(of: terminator) else { + // A response head has no business being this long; without the + // cap a peer that never ends its head would buffer forever. + guard buffer.count <= 16 * 1024 else { + throw Failure.malformedUpgrade("response head never ended") + } + return .incomplete + } + let head = String(decoding: buffer[buffer.startIndex..= 2, status[0].hasPrefix("HTTP/"), + let code = Int(status[1]) + else { throw Failure.malformedUpgrade("no status line") } + guard code == 101 else { + let body = String( + decoding: buffer[end.upperBound...].prefix(200), as: UTF8.self) + throw Failure.upgradeRefused(status: code, body: body) + } + var headers: [String: String] = [:] + for line in lines.dropFirst() { + guard let colon = line.firstIndex(of: ":") else { continue } + headers[line[.. Data { + precondition(maskKey.count == 4) + var frame = Data([0x80 | opcode.rawValue]) + let count = payload.count + switch count { + case ..<126: + frame.append(0x80 | UInt8(count)) + case ..<65_536: + frame.append(0x80 | 126) + frame.append(contentsOf: [UInt8(count >> 8), UInt8(count & 0xFF)]) + default: + frame.append(0x80 | 127) + for shift in stride(from: 56, through: 0, by: -8) { + frame.append(UInt8((UInt64(count) >> UInt64(shift)) & 0xFF)) + } + } + frame.append(contentsOf: maskKey) + frame.append(contentsOf: payload.enumerated().map { $0.element ^ maskKey[$0.offset % 4] }) + return frame + } + + static func closeFrame(code: UInt16 = 1000) -> Data { + frame(.close, payload: Data([UInt8(code >> 8), UInt8(code & 0xFF)])) + } + + // MARK: - Frames in + + /// Incremental reader of server frames. Bytes arrive in whatever pieces + /// the pipe delivers; `next()` returns each complete message in order + /// and nil when it needs more. + struct Decoder { + private var buffer = Data() + /// The data message being assembled across fragments. + private var partial: (opcode: Opcode, payload: Data)? + + mutating func append(_ bytes: Data) { + buffer.append(bytes) + } + + mutating func next() throws -> Message? { + while let frame = try nextFrame() { + if frame.opcode.isControl { + // A control frame may sit between the fragments of a + // data message and is never fragmented itself. + guard frame.fin, frame.payload.count <= 125 else { + throw Failure.protocolViolation("fragmented or oversized control frame") + } + switch frame.opcode { + case .ping: return .ping(frame.payload) + case .pong: return .pong(frame.payload) + default: return closeMessage(frame.payload) + } + } + switch frame.opcode { + case .continuation: + guard var assembling = partial else { + throw Failure.protocolViolation("continuation with nothing to continue") + } + assembling.payload.append(frame.payload) + guard assembling.payload.count <= WebSocketCodec.maxMessageBytes else { + throw Failure.messageTooLarge(assembling.payload.count) + } + partial = frame.fin ? nil : assembling + if frame.fin { return message(assembling.opcode, assembling.payload) } + default: + guard partial == nil else { + throw Failure.protocolViolation("new message inside a fragmented one") + } + if frame.fin { return message(frame.opcode, frame.payload) } + partial = (frame.opcode, frame.payload) + } + } + return nil + } + + private func message(_ opcode: Opcode, _ payload: Data) -> Message { + opcode == .text ? .text(payload) : .binary(payload) + } + + private func closeMessage(_ payload: Data) -> Message { + guard payload.count >= 2 else { return .close(code: nil, reason: "") } + let bytes = [UInt8](payload) + return .close( + code: UInt16(bytes[0]) << 8 | UInt16(bytes[1]), + reason: String(decoding: bytes[2...], as: UTF8.self) + ) + } + + private struct Frame { + var fin: Bool + var opcode: Opcode + var payload: Data + } + + /// Pops one whole frame off the buffer, or nil if it is not all here. + private mutating func nextFrame() throws -> Frame? { + let bytes = buffer + guard bytes.count >= 2 else { return nil } + let base = bytes.startIndex + let first = bytes[base], second = bytes[base + 1] + guard first & 0x70 == 0 else { + throw Failure.protocolViolation("reserved bits set with no extension negotiated") + } + guard let opcode = Opcode(rawValue: first & 0x0F) else { + throw Failure.protocolViolation("unknown opcode \(first & 0x0F)") + } + var offset = 2 + var length = Int(second & 0x7F) + if length == 126 { + guard bytes.count >= offset + 2 else { return nil } + length = Int(bytes[base + 2]) << 8 | Int(bytes[base + 3]) + offset += 2 + } else if length == 127 { + guard bytes.count >= offset + 8 else { return nil } + var wide: UInt64 = 0 + for index in 0..<8 { wide = wide << 8 | UInt64(bytes[base + 2 + index]) } + guard wide <= UInt64(WebSocketCodec.maxMessageBytes) else { + throw Failure.messageTooLarge(Int(clamping: wide)) + } + length = Int(wide) + offset += 8 + } + guard length <= WebSocketCodec.maxMessageBytes else { + throw Failure.messageTooLarge(length) + } + // A server frame is never masked; one that is gets unmasked + // rather than refused — being liberal here costs nothing. + let masked = second & 0x80 != 0 + var key: [UInt8] = [] + if masked { + guard bytes.count >= offset + 4 else { return nil } + key = [UInt8](bytes[(base + offset)..<(base + offset + 4)]) + offset += 4 + } + guard bytes.count >= offset + length else { return nil } + var payload = Data(bytes[(base + offset)..<(base + offset + length)]) + if masked { + payload = Data(payload.enumerated().map { $0.element ^ key[$0.offset % 4] }) + } + buffer = Data(bytes[(base + offset + length)...]) + return Frame(fin: first & 0x80 != 0, opcode: opcode, payload: payload) + } + } +} diff --git a/Multiplex/Services/AttentionCenter.swift b/Multiplex/Services/AttentionCenter.swift index 9c510e65..10a2facd 100644 --- a/Multiplex/Services/AttentionCenter.swift +++ b/Multiplex/Services/AttentionCenter.swift @@ -71,10 +71,13 @@ final class AttentionCenter { /// Probe-plane event — any session on any host, attached or not. func handle(_ alert: AttentionAlert) { guard isActive else { return drop(alert.sessionName, "locked") } + // The ALERT's backend, not the host's primary: a secondary backend's + // session shares names with the primary's, and a focused tmux `work` + // tab must not swallow the alert of a Rex or herdr `work`. guard !isFocused( hostID: alert.host.id, sessionName: alert.sessionName, - backend: alert.host.sessionBackend + backend: alert.backend ) else { return drop(alert.sessionName, "focused") } post(alert) } diff --git a/Multiplex/Services/BackendDiscovery.swift b/Multiplex/Services/BackendDiscovery.swift index 6fc40ddd..71e48580 100644 --- a/Multiplex/Services/BackendDiscovery.swift +++ b/Multiplex/Services/BackendDiscovery.swift @@ -73,6 +73,16 @@ enum BackendDiscovery { + "{ echo \(presentMarker); " + "\(TmuxProbe.tmuxCommand) list-sessions -F 'D #{session_name}'" + " 2>/dev/null || true; }; " + case .rex: + // On macOS the CLI lives inside the app bundle, which only the + // Rex PATH names. `RexProbe.sessionListVerb` carries the + // autostart refusal: a rider that started a Rex server on every + // host that merely has the binary would be this feature's worst + // possible side effect. + command += RemoteCommandEnvironment.rexPathPrefix + + "command -v rex >/dev/null 2>&1 && " + + "{ echo \(presentMarker); " + + RexProbe.sessionListVerb + "; }; " } return command + "echo \(endMarker); " } @@ -244,6 +254,10 @@ enum BackendDiscovery { let name = String(line.dropFirst(2)) return name.isEmpty ? nil : name } + case .rex: + // One id per line. The offer states a count, and a Rex label is + // not unique anyway, so the ids ARE the list. + return RexProbe.parseSessionIDs(lines) } } diff --git a/Multiplex/Services/ConnectionHub.swift b/Multiplex/Services/ConnectionHub.swift index a629fde5..12e4d719 100644 --- a/Multiplex/Services/ConnectionHub.swift +++ b/Multiplex/Services/ConnectionHub.swift @@ -226,6 +226,20 @@ final class HostConnectionModel { /// The backend's binary isn't on the host's PATH — proved by the /// mint's own first exec, not guessed from an empty answer. case backendMissing(Host.SessionBackend) + /// The backend is installed and its server is not running, and + /// Multiplex does not start it — Rex (`RexProbe`). tmux and herdr + /// never report this: their mint brings the server up. + case serverNotRunning(Host.SessionBackend) + + /// The sentence every surface shows for this failure. + func message(hostName: String) -> String { + switch self { + case .backendMissing(let backend): + HostGuide.backendMissingMessage(backend, hostName: hostName) + case .serverNotRunning(let backend): + HostGuide.serverNotRunningMessage(backend, hostName: hostName) + } + } } @ObservationIgnored private var lastRefreshed: Date? /// Observation-friendly summaries: views that only need liveness or a @@ -327,6 +341,10 @@ final class HostConnectionModel { /// attribute an aggregate busy → idle edge to the front pane without /// borrowing its agent name when a background pane actually finished. @ObservationIgnored private var previousHerdrPaneStatuses: [SessionKey: [String: HerdrProbe.AgentStatus]] = [:] + /// Rex: session → the statuses its programs reported (OSC 7501) in the + /// last probe — the attention authority wherever a program reports one. + /// Never persisted; NEEDS YOU is re-earned live. + @ObservationIgnored private var rexSignals: [SessionKey: RexProbe.SessionSignals] = [:] /// Last keychain check answer + when it landed. `.notMacOS` is /// structural and never re-asked on this connection; other verdicts /// refresh after `keychainVerdictTTL` while the symptom persists. @@ -417,6 +435,12 @@ final class HostConnectionModel { let connection else { return nil } + // A Rex tab has no one-exec "which pane is in front" query to make + // — its block was chosen at attach — and without this the tmux + // query below would run against a Rex session's name. nil means the + // fast path is unavailable; the wall probe's record still answers. + guard backend != .rex else { return nil } + activePaneProbeInFlight = true defer { activePaneProbeInFlight = false } @@ -783,6 +807,29 @@ final class HostConnectionModel { ), outputBytes: output.utf8.count ) + case .rex: + let output = try await deadlined { + try await connection.exec( + RexProbe.probeCommand(discovering: discovering)) + } + try Task.checkCancellation() + let rexParsed = await Task.detached(priority: .userInitiated) { + RexProbe.parseProbe(output) + }.value + // Same rule as herdr's bake state: a pass a backend switch or + // suspension invalidated must not replace the attention inputs. + guard refreshGeneration == generation else { throw CancellationError() } + rexSignals = rexParsed.signals.keyed(backend: .rex) + return BackendProbe( + backend: .rex, + parsed: TmuxProbe.ParsedProbe( + state: rexParsed.state.tmuxState, + tails: rexParsed.tails, + miniatures: rexParsed.miniatures, + discovery: rexParsed.discovery + ), + outputBytes: output.utf8.count + ) } } @@ -1099,6 +1146,40 @@ final class HostConnectionModel { hasBell: false, offersDialogSummary: false ) + case .rex: + let pane = session.activeWindow?.activePane + let title = pane?.title ?? session.activeWindow?.paneTitle ?? "" + let signals = rexSignals[session.id] ?? RexProbe.SessionSignals() + // A program that reports its own status is the authority, and + // the fold covers every block in the session — a blocked agent + // in a background window still needs you. + if let state = RexProbe.sessionAgentState(signals.reported) { + // Alert metadata speaks for the fronted block only when its + // own records produced the verdict (herdr's rule): the tail + // the summary reads is that block's screen and no other's. + let front = RexProbe.frontProducedSessionState( + state, front: signals.front) + return AttentionVerdict( + state: state, + agent: front ? pane?.agent : nil, + paneTitle: front ? title : "", + hasBell: false, + offersDialogSummary: front + ) + } + // Nothing reported: read the fronted block the way a tmux tile + // is read, from its title and screen. Rex latches no bell. + return AttentionVerdict( + state: AgentAttention.classifyVerified( + title: title, + tail: attentionTails[session.id] ?? [], + agent: pane?.agent + ), + agent: pane?.agent, + paneTitle: title, + hasBell: false, + offersDialogSummary: true + ) } } @@ -1219,7 +1300,10 @@ final class HostConnectionModel { sessionCreateFailure = nil do { let connection = try await ensureConnection() - if backend == .herdr { + switch backend { + case .tmux: + break + case .herdr: // The tmux conf rider applies to the tmux path only; the // two directory riders resolve inside the herdr mint (the // session server inherits the spawn's cwd). @@ -1228,6 +1312,12 @@ final class HostConnectionModel { startingIn: directory, running: script, typing: launch, over: connection ) + case .rex: + return try await createRexSession( + base: base, inDirectoryOf: sourceSession, + startingIn: directory, running: script, typing: launch, + over: connection + ) } let command = TmuxProbe.newSessionCommand( // Unique within TMUX's namespace only: a herdr session of @@ -1253,6 +1343,55 @@ final class HostConnectionModel { } } + /// The Rex mint: one exec that creates a session holding one shell + /// terminal, with the setup lines handed to the server as the + /// terminal's `initial_input` — so they are typed before any client is + /// attached, the tmux mint's own ordering, with nothing left to poll + /// for. The route carries the new session's ID (a label is not one). + /// + /// The directory riders follow the tmux mint: a source session's + /// fronted-terminal cwd wins, an explicit directory is consulted only + /// without one, and every miss is $HOME. The source is resolved to its + /// id against the latest probe — a name the probe no longer lists has + /// no directory to offer, and the mint starts in $HOME rather than + /// guess. The tmux conf rider does not apply. + /// + /// Throws what the exec throws, so a dead control link is reported as + /// one by the caller. A healthy link that could not create the session + /// states why in `sessionCreateFailure` — no `rex` on the host, or no + /// server running, which Multiplex does not start (`RexProbe`). + private func createRexSession( + base: String, inDirectoryOf sourceSession: String?, + startingIn directory: String?, running script: String?, + typing launch: String?, over connection: SSHConnection + ) async throws -> TerminalRoute.Mode? { + let existing = sessions(on: .rex) + let sourceID = sourceSession + .flatMap { name in existing.first { $0.name == name }?.tmuxID } + .flatMap { RexProbe.bakeableSessionID($0) ? $0 : nil } + let command = RexProbe.mintCommand( + label: RexProbe.uniqueSessionLabel( + base: base, existing: existing.map(\.name)), + inDirectoryOf: sourceID, + startingIn: directory, + typing: [script, launch].compactMap { $0 } + ) + let outcome = RexProbe.parseMint( + try await deadlined { try await connection.exec(command) }) + switch outcome { + case .created(let name, let id): + refresh() + return .rexAttach(sessionName: name, sessionID: id) + case .rexMissing: + sessionCreateFailure = .backendMissing(.rex) + case .noServer: + sessionCreateFailure = .serverNotRunning(.rex) + case .failed: + break + } + return nil + } + /// The herdr mint: a session is created by attaching to it, so the /// mint IS the attach route — but the client needs a PTY, and setup /// typing needs the fresh session's pane id. `spawnSessionCommand` @@ -1437,6 +1576,10 @@ final class HostConnectionModel { running script: String? = nil, typing launch: String? ) async -> TerminalRoute.Mode? { + // Multiplex opens no new window or tab inside a Rex session — a + // launch lands in a fresh one (`createSession`) — and the tmux + // verbs below must not aim at its name. + guard backend != .rex else { return nil } resetConnectRetryBackoff() let reusedLink = connection != nil && phase == .connected do { @@ -1623,6 +1766,10 @@ final class HostConnectionModel { // parks as stopped. Session names are herdr's own unique // identity, so the name is the target. command = HerdrProbe.closeSessionCommand(for: session) + case .rex: + // By id — a Rex label is not unique, and killing by a shared + // one is refused by the CLI. nil when the record names no id. + command = RexProbe.killCommand(for: session) } if let command { _ = try? await deadlined { try await connection.exec(command) } @@ -1668,6 +1815,7 @@ final class HostConnectionModel { herdrTailTargets = [] herdrPaneStatuses = [:] previousHerdrPaneStatuses = [:] + rexSignals = [:] herdrPresent = false discovery = [:] keychainNotice = nil diff --git a/Multiplex/Services/ExternalActionRouter.swift b/Multiplex/Services/ExternalActionRouter.swift index 05d54d54..5277a85f 100644 --- a/Multiplex/Services/ExternalActionRouter.swift +++ b/Multiplex/Services/ExternalActionRouter.swift @@ -212,8 +212,7 @@ enum ExternalActionPerformer { // every monitored backend's sessions are candidates and the record // that matches carries the backend the attach must use. // `host.sessionBackend` is the tie-break, never the assumption. - let sessions = backend.map { scopedSessions(model, to: $0) } - ?? model.allSessions + let sessions = openableSessions(model, backend: backend) // A widget tile names the exact session it showed; a session that // died since that snapshot falls back to the last one opened here, // then the most recent — the widgets' own order. @@ -230,11 +229,11 @@ enum ExternalActionPerformer { sessionName: target.name, backend: target.backend ) { return } - open( - mode: .attach(host: host, session: target), - on: host, - context: context - ) + // nil only for a Rex record that names no usable id — nothing + // to attach, and nothing else it would be right to open instead. + guard let mode = TerminalRoute.Mode.attach(host: host, session: target) + else { return } + open(mode: mode, on: host, context: context) } else { // Headless creation inherits the New Session sheet's remembered // setup script (nil unless its REMEMBER opt-in is on) — a widget @@ -264,6 +263,14 @@ enum ExternalActionPerformer { model.host.monitors(backend) ? model.sessions(on: backend) : [] } + /// The sessions an external action may open: a named backend's when + /// one is named, every monitored backend's otherwise. + private static func openableSessions( + _ model: HostConnectionModel, backend: Host.SessionBackend? + ) -> [TmuxSession] { + backend.map { scopedSessions(model, to: $0) } ?? model.allSessions + } + private static func openAgent( _ agent: AgentKind, prompt: String?, @@ -293,8 +300,13 @@ enum ExternalActionPerformer { // (fail-soft, openShell's rule). An in-session create that FAILS // stays a visible failure instead — a fallback mint there would // hide it behind a surprise second session. - let candidates = backend.map { scopedSessions(model, to: $0) } - ?? model.allSessions + // Launching INTO a session types a command in a fresh window or tab + // of it. Multiplex opens no window inside a Rex session + // (`HostConnectionModel.launchInSession`), so one named as the + // target resolves to nothing and the launch falls through to a + // fresh session — on Rex when the action named Rex. + let candidates = openableSessions(model, backend: backend) + .filter { $0.backend != .rex } if case .existingSession(let name, let placement) = target, let session = candidates.first(where: { $0.name == name }) { guard let mode = await model.launchInSession( @@ -332,7 +344,7 @@ enum ExternalActionPerformer { guard let created = await model.createSession( base: agent.launchCommand, // A named backend mints there; nil is the host's default. One - // the host no longer monitors falls back rather than failing — + // the host no longer monitors falls back rather than failing: // minting is not the ambiguous case, attaching is. backend: backend.flatMap { host.monitors($0) ? $0 : nil }, inDirectoryOf: nil, @@ -417,7 +429,8 @@ enum ExternalActionPerformer { // The RESOLVED session's backend names the thing that didn't // happen, not the host's primary. switch (backend, placement) { - case (.tmux, _): noun = String(localized: "window") + // `.rex` never resolves as a launch target (see `openAgent`). + case (.tmux, _), (.rex, _): noun = String(localized: "window") case (.herdr, .tab): noun = String(localized: "tab") case (.herdr, .workspace): noun = String(localized: "workspace") } @@ -441,15 +454,12 @@ enum ExternalActionPerformer { // createSession marks the host failed when the control link IS the // problem; reuse that reason when it exists. let message: String - switch model.sessionCreateFailure { - case .backendMissing(let backend): - message = HostGuide.backendMissingMessage(backend, hostName: host.name) - case nil: - if case .failed(let reason) = model.phase { - message = reason - } else { - message = String(localized: "Couldn't create the session on \(host.name).") - } + if let failure = model.sessionCreateFailure { + message = failure.message(hostName: host.name) + } else if case .failed(let reason) = model.phase { + message = reason + } else { + message = String(localized: "Couldn't create the session on \(host.name).") } context.presentFailure(ExternalActionFailure(hostName: host.name, message: message)) } diff --git a/Multiplex/Services/FileViewerController.swift b/Multiplex/Services/FileViewerController.swift index 9eff5ade..dda640c0 100644 --- a/Multiplex/Services/FileViewerController.swift +++ b/Multiplex/Services/FileViewerController.swift @@ -516,6 +516,12 @@ final class FileViewerController: AuxiliaryPaneController { TmuxProbe.pathAnchorCommand(sessionName: session.name) case .herdr: HerdrProbe.snapshotCommand(sessionName: session.name) + case .rex: + // A Rex tab has no exec to ask where its block's program is + // (the answer lives behind the server's API, not a command). A + // no-op's empty answer parses to "no anchor": the $HOME + // fallback, the same posture as a pane that will not answer. + ":" } } @@ -532,6 +538,8 @@ final class FileViewerController: AuxiliaryPaneController { HerdrProbe.parsePaneWorkingDirectory( output, atScreenCell: cell, screenSize: screenSize ) + case .rex: + nil } } diff --git a/Multiplex/Services/RexProbe.swift b/Multiplex/Services/RexProbe.swift new file mode 100644 index 00000000..820bd55a --- /dev/null +++ b/Multiplex/Services/RexProbe.swift @@ -0,0 +1,912 @@ +import Foundation + +/// Builds and parses the `rex` CLI commands that put Rex sessions on the deck +/// and create new ones — the sibling of `TmuxProbe` and `HerdrProbe`. Pure functions, +/// exercised by unit tests against output captured from a live server. +/// +/// Rex (superlogical.com/rex) is a multiplexer whose sessions are rendered by +/// a native app, not by a client drawing in a terminal. Wire facts, measured +/// against Rex 0.1.0-preview.19 / API revision 14 on 2026-11-16 (a throwaway +/// server; fixtures under MultiplexTests/Fixtures): +/// - **There is nothing to attach.** No `rex attach` exists, and `rex block +/// stream` answers `not implemented`. Live output is only the server's +/// WebSocket data stream, which opens with a Ghostty-format binary +/// snapshot — what `RexSession` speaks for a tab. +/// - `rex do -e --json` runs a script on ONE control connection and +/// prints its return value as JSON, so a whole wall probe — sessions, +/// layouts, titles, processes, reported statuses, the fronted screen — is +/// one exec and one connection (30 ms and 3 KB for three sessions). +/// - `session.view` and every block method fail with `conflict` until the +/// connection is attached. `session.attach_all` is the attachment that +/// does NOT join a session: the probe is never listed among its clients +/// and no `client_connected` event fires every five seconds. +/// - The CLI autostarts a personal server when none is running. Nothing +/// here does — not a probe every five seconds, and not a mint either. +/// A server started from an SSH login would be the one the host's own +/// Rex app then adopts, and how that server differs from one the app +/// starts in the desktop session was NOT measured; refusing is the +/// choice that cannot change how the user's Rex behaves. So every +/// invocation carries `REX_AUTOSTART=0`; a missing server then exits 4, +/// the CLI's documented "server unreachable" status, and a mint says so +/// instead of starting one (`Host.SessionBackend.canBeDefault` is the +/// same decision as a record rule). +/// - `rex do` takes its arguments as `KEY=VALUE` pairs — typed by how they +/// are spelled, so a label `1e3` arrives as the number 1000 — or as one +/// JSON object through `--args`, which keeps every string a string. The +/// mint uses the JSON form. +/// - A new terminal's `cwd` option is taken literally: `~` is not expanded +/// and a directory that does not exist silently starts in $HOME. The +/// script's Lua runs in the CLI process, so `os.getenv` reads the exec's +/// own environment — how a shell-resolved directory reaches it. +/// - `initial_input` is typed into the fresh shell once it is up; a +/// carriage return is Enter, and several lines run in order. +/// - Labels are not identities: two sessions may share one, and an unnamed +/// session gets a generated one. The id (`session:`) is the only +/// unambiguous target — it rides `TmuxSession.tmuxID` — and +/// `sessionNames` makes the displayed names unique. +/// - `--json` output is pretty-printed even when piped, and an empty Lua +/// table encodes as `{}`, never `[]` — hence `LuaArray`. +/// - `format` returns the screen AND its scrollback, oldest first, and its +/// `max_bytes` counts JSON-encoded bytes. The tail is therefore read with +/// `blob_read` at an offset from the end, with no cap of its own. +/// - Programs report idle / working / done / blocked / error through OSC +/// 7501 ("Program Status Protocol"), which the server keeps per block. +/// That is the attention authority when present; a block that reports +/// nothing falls back to the title-and-screen heuristics tmux tiles use. +/// +/// The parser maps Rex's model onto the existing records — **session → +/// `TmuxSession`, window (a tab) → `TmuxWindow`, terminal block → +/// `TmuxPane`** — so the wall, the snapshot cache, and the attention +/// pipeline keep working untouched. +enum RexProbe { + static let pathPrefix = RemoteCommandEnvironment.rexPathPrefix + + /// Every `rex` invocation the app makes. Autostart is refused through + /// the documented environment switch rather than the `--autostart` flag + /// so a build that predates the flag still answers instead of failing + /// on an unknown option. + static let rexCommand = "REX_AUTOSTART=0 rex" + + /// The byte bridge an attach rides (`RexSession`): stdin and stdout + /// joined to the server's socket. It is the command Rex's own `ssh://` + /// transport runs on the far side — which is why it finds the server by + /// itself, on every platform — but it is `__internal`: hidden from + /// `rex help` and unversioned. If a release renames it the attach fails + /// with the CLI's own "unknown command" on the tab's ended line. + static let bridgeCommand = pathPrefix + + "REX_AUTOSTART=0; export REX_AUTOSTART; exec rex __internal dial-stdio" + + private static let noRexMarker = "MULTIPLEX_NO_REX" + private static let probeMarker = "MULTIPLEX_REX_PROBE" + private static let mintMarker = "MULTIPLEX_REX_MINT" + private static let exitMarker = "MULTIPLEX_REX_EXIT" + /// The CLI's documented exit status for "the server could not be + /// reached" — with autostart off, simply "no server is running". + private static let serverUnreachableExit = 4 + + /// How much of the fronted screen each probe reads, from the end. Sized + /// to cover the tmux probe's 30 captured rows at a wide terminal; the + /// parser keeps `tailLines` of them. + private static let tailBytes = 6144 + private static let tailLines = 30 + + // MARK: - Probe command + + /// The probe script. Lua, because `rex do` is the one way to make many + /// API calls over a single connection and get one JSON document back. + /// + /// Every call is nil-checked: a block or session can close between two + /// calls, and `rex.call` then returns nil rather than raising. A session + /// whose view failed is still listed (a tile with no spine), exactly as + /// a herdr session without a snapshot is. + /// + /// Contains no single quote, so shell-quoting it is one pair of quotes. + private static let probeScript: String = """ + local T = "com.superlogical.terminal." + local out = { sessions = {} } + rex.call("session.attach_all", { event_scope = "session" }) + local list = rex.call("session.list") + if not list then return out end + out.ok = true + for _, s in ipairs(list.sessions or {}) do + local sid = s.session_id + local item = { id = sid, label = s.label, windows = {} } + local apps = rex.call("client.list", { session_id = sid, kinds = { "app" } }) + if apps and apps.clients then item.clients = #apps.clients end + local view = rex.call("session.view", { session_id = sid }) + if view then + item.active = view.active_window_id + local front = nil + for _, w in ipairs(view.windows or {}) do + local win = { id = w.window_id, label = w.label, focus = w.focused_block_id, blocks = {} } + for _, layer in ipairs(w.layers or {}) do + for _, b in ipairs(layer.blocks or {}) do + if b.creator_name == "com.superlogical.terminal" then + local a = { session_id = sid, block_id = b.block_id, args = {} } + local blk = { id = b.block_id, label = b.label } + local t = rex.call(T .. "title", a) + if t then blk.title = t.title end + local p = rex.call(T .. "process", a) + if p and p.foreground then + blk.pid = p.foreground.pid + blk.name = p.foreground.name + blk.argv0 = p.foreground.argv0 + blk.script = p.foreground.script + end + local st = rex.call(T .. "program_status", a) + if st and st.records then + local recs = {} + for _, r in ipairs(st.records) do + recs[#recs + 1] = { state = r.state, kind = r.kind, app = r.effective_app or r.app } + end + if #recs > 0 then blk.status = recs end + end + win.blocks[#win.blocks + 1] = blk + end + end + end + if w.window_id == view.active_window_id then front = w.focused_block_id end + item.windows[#item.windows + 1] = win + end + if front then + local f = rex.call(T .. "format", { session_id = sid, block_id = front, + args = { format = "text", trim = true, max_bytes = 1 } }) + if f and f.id and f.total then + local off = 0 + if f.total > \(tailBytes) then off = f.total - \(tailBytes) end + local rest = rex.call(T .. "blob_read", { session_id = sid, block_id = front, + args = { id = f.id, offset = off } }) + if rest then + item.tail = rest.data + if off > 0 then item.clipped = true end + end + elseif f then + item.tail = f.content + end + end + end + out.sessions[#out.sessions + 1] = item + end + return out + """ + .split(separator: "\n") + .map { $0.drop(while: { $0 == " " }) } + .joined(separator: "\n") + + /// One exec round trip: presence, then the script's JSON, then the CLI's + /// exit status — which is how "no server running" (4) is told apart from + /// a probe that genuinely failed. + /// + /// `discovering` carries the mixed-host discovery riders. Rex is only + /// ever a secondary probe today, so every real caller passes `[]`; the + /// parameter keeps the three probe builders the same shape. The riders + /// lead, before this probe's own presence guard, for the reason + /// `BackendDiscovery.riderPrefix` states. + static func probeCommand(discovering: Set = []) -> String { + BackendDiscovery.riderPrefix(discovering: discovering, excluding: .rex) + + pathPrefix + + "command -v rex >/dev/null 2>&1 || { echo \(noRexMarker); exit 0; }; " + + "echo \(probeMarker); " + + "\(rexCommand) do -e \(probeScript.shellQuoted) --json 2>/dev/null; " + + "echo \"\(exitMarker) $?\"" + } + + // MARK: - Parsed result + + /// What a host's Rex server currently looks like, kept apart from + /// `TmuxState` so the pure layer states Rex truth and the wall chooses + /// its vocabulary (`tmuxState`). + enum State: Equatable { + case rexMissing + /// `rex` is installed and no server is running, or one is running + /// with no sessions. Either way there is nothing to show. + case noServer + case sessions([TmuxSession]) + case failed(String) + } + + /// One state a program reported through OSC 7501. The protocol's own + /// rule for a value this build has never heard of is "treat it as idle"; + /// `.unknown` keeps that case visible so it makes no claim instead. + enum ProgramState: String, Equatable { + case idle, working, done, blocked, error, unknown + } + + /// One program-status record of one block, reduced to what attention + /// needs: the state, and what a blocked program is waiting for. + struct ProgramStatus: Equatable { + var state: ProgramState + var kind: AttentionKind? + } + + /// One session's reported statuses — the attention authority, never + /// persisted (NEEDS YOU is re-earned live). + struct SessionSignals: Equatable { + /// Every record of every block in the session, background windows + /// included: a blocked program the session is not fronting still + /// needs you. + var reported: [ProgramStatus] = [] + /// The fronted block's own records — whether that block produced the + /// session's verdict decides if an alert may borrow its agent name. + var front: [ProgramStatus] = [] + } + + /// Everything derived from one probe response, shaped like + /// `TmuxProbe.ParsedProbe` so the connection model consumes either. + struct ParsedProbe { + var state: State + /// Session name → the fronted block's last lines, unclipped. + var tails: [String: [String]] + var miniatures: [String: [String]] + /// Session name → reported statuses. + var signals: [String: SessionSignals] + var discovery: [Host.SessionBackend: BackendDiscovery.Result] = [:] + } + + static func parseProbe(_ output: String) -> ParsedProbe { + var result = ParsedProbe( + state: .failed(String(localized: "unreadable rex probe response")), + tails: [:], miniatures: [:], signals: [:] + ) + let reading = BackendDiscovery.read(output) + result.discovery = reading.results + + let json: String + switch scriptReply(in: reading.remainder, marker: probeMarker) { + case .rexMissing: + result.state = .rexMissing + return result + case .unreadable: + return result + case .exited(let exitCode): + result.state = exitCode == serverUnreachableExit + ? .noServer + : .failed(String(localized: "rex answered with exit status \(String(exitCode))")) + return result + case .json(let text): + json = text + } + guard let document = try? JSONDecoder().decode( + Document.self, from: Data(json.utf8)), + document.ok == true + else { return result } + + let entries = document.sessions.elements + guard !entries.isEmpty else { + result.state = .noServer + return result + } + let names = sessionNames(for: entries.map { (id: $0.id, label: $0.label ?? "") }) + var sessions: [TmuxSession] = [] + for (index, entry) in entries.enumerated() { + let name = names[index] + sessions.append(session(entry: entry, name: name, index: index)) + result.signals[name] = signals(of: entry) + guard let tail = entry.tail else { continue } + var tailLines = tail.split(separator: "\n", omittingEmptySubsequences: false) + .map(String.init) + // A read that started mid-screen starts mid-line. + if entry.clipped == true, !tailLines.isEmpty { tailLines.removeFirst() } + let visible = Array(TmuxProbe.visibleTail(tailLines).suffix(Self.tailLines)) + guard !visible.isEmpty else { continue } + result.tails[name] = visible + result.miniatures[name] = TmuxProbe.miniatureTail(visible) + } + result.state = .sessions(sessions) + return result + } + + /// What one `rex do` exec answered: the script's JSON, found between + /// the command's own marker and the exit line it always prints last. + private enum ScriptReply { + case rexMissing + case unreadable + /// The CLI's own non-zero exit status. + case exited(Int) + case json(String) + } + + private static func scriptReply(in output: String, marker: String) -> ScriptReply { + guard let range = markerRange(of: marker, in: output) else { + // The presence guard `exit`s before the marker prints, so the + // no-rex marker is only ever looked for in a response that has + // no script output a screen could have forged it into. + let missing = output.split(separator: "\n", omittingEmptySubsequences: true) + .contains { $0.trimmingCharacters(in: .whitespaces) == noRexMarker } + return missing ? .rexMissing : .unreadable + } + // The exit line is the LAST thing the command prints, and the JSON + // above it is indented and quoted, so only the command's own `echo` + // can start a line with the marker. + let lines = output[range.upperBound...] + .split(separator: "\n", omittingEmptySubsequences: false) + guard let exitIndex = lines.lastIndex(where: { $0.hasPrefix(exitMarker + " ") }), + let exitCode = Int(lines[exitIndex].dropFirst(exitMarker.count + 1) + .trimmingCharacters(in: .whitespaces)) + else { return .unreadable } + guard exitCode == 0 else { return .exited(exitCode) } + return .json(lines[.. Range? { + output.range(of: marker + "\n", options: .anchored) + ?? output.range(of: "\n" + marker + "\n") + } + + // MARK: - Wire types (decoded tolerantly — unknown fields ignored) + + /// A JSON array as Rex's Lua encoder writes it: `[…]` when it has + /// elements, `{}` when it has none (an empty Lua table carries no hint + /// that it was a list). Anything that is not an array decodes as empty, + /// and one malformed element drops that element, not the list. + private struct LuaArray: Decodable { + var elements: [Element] = [] + + init() {} + + init(from decoder: any Decoder) throws { + guard var container = try? decoder.unkeyedContainer() else { return } + while !container.isAtEnd { + if let element = try? container.decode(Element.self) { + elements.append(element) + } else { + // Step past what could not be read, or the loop never ends. + _ = try? container.decode(Skipped.self) + } + } + } + + private struct Skipped: Decodable {} + } + + private struct Document: Decodable { + /// Set by the script only once `session.list` answered. + var ok: Bool? + var sessions: LuaArray + + enum CodingKeys: String, CodingKey { case ok, sessions } + + init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + ok = try container.decodeIfPresent(Bool.self, forKey: .ok) + sessions = (try? container.decode( + LuaArray.self, forKey: .sessions)) ?? LuaArray() + } + } + + private struct SessionEntry: Decodable { + var id: String + var label: String? + var active: String? + var clients: Int? + var tail: String? + var clipped: Bool? + var windows: LuaArray? + } + + private struct WindowEntry: Decodable { + var id: String + var label: String? + var focus: String? + var blocks: LuaArray? + } + + private struct BlockEntry: Decodable { + var id: String + var label: String? + var title: String? + var pid: Int? + var name: String? + var argv0: String? + var script: String? + var status: LuaArray? + } + + private struct StatusEntry: Decodable { + var state: String? + var kind: String? + var app: String? + } + + // MARK: - Mapping (session → TmuxSession, window → window, block → pane) + + /// Display names, unique per host, in the entries' own order. + /// + /// A session's NAME is its identity everywhere above this file + /// (`SessionKey`), but a Rex label is not one. A label that is unique on + /// the server is used as is; a label shared by several sessions — or an + /// empty one — is spelled with the tail of the session id, the way the + /// CLI's own listing tells them apart (`work …8d7863`). + /// + /// EVERY holder of a shared label is suffixed, never "all but the + /// first": when a second `work` appears the first one's identity + /// changes, which costs it a saved tile position and one attention + /// baseline. Keeping the bare name on whichever session happened to be + /// older would instead hand that name — and its baseline — to a + /// different session the day the older one is closed, and announce a + /// turn that never ended. + static func sessionNames(for entries: [(id: String, label: String)]) -> [String] { + let labels = entries.map { displayLabel($0.label) } + var counts: [String: Int] = [:] + for label in labels { counts[label.lowercased(), default: 0] += 1 } + var seen = Set() + return entries.indices.map { index in + let label = labels[index] + var name = label + if label.isEmpty || counts[label.lowercased(), default: 0] > 1 { + let suffix = "…" + shortID(entries[index].id) + name = label.isEmpty ? suffix : "\(label) \(suffix)" + } + // Ids are unique, so this only fires for a response that repeats + // one; the full id is the tie-break of last resort. + if !seen.insert(name).inserted { + name = "\(name) \(entries[index].id)" + seen.insert(name) + } + return name + } + } + + /// A label as a tile can show it: control characters removed (a label + /// is user text and lands in a single-line chassis row), ends trimmed. + private static func displayLabel(_ label: String) -> String { + String(String.UnicodeScalarView(label.unicodeScalars.filter { + !CharacterSet.controlCharacters.contains($0) + })).trimmingCharacters(in: .whitespaces) + } + + /// The id's last six characters — the short form Rex's own listings + /// print and accept as a target. + private static func shortID(_ id: String) -> String { + String(id.suffix(6)) + } + + private static func session( + entry: SessionEntry, name: String, index: Int + ) -> TmuxSession { + TmuxSession( + name: name, + windows: windows(of: entry), + clientCount: max(0, entry.clients ?? 0), + // Rex states no creation time. The list is in creation order, + // so the position stands in — `HerdrProbe.isSyntheticCreated` + // is how a tile knows not to render it as an age, while "most + // recent" still sorts by it. + created: Date(timeIntervalSince1970: TimeInterval(index)), + tmuxID: entry.id, + serverHost: "", + backend: .rex + ) + } + + private static func windows(of entry: SessionEntry) -> [TmuxWindow] { + let entries = entry.windows?.elements ?? [] + // Fail open to the first window when the server named none active: + // the active window carries the tile's agent/title line. + let activeID = entry.active ?? entries.first?.id + return entries.enumerated().map { offset, window in + let blocks = window.blocks?.elements ?? [] + let focusID = window.focus ?? blocks.first?.id + let panes = blocks.enumerated().map { blockOffset, block in + TmuxPane( + index: blockOffset, + isActive: block.id == focusID, + tmuxID: block.id, + pid: block.pid ?? 0, + tty: "", + command: block.name ?? "", + title: block.title ?? "", + agent: agent(of: block) + ) + } + var mapped = TmuxWindow( + // Tab order, counted from one as Rex's own `-w 2` does. + index: offset + 1, + name: windowName( + window, position: offset + 1, + focusedBlockLabel: blocks.first { $0.id == focusID }?.label), + isActive: window.id == activeID, + hasBell: false, + hasActivity: false, + panes: panes + ) + if let active = panes.first(where: \.isActive) { + mapped.agent = active.agent + mapped.paneTitle = active.title + } + return mapped + } + } + + /// A window nobody named carries a generated label built from its own + /// id (`Window 262b0b23`, observed on preview.19) — noise on a spine + /// line. Only that exact shape is replaced, so a label someone chose is + /// never second-guessed, and a server that generates labels differently + /// simply shows its own. + /// + /// The stand-in is the focused block's label (`shell`, or whatever the + /// block was named — `agent`, `logs`): the nearest thing Rex has to + /// tmux naming a window after what runs in it. `window N` is the last + /// resort only, because the spine already leads each line with N and + /// the first headless run read `1 WINDOW 1`. + private static func windowName( + _ window: WindowEntry, position: Int, focusedBlockLabel: String? + ) -> String { + let label = displayLabel(window.label ?? "") + let generated = "Window " + window.id.suffix(8) + guard label.isEmpty || label == generated else { return label } + let blockLabel = displayLabel(focusedBlockLabel ?? "") + return blockLabel.isEmpty ? String(localized: "window \(position)") : blockLabel + } + + /// Which agent owns a block. The foreground process is the authority; + /// its OSC title is the tmux probe's own cheap pass; the program's + /// reported `app` is consulted last, because a status record outlives + /// the program that wrote it (`done` survives exit by design). + private static func agent(of block: BlockEntry) -> AgentKind? { + if let direct = AgentSignature.classify( + command: block.name ?? "", title: block.title ?? "") { + return direct + } + // `script` names what an interpreter is running (`node …/claude`), + // the shape `AgentSignature.match` already knows how to read. + let argv = [block.argv0 ?? block.name, block.script] + .compactMap { $0 } + .filter { !$0.isEmpty } + .joined(separator: " ") + if let matched = AgentSignature.match(argv: argv) { return matched } + return (block.status?.elements ?? []).lazy + .compactMap(\.app) + .compactMap(AgentKind.init(programStatusApp:)) + .first + } + + private static func signals(of entry: SessionEntry) -> SessionSignals { + var signals = SessionSignals() + let windows = entry.windows?.elements ?? [] + let activeID = entry.active ?? windows.first?.id + for window in windows { + let blocks = window.blocks?.elements ?? [] + let focusID = window.focus ?? blocks.first?.id + for block in blocks { + let statuses = (block.status?.elements ?? []).map(programStatus(from:)) + signals.reported += statuses + if window.id == activeID, block.id == focusID { + signals.front = statuses + } + } + } + return signals + } + + private static func programStatus(from entry: StatusEntry) -> ProgramStatus { + // The protocol's three kinds; `auth` (a password or token) is a + // prompt the user has to answer, which is what `.question` means + // here. Absent or unrecognized stays nil — the generic prompt. + let kind: AttentionKind? = switch entry.kind { + case "permission": .permission + case "question", "auth": .question + default: nil + } + return ProgramStatus( + state: ProgramState(rawValue: entry.state ?? "") ?? .unknown, + kind: kind + ) + } + + // MARK: - Open Terminal menu + + /// One row of a Rex tile's Open Terminal menu: the window, then what + /// tells its terminals apart — the program's own title, else the + /// foreground command, else the terminal's position in the window. + static func terminalMenuTitle(window: TmuxWindow, pane: TmuxPane) -> String { + let what = [pane.title, pane.command] + .map { $0.trimmingCharacters(in: .whitespaces) } + .first { !$0.isEmpty } + ?? String(localized: "terminal \(pane.index + 1)") + return "\(window.name) — \(what)" + } + + /// The tab mode for one named terminal of a session — the menu row's + /// press. nil when the record carries no usable session id. + static func attachMode( + session: TmuxSession, window: TmuxWindow, pane: TmuxPane + ) -> TerminalRoute.Mode? { + guard bakeableSessionID(session.tmuxID), !pane.tmuxID.isEmpty else { return nil } + return .rexAttach( + sessionName: session.name, + sessionID: session.tmuxID, + block: RexBlockRef(id: pane.tmuxID, label: window.name) + ) + } + + // MARK: - Session actions + + /// A session id the app may splice into a command: `session:` and a + /// UUID's characters, nothing a shell could reinterpret. What the parser + /// reports is truth; what reaches a shell line is vetted here. + static func bakeableSessionID(_ id: String) -> Bool { + let prefix = "session:" + guard id.hasPrefix(prefix), id.utf8.count <= 64 else { return false } + let rest = id.dropFirst(prefix.count) + return !rest.isEmpty && rest.unicodeScalars.allSatisfy { scalar in + (scalar >= "0" && scalar <= "9") + || (scalar >= "a" && scalar <= "f") + || (scalar >= "A" && scalar <= "F") + || scalar == "-" + } + } + + /// The deck tile's destructive close. Aimed at the session's ID, never + /// its label: labels are shared, and `rex kill work` on a server with + /// two of them refuses both. nil when the record carries no usable id — + /// a tile restored from a snapshot always has one, so this is only a + /// response that never named it. + static func killCommand(for session: TmuxSession) -> String? { + guard bakeableSessionID(session.tmuxID) else { return nil } + return pathPrefix + + "\(rexCommand) kill \(session.tmuxID.shellQuoted) >/dev/null 2>&1; true" + } + + /// The discovery rider's list verb, without the PATH export: one id per + /// line. Ids rather than `ls --json`, which is pretty-printed across + /// lines and would need a document parser for what is only ever counted. + static let sessionListVerb = "\(rexCommand) ls -q 2>/dev/null || true" + + /// The session ids in a `ls -q` answer. Anything that is not an id — + /// login-shell noise, a warning — is not a session. + static func parseSessionIDs(_ lines: [some StringProtocol]) -> [String] { + lines.map { $0.trimmingCharacters(in: .whitespaces) } + .filter(bakeableSessionID) + } + + // MARK: - New session + + /// The server's own limit is 128 characters; this leaves room for the + /// `-N` a taken label gains. + private static let maxLabelLength = 120 + /// The environment variable a shell-resolved start directory rides in. + private static let directoryVariable = "MULTIPLEX_REX_CWD" + + /// The label a new session is asked for: read the way a label coming + /// back is (`displayLabel` — so the name the tab is opened under is the + /// name the next probe reports), clamped, and never empty. An empty + /// label makes the server invent one (`quiet-meadow`), which nothing + /// here could have predicted. + static func sessionLabel(base: String) -> String { + let label = String(displayLabel(base).prefix(maxLabelLength)) + .trimmingCharacters(in: .whitespaces) + return label.isEmpty ? "session" : label + } + + /// `sessionLabel`, respelled `-2`, `-3`, … while taken — tmux's own + /// scheme. Compared without case, as `sessionNames` counts: two labels + /// that differ only by case would both be shown with an id tail. + static func uniqueSessionLabel(base: String, existing: some Sequence) -> String { + let base = sessionLabel(base: base) + let taken = Set(existing.map { $0.lowercased() }) + guard taken.contains(base.lowercased()) else { return base } + var suffix = 2 + while taken.contains("\(base)-\(suffix)".lowercased()) { suffix += 1 } + return "\(base)-\(suffix)" + } + + /// The mint script. One connection: read the live labels, settle the + /// name against them (Rex itself would happily create a second `work`, + /// and both would then be shown with an id tail), resolve the start + /// directory, create the session with one shell terminal, and report + /// the id and the label the server actually stored. + /// + /// The source session's directory is its fronted terminal's, the same + /// one the tile shows; it wins over an explicit directory, and every + /// miss is $HOME — `TmuxProbe.newSessionCommand`'s own precedence. + /// + /// Contains no single quote, so shell-quoting it is one pair of quotes. + private static let mintScript: String = """ + local T = "com.superlogical.terminal." + local a = rex.args or {} + local function text(v) if type(v) == "string" then return v end return "" end + rex.call("session.attach_all", { event_scope = "session" }) + local list = rex.call("session.list") + if not list then return { ok = false } end + local taken = {} + for _, s in ipairs(list.sessions or {}) do taken[string.lower(text(s.label))] = true end + local label = text(a.label) + if taken[string.lower(label)] then + local n = 2 + while taken[string.lower(label .. "-" .. n)] do n = n + 1 end + label = label .. "-" .. n + end + local cwd = "" + local source = text(a.source) + if source ~= "" then + local view = rex.call("session.view", { session_id = source }) + if view then + for _, w in ipairs(view.windows or {}) do + if w.window_id == view.active_window_id and w.focused_block_id then + local p = rex.call(T .. "process", { session_id = source, block_id = w.focused_block_id, args = {} }) + if p and p.foreground then cwd = text(p.foreground.cwd) end + end + end + end + elseif os and os.getenv then + cwd = text(os.getenv("\(directoryVariable)")) + end + local block = { flavor = T .. "shell" } + local options = {} + if cwd ~= "" then options.cwd = cwd end + if text(a.input) ~= "" then options.initial_input = text(a.input) end + if next(options) then block.options = options end + local made = rex.call("session.create", { label = label, initial_windows = { { layout = { block = block } } } }) + if not made or not made.session_id then return { ok = false } end + local after = rex.call("session.list") + for _, s in ipairs((after and after.sessions) or {}) do + if s.session_id == made.session_id then label = text(s.label) end + end + return { ok = true, id = made.session_id, label = label } + """ + .split(separator: "\n") + .map { $0.drop(while: { $0 == " " }) } + .joined(separator: "\n") + + /// Create a session with one shell terminal, over the control + /// connection — the Rex arm of `HostConnectionModel.createSession`. + /// + /// - `label`: what `sessionLabel` made of the requested name. The + /// script settles it against the server's live labels. + /// - `sourceSessionID`: start where that session's fronted terminal is. + /// - `directory`: an explicit start directory, consulted only without a + /// source. The SHELL resolves it — `~`, a path relative to $HOME, a + /// directory that is not there — because the server takes `cwd` + /// literally; what it resolved to rides the environment into the + /// script, and nothing at all when it does not exist. + /// - `lines`: typed into the fresh shell in order, each followed by + /// Enter — the setup script, then the launch line. Same shell, so + /// what the first exports is live for the second. + /// + /// The values the user typed travel as ONE JSON argument, never as + /// script text, so no label or prompt can become Lua. Always exits 0 + /// (Citadel throws on a non-zero status); the CLI's own status is the + /// last line, as in the probe. + static func mintCommand( + label: String, inDirectoryOf sourceSessionID: String?, + startingIn directory: String?, typing lines: [String] + ) -> String { + var arguments = ["label": label] + var environment = "" + var resolve = "" + if let sourceSessionID { + arguments["source"] = sourceSessionID + } else if let directory { + resolve = "d=\(directory.shellQuotedDirectory); " + + "d=$(CDPATH= cd -- \"$d\" 2>/dev/null && pwd); " + environment = "\(directoryVariable)=\"$d\" " + } + let input = lines.map { $0 + "\r" }.joined() + if !input.isEmpty { arguments["input"] = input } + let json = (try? JSONSerialization.data( + withJSONObject: arguments, options: [.sortedKeys, .withoutEscapingSlashes] + )).map { String(decoding: $0, as: UTF8.self) } ?? "{}" + return pathPrefix + + "command -v rex >/dev/null 2>&1 || { echo \(noRexMarker); exit 0; }; " + + resolve + + "echo \(mintMarker); " + + environment + + "\(rexCommand) do -e \(mintScript.shellQuoted) --args \(json.shellQuoted)" + + " --json 2>/dev/null; " + + "echo \"\(exitMarker) $?\"" + } + + /// How a mint ended. + enum MintOutcome: Equatable { + /// `name` is the session's name as the next probe will report it. + case created(name: String, id: String) + case rexMissing + /// `rex` is installed and no server is running. Multiplex does not + /// start one, so there was nothing to create the session in. + case noServer + case failed + } + + private struct MintReply: Decodable { + var ok: Bool? + var id: String? + var label: String? + } + + static func parseMint(_ output: String) -> MintOutcome { + switch scriptReply(in: output, marker: mintMarker) { + case .rexMissing: + return .rexMissing + case .unreadable: + return .failed + case .exited(let exitCode): + return exitCode == serverUnreachableExit ? .noServer : .failed + case .json(let json): + guard let reply = try? JSONDecoder().decode(MintReply.self, from: Data(json.utf8)), + reply.ok == true, let id = reply.id, bakeableSessionID(id) + else { return .failed } + // Spelled as `sessionNames` would spell a session that is alone + // under its label — which the script just made true. + let label = displayLabel(reply.label ?? "") + return .created(name: label.isEmpty ? "…" + shortID(id) : label, id: id) + } + } + + // MARK: - Attention + + /// A session tile's attention when its programs report status: the fold + /// of every record in the session. Any blocked program needs you; else + /// any working one means busy; else anything that vouched for itself + /// means idle; nothing but `unknown` makes no claim. `done` and `error` + /// fold to idle on purpose — handing the tracker that busy → idle edge + /// is what announces the turn exactly once, herdr's own rule. + static func sessionAgentState( + _ statuses: some Sequence + ) -> PaneAgentState? { + var sawWorking = false + var sawKnown = false + var blocked: AttentionKind? + for status in statuses { + switch status.state { + case .blocked: + // A question outranks a bare permission prompt only in that + // the first blocked record names the kind; either way the + // tile needs you. + if blocked == nil { blocked = status.kind ?? .permission } + case .working: sawWorking = true + case .idle, .done, .error: sawKnown = true + case .unknown: break + } + } + if let blocked { return .needsYou(blocked) } + if sawWorking { return .busy } + return sawKnown ? .idle : nil + } + + /// Whether the fronted block's own records agree with the session-level + /// verdict. Alert metadata only: a blocked background window must not + /// borrow the fronted block's agent name or screen. + static func frontProducedSessionState( + _ state: PaneAgentState?, front: [ProgramStatus] + ) -> Bool { + guard let state, !front.isEmpty else { return false } + return sessionAgentState(front) == state + } +} + +extension RexProbe.State { + /// The wall consumes `TmuxState`; Rex states fold onto it. Rex is only + /// ever a secondary, so `missing` and `no server` render nothing — the + /// user asked to see its sessions if they exist. + var tmuxState: TmuxState { + switch self { + case .rexMissing: .tmuxMissing + case .noServer: .noServer + case .sessions(let sessions): .sessions(sessions) + case .failed(let message): .failed(message) + } + } +} + +extension AgentKind { + /// The `app` a program names itself with in an OSC 7501 report. The + /// protocol's own example is `claude-code`; every other spelling here + /// is the agent's command name, the only thing it can plausibly report. + /// Unrecognized apps (`cargo`, `terraform`) are programs, not agents. + init?(programStatusApp app: String) { + switch app.lowercased() { + case "claude-code", "claude": self = .claudeCode + case "codex": self = .codex + case "pi": self = .pi + case "grok": self = .grok + case "antigravity", "agy": self = .antigravity + case "hermes", "hermes-agent": self = .hermes + default: return nil + } + } +} diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift new file mode 100644 index 00000000..2f82e58c --- /dev/null +++ b/Multiplex/Services/RexSession.swift @@ -0,0 +1,843 @@ +import Foundation +import OSLog + +/// One WebSocket to a Rex server, carried over a `RemotePipe`. +/// +/// `open` performs the upgrade and returns once frames can flow. Messages +/// then arrive on `messages` in order; pings are answered here, so a +/// consumer only ever sees text, binary, and the closing frame. +struct RexSocket: Sendable { + let messages: AsyncThrowingStream + private let pipe: RemotePipe + + static func open( + over pipe: RemotePipe, path: String, subprotocol: String + ) async throws -> RexSocket { + let key = WebSocketCodec.makeKey() + let (messages, feed) = AsyncThrowingStream.makeStream() + try await pipe.write(WebSocketCodec.upgradeRequest( + path: path, host: "rex", subprotocol: subprotocol, key: key)) + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let upgraded = RexOneShot(continuation) + let reader = Task { + var head = Data() + var isUpgraded = false + var decoder = WebSocketCodec.Decoder() + do { + for try await chunk in pipe.incoming { + if isUpgraded { + decoder.append(chunk) + } else { + head.append(chunk) + guard case .upgraded(let remainder) = + try WebSocketCodec.readUpgradeResponse( + head, key: key, subprotocol: subprotocol) + else { continue } + isUpgraded = true + head = Data() + decoder.append(remainder) + upgraded.succeed() + } + while let message = try decoder.next() { + switch message { + case .ping(let payload): + // The server drops a connection after three + // unanswered pings. + try await pipe.write( + WebSocketCodec.frame(.pong, payload: payload)) + case .pong: + break + case .close: + feed.yield(message) + feed.finish() + return + case .text, .binary: + feed.yield(message) + } + } + } + if !upgraded.fail(RexSession.Failure(String( + localized: "The Rex server closed the connection before answering."))) { + feed.finish() + } + } catch { + if !upgraded.fail(error) { feed.finish(throwing: error) } + } + } + feed.onTermination = { _ in reader.cancel() } + } + return RexSocket(messages: messages, pipe: pipe) + } + + func send(_ opcode: WebSocketCodec.Opcode, _ payload: Data) async throws { + try await pipe.write(WebSocketCodec.frame(opcode, payload: payload)) + } + + /// Says goodbye and drops the channel. Status 1000 matters on a data + /// connection: it is what ends the stream instead of parking it for a + /// resume nobody will send. + func close() async { + try? await pipe.write(WebSocketCodec.closeFrame(code: 1000)) + pipe.close() + } +} + +/// Resumes a continuation exactly once — the upgrade completing vs. the +/// pipe ending first. +private final class RexOneShot: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + + init(_ continuation: CheckedContinuation) { + self.continuation = continuation + } + + private func take() -> CheckedContinuation? { + lock.withLock { + let taken = continuation + continuation = nil + return taken + } + } + + func succeed() { + take()?.resume() + } + + /// False when the continuation had already been resumed. + func fail(_ error: Error) -> Bool { + guard let continuation = take() else { return false } + continuation.resume(throwing: error) + return true + } +} + +/// A terminal tab attached to one Rex terminal block — the third +/// `TerminalTransport`, beside the SSH PTY and mosh. +/// +/// Rex has no terminal client to run in a PTY (see `RexProbe`), so this IS +/// the client: it speaks the server's WebSocket API through two byte pipes +/// on the tab's SSH connection (`SSHConnection.openPipe` running `rex +/// __internal dial-stdio`, the bridge Rex's own `ssh://` transport uses). +/// +/// - The **control** connection attaches to the session, claims the block, +/// sizes it, and carries every keystroke as a +/// `com.superlogical.terminal.write` call. +/// - The **data** connection carries the block's output, one way. +/// +/// What is deliberate here: +/// - **The screen is bootstrapped from `format`, not from the stream.** The +/// stream opens with a Ghostty binary snapshot SwiftTerm cannot read +/// (`RexTerminalStream` drops it), so the starting screen comes from the +/// `vt` rendering instead. The block is claimed and sized BEFORE either +/// is asked for, so both describe the terminal at this tab's size. +/// - **The two are not atomic, and the gap errs toward repeating.** The +/// stream is opened first and held while `format` is fetched: output the +/// program wrote in between is drawn twice (once inside the rendering, +/// once from the stream) rather than lost. Lost bytes can leave a mode +/// wrong for the rest of the session; a repeated line is one line. +/// - **The last client to type owns the size**, as with tmux's latest-client +/// rule. Another client (the Rex app) can claim the block back; the next +/// keystroke here claims it again and re-sizes it. +/// - **The palette is the app's.** `extra_palette` is not requested: it +/// would repaint the tab in Rex's theme. +/// - **A tab attached during a full-screen program redraws when it exits.** +/// While one is up, `format` renders only its screen — the shell history +/// underneath cannot be asked for — so the emulator's primary screen +/// starts empty and leaving vim showed a bare prompt (seen on the first +/// headless run). `AlternateScreenExitWatch` notices the exit and the +/// screen is fetched again, under the same hold-then-flush rule as the +/// attach. +actor RexSession: TerminalTransport { + /// A reason a person can read — the tab's ended line. + struct Failure: Error, Equatable { + var message: String + + init(_ message: String) { + self.message = message + } + } + + private static let log = Logger( + subsystem: "app.multiplexterm.multiplex", category: "rex") + + /// How much of a `vt` rendering one request asks for (the method caps + /// it near 960 KiB), and how large a rendering is still worth fetching + /// in full. A terminal keeps up to 64 MiB of scrollback; past this the + /// attach draws a plain-text tail instead of waiting on megabytes. + private static let bootstrapChunk = 900_000 + private static let bootstrapLimit = 3_000_000 + private static let plainTailBytes = 16 * 1024 + + /// Opens one byte pipe to the Rex server's socket; called twice per + /// attach (control, then data). A closure rather than the connection + /// itself so the whole session can be driven by an in-process server + /// under test. + private let openPipe: @Sendable () async throws -> RemotePipe + /// Drops whatever the pipes ride on — the tab's SSH connection. + private let closeLink: @Sendable () async -> Void + private let sessionID: String + private let preferredBlockID: String? + private let clientVersion: String + + private var control: RexSocket? + private var data: RexSocket? + private var controlReader: Task? + private var dataReader: Task? + + private struct Reply: @unchecked Sendable { + var payload: [String: Any] + } + private var pending: [String: CheckedContinuation] = [:] + private var timeouts: [String: Task] = [:] + private var requestCount = 0 + + private enum Milestone: Hashable { case welcome, dataWelcome, live } + private var reached: Set = [] + private var waiters: [Milestone: CheckedContinuation] = [:] + + private var clientID: String? + private(set) var blockID: String? + private var owner: String? + private var stream: RexTerminalStream? + /// Stream output that arrived before the bootstrap was drawn. + private var held = Data() + private var isBootstrapped = false + /// Set while the emulator's primary screen is known to be incomplete — + /// the bootstrap was rendered during a full-screen program. + private var exitWatch: AlternateScreenExitWatch? + private var lastOutput = ContinuousClock.now + private var isOpen = false + private var isClosed = false + private var size: (cols: Int, rows: Int) = (80, 24) + private var input = RexInputEncoder() + private var pendingInput = "" + private var isWriting = false + private var isSwitching = false + /// Bumped whenever the data connection is replaced. A reader reports + /// with the generation it was started under, so a retired stream's + /// last words are recognised as that and dropped. + private var dataGeneration = 0 + + private var onData: (@Sendable (Data) -> Void)? + private var onClose: (@Sendable (String?) -> Void)? + + init( + openPipe: @escaping @Sendable () async throws -> RemotePipe, + closeLink: @escaping @Sendable () async -> Void, + sessionID: String, blockID: String?, clientVersion: String + ) { + self.openPipe = openPipe + self.closeLink = closeLink + self.sessionID = sessionID + preferredBlockID = blockID + self.clientVersion = clientVersion + } + + /// The app's form: both pipes ride `connection`, each running the Rex + /// CLI's stdio bridge, and closing the session closes the connection. + init( + connection: SSHConnection, sessionID: String, blockID: String?, + clientVersion: String + ) { + self.init( + openPipe: { try await connection.openPipe(running: RexProbe.bridgeCommand) }, + closeLink: { await connection.close() }, + sessionID: sessionID, blockID: blockID, clientVersion: clientVersion + ) + } + + // MARK: - Opening + + /// Attaches and returns once the terminal's current screen has been + /// handed to `onData`. `onClose` fires at most once, later, when the + /// block or the link ends on its own (nil for a clean end). + func open( + cols: Int, rows: Int, + onData: @Sendable @escaping (Data) -> Void, + onClose: @Sendable @escaping (String?) -> Void + ) async throws { + self.onData = onData + self.onClose = onClose + size = (cols, rows) + do { + try await attach() + isOpen = true + } catch { + let failure = Self.failure(from: error) + await teardown(failing: failure) + throw failure + } + } + + private func attach() async throws { + let control = try await RexSocket.open( + over: try await openPipe(), + path: RexWire.controlPath, subprotocol: RexWire.controlSubprotocol) + self.control = control + try await control.send(.text, RexWire.hello(clientVersion: clientVersion)) + startControlReader(control) + try await wait(for: .welcome) + + let attached = try await call("session.attach", ["session_id": sessionID]) + if let id = attached["client_id"] as? String { clientID = id } + let blocks = RexWire.terminalBlocks( + inView: attached["view"] as? [String: Any] ?? [:]) + guard let block = RexWire.attachTarget(in: blocks, preferring: preferredBlockID) else { + throw Failure(String(localized: "This Rex session has no terminal to open.")) + } + try await showBlock(block.id) + } + + /// Points the tab at one terminal block: claim and size it, open its + /// stream, draw its screen. The attach's second half, and the whole of + /// a switch. + private func showBlock(_ blockID: String) async throws { + self.blockID = blockID + // Claim and size first: the rendering and the stream below must + // both describe the terminal at THIS tab's size. + await claimAndSize() + + let ticket = try await call("data.connect", [ + "session_id": sessionID, + "block_id": blockID, + "data_ref_id": "terminal", + "subprotocol": RexWire.terminalSubprotocol, + ]) + guard let hello = (ticket["ticket"] as? String).flatMap(RexWire.dataHello) else { + throw Failure(String(localized: "The Rex server issued no usable stream ticket.")) + } + let data = try await RexSocket.open( + over: try await openPipe(), + path: RexWire.dataPath, subprotocol: RexWire.terminalSubprotocol) + self.data = data + try await data.send(.binary, hello) + startDataReader(data) + try await wait(for: .dataWelcome) + // The snapshot has passed once the first server message arrives; + // only then is the terminal's state settled enough to render. + try await wait(for: .live) + + await drawScreen(blockID: blockID) + } + + /// The directory the terminal on show is working in — what a file drop + /// lands in and a file viewer opens at. nil when the tab is not live or + /// the server cannot say. + func workingDirectory() async -> String? { + guard isOpen, !isClosed, let blockID, + let process = try? await call( + RexWire.terminalCreator + ".process", + RexWire.blockPayload(sessionID: sessionID, blockID: blockID)) + else { return nil } + return RexWire.workingDirectory(inProcess: process) + } + + // MARK: - Switching terminals + + /// Every terminal of the session, as the REX panel's Switch Terminal + /// rows, with the one this tab shows marked. Read fresh each time the + /// panel opens: windows come and go in Rex without telling the tab. + func terminalChoices() async -> [TmuxWindowChoice]? { + guard isOpen, !isClosed, + let view = try? await call("session.view", ["session_id": sessionID]) + else { return nil } + return RexWire.terminalChoices( + in: RexWire.terminalBlocks(inView: view), showing: blockID) + } + + /// Points this tab at another terminal of the same session, in place: + /// the control connection and the tab stay, only the stream and the + /// screen change. + /// + /// The old block is given up as well as left. Owning a block is what + /// makes it follow this tab's size, and a terminal nobody here is + /// looking at any more has no business keeping it — the Rex window + /// showing it gets its own size back. A switch that cannot complete + /// ends the tab with the reason rather than leaving it on a dead + /// stream; RECONNECT then attaches afresh. + func switchBlock(to newID: String) async { + guard isOpen, !isClosed, !isSwitching, newID != blockID else { return } + isSwitching = true + defer { isSwitching = false } + let previous = blockID + + // Retire the old stream. The generation bump is what keeps its + // reader's parting "ended" from being read as the TAB ending. + dataGeneration += 1 + let oldData = data + data = nil + await oldData?.close() + dataReader?.cancel() + dataReader = nil + stream = nil + reached.subtract([.dataWelcome, .live]) + held = Data() + isBootstrapped = false + exitWatch = nil + pendingInput = "" + input = RexInputEncoder() + + if let previous { + _ = try? await call("session.disown_block", [ + "session_id": sessionID, "block_ids": [previous], + ]) + } + do { + try await showBlock(newID) + } catch { + finish(Self.failure(from: error).message) + } + } + + /// Renders the terminal's current screen into the emulator, then lets + /// the stream through. Stream output is held from the moment this is + /// called (the attach holds it from the start) to the moment the + /// rendering has been drawn, so nothing is drawn UNDER a rendering that + /// was taken later, and nothing that arrived meanwhile is dropped. + private func drawScreen(blockID: String) async { + isBootstrapped = false + let onAlternateScreen = await isOnAlternateScreen(blockID: blockID) + let screen = await bootstrapScreen(blockID: blockID) + guard !isClosed else { return } + // RIS first: a resumed tab still shows what the last run drew. + onData?(Data([0x1B, 0x63]) + screen) + exitWatch = onAlternateScreen ? AlternateScreenExitWatch() : nil + isBootstrapped = true + if !held.isEmpty { + let pending = held + held = Data() + deliver(pending) + } + } + + /// Stream output on its way to the emulator. The one place that also + /// watches for a full-screen program exiting, when that matters. + private func deliver(_ output: Data) { + onData?(output) + lastOutput = .now + guard exitWatch?.sawExit(in: output) == true, let blockID else { return } + exitWatch = nil + Task { await self.redrawOnceQuiet(blockID: blockID) } + } + + /// A full-screen program just exited: wait for the burst that follows + /// it to finish, then render the screen again. + /// + /// The wait is what keeps the redraw from repeating the shell's prompt. + /// Output that arrives while a rendering is being fetched is held and + /// drawn after it, so anything the rendering already contains is drawn + /// twice — and a shell prints its prompt within milliseconds of the + /// program leaving (the first headless run ended on `$ $`). Letting that + /// burst through first, to be replaced by a rendering taken once the + /// terminal has gone quiet, leaves nothing in the window to repeat. A + /// terminal that never goes quiet is redrawn anyway after the cap. + private func redrawOnceQuiet(blockID: String) async { + let started = ContinuousClock.now + while !isClosed { + try? await Task.sleep(for: .milliseconds(60)) + let now = ContinuousClock.now + if now - lastOutput >= .milliseconds(120) || now - started >= .milliseconds(800) { + break + } + } + guard !isClosed else { return } + await drawScreen(blockID: blockID) + } + + /// Whether a full-screen program currently owns the terminal. Asked of + /// the server rather than read out of the rendering: `modes` states it + /// outright. An answer that cannot be had reads as "no". + private func isOnAlternateScreen(blockID: String) async -> Bool { + let modes = try? await call( + RexWire.terminalCreator + ".modes", + RexWire.blockPayload(sessionID: sessionID, blockID: blockID)) + return modes?["screen"] as? String == "alternate" + } + + /// Makes this client the block's owner and gives it this tab's size. + /// Best effort: a refusal leaves the terminal at someone else's size, + /// which is wrong-looking but not fatal. + private func claimAndSize() async { + guard let blockID else { return } + if let claimed = try? await call("session.own_block", [ + "session_id": sessionID, "block_ids": [blockID], "mode": "take", + ]) { + let mine = (claimed["blocks"] as? [[String: Any]])? + .first { $0["block_id"] as? String == blockID } + owner = mine?["owner"] as? String ?? clientID + } + _ = try? await call( + RexWire.terminalCreator + ".resize", + RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, + args: ["columns": size.cols, "rows": size.rows])) + } + + /// The terminal's screen and scrollback as escape sequences SwiftTerm + /// can draw. Falls back to a plain-text tail for a terminal whose + /// rendering is too large to wait for, and to nothing at all — the + /// stream alone — if the server will not render. + private func bootstrapScreen(blockID: String) async -> Data { + let method = RexWire.terminalCreator + ".format" + guard let first = try? await call(method, RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, + args: [ + "format": "vt", + "extra_cursor": true, + "extra_modes": true, + "extra_scrolling_region": true, + "extra_style": true, + "extra_charsets": true, + "extra_keyboard": true, + "extra_kitty_keyboard": true, + "extra_tabstops": true, + "max_bytes": Self.bootstrapChunk, + ])) + else { return Data() } + var text = first["content"] as? String ?? "" + guard let id = first["id"] as? Int else { return Data(text.utf8) } + let total = first["total"] as? Int ?? .max + guard total <= Self.bootstrapLimit else { + return await plainTail(blockID: blockID) + } + var offset = text.utf8.count + while offset < total { + guard let more = try? await call( + RexWire.terminalCreator + ".blob_read", + RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, + args: ["id": id, "offset": offset, "max_bytes": Self.bootstrapChunk])), + let piece = more["data"] as? String, !piece.isEmpty + else { break } + text += piece + offset += piece.utf8.count + if more["eof"] as? Bool == true { break } + } + return Data(text.utf8) + } + + /// The last screenful or so as plain text — no colors, but the user + /// lands on what the terminal was showing rather than on nothing. Read + /// from the END (`RexProbe` explains why a capped read stops short). + private func plainTail(blockID: String) async -> Data { + let creator = RexWire.terminalCreator + guard let first = try? await call(creator + ".format", RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, + args: ["format": "text", "trim": true, "max_bytes": 1])), + let id = first["id"] as? Int, let total = first["total"] as? Int + else { return Data() } + let offset = max(0, total - Self.plainTailBytes) + guard let rest = try? await call(creator + ".blob_read", RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, args: ["id": id, "offset": offset])), + let tail = rest["data"] as? String + else { return Data() } + var lines = tail.split(separator: "\n", omittingEmptySubsequences: false) + // A read that started mid-screen starts mid-line. + if offset > 0, !lines.isEmpty { lines.removeFirst() } + return Data(lines.joined(separator: "\r\n").utf8) + } + + // MARK: - TerminalTransport + + func write(_ data: Data) async throws { + guard isOpen, !isClosed else { throw Failure("not attached") } + // Mid-switch the screen on show is the terminal being left; a key + // pressed then is dropped rather than typed into one not yet drawn. + guard !isSwitching else { return } + pendingInput += input.encode(data) + // One write in flight at a time: the server runs block methods + // concurrently, so two calls could land out of order. Whatever is + // typed meanwhile rides the next call as one string. + guard !isWriting else { return } + isWriting = true + defer { isWriting = false } + while !pendingInput.isEmpty, !isClosed, let blockID { + let text = pendingInput + pendingInput = "" + // Typing is what claims the size back from another client. + if owner != clientID { await claimAndSize() } + do { + _ = try await call( + RexWire.terminalCreator + ".write", + RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, args: ["data": text])) + } catch { + Self.log.debug("write failed: \(String(describing: error), privacy: .public)") + } + } + } + + func resize(cols: Int, rows: Int) async throws { + size = (cols, rows) + guard isOpen, !isClosed, let blockID else { return } + // Applies at once while this client owns the block, and otherwise + // waits server-side until it does — never a failure worth raising. + _ = try? await call( + RexWire.terminalCreator + ".resize", + RexWire.blockPayload( + sessionID: sessionID, blockID: blockID, + args: ["columns": cols, "rows": rows])) + } + + /// Idempotent, and always closes the SSH connection the two pipes ride: + /// a tab that ended on its own (`finish`) still has that link to drop. + func close() async { + if !isClosed { + isClosed = true + await teardown(failing: Failure("closed")) + } + await closeLink() + } + + // MARK: - Requests + + private func call( + _ method: String, _ payload: [String: Any]?, timeout: Double = 10 + ) async throws -> [String: Any] { + guard let control else { throw Failure("not connected") } + requestCount += 1 + let id = "m\(requestCount)" + let message = RexWire.request(id: id, method: method, payload: payload) + let reply: Reply = try await withCheckedThrowingContinuation { continuation in + pending[id] = continuation + timeouts[id] = Task { [weak self] in + do { try await Task.sleep(for: .seconds(timeout)) } catch { return } + await self?.settle(id, .failure(Failure(String( + localized: "The Rex server did not answer in time.")))) + } + Task { [weak self] in + do { + try await control.send(.text, message) + } catch { + await self?.settle(id, .failure(error)) + } + } + } + return reply.payload + } + + private func settle(_ id: String, _ result: Result) { + timeouts.removeValue(forKey: id)?.cancel() + pending.removeValue(forKey: id)?.resume(with: result) + } + + // MARK: - Milestones + + private func wait(for milestone: Milestone, seconds: Double = 10) async throws { + guard !reached.contains(milestone) else { return } + let timer = Task { [weak self] in + do { try await Task.sleep(for: .seconds(seconds)) } catch { return } + await self?.fail(milestone, Failure(String( + localized: "The Rex server did not answer in time."))) + } + defer { timer.cancel() } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + waiters[milestone] = continuation + } + } + + private func reach(_ milestone: Milestone) { + reached.insert(milestone) + waiters.removeValue(forKey: milestone)?.resume() + } + + private func fail(_ milestone: Milestone, _ error: Error) { + waiters.removeValue(forKey: milestone)?.resume(throwing: error) + } + + // MARK: - Control connection + + private func startControlReader(_ socket: RexSocket) { + controlReader = Task { [weak self] in + do { + for try await message in socket.messages { + await self?.handleControl(message) + } + await self?.linkEnded(nil) + } catch { + await self?.linkEnded(Self.failure(from: error).message, failed: true) + } + } + } + + private func handleControl(_ message: WebSocketCodec.Message) { + switch message { + case .text(let text): + switch RexWire.decodeInbound(text) { + case .welcome(let id)?: + if let id { clientID = id } + reach(.welcome) + case .response(let id, let result)?: + settle(id, result.map(Reply.init(payload:)).mapError { $0 as Error }) + case .event(let type, let fields)?: + handleEvent(type, fields) + case .unknown?, nil: + break + } + case .close(_, let reason): + linkEnded(reason.isEmpty ? nil : reason) + case .binary, .ping, .pong: + break + } + } + + private func handleEvent(_ type: String, _ fields: [String: Any]) { + guard fields["block_id"] as? String == blockID else { return } + switch type { + case "block_owner_changed": + // nil when the event names no owner — the next keystroke then + // claims the block again, which is the safe reading. + owner = fields["owner"] as? String + case "block_closed": + finish(nil) + default: + break + } + } + + // MARK: - Data connection + + private func startDataReader(_ socket: RexSocket) { + let generation = dataGeneration + dataReader = Task { [weak self] in + do { + for try await message in socket.messages { + await self?.handleData(message, generation: generation) + } + await self?.dataLinkEnded(nil, generation: generation) + } catch { + await self?.dataLinkEnded( + Self.failure(from: error).message, failed: true, generation: generation) + } + } + } + + private func dataLinkEnded(_ reason: String?, failed: Bool = false, generation: Int) { + guard generation == dataGeneration else { return } + linkEnded(reason, failed: failed) + } + + private func handleData(_ message: WebSocketCodec.Message, generation: Int) { + guard generation == dataGeneration else { return } + switch message { + case .binary(let bytes): + guard var stream else { + switch RexWire.parseDataReply(bytes) { + case .welcome(let nonce)?: + self.stream = RexTerminalStream(nonce: nonce) + reach(.dataWelcome) + case .reject(let reason)?: + fail(.dataWelcome, Failure(String(localized: """ + The Rex server refused the terminal stream: \ + \(RexWire.rejectDescription(reason)). + """))) + case nil: + fail(.dataWelcome, Failure(String( + localized: "The Rex server answered the stream handshake unreadably."))) + } + return + } + let events = stream.consume(bytes) + self.stream = stream + if stream.isLive { reach(.live) } + for event in events { + switch event { + case .output(let output): + if isBootstrapped { deliver(output) } else { held.append(output) } + case .resize, .childExited: + // The size is this tab's own while it owns the block, + // and a program's exit closes the block, which arrives + // as the stream's close. Neither needs acting on here. + break + } + } + case .close(let code, let reason): + // 4000 is "block closed" and 1000 a stream that simply ended — + // both a clean end, like a shell exiting. + if code == 4000 || code == 1000 || code == nil { + finish(nil) + } else { + finish(String(localized: "Rex closed the terminal stream: \(reason).")) + } + case .text, .ping, .pong: + break + } + } + + // MARK: - Ending + + /// A connection ended without this side asking. Before the attach has + /// finished that is a failed attach (thrown from `open`); after, it is + /// the tab ending. + /// + /// `failed` marks a link that broke rather than closed. Under a live + /// tab that is said as what it is — the connection was lost — and the + /// error underneath is left out: it is the transport's own shorthand + /// (`Already closed`, seen on the first headless run), which reads as a + /// second, unrelated failure. During the attach the detail IS the + /// reason ("no Rex server is running"), so it is kept. + private func linkEnded(_ reason: String?, failed: Bool = false) { + guard !isClosed else { return } + guard isOpen else { + let failure = Failure(reason ?? String( + localized: "The connection to the Rex server ended.")) + for milestone in Array(waiters.keys) { fail(milestone, failure) } + for id in Array(pending.keys) { settle(id, .failure(failure)) } + return + } + finish(failed + ? String(localized: "The connection to the Rex server was lost.") + : reason) + } + + private func finish(_ reason: String?) { + guard !isClosed else { return } + isClosed = true + let notify = isOpen ? onClose : nil + Task { + await self.teardown(failing: Failure(reason ?? "ended")) + notify?(reason) + } + } + + private func teardown(failing failure: Failure) async { + for milestone in Array(waiters.keys) { fail(milestone, failure) } + for id in Array(pending.keys) { settle(id, .failure(failure)) } + let data = self.data, control = self.control + self.data = nil + self.control = nil + // Say goodbye BEFORE the readers are cancelled: cancelling a reader + // tears its pipe down, and a connection that just drops is kept by + // the server for a minute — its client listed as "connection lost", + // its stream parked for a resume nobody will send (seen on the + // first headless run). The data connection goes first, with status + // 1000, which ends the stream; a control connection closed with a + // close frame ends its client at once. + await data?.close() + await control?.close() + controlReader?.cancel() + dataReader?.cancel() + controlReader = nil + dataReader = nil + } + + /// Turns whatever the layers below threw into one readable sentence. + private static func failure(from error: Error) -> Failure { + if let failure = error as? Failure { return failure } + if let server = error as? RexWire.ServerError { + return Failure(server.code == "session_not_found" + ? String(localized: "This Rex session no longer exists.") + : String(localized: "The Rex server refused: \(server.message)")) + } + if case SSHConnectionError.connectFailed(let detail) = error { + return Failure(String(localized: "Couldn't reach the Rex server. \(detail)")) + } + if case WebSocketCodec.Failure.upgradeRefused(let status, _) = error { + return Failure(String( + localized: "The Rex server refused the connection (\(String(status))).")) + } + return Failure(String( + localized: "Couldn't attach the Rex session. \(error.localizedDescription)")) + } +} diff --git a/Multiplex/Services/SSHConnection.swift b/Multiplex/Services/SSHConnection.swift index 2be062c3..927a42c9 100644 --- a/Multiplex/Services/SSHConnection.swift +++ b/Multiplex/Services/SSHConnection.swift @@ -816,6 +816,95 @@ actor SSHConnection { try await stdinWriter.write(ByteBuffer(bytes: data)) } + // MARK: Raw byte pipe + + /// Opens a binary-safe, bidirectional byte pipe to `command` on the + /// host — its stdin and stdout, nothing in between. Several can be open + /// on one connection, each on a channel of its own beside the PTY. + /// + /// Exec cannot do this: Citadel 0.12.0's exec API returns output only + /// and keeps the channel to itself, so nothing can write stdin. What it + /// does expose is a SHELL channel without a PTY (`withTTY`): the login + /// shell runs on plain pipes — no line discipline, so bytes pass + /// untouched — and is handed over with one line, the PTY handoff's own + /// cross-shell `exec sh -c '…'` form. + /// + /// The command echoes a per-pipe marker first. Everything a login + /// script printed before it is dropped, and — the part that matters — + /// the caller writes nothing until the marker has arrived: a shell + /// reading its script from a pipe may read ahead, and bytes sent before + /// the `exec` could be swallowed as shell input instead of reaching the + /// command. Returns once the marker is seen; a channel that ends first + /// throws with the head of what it wrote to stderr. + func openPipe(running command: String) async throws -> RemotePipe { + guard let client else { throw SSHConnectionError.notConnected } + let marker = "MPXPIPE-" + UUID().uuidString.prefix(8) + let handoff = RemoteShellEnvelope.handoff("echo \(marker); \(command)") + "\n" + let markerLine = Data((marker + "\n").utf8) + let (incoming, feed) = AsyncThrowingStream.makeStream() + let writer = PipeWriter() + + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let gate = OneShotGate(continuation) + let run = Task { + var stderrHead = Data() + do { + try await client.withTTY { inbound, outbound in + try await outbound.write(ByteBuffer(string: handoff)) + var head = Data() + var ready = false + for try await chunk in inbound { + switch chunk { + case .stdout(let buffer): + let data = Data(buffer.readableBytesView) + guard !ready else { + feed.yield(data) + continue + } + head.append(data) + if let found = head.range(of: markerLine) { + ready = true + writer.set(outbound) + let rest = Data(head[found.upperBound...]) + head = Data() + gate.open() + if !rest.isEmpty { feed.yield(rest) } + } else if head.count > 64 * 1024 { + throw SSHConnectionError.connectFailed( + "the remote shell never ran the handoff") + } + case .stderr(let buffer): + if stderrHead.count < 2048 { + stderrHead.append( + Data(buffer.readableBytesView.prefix(2048 - stderrHead.count))) + } + } + } + } + writer.clear() + let detail = String(decoding: stderrHead, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + if !gate.fail(SSHConnectionError.connectFailed( + detail.isEmpty ? "the remote command ended before it started" : detail)) { + feed.finish() + } + } catch { + writer.clear() + let detail = String(decoding: stderrHead, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + let failure = SSHConnectionError.connectFailed( + detail.isEmpty ? self.shortDescription(of: error) : detail) + if !gate.fail(failure) { + feed.finish(throwing: failure) + } + } + } + feed.onTermination = { _ in run.cancel() } + writer.onClose = { run.cancel() } + } + return RemotePipe(incoming: incoming, writer: writer) + } + func resize(cols: Int, rows: Int) async throws { guard let stdinWriter else { return } try await stdinWriter.changeSize(cols: cols, rows: rows, pixelWidth: 0, pixelHeight: 0) @@ -831,6 +920,80 @@ actor SSHConnection { } } +/// One end of `SSHConnection.openPipe`: the remote command's stdout as a +/// stream of chunks, and its stdin. Closing — or dropping the stream — +/// closes the channel, which ends the command. +struct RemotePipe: Sendable { + let incoming: AsyncThrowingStream + fileprivate let writer: PipeWriter + + fileprivate init(incoming: AsyncThrowingStream, writer: PipeWriter) { + self.incoming = incoming + self.writer = writer + } + + /// A pipe over closures — what a test stands in for a channel with. + init( + incoming: AsyncThrowingStream, + write: @escaping @Sendable (Data) async throws -> Void, + close: @escaping @Sendable () -> Void + ) { + self.incoming = incoming + writer = PipeWriter(write: write, close: close) + } + + func write(_ data: Data) async throws { + try await writer.write(data) + } + + func close() { + writer.close() + } +} + +/// Holds the channel's stdin writer from the moment the handoff completes +/// to the moment the channel ends. Written from the channel's task and read +/// from whoever holds the pipe, hence the lock. +private final class PipeWriter: @unchecked Sendable { + private let lock = NSLock() + private var channelWriter: TTYStdinWriter? + private var customWrite: (@Sendable (Data) async throws -> Void)? + var onClose: (@Sendable () -> Void)? + + init() {} + + init( + write: @escaping @Sendable (Data) async throws -> Void, + close: @escaping @Sendable () -> Void + ) { + customWrite = write + onClose = close + } + + func set(_ writer: TTYStdinWriter) { + lock.withLock { channelWriter = writer } + } + + func clear() { + lock.withLock { channelWriter = nil } + } + + func write(_ data: Data) async throws { + if let customWrite { + try await customWrite(data) + return + } + guard let writer = lock.withLock({ channelWriter }) else { + throw SSHConnectionError.notConnected + } + try await writer.write(ByteBuffer(bytes: data)) + } + + func close() { + onClose?() + } +} + /// Resumes a continuation exactly once, from whichever side gets there first /// (the PTY going live vs. the channel failing during setup). private final class OneShotGate: @unchecked Sendable { diff --git a/Multiplex/Services/TerminalSessionController.swift b/Multiplex/Services/TerminalSessionController.swift index d43d45d7..b090243d 100644 --- a/Multiplex/Services/TerminalSessionController.swift +++ b/Multiplex/Services/TerminalSessionController.swift @@ -131,6 +131,9 @@ final class TerminalSessionController { private(set) var terminalView: TerminalView? /// The byte pipe under this tab — SSH PTY or mosh session. private var transport: (any TerminalTransport)? + /// The terminal a Rex tab was last switched to from its REX panel — + /// preferred over the route's own block on the next transport run. + private var rexBlockOverride: String? /// SSH path only: the exec/SFTP surface (pane cwd, file drops). nil on /// mosh tabs — their bootstrap SSH connection is transient by design. private var connection: SSHConnection? @@ -435,13 +438,102 @@ final class TerminalSessionController { generation: Int, output: TerminalOutputCoalescer ) async { - if host.useMosh { + if let target = route.rexTarget { + // Before the mosh question: a Rex tab has no PTY for + // mosh-server to run, so it rides SSH whatever the host prefers. + await runRex( + sessionID: target.sessionID, + blockID: rexBlockOverride ?? target.blockID, + generation: generation, output: output) + } else if host.useMosh { await runMosh(generation: generation, output: output) } else { await runSSH(generation: generation, output: output) } } + /// Rex: the tab's SSH connection carries no PTY at all — two byte pipes + /// to the Rex server instead, and `RexSession` speaking its protocol + /// over them. The connection stays this tab's exec surface, exactly as + /// on an SSH tab. + private func runRex( + sessionID: String, + blockID: String?, + generation: Int, + output: TerminalOutputCoalescer + ) async { + let secrets = await HostSecrets.loadOffMain(for: host) + guard transportGeneration == generation, !Task.isCancelled else { return } + let connection = SSHConnection(host: host, secrets: secrets) + guard transportGeneration == generation else { + await connection.close() + return + } + let session = RexSession( + connection: connection, + sessionID: sessionID, + blockID: blockID, + clientVersion: Bundle.main.object( + forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + ) + self.connection = connection + transport = session + do { + try await connection.connect() + try Task.checkCancellation() + guard transportGeneration == generation, + self.connection === connection + else { + await session.close() + return + } + let openedSize = TerminalSize(cols: lastCols, rows: lastRows) + try await session.open( + cols: openedSize.cols, + rows: openedSize.rows, + onData: { data in + output.append(data) + }, + onClose: { [weak self] reason in + Task { @MainActor [weak self] in + self?.handleClose( + reason: reason, + generation: generation, + output: output + ) + } + } + ) + try Task.checkCancellation() + guard transportGeneration == generation, + self.connection === connection + else { + await session.close() + return + } + startTransportPumps(for: session, openedAt: openedSize) + markLive() + #if DEBUG + debugAutoSwitchRexTerminal() + #endif + } catch { + // Closes the SSH connection too — the session owns that link. + await session.close() + guard transportGeneration == generation, + self.connection === connection + else { return } + captureKeyPassphraseChallenge(from: error) + let message = (error as? RexSession.Failure)?.message + ?? (error as? SSHConnectionError)?.userMessage(host: host) + ?? String(localized: "Couldn't reach \(host.name). \(error.localizedDescription)") + status = .ended(message) + self.connection = nil + transport = nil + outputCoalescer = nil + considerAutomaticResume() + } + } + private func runSSH( generation: Int, output: TerminalOutputCoalescer @@ -1008,9 +1100,14 @@ final class TerminalSessionController { else { return } selectTextClampGeneration &+= 1 let generation = selectTextClampGeneration + // A Rex tab shows exactly one terminal block, so there are no + // sibling panes to clamp a selection to, and no pane-rect query to + // make. The `.rex` arms below keep these switches total. + guard backend != .rex else { return } let command = switch backend { case .tmux: TmuxProbe.paneRectsCommand(sessionName: sessionName) case .herdr: HerdrProbe.snapshotCommand(sessionName: sessionName) + case .rex: ":" } // Cancellation ends a superseded fetch at its next sleep — resize // re-enters here on every keyboard show/hide, and the generation @@ -1038,6 +1135,7 @@ final class TerminalSessionController { let round = switch backend { case .tmux: TmuxProbe.parsePaneRects(output) case .herdr: HerdrProbe.parsePaneScreenRects(output, screenSize: screenSize) + case .rex: [PaneScreenRectEntry]() } // No answer keeps the current no-clamp behavior; // retrying could not distinguish a host without the @@ -1069,6 +1167,8 @@ final class TerminalSessionController { await executeControlCommand(HerdrProbe.focusPaneDirectionCommand( sessionName: sessionName, direction: direction )) + case .rex: + return } } } @@ -1149,6 +1249,7 @@ final class TerminalSessionController { switch route.sessionBackend { case .tmux: await loadTmuxWindowList() case .herdr: await loadHerdrWorkspaceList() + case .rex: await loadRexTerminalList() case nil: nil } } @@ -1157,10 +1258,53 @@ final class TerminalSessionController { switch route.sessionBackend { case .tmux: selectTmuxWindow(choice) case .herdr: selectHerdrWorkspace(choice) + case .rex: selectRexTerminal(choice) case nil: break } } + #if DEBUG + private static var debugRexSwitchFired = false + + /// `MULTIPLEX_AUTO_REX_SWITCH=` — the headless stand-in for pressing + /// the REX panel's nth Switch Terminal row (simctl has no tap). It goes + /// through the same two entry points the panel uses, six seconds after + /// the first Rex tab goes live, once per process. + private func debugAutoSwitchRexTerminal() { + guard !Self.debugRexSwitchFired, + let raw = ProcessInfo.processInfo.environment["MULTIPLEX_AUTO_REX_SWITCH"], + let position = Int(raw), position > 0 + else { return } + Self.debugRexSwitchFired = true + Task { [weak self] in + try? await Task.sleep(for: .seconds(6)) + guard let self, let choices = await self.loadRexTerminalList(), + choices.indices.contains(position - 1) + else { return } + self.selectRexTerminal(choices[position - 1]) + } + } + #endif + + /// The REX panel's Switch Terminal rows: every terminal of this tab's + /// session, asked of the server over the tab's own control connection. + func loadRexTerminalList() async -> [TmuxWindowChoice]? { + guard status == .live, let session = transport as? RexSession else { return nil } + return await session.terminalChoices() + } + + /// Point this tab at another terminal of its session, in place. Unlike + /// tmux and herdr, where the remote client redraws itself, the tab's + /// own transport does the switching (`RexSession.switchBlock`). The + /// choice is remembered for this controller's life so a reconnect comes + /// back to the terminal the user was on, not the one the tab opened + /// with. + func selectRexTerminal(_ choice: TmuxWindowChoice) { + guard status == .live, let session = transport as? RexSession else { return } + rexBlockOverride = choice.tmuxID + Task { await session.switchBlock(to: choice.tmuxID) } + } + /// The shortcut panel's window list, read through the control path so /// SSH and mosh tabs answer alike. A failure returns nil and the panel /// simply shows no window section — the shortcut grid stays useful. @@ -1911,6 +2055,16 @@ final class TerminalSessionController { TmuxProbe.gitWorktreeCheckCommand(directory: cwd) )) ?? "" return (cwd, TmuxProbe.parseDropDestination(check).insideGitWorktree) + case .rex: + // Rex answers over the tab's own control connection rather than + // an exec, and — like herdr — hands the path home as data, so + // the corral check is its own exec with it respliced. + guard let cwd = await (transport as? RexSession)?.workingDirectory() + else { return (nil, false) } + let check = (try? await connection.exec( + TmuxProbe.gitWorktreeCheckCommand(directory: cwd) + )) ?? "" + return (cwd, TmuxProbe.parseDropDestination(check).insideGitWorktree) case nil: return (nil, false) } @@ -2238,6 +2392,9 @@ final class TerminalSessionController { return HerdrProbe.parsePaneWorkingDirectory( output, atScreenCell: cell, screenSize: screenSize ) + case .rex: + // One tab is one terminal, so the pressed cell is always its. + return await (transport as? RexSession)?.workingDirectory() case nil: return nil } diff --git a/Multiplex/Services/WidgetStatePublisher.swift b/Multiplex/Services/WidgetStatePublisher.swift index 8b5e19cf..daa61fc6 100644 --- a/Multiplex/Services/WidgetStatePublisher.swift +++ b/Multiplex/Services/WidgetStatePublisher.swift @@ -105,7 +105,10 @@ enum WidgetStateBuilder { lastAttached: SessionKey?, miniatureLines: (TmuxSession) -> [String] ) -> WidgetHostState { - WidgetHostState( + // A widget row is a session to OPEN and a pick list is where a NEW + // session can run; both are every monitored backend's. + let qualifiesBackend = host.showsBackendIdentity + return WidgetHostState( id: host.id, name: host.name, address: host.address, @@ -116,7 +119,7 @@ enum WidgetStateBuilder { // Rows carry a backend only where it disambiguates. On // a single-backend host nil keeps every row — and every // link built from one — byte-identical to before. - qualifiesBackend: host.showsBackendIdentity + qualifiesBackend: qualifiesBackend ) }, probedAt: probedAt, @@ -130,7 +133,7 @@ enum WidgetStateBuilder { lastAttached: lastAttached.map { WidgetSessionRef( name: $0.name, - backendRaw: host.showsBackendIdentity ? $0.backend.rawValue : nil + backendRaw: qualifiesBackend ? $0.backend.rawValue : nil ) } ) diff --git a/Multiplex/Views/Deck/AddHostSheet.swift b/Multiplex/Views/Deck/AddHostSheet.swift index da5fac40..9c5155ea 100644 --- a/Multiplex/Views/Deck/AddHostSheet.swift +++ b/Multiplex/Views/Deck/AddHostSheet.swift @@ -1697,11 +1697,20 @@ final class AddHostViewController: UIViewController, UITextFieldDelegate, alternative for hosts that run it. """) } - if enabled.count > 1 { + if enabled.contains(.rex) { + detail += "\n\n" + HostGuide.rexSessionsNote + } + if enabled.count == 2 { detail += "\n\n" + String(localized: """ Both are shown, each tile marked with the backend \ it came from. That \(HostGuide.secondBackendCost). """) + } else if enabled.count > 2 { + detail += "\n\n" + String(localized: """ + All of them are shown, each tile marked with the backend \ + it came from. Every extra backend adds a probe of its own \ + to each deck refresh. + """) } return detail } @@ -1729,11 +1738,13 @@ final class AddHostViewController: UIViewController, UITextFieldDelegate, // The default is only a question when there is more than one answer. // On the single-backend host — the overwhelmingly common case — the // section is exactly one labelled control, as it always was. - if enabledBackends.count > 1 { + // + // The answers are the checked backends a NEW session can run on: + // Rex is checked without ever being a default. + let defaultChoices = form.backendSelection.defaultChoices + if defaultChoices.count > 1 { let bar = AddHostChoiceBar( - choices: Host.SessionBackend.allCases - .filter(enabledBackends.contains) - .map { ($0.rawValue, $0) }, + choices: defaultChoices.map { ($0.rawValue, $0) }, selection: form.sessionBackend ) { [weak self] backend in guard let self else { return } diff --git a/Multiplex/Views/Deck/BindPane.swift b/Multiplex/Views/Deck/BindPane.swift index c2ff5994..65a06ce4 100644 --- a/Multiplex/Views/Deck/BindPane.swift +++ b/Multiplex/Views/Deck/BindPane.swift @@ -324,7 +324,9 @@ final class BindPaneViewController: UIViewController { static func backendDetail(for backends: Host.BackendSelection) -> String { guard !backends.isMixed else { return BindPaneCopy.backendMixedDetail } return switch backends.preferred { - case .tmux: BindPaneCopy.backendTmuxDetail + // Rex is never the default (`Host.BackendSelection`), so `.rex` + // never reaches here; folded with tmux to stay total. + case .tmux, .rex: BindPaneCopy.backendTmuxDetail case .herdr: BindPaneCopy.backendHerdrDetail } } @@ -358,7 +360,11 @@ final class BindPaneViewController: UIViewController { let checks = AddHostCheckBar( // The button face uppercases; pass the natural spelling so // VoiceOver reads "tmux", not the letters T-M-U-X. - choices: Host.SessionBackend.allCases.map { ($0.rawValue, $0) }, + // Binding sets up the host's DEFAULT backends. Rex, which is + // never one, is switched on afterwards — the deck rail + // offers it the moment its sessions are seen, and Host Settings + // lists it. + choices: Host.SessionBackend.defaultCases.map { ($0.rawValue, $0) }, selection: backends.enabled ) { [weak bind] enabled in bind?.backends.setEnabled(enabled) @@ -369,9 +375,7 @@ final class BindPaneViewController: UIViewController { guard backends.isMixed else { return } let bar = AddHostChoiceBar( - choices: Host.SessionBackend.allCases - .filter(backends.enabled.contains) - .map { ($0.rawValue, $0) }, + choices: backends.defaultChoices.map { ($0.rawValue, $0) }, selection: backends.preferred ) { [weak bind] backend in bind?.backends.setPreferred(backend) diff --git a/Multiplex/Views/Deck/FleetWall.swift b/Multiplex/Views/Deck/FleetWall.swift index 71cd0e35..b829ebc8 100644 --- a/Multiplex/Views/Deck/FleetWall.swift +++ b/Multiplex/Views/Deck/FleetWall.swift @@ -678,10 +678,21 @@ final class FleetWallViewController: UIViewController { self?.focusOrAttach(host, session: session) }, openDuplicateSession: { [weak self] session in - self?.open(TerminalRoute( - hostID: host.id, - mode: .attach(host: host, session: session) - )) + guard let mode = TerminalRoute.Mode.attach(host: host, session: session) + else { + self?.presentCannotOpen(session, on: host) + return + } + self?.open(TerminalRoute(hostID: host.id, mode: mode)) + }, + openSessionPane: { [weak self] session, window, pane in + guard let mode = RexProbe.attachMode( + session: session, window: window, pane: pane) + else { + self?.presentCannotOpen(session, on: host) + return + } + self?.open(TerminalRoute(hostID: host.id, mode: mode)) }, requestNewSession: { [weak self] in self?.presentNewSession(on: host) }, requestNewHerdrTab: { [weak self] session in @@ -746,14 +757,19 @@ final class FleetWallViewController: UIViewController { private func confirmBackendOffer(_ backend: Host.SessionBackend, for host: Host) { let name = backend.rawValue let primary = host.sessionBackend.rawValue + var message = String(localized: """ + \(host.name) is running \(name) as well as \(primary). \ + Showing both \(HostGuide.secondBackendCost). + + New sessions still start on \(primary). + """) + // Say what a tile of this backend does, where it differs. + if backend == .rex { + message += "\n\n" + HostGuide.rexSessionsNote + } let alert = UIAlertController( title: String(localized: "Also Show \(name) Sessions"), - message: String(localized: """ - \(host.name) is running \(name) as well as \(primary). \ - Showing both \(HostGuide.secondBackendCost). - - New sessions still start on \(primary). - """), + message: message, preferredStyle: .alert ) alert.addAction(UIAlertAction( @@ -893,7 +909,27 @@ final class FleetWallViewController: UIViewController { ) { return } - open(TerminalRoute(hostID: host.id, mode: .attach(host: host, session: session))) + guard let mode = TerminalRoute.Mode.attach(host: host, session: session) else { + presentCannotOpen(session, on: host) + return + } + open(TerminalRoute(hostID: host.id, mode: mode)) + } + + /// A tile whose record cannot be attached — a Rex session the probe + /// reported without a usable id. Rare, but a tile that ignores its + /// press reads as a broken one, so it answers. + private func presentCannotOpen(_ session: TmuxSession, on host: Host) { + let alert = UIAlertController( + title: String(localized: "Couldn't Open Session"), + message: String(localized: """ + \(host.name) reported “\(session.name)” without the id \ + needed to attach it. Try again after the next refresh. + """), + preferredStyle: .alert + ) + alert.addAction(UIAlertAction(title: String(localized: "OK"), style: .cancel)) + present(alert, animated: true) } private func presentNewSession(on host: Host) { @@ -958,16 +994,13 @@ final class FleetWallViewController: UIViewController { on host: Host, model: HostConnectionModel ) { let message: String - switch model.sessionCreateFailure { - case .backendMissing(let backend): - message = HostGuide.backendMissingMessage(backend, hostName: host.name) - case nil: - if case .failed(let reason) = model.phase { - message = reason - } else { - message = String( - localized: "Couldn't create the session on \(host.name).") - } + if let failure = model.sessionCreateFailure { + message = failure.message(hostName: host.name) + } else if case .failed(let reason) = model.phase { + message = reason + } else { + message = String( + localized: "Couldn't create the session on \(host.name).") } let alert = UIAlertController( title: String(localized: "Couldn't Create Session"), @@ -1090,7 +1123,10 @@ final class FleetWallViewController: UIViewController { // itself refuses to delete (it parks as a stopped tile instead). // The copy carries both truths because the app deliberately // doesn't know which session is the default. - let message = host.sessionBackend == .herdr + // The SESSION's backend: on a mixed host the tile being deleted + // need not be the primary's, and the copy describes what its own + // multiplexer will do. + let message = session.backend == .herdr ? String(localized: """ Stops “\(session.name)” on \(host.name) and everything running in it, \ and deletes its saved state (herdr keeps its default session on disk, stopped). @@ -1560,6 +1596,8 @@ private struct FleetHostSectionConfiguration { var openShell: () -> Void var openSession: (TmuxSession) -> Void var openDuplicateSession: (TmuxSession) -> Void + /// One named terminal of a Rex session, as its own tab. + var openSessionPane: (TmuxSession, TmuxWindow, TmuxPane) -> Void var requestNewSession: () -> Void var requestNewHerdrTab: (TmuxSession) -> Void var requestDeleteSession: (TmuxSession) -> Void @@ -1937,8 +1975,10 @@ private final class FleetHostSectionView: UIView { session: session, lines: snapshot.miniatures[session.id] ?? [], attention: snapshot.attention[session.id], + // Rex tiles take it too: a program that reports no + // status is read from its title, exactly as tmux's is. usesTmuxAttentionFallback: snapshot.hasLiveProbe - && session.backend == .tmux, + && session.backend != .herdr, hasOpenTab: snapshot.openSessions.contains(session.id), sessionBackend: session.backend, showsBackendIdentity: host.showsBackendIdentity, @@ -1989,6 +2029,9 @@ private final class FleetHostSectionView: UIView { animations: move ) } + }, + openPane: { [weak self] window, pane in + self?.configuration.openSessionPane(session, window, pane) } )) items.append(FleetGridItem(id: key, view: tile)) @@ -2985,6 +3028,10 @@ struct FleetSessionTileConfiguration { let copyHandoffCommand: () -> Void let delete: () -> Void let droppedSession: (String) -> Void + /// Opens ONE terminal of the session as its own tab — the Rex tile's + /// Open Terminal rows. A `var` with a default so the tiles of every + /// other backend, and their tests, construct exactly as before. + var openPane: (TmuxWindow, TmuxPane) -> Void = { _, _ in } /// Whether the session is attached right now — the LIVE lamp's one /// authority, resolved per backend by `SessionBackend.isSessionLive`. @@ -3110,6 +3157,24 @@ final class FleetSessionTileView: FleetPressView, configuration.attachNewWindow() }, ] + // A Rex tab shows one terminal, and a press opens the one the + // session is fronting. The others are reached here — only when + // there ARE others, so a one-terminal session's menu is as short + // as any tile's. + if configuration.sessionBackend == .rex, + configuration.session.paneCount > 1 { + let rows = configuration.session.windows.flatMap { window in + (window.panes ?? []).map { pane in + UIAction( + title: RexProbe.terminalMenuTitle(window: window, pane: pane) + ) { _ in + configuration.openPane(window, pane) + } + } + } + children.append(UIMenu( + title: String(localized: "Open Terminal"), children: rows)) + } if configuration.sessionBackend == .herdr { // The terminal window's + TAB row, reachable from the deck; // one title source so the surfaces can't drift. @@ -3119,9 +3184,14 @@ final class FleetSessionTileView: FleetPressView, configuration.newHerdrTab() }) } - children.append(UIAction(title: String(localized: "Copy Command for Handoff")) { _ in - configuration.copyHandoffCommand() - }) + // Only where there IS a command to hand over: Rex has no + // terminal client, so no line opens its session in a shell. + if SessionHandoff.command(session: configuration.session) != nil { + children.append( + UIAction(title: String(localized: "Copy Command for Handoff")) { _ in + configuration.copyHandoffCommand() + }) + } children.append( UIAction( title: String(localized: "Delete Session…"), @@ -4042,7 +4112,10 @@ struct NewSessionFormState { var defaultNameBase: String { Self.defaultNameBase(for: backend) } private static func defaultNameBase(for backend: Host.SessionBackend) -> String { - backend == .herdr ? "session" : "main" + switch backend { + case .tmux: "main" + case .herdr, .rex: "session" + } } /// The backend's own namer: the prefill must match what the mint will @@ -4055,6 +4128,7 @@ struct NewSessionFormState { return switch backend { case .tmux: TmuxProbe.uniqueSessionName(base: base, existing: existing) case .herdr: HerdrProbe.uniqueSessionName(base: base, existing: existing) + case .rex: RexProbe.uniqueSessionLabel(base: base, existing: existing) } } diff --git a/Multiplex/Views/Settings/FAQView.swift b/Multiplex/Views/Settings/FAQView.swift index 1a12383f..07b20078 100644 --- a/Multiplex/Views/Settings/FAQView.swift +++ b/Multiplex/Views/Settings/FAQView.swift @@ -155,7 +155,8 @@ private final class FAQMultiplexerInstallView: UIView { let bar = AddHostChoiceBar( // The button face uppercases; pass the natural spelling so // VoiceOver reads "tmux", not the letters T-M-U-X. - choices: Host.SessionBackend.allCases.map { ($0.rawValue, $0) }, + // Install roads for what a host RUNS sessions on. + choices: Host.SessionBackend.defaultCases.map { ($0.rawValue, $0) }, selection: backend ) { [weak self] backend in self?.show(backend) diff --git a/Multiplex/Views/Terminal/TerminalKeyBar.swift b/Multiplex/Views/Terminal/TerminalKeyBar.swift index 9fffd6d7..3fa3a019 100644 --- a/Multiplex/Views/Terminal/TerminalKeyBar.swift +++ b/Multiplex/Views/Terminal/TerminalKeyBar.swift @@ -1507,13 +1507,11 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface key: .showShortcutPanel, slot: .shortcuts, face: .text( - backend == .herdr ? "HRDR" : "TMUX", + backend.shortcutKeyCaption, font: UIKitChassis.monoFont(9, weight: .semibold), kerning: 0.7 ), - accessibility: backend == .herdr - ? String(localized: "Show herdr shortcuts") - : String(localized: "Show tmux shortcuts"), + accessibility: backend.shortcutKeyAccessibilityLabel, identifier: "tmux" )) } diff --git a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift index 63f31fa4..0e3be043 100644 --- a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift @@ -239,7 +239,7 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg bareChrome: configuration.bareChrome, keyRailHidden: configuration.keyRailHidden, isActive: configuration.isActive && configuration.focusAllowed, - shortcutBackend: configuration.controller?.route.sessionBackend, + shortcutBackend: configuration.controller?.route.shortcutBackend, keyCommandPlan: configuration.keyCommandPlan ) } diff --git a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift index 2f06ef40..a48207d5 100644 --- a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift @@ -1476,8 +1476,9 @@ final class TerminalWindowViewController: UIViewController, creatingTab = true // + TAB means "another one like this": the sibling session is minted // on THIS tab's backend, not the host's default, so a herdr tab on a - // tmux-default mixed host keeps producing herdr siblings. A backend - // the host no longer monitors falls back to the default. + // tmux-default mixed host keeps producing herdr siblings, and a Rex + // tab Rex ones. A backend the host no longer monitors falls back + // to the default. let backend = activeTab.sessionBackend .flatMap { host.monitors($0) ? $0 : nil } ?? host.sessionBackend @@ -1506,13 +1507,7 @@ final class TerminalWindowViewController: UIViewController, ) else { presentNewTabFailure( hostName: host.name, target: .session, - reason: model.sessionCreateFailure.map { - switch $0 { - case .backendMissing(let backend): - HostGuide.backendMissingMessage( - backend, hostName: host.name) - } - }) + reason: model.sessionCreateFailure?.message(hostName: host.name)) return } let tab = TerminalRoute(hostID: host.id, mode: created) @@ -2934,7 +2929,7 @@ extension TerminalWindowViewController { } : nil, fullScreenActive: fullScreenColumn, extraNewTabTarget: extraNewTabTarget, - shortcutBackend: activeTab?.sessionBackend, + shortcutBackend: activeTab?.shortcutBackend, style: vertical ? .verticalColumn : profile.style, deckControl: shell?.deckControl ?? .back, availableWidth: vertical ? column.width : umdAvailableWidth, diff --git a/Multiplex/Views/Terminal/UMDBarUIKit.swift b/Multiplex/Views/Terminal/UMDBarUIKit.swift index 1b8e80fb..f580072a 100644 --- a/Multiplex/Views/Terminal/UMDBarUIKit.swift +++ b/Multiplex/Views/Terminal/UMDBarUIKit.swift @@ -483,12 +483,10 @@ final class UMDBarViewController: UIViewController, case .shortcut: guard let backend = configuration.shortcutBackend else { return nil } let chip = UMDColumnChip( - caption: backend == .herdr ? "HRDR" : "TMUX", + caption: backend.shortcutKeyCaption, systemImage: "command", prominent: false, - accessibilityLabel: backend == .herdr - ? String(localized: "Show herdr shortcuts") - : String(localized: "Show tmux shortcuts") + accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) chip.accessibilityIdentifier = "umd.tmux" chip.isEnabled = state.status == .live @@ -860,12 +858,10 @@ final class UMDBarViewController: UIViewController, /// hooks address "umd.tmux" for either backend's shortcut chip. private func shortcutButton(_ backend: Host.SessionBackend) -> UMDBarButton { let button = UMDBarButton( - caption: backend == .herdr ? "HRDR" : "TMUX", + caption: backend.shortcutKeyCaption, systemImage: "command", prominent: false, - accessibilityLabel: backend == .herdr - ? String(localized: "Show herdr shortcuts") - : String(localized: "Show tmux shortcuts") + accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) button.accessibilityIdentifier = "umd.tmux" button.isEnabled = currentObservedState.status == .live diff --git a/MultiplexTests/Fixtures/rex-probe-preview19.txt b/MultiplexTests/Fixtures/rex-probe-preview19.txt new file mode 100644 index 00000000..50c07bff --- /dev/null +++ b/MultiplexTests/Fixtures/rex-probe-preview19.txt @@ -0,0 +1,131 @@ +MULTIPLEX_REX_PROBE +{ + "ok": true, + "sessions": [ + { + "active": "window:01a1e1e3-47f9-7e8a-b2a7-c781d6b553f0", + "clients": 0, + "id": "session:01a1e1e3-47e5-7497-bde1-74a5768d7863", + "label": "work", + "tail": "editing README", + "windows": [ + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a1e1e3-47e6-7042-8802-7dd67693eaba", + "label": "shell", + "name": "sleep", + "pid": 59141, + "title": "vim README.md" + }, + { + "argv0": "sleep", + "id": "block:01a1e1e3-4810-7831-92b7-22087aff9bc8", + "label": "logs", + "name": "sleep", + "pid": 59144, + "title": "" + } + ], + "focus": "block:01a1e1e3-47e6-7042-8802-7dd67693eaba", + "id": "window:01a1e1e3-47f9-7e8a-b2a7-c781d6b553f0", + "label": "editor" + }, + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a1e1e3-4831-74e9-bcbb-3be3cdeb744a", + "label": "agent", + "name": "sleep", + "pid": 59147, + "status": [ + { + "app": "claude-code", + "kind": "permission", + "state": "blocked" + } + ], + "title": "✳ Claude Code" + } + ], + "focus": "block:01a1e1e3-4831-74e9-bcbb-3be3cdeb744a", + "id": "window:01a1e1e3-483d-7bfe-a0dc-9973262b0b23", + "label": "Window 262b0b23" + } + ] + }, + { + "active": "window:01a1e1e4-8254-7315-add9-546cee26a496", + "clients": 0, + "clipped": true, + "id": "session:01a1e1e3-4870-742a-9d13-2b5e9df0ada5", + "label": "floral-river", + "tail": "258 測試多位元組輸出內容 ✳\n行 259 測試多位元組輸出內容 ✳\n行 260 測試多位元組輸出內容 ✳\n行 261 測試多位元組輸出內容 ✳\n行 262 測試多位元組輸出內容 ✳\n行 263 測試多位元組輸出內容 ✳\n行 264 測試多位元組輸出內容 ✳\n行 265 測試多位元組輸出內容 ✳\n行 266 測試多位元組輸出內容 ✳\n行 267 測試多位元組輸出內容 ✳\n行 268 測試多位元組輸出內容 ✳\n行 269 測試多位元組輸出內容 ✳\n行 270 測試多位元組輸出內容 ✳\n行 271 測試多位元組輸出內容 ✳\n行 272 測試多位元組輸出內容 ✳\n行 273 測試多位元組輸出內容 ✳\n行 274 測試多位元組輸出內容 ✳\n行 275 測試多位元組輸出內容 ✳\n行 276 測試多位元組輸出內容 ✳\n行 277 測試多位元組輸出內容 ✳\n行 278 測試多位元組輸出內容 ✳\n行 279 測試多位元組輸出內容 ✳\n行 280 測試多位元組輸出內容 ✳\n行 281 測試多位元組輸出內容 ✳\n行 282 測試多位元組輸出內容 ✳\n行 283 測試多位元組輸出內容 ✳\n行 284 測試多位元組輸出內容 ✳\n行 285 測試多位元組輸出內容 ✳\n行 286 測試多位元組輸出內容 ✳\n行 287 測試多位元組輸出內容 ✳\n行 288 測試多位元組輸出內容 ✳\n行 289 測試多位元組輸出內容 ✳\n行 290 測試多位元組輸出內容 ✳\n行 291 測試多位元組輸出內容 ✳\n行 292 測試多位元組輸出內容 ✳\n行 293 測試多位元組輸出內容 ✳\n行 294 測試多位元組輸出內容 ✳\n行 295 測試多位元組輸出內容 ✳\n行 296 測試多位元組輸出內容 ✳\n行 297 測試多位元組輸出內容 ✳\n行 298 測試多位元組輸出內容 ✳\n行 299 測試多位元組輸出內容 ✳\n行 300 測試多位元組輸出內容 ✳\n行 301 測試多位元組輸出內容 ✳\n行 302 測試多位元組輸出內容 ✳\n行 303 測試多位元組輸出內容 ✳\n行 304 測試多位元組輸出內容 ✳\n行 305 測試多位元組輸出內容 ✳\n行 306 測試多位元組輸出內容 ✳\n行 307 測試多位元組輸出內容 ✳\n行 308 測試多位元組輸出內容 ✳\n行 309 測試多位元組輸出內容 ✳\n行 310 測試多位元組輸出內容 ✳\n行 311 測試多位元組輸出內容 ✳\n行 312 測試多位元組輸出內容 ✳\n行 313 測試多位元組輸出內容 ✳\n行 314 測試多位元組輸出內容 ✳\n行 315 測試多位元組輸出內容 ✳\n行 316 測試多位元組輸出內容 ✳\n行 317 測試多位元組輸出內容 ✳\n行 318 測試多位元組輸出內容 ✳\n行 319 測試多位元組輸出內容 ✳\n行 320 測試多位元組輸出內容 ✳\n行 321 測試多位元組輸出內容 ✳\n行 322 測試多位元組輸出內容 ✳\n行 323 測試多位元組輸出內容 ✳\n行 324 測試多位元組輸出內容 ✳\n行 325 測試多位元組輸出內容 ✳\n行 326 測試多位元組輸出內容 ✳\n行 327 測試多位元組輸出內容 ✳\n行 328 測試多位元組輸出內容 ✳\n行 329 測試多位元組輸出內容 ✳\n行 330 測試多位元組輸出內容 ✳\n行 331 測試多位元組輸出內容 ✳\n行 332 測試多位元組輸出內容 ✳\n行 333 測試多位元組輸出內容 ✳\n行 334 測試多位元組輸出內容 ✳\n行 335 測試多位元組輸出內容 ✳\n行 336 測試多位元組輸出內容 ✳\n行 337 測試多位元組輸出內容 ✳\n行 338 測試多位元組輸出內容 ✳\n行 339 測試多位元組輸出內容 ✳\n行 340 測試多位元組輸出內容 ✳\n行 341 測試多位元組輸出內容 ✳\n行 342 測試多位元組輸出內容 ✳\n行 343 測試多位元組輸出內容 ✳\n行 344 測試多位元組輸出內容 ✳\n行 345 測試多位元組輸出內容 ✳\n行 346 測試多位元組輸出內容 ✳\n行 347 測試多位元組輸出內容 ✳\n行 348 測試多位元組輸出內容 ✳\n行 349 測試多位元組輸出內容 ✳\n行 350 測試多位元組輸出內容 ✳\n行 351 測試多位元組輸出內容 ✳\n行 352 測試多位元組輸出內容 ✳\n行 353 測試多位元組輸出內容 ✳\n行 354 測試多位元組輸出內容 ✳\n行 355 測試多位元組輸出內容 ✳\n行 356 測試多位元組輸出內容 ✳\n行 357 測試多位元組輸出內容 ✳\n行 358 測試多位元組輸出內容 ✳\n行 359 測試多位元組輸出內容 ✳\n行 360 測試多位元組輸出內容 ✳\n行 361 測試多位元組輸出內容 ✳\n行 362 測試多位元組輸出內容 ✳\n行 363 測試多位元組輸出內容 ✳\n行 364 測試多位元組輸出內容 ✳\n行 365 測試多位元組輸出內容 ✳\n行 366 測試多位元組輸出內容 ✳\n行 367 測試多位元組輸出內容 ✳\n行 368 測試多位元組輸出內容 ✳\n行 369 測試多位元組輸出內容 ✳\n行 370 測試多位元組輸出內容 ✳\n行 371 測試多位元組輸出內容 ✳\n行 372 測試多位元組輸出內容 ✳\n行 373 測試多位元組輸出內容 ✳\n行 374 測試多位元組輸出內容 ✳\n行 375 測試多位元組輸出內容 ✳\n行 376 測試多位元組輸出內容 ✳\n行 377 測試多位元組輸出內容 ✳\n行 378 測試多位元組輸出內容 ✳\n行 379 測試多位元組輸出內容 ✳\n行 380 測試多位元組輸出內容 ✳\n行 381 測試多位元組輸出內容 ✳\n行 382 測試多位元組輸出內容 ✳\n行 383 測試多位元組輸出內容 ✳\n行 384 測試多位元組輸出內容 ✳\n行 385 測試多位元組輸出內容 ✳\n行 386 測試多位元組輸出內容 ✳\n行 387 測試多位元組輸出內容 ✳\n行 388 測試多位元組輸出內容 ✳\n行 389 測試多位元組輸出內容 ✳\n行 390 測試多位元組輸出內容 ✳\n行 391 測試多位元組輸出內容 ✳\n行 392 測試多位元組輸出內容 ✳\n行 393 測試多位元組輸出內容 ✳\n行 394 測試多位元組輸出內容 ✳\n行 395 測試多位元組輸出內容 ✳\n行 396 測試多位元組輸出內容 ✳\n行 397 測試多位元組輸出內容 ✳\n行 398 測試多位元組輸出內容 ✳\n行 399 測試多位元組輸出內容 ✳\n行 400 測試多位元組輸出內容 ✳", + "windows": [ + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a1e1e3-4870-7599-8abf-9ebef49bbe32", + "label": "shell", + "name": "sleep", + "pid": 59153, + "title": "" + } + ], + "focus": "block:01a1e1e3-4870-7599-8abf-9ebef49bbe32", + "id": "window:01a1e1e3-487b-7a6f-a912-f254561e92e1", + "label": "Window 561e92e1" + }, + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a1e1e4-8245-79a8-8f5b-05464cfb5967", + "label": "long", + "name": "sleep", + "pid": 59475, + "title": "" + } + ], + "focus": "block:01a1e1e4-8245-79a8-8f5b-05464cfb5967", + "id": "window:01a1e1e4-8254-7315-add9-546cee26a496", + "label": "Window ee26a496" + } + ] + }, + { + "active": "window:01a1e1ef-0d15-71b5-8c1d-58d858119252", + "clients": 0, + "id": "session:01a1e1ef-0d07-7b9c-86f1-8ee05a04272d", + "label": "work", + "tail": "Compiling...", + "windows": [ + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a1e1ef-0d07-7c31-92cd-055b6ba6c35f", + "label": "shell", + "name": "sleep", + "pid": 70691, + "status": [ + { + "app": "cargo", + "state": "working" + } + ], + "title": "" + } + ], + "focus": "block:01a1e1ef-0d07-7c31-92cd-055b6ba6c35f", + "id": "window:01a1e1ef-0d15-71b5-8c1d-58d858119252", + "label": "Window 58119252" + } + ] + } + ] +} +MULTIPLEX_REX_EXIT 0 diff --git a/MultiplexTests/Fixtures/rex-terminal-stream-preview19.bin b/MultiplexTests/Fixtures/rex-terminal-stream-preview19.bin new file mode 100644 index 0000000000000000000000000000000000000000..ec9222a76265f7a4f27c3a3e84f87cfc05efb3a3 GIT binary patch literal 2322 zcmbuA&ud&&6vxlB(S~3aW>cXN<1Erm2Hx-cW&*`UpyDD8jEgM9OJ?%Mgbqzehor3t zm5YFM6SNBnxVRcBBE}Msh9WNFLat=xA|gbH{SU6+^T-_WM>l%mWzM-jzMt(`oZHfQH5RH6IliS9l4<=z~+8)&Up{_v(CKu3oNa#f-5b9? zzIx}Aqi;X_X?6eelarHDT@x81OXMI)$h0PHNL$j5wC6>m$rv)0j3eWDuhnD?SxeTD z^?cN6a)z8G=g4^|k=Nu6c}w2GD+{wUv~U=^J#%;%t*zEhYtL9@#%N=;aoTuxfkkVy zwc0vuJ)6Q_XSB20Iqf_=;;8mUd#k{%Y_RpI%}LW&ZBym!d~O8@y>XZhkn2&PNN;DA0|*CTtf_|;SyWn17K)F z8d{z^$IHkuoVA`CiTZ#==A3mNeMPx&fko?`_2?ryjRwFMwxiLg7Og}-U=yd&4tPSr zs1U9p2GckRTkruev?1;Jig-7ckz;t=7#fNCfJNr;)hfRYTyA;6xKX~(@{-t8*>}F) zvX$(y><-^{Suk5JYv9W-ZE*!93DVHQEund+38>-W;jyu?@$vD=$;luH8jZ%x%*^cU z?EL(EtJUguyX))g{eFLQb8~BJYkPZpXJ==3cXw}Z@8ICz@bK{H=;-+P`1JJj8E?x! zrq5A^x%)4C`jp?sX<5IB>|e+5UuVzLUA*GG{^h%K)GW{RX`g5UyRZ{K0e_R37^ROe zwT0)ivu6*V53&CtKKJqbe3n0{&=B?weSn9ar`~e=`b0PgqCpT3f@Bb+gCH9OY7pdu zpiURg1Otgei6V(&i4uuYi86_lM7c!5h=dUdBN9d=j7S)fFd|_@!iaO_vVI;yxgpmj%5k?}6L>P%MQemXRNQIFKBNav}j8qt@ zFj8Tp!pMY?2_q9mCX7rNnJ_Y8WWvaVkqJWyLkU9(LkU9(LkU9(LkU9(LkS}nM$Z36 zd0Z&}UhcPlc&?0&Cw?E{mxt)%7dPK7r^<}z%5Tjpm-Je3E1XUOmGcv3DpirHt9m~D zZnbxNwWv0#YsJmwJ4JP>+Ft42tTysss=BtafhbBaS9H62V|lT+q*rfY@oZ+PSbk@z zS5Af5RCQ(JMzIE|c6YhB(Q5?ZLRf^0Nlm3uTvIA()#{-tYH^yVI1O5PnikdfF1=O0 z@Od;k@*ix5f%uFO{U4uctrZmk%);?PI}d7ks}lwF`a;$Y>VNu-M@P70i?!D6+UnX$ Nt3b}bSa~u!@(1~R_QL=G literal 0 HcmV?d00001 diff --git a/MultiplexTests/RexProbeTests.swift b/MultiplexTests/RexProbeTests.swift new file mode 100644 index 00000000..b2ad185a --- /dev/null +++ b/MultiplexTests/RexProbeTests.swift @@ -0,0 +1,804 @@ +import UIKit +import XCTest +@testable import Multiplex + +/// Anchors `Bundle(for:)` fixture loading, the BindProtocolTests pattern. +private final class RexFixtureAnchor {} + +/// Rex on the deck: the probe, the record rules, and the tile. (Attaching a +/// Rex terminal is `RexWireTests`.) The probe fixture is the verbatim output of +/// the shipped probe command against a throwaway Rex 0.1.0-preview.19 server +/// (API revision 14, captured 2026-11-16) holding three sessions: +/// - `work` — window `editor` (a titled block beside an untitled split) and +/// an unnamed window whose block reports `blocked` / `permission` for +/// `claude-code`; the session fronts `editor`. +/// - an unnamed session Rex labelled `floral-river`, fronting a block with +/// 400 multibyte lines of scrollback (so its tail is a clipped read). +/// - a SECOND `work`, whose block reports `working` for `cargo`. +@MainActor +final class RexProbeTests: XCTestCase { + private func fixture() throws -> String { + let url = try XCTUnwrap( + Bundle(for: RexFixtureAnchor.self) + .url(forResource: "rex-probe-preview19", withExtension: "txt")) + return try String(contentsOf: url, encoding: .utf8) + } + + private func sessions(_ probe: RexProbe.ParsedProbe) throws -> [TmuxSession] { + guard case .sessions(let sessions) = probe.state else { + XCTFail("expected sessions, got \(probe.state)") + return [] + } + return sessions + } + + private func response(json: String, exit: Int = 0) -> String { + "MULTIPLEX_REX_PROBE\n\(json)\nMULTIPLEX_REX_EXIT \(exit)\n" + } + + // MARK: The command + + func testTheProbeNeverStartsAServerAndReportsItsExitStatus() { + let command = RexProbe.probeCommand() + // The CLI autostarts a server by default; a probe that did would + // leave one running on every host that merely has the binary. + XCTAssertTrue(command.contains("REX_AUTOSTART=0 rex do -e '")) + XCTAssertTrue(command.contains( + "command -v rex >/dev/null 2>&1 || { echo MULTIPLEX_NO_REX; exit 0; }")) + XCTAssertTrue(command.hasSuffix("echo \"MULTIPLEX_REX_EXIT $?\"")) + // One connection that attaches without JOINING any session. + XCTAssertTrue(command.contains("session.attach_all")) + XCTAssertFalse(command.contains("\"session.attach\"")) + // The script is one single-quoted argument: a quote inside it would + // end the argument early. + let script = command.components(separatedBy: "do -e '")[1] + .components(separatedBy: "' --json")[0] + XCTAssertFalse(script.contains("'")) + } + + func testTheProbeLooksForRexWhereAMacKeepsIt() { + let command = RexProbe.probeCommand() + XCTAssertTrue(command.contains( + "$HOME/Library/Application Support/com.superlogical.rex/RexServer" + + "/Versions/Current/Rex Server.app/Contents/MacOS")) + XCTAssertTrue(command.contains( + "/Applications/Rex Beta.app/Contents/Helpers/Rex Server.rex/Contents/MacOS")) + } + + func testRidersLeadTheProbeAndASecondaryCarriesNone() { + XCTAssertTrue(RexProbe.probeCommand().hasPrefix("PATH=")) + let riding = RexProbe.probeCommand(discovering: [.tmux, .rex]) + XCTAssertTrue(riding.hasPrefix("echo MULTIPLEX_DISCOVER tmux; ")) + // A probe never discovers itself. + XCTAssertFalse(riding.contains("MULTIPLEX_DISCOVER rex")) + } + + // MARK: The fixture + + func testSessionsMapOntoTilesWithUniqueNames() throws { + let probe = RexProbe.parseProbe(try fixture()) + let sessions = try sessions(probe) + // Two sessions share the label `work`; BOTH are spelled with the + // tail of their id, and the unique one keeps its label. + XCTAssertEqual( + sessions.map(\.name), + ["work …8d7863", "floral-river", "work …04272d"]) + XCTAssertEqual(Set(sessions.map(\.id)).count, 3) + XCTAssertTrue(sessions.allSatisfy { $0.backend == .rex }) + // The id is the only unambiguous target. + XCTAssertEqual( + sessions[0].tmuxID, "session:01a1e1e3-47e5-7497-bde1-74a5768d7863") + // Rex states no creation time; the list position stands in. + XCTAssertTrue(sessions.allSatisfy { HerdrProbe.isSyntheticCreated($0.created) }) + XCTAssertLessThan(sessions[0].created, sessions[2].created) + } + + func testWindowsAndBlocksBecomeTheSpine() throws { + let work = try XCTUnwrap( + try sessions(RexProbe.parseProbe(try fixture())).first) + XCTAssertEqual(work.windows.map(\.index), [1, 2]) + // A label someone chose is kept; Rex's generated `Window ` gives + // way to the focused block's label. + XCTAssertEqual(work.windows.map(\.name), ["editor", "agent"]) + XCTAssertEqual(work.windows.map(\.isActive), [true, false]) + + let editor = work.windows[0] + XCTAssertEqual(editor.paneCount, 2) + XCTAssertEqual(editor.panes?.map(\.isActive), [true, false]) + XCTAssertEqual(editor.paneTitle, "vim README.md") + XCTAssertEqual(editor.panes?.first?.command, "sleep") + XCTAssertEqual( + editor.panes?.first?.tmuxID, + "block:01a1e1e3-47e6-7042-8802-7dd67693eaba") + + // The agent is in a window the session is not fronting — still seen. + XCTAssertEqual(work.windows[1].activeAgent, .claudeCode) + XCTAssertEqual(work.detectedAgents, [.claudeCode]) + XCTAssertNil(work.activeAgent) + } + + func testAnUnnamedWindowWithAnUnnamedBlockFallsBackToItsPosition() throws { + let probe = RexProbe.parseProbe(response(json: """ + {"ok":true,"sessions":[ + {"id":"session:0000-dddddd","label":"bare","windows":[ + {"id":"window:0000-11112222","label":"Window 11112222", + "blocks":[{"id":"block:1","label":""}]}, + {"id":"window:0000-33334444","label":"Window kept by hand", + "blocks":[{"id":"block:2","label":"shell"}]} + ]} + ]} + """)) + let session = try XCTUnwrap(try sessions(probe).first) + // Only the exact generated shape is replaced. + XCTAssertEqual(session.windows.map(\.name), ["window 1", "Window kept by hand"]) + } + + func testTheFrontedBlocksScreenFeedsTheMiniature() throws { + let probe = RexProbe.parseProbe(try fixture()) + XCTAssertEqual(probe.tails["work …8d7863"], ["editing README"]) + XCTAssertEqual(probe.tails["work …04272d"], ["Compiling..."]) + XCTAssertEqual(probe.miniatures["work …8d7863"], ["editing README"]) + } + + func testAClippedTailDropsItsPartialFirstLine() throws { + let probe = RexProbe.parseProbe(try fixture()) + let tail = try XCTUnwrap(probe.tails["floral-river"]) + // The read started mid-screen, so the fixture's first line is the + // back half of one (`258 測試…`, its leading `行 ` cut off). + XCTAssertTrue(tail.allSatisfy { $0.hasPrefix("行 ") }) + XCTAssertEqual(tail.last, "行 400 測試多位元組輸出內容 ✳") + XCTAssertEqual(tail.count, 30) + XCTAssertEqual( + probe.miniatures["floral-river"]?.count, TmuxProbe.miniatureLines) + } + + func testReportedStatusesFoldAcrossEveryBlockOfASession() throws { + let probe = RexProbe.parseProbe(try fixture()) + let blocked = try XCTUnwrap(probe.signals["work …8d7863"]) + XCTAssertEqual( + blocked.reported, + [RexProbe.ProgramStatus(state: .blocked, kind: .permission)]) + XCTAssertEqual( + RexProbe.sessionAgentState(blocked.reported), .needsYou(.permission)) + // The blocked program is NOT in the fronted block, so an alert may + // not borrow that block's agent or screen. + XCTAssertTrue(blocked.front.isEmpty) + XCTAssertFalse(RexProbe.frontProducedSessionState( + .needsYou(.permission), front: blocked.front)) + + let working = try XCTUnwrap(probe.signals["work …04272d"]) + XCTAssertEqual(RexProbe.sessionAgentState(working.reported), .busy) + XCTAssertTrue(RexProbe.frontProducedSessionState(.busy, front: working.front)) + + // Nothing reported means no claim — the tile falls back to its title. + let silent = try XCTUnwrap(probe.signals["floral-river"]) + XCTAssertNil(RexProbe.sessionAgentState(silent.reported)) + } + + // MARK: Attention fold + + func testTheStatusFoldRanksBlockedOverWorkingOverSettled() { + func status( + _ state: RexProbe.ProgramState, _ kind: AttentionKind? = nil + ) -> RexProbe.ProgramStatus { + RexProbe.ProgramStatus(state: state, kind: kind) + } + XCTAssertEqual( + RexProbe.sessionAgentState([status(.working), status(.blocked, .question)]), + .needsYou(.question)) + // A blocked program that names no kind is the generic prompt. + XCTAssertEqual( + RexProbe.sessionAgentState([status(.blocked)]), .needsYou(.permission)) + XCTAssertEqual( + RexProbe.sessionAgentState([status(.done), status(.working)]), .busy) + // `done` and `error` settle to idle: that busy → idle edge is the + // turn-ended alert. + XCTAssertEqual(RexProbe.sessionAgentState([status(.done)]), .idle) + XCTAssertEqual(RexProbe.sessionAgentState([status(.error)]), .idle) + XCTAssertNil(RexProbe.sessionAgentState([status(.unknown)])) + XCTAssertNil(RexProbe.sessionAgentState([])) + } + + // MARK: States + + func testAHostWithoutRexReportsItMissing() { + XCTAssertEqual(RexProbe.parseProbe("MULTIPLEX_NO_REX\n").state, .rexMissing) + // Login-shell noise ahead of the marker is tolerated. + XCTAssertEqual( + RexProbe.parseProbe("Welcome to devbox\nMULTIPLEX_NO_REX\n").state, + .rexMissing) + XCTAssertEqual(RexProbe.State.rexMissing.tmuxState, .tmuxMissing) + } + + func testNoRunningServerIsNoServerNotAFailure() { + // Exit 4 is the CLI's "server could not be reached"; with autostart + // off that is simply nothing running. + let probe = RexProbe.parseProbe("MULTIPLEX_REX_PROBE\nMULTIPLEX_REX_EXIT 4\n") + XCTAssertEqual(probe.state, .noServer) + XCTAssertEqual(probe.state.tmuxState, .noServer) + } + + func testAnyOtherExitStatusIsAFailureThatNamesIt() { + let probe = RexProbe.parseProbe("MULTIPLEX_REX_PROBE\nMULTIPLEX_REX_EXIT 2\n") + guard case .failed(let message) = probe.state else { + return XCTFail("expected a failure, got \(probe.state)") + } + XCTAssertTrue(message.contains("2")) + } + + func testAServerWithNoSessionsRendersNothing() { + // An empty Lua table encodes as `{}`, never `[]`. + let probe = RexProbe.parseProbe(response(json: #"{"ok":true,"sessions":{}}"#)) + XCTAssertEqual(probe.state, .noServer) + } + + func testAScriptThatNeverReachedTheSessionListIsUnreadable() { + // `ok` is only set once `session.list` answered. + let probe = RexProbe.parseProbe(response(json: #"{"sessions":{}}"#)) + guard case .failed = probe.state else { + return XCTFail("expected a failure, got \(probe.state)") + } + guard case .failed = RexProbe.parseProbe("garbage").state else { + return XCTFail("garbage must not parse") + } + // A response cut off before its exit line reports nothing. + guard case .failed = RexProbe.parseProbe( + "MULTIPLEX_REX_PROBE\n{\"ok\":true,").state + else { return XCTFail("a truncated response must not parse") } + } + + func testASessionWhoseViewFailedIsStillATile() throws { + // The view call can lose a race with a closing session; the session + // is listed with no spine rather than dropped. + let probe = RexProbe.parseProbe(response(json: """ + {"ok":true,"sessions":[ + {"id":"session:0000-aaaaaa","label":"solo","windows":{}} + ]} + """)) + let session = try XCTUnwrap(try sessions(probe).first) + XCTAssertEqual(session.name, "solo") + XCTAssertTrue(session.windows.isEmpty) + XCTAssertNil(probe.tails["solo"]) + } + + func testAScreenCannotForgeTheExitLine() throws { + // Screen text arrives JSON-escaped inside a quoted, indented value, + // so it can never start a line with the marker. + let probe = RexProbe.parseProbe(response(json: """ + {"ok":true,"sessions":[ + {"id":"session:0000-bbbbbb","label":"sly", + "tail":"hello\\nMULTIPLEX_REX_EXIT 4\\nMULTIPLEX_NO_REX","windows":{}} + ]} + """)) + XCTAssertEqual(try sessions(probe).map(\.name), ["sly"]) + XCTAssertEqual( + probe.tails["sly"], + ["hello", "MULTIPLEX_REX_EXIT 4", "MULTIPLEX_NO_REX"]) + } + + func testAttachedAppClientsLightTheLiveLamp() throws { + let probe = RexProbe.parseProbe(response(json: """ + {"ok":true,"sessions":[ + {"id":"session:0000-cccccc","label":"shown","clients":2,"windows":{}} + ]} + """)) + let session = try XCTUnwrap(try sessions(probe).first) + XCTAssertEqual(session.clientCount, 2) + XCTAssertTrue(Host.SessionBackend.rex.reportsClientCount) + XCTAssertTrue(Host.SessionBackend.rex.isSessionLive( + clientCount: session.clientCount, hasOpenTab: false)) + // This app attaches as kind `other`, so its own tab is not in that + // count and lights the lamp by itself. + XCTAssertTrue(Host.SessionBackend.rex.isSessionLive(clientCount: 0, hasOpenTab: true)) + XCTAssertFalse(Host.SessionBackend.rex.isSessionLive(clientCount: 0, hasOpenTab: false)) + } + + // MARK: Names + + func testSharedAndEmptyLabelsAreSpelledWithTheIDTail() { + XCTAssertEqual( + RexProbe.sessionNames(for: [ + (id: "session:1111-aaaaaa", label: "work"), + (id: "session:2222-bbbbbb", label: "notes"), + // Rex matches labels case-insensitively, so these collide. + (id: "session:3333-cccccc", label: "Work"), + (id: "session:4444-dddddd", label: " "), + ]), + ["work …aaaaaa", "notes", "Work …cccccc", "…dddddd"]) + } + + func testControlCharactersNeverReachATileName() { + XCTAssertEqual( + RexProbe.sessionNames(for: [(id: "session:1-abcdef", label: "a\u{1B}[31mb\n")]), + ["a[31mb"]) + } + + // MARK: Actions + + func testKillAimsAtTheIDAndRefusesAnythingElse() throws { + var session = TmuxSession( + name: "work …8d7863", windows: [], created: .distantPast, + tmuxID: "session:01a1e1e3-47e5-7497-bde1-74a5768d7863", backend: .rex) + let command = try XCTUnwrap(RexProbe.killCommand(for: session)) + XCTAssertTrue(command.contains( + "REX_AUTOSTART=0 rex kill 'session:01a1e1e3-47e5-7497-bde1-74a5768d7863'")) + XCTAssertTrue(command.hasSuffix("; true")) + + // A label is not a target: two sessions can share it. + session.tmuxID = "" + XCTAssertNil(RexProbe.killCommand(for: session)) + session.tmuxID = "session:x; rm -rf ~" + XCTAssertNil(RexProbe.killCommand(for: session)) + XCTAssertFalse(RexProbe.bakeableSessionID("work")) + XCTAssertFalse(RexProbe.bakeableSessionID("session:")) + } + + // MARK: Discovery + + func testTheRiderCountsSessionsWithoutStartingAServer() { + let rider = BackendDiscovery.riderCommand(for: .rex) + XCTAssertTrue(rider.contains("REX_AUTOSTART=0 rex ls -q 2>/dev/null || true")) + XCTAssertTrue(rider.contains("command -v rex >/dev/null 2>&1 && ")) + + let reading = BackendDiscovery.read(""" + MULTIPLEX_DISCOVER rex + MPXD_PRESENT + session:01a1e1e3-47e5-7497-bde1-74a5768d7863 + session:01a1e1e3-4870-742a-9d13-2b5e9df0ada5 + a stray warning line + MULTIPLEX_DISCOVER_END + S $0 0 1 main + """) + let result = try? XCTUnwrap(reading.results[.rex]) + XCTAssertEqual(result?.isInstalled, true) + XCTAssertEqual(result?.sessionCount, 2) + XCTAssertEqual(result?.offersSessions, true) + XCTAssertEqual(reading.remainder, "S $0 0 1 main") + XCTAssertEqual( + FleetBackendOffer(backend: .rex, sessionCount: 2).chipCaption, "+ REX · 2") + } + + func testEveryPrimaryProbeAsksAfterRex() { + XCTAssertTrue(TmuxProbe.probeCommand(discovering: [.herdr, .rex]) + .contains("MULTIPLEX_DISCOVER rex")) + XCTAssertTrue(HerdrProbe.probeCommand( + sessionNames: nil, tailTargets: [], discovering: [.tmux, .rex] + ).contains("MULTIPLEX_DISCOVER rex")) + } + + // MARK: The record — attachable, never the primary + + func testRexIsNeverTheHostsPrimary() { + var host = Host(name: "devbox", hostname: "127.0.0.1", username: "dev") + host.sessionBackend = .rex + // The write keeps the old primary and shows Rex beside it. + XCTAssertEqual(host.sessionBackend, .tmux) + XCTAssertEqual(host.secondaryBackends, [.rex]) + XCTAssertEqual(host.monitoredBackends, [.tmux, .rex]) + XCTAssertTrue(host.showsBackendIdentity) + + XCTAssertFalse(Host.SessionBackend.rex.canBeDefault) + XCTAssertEqual(Host.SessionBackend.defaultCases, [.tmux, .herdr]) + } + + func testARecordNamingRexAsPrimaryDecodesWithTmuxLeading() throws { + let json = """ + {"name":"devbox","hostname":"127.0.0.1","username":"dev", + "sessionBackend":"rex","secondaryBackends":["herdr"]} + """ + let host = try JSONDecoder().decode(Host.self, from: Data(json.utf8)) + XCTAssertEqual(host.sessionBackend, .tmux) + XCTAssertEqual(host.secondaryBackends, [.herdr, .rex]) + } + + func testTheBackendSelectionNeverLeavesAHostWithNothingToRunOn() { + var selection = Host.BackendSelection(preferred: .tmux, also: [.rex]) + XCTAssertEqual(selection.defaultChoices, [.tmux]) + XCTAssertTrue(selection.isMixed) + + // Unchecking the only backend that can host a terminal is refused. + selection.setEnabled([.rex]) + XCTAssertEqual(selection.enabled, [.tmux, .rex]) + // Rex cannot be chosen as the default. + selection.setPreferred(.rex) + XCTAssertEqual(selection.preferred, .tmux) + + // Unchecking the default promotes one that can run sessions. + selection.setEnabled([.herdr, .rex]) + XCTAssertEqual(selection.preferred, .herdr) + XCTAssertEqual(selection.secondaries, [.rex]) + + // A selection handed Rex as its default leads with a real one. + let demoted = Host.BackendSelection(preferred: .rex, also: [.herdr]) + XCTAssertEqual(demoted.preferred, .herdr) + XCTAssertEqual(demoted.enabled, [.herdr, .rex]) + } + + func testASetOfBackendsEncodesSorted() throws { + var host = Host(name: "devbox", hostname: "127.0.0.1", username: "dev") + host.secondaryBackends = [.rex, .herdr] + let encoder = JSONEncoder() + encoder.outputFormatting = .sortedKeys + let first = try encoder.encode(host) + // `Set` iterates in a per-process order; the record must not. + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: first) as? [String: Any]) + XCTAssertEqual(object["secondaryBackends"] as? [String], ["herdr", "rex"]) + let decoded = try JSONDecoder().decode(Host.self, from: first) + XCTAssertEqual(decoded.secondaryBackends, [.herdr, .rex]) + XCTAssertEqual(try encoder.encode(decoded), first) + } + + // MARK: Attaching goes by id + + func testARexSessionAttachesByItsIDNeverItsLabel() throws { + let id = "session:01a1e1e3-47e5-7497-bde1-74a5768d7863" + let host = Host(name: "devbox", hostname: "127.0.0.1", username: "dev") + let session = TmuxSession( + name: "work …8d7863", windows: [], created: .distantPast, + tmuxID: id, backend: .rex) + let mode = try XCTUnwrap(TerminalRoute.Mode.attach(host: host, session: session)) + XCTAssertEqual(mode, .rexAttach(sessionName: "work …8d7863", sessionID: id)) + + let route = TerminalRoute(hostID: host.id, mode: mode) + XCTAssertNil(route.rexTarget?.blockID) + XCTAssertEqual(route.sessionBackend, .rex) + XCTAssertEqual(route.sessionKey, session.id) + XCTAssertEqual(route.rexTarget?.sessionID, id) + XCTAssertEqual(route.displayName, "work …8d7863") + // No client runs in a PTY, so there is nothing to hand a shell — + // over SSH or over mosh. + XCTAssertNil(route.remoteCommand) + XCTAssertNil(route.moshRemoteCommand) + XCTAssertFalse(route.usesTmux) + // Its rail key opens the REX panel — never a TMUX one. + XCTAssertEqual(route.shortcutBackend, .rex) + XCTAssertEqual(Host.SessionBackend.rex.shortcutKeyCaption, "REX") + XCTAssertEqual(Host.SessionBackend.tmux.shortcutKeyCaption, "TMUX") + XCTAssertEqual(Host.SessionBackend.herdr.shortcutKeyCaption, "HRDR") + // The panel has no shortcut rows (Rex has no prefix-key client), + // only the list that switches the tab's terminal. + let panel = ShortcutPanelContent.content(for: route.shortcutBackend) + XCTAssertEqual(panel, .rex) + XCTAssertEqual(panel?.sections, []) + XCTAssertEqual(panel?.switchSectionTitle, "Switch Terminal") + + // A label is not a target: two sessions can share one. + XCTAssertNil(TerminalRoute.Mode.attach(backend: .rex, sessionName: "work")) + XCTAssertNil(TerminalRoute.Mode.attach( + backend: .rex, sessionName: "work", sessionID: "work; rm -rf ~")) + XCTAssertEqual( + TerminalRoute.Mode.attach(backend: .tmux, sessionName: "work"), + .attach(sessionName: "work")) + // Rex has no terminal client, so no line opens it in a host shell. + XCTAssertNil(SessionHandoff.command(session: session)) + } + + func testARexRouteSurvivesARelaunch() throws { + for block in [nil, RexBlockRef(id: "block:b", label: "editor")] { + let route = TerminalRoute( + hostID: UUID(), + mode: .rexAttach( + sessionName: "api", sessionID: "session:0000-aaaaaa", block: block)) + let decoded = try JSONDecoder().decode( + TerminalRoute.self, from: JSONEncoder().encode(route)) + XCTAssertEqual(decoded, route) + } + // A route saved before a tab could name a terminal has no `block`. + let legacy = try JSONDecoder().decode( + TerminalRoute.Mode.self, + from: Data(#"{"rexAttach":{"sessionName":"api","sessionID":"session:0000-aaaaaa"}}"#.utf8)) + XCTAssertEqual( + legacy, .rexAttach(sessionName: "api", sessionID: "session:0000-aaaaaa")) + } + + func testOpenTerminalNamesEachTerminalAndTargetsItsBlock() throws { + let session = try XCTUnwrap( + try sessions(RexProbe.parseProbe(try fixture())).first) + let rows = session.windows.flatMap { window in + (window.panes ?? []).map { RexProbe.terminalMenuTitle(window: window, pane: $0) } + } + // The title a program set, else the command in front. + XCTAssertEqual(rows, ["editor — vim README.md", "editor — sleep", "agent — ✳ Claude Code"]) + + let window = session.windows[0] + let pane = try XCTUnwrap(window.panes?.last) + let mode = try XCTUnwrap( + RexProbe.attachMode(session: session, window: window, pane: pane)) + let route = TerminalRoute(hostID: UUID(), mode: mode) + XCTAssertEqual(route.rexTarget?.sessionID, session.tmuxID) + XCTAssertEqual(route.rexTarget?.blockID, "block:01a1e1e3-4810-7831-92b7-22087aff9bc8") + // Same session identity as the tile — the deck still finds the tab — + // but a label that says which terminal this one is. + XCTAssertEqual(route.sessionKey, session.id) + XCTAssertEqual(route.displayName, "work …8d7863 · editor") + // A tile press names no terminal: the fronted one, chosen at attach. + let fronted = TerminalRoute( + hostID: UUID(), + mode: try XCTUnwrap(TerminalRoute.Mode.attach( + host: Host(name: "a", hostname: "b", username: "c"), session: session))) + XCTAssertNil(fronted.rexTarget?.blockID) + } + + func testOnlyAMultiTerminalRexTileOffersOpenTerminal() throws { + let fixtureSessions = try sessions(RexProbe.parseProbe(try fixture())) + func menuTitles(_ session: TmuxSession) -> [String] { + let tile = FleetSessionTileView() + tile.configure(FleetSessionTileConfiguration( + hostID: UUID(), session: session, lines: [], attention: nil, + usesTmuxAttentionFallback: false, hasOpenTab: false, + sessionBackend: session.backend, showsBackendIdentity: true, + compact: false, selected: false, + duplicateAttachTitle: "Attach in New Window", + openTabAccessibilityText: "Open", + attach: {}, attachNewWindow: {}, newHerdrTab: {}, + copyHandoffCommand: {}, delete: {}, droppedSession: { _ in } + )) + return tile.menuProvider?()?.children.map(\.title) ?? [] + } + // Three terminals across two windows. + XCTAssertEqual( + menuTitles(fixtureSessions[0]), + ["Attach in New Window", "Open Terminal", "Delete Session…"]) + // One terminal: a press already opens it. + XCTAssertEqual( + menuTitles(fixtureSessions[2]), ["Attach in New Window", "Delete Session…"]) + } + + func testABannerForARexSessionCanAttachIt() { + XCTAssertTrue(AttentionTapTarget( + hostID: UUID(), sessionName: "work", backend: .rex + ).sessionIsAttachable) + } + + func testWidgetsListRexSessionsAndOfferRexToRunOn() { + var host = Host(name: "devbox", hostname: "127.0.0.1", username: "dev") + host.secondaryBackends = [.rex] + let tmux = TmuxSession(name: "main", windows: [], created: .distantPast) + let rex = TmuxSession( + name: "work", windows: [], created: .distantPast, backend: .rex) + let state = WidgetStateBuilder.hostState( + host: host, sessions: [tmux, rex], miniatures: [:], probedAt: nil) + // A row is a session to open; both backends' are. + XCTAssertEqual(state.sessions.map(\.name), ["main", "work"]) + XCTAssertEqual(state.sessions.map(\.backendRaw), ["tmux", "rex"]) + // A pick list is where a NEW session runs: the default first, then + // Rex, which can run one without ever being the default. + XCTAssertEqual(state.backendsRaw, ["tmux", "rex"]) + } + + // MARK: New session + + /// A reply as preview.19 prints it (2026-11-16): pretty-printed, keys + /// sorted, the CLI's exit status on the command's own last line. + private func mintReply(_ body: String, exit: Int = 0) -> String { + "MULTIPLEX_REX_MINT\n\(body)\nMULTIPLEX_REX_EXIT \(exit)\n" + } + + func testAMintReportsTheSessionTheServerActuallyMade() { + let reply = mintReply(""" + { + "id": "session:01a1e24f-9765-74c6-9227-dda638130537", + "label": "api-2", + "ok": true + } + """) + XCTAssertEqual( + RexProbe.parseMint(reply), + .created(name: "api-2", id: "session:01a1e24f-9765-74c6-9227-dda638130537")) + // Login-shell noise ahead of the marker changes nothing. + XCTAssertEqual( + RexProbe.parseMint("Last login: Mon Nov 16\n" + reply), + .created(name: "api-2", id: "session:01a1e24f-9765-74c6-9227-dda638130537")) + } + + func testAMintWithNoServerSaysSoInsteadOfLookingLikeABrokenLink() { + // Autostart is off, so the CLI exits 4 and prints nothing on stdout. + XCTAssertEqual(RexProbe.parseMint(mintReply("", exit: 4)), .noServer) + XCTAssertEqual(RexProbe.parseMint("MULTIPLEX_NO_REX\n"), .rexMissing) + // Any other status, a script that gave up, an id nothing could be + // attached by, and an answer cut short are all just "not created". + XCTAssertEqual(RexProbe.parseMint(mintReply("", exit: 1)), .failed) + XCTAssertEqual(RexProbe.parseMint(mintReply("{\n \"ok\": false\n}")), .failed) + XCTAssertEqual( + RexProbe.parseMint(mintReply("{\"ok\": true, \"id\": \"work; rm -rf\", \"label\": \"x\"}")), + .failed) + XCTAssertEqual(RexProbe.parseMint("MULTIPLEX_REX_MINT\n{\n \"ok\": true"), .failed) + XCTAssertEqual(RexProbe.parseMint(""), .failed) + } + + func testAMintedSessionIsNamedAsTheNextProbeWillNameIt() { + // A label comes back through the same reading a probed one gets, + // and a session the server left unlabeled is spelled by its id tail + // — `sessionNames`' own spelling, so the tab and the tile agree. + let unlabeled = mintReply(""" + {"id": "session:01a1e24f-a3e4-74ca-90c0-8cfddb282ebc", "label": "", "ok": true} + """) + XCTAssertEqual( + RexProbe.parseMint(unlabeled), + .created(name: "…282ebc", id: "session:01a1e24f-a3e4-74ca-90c0-8cfddb282ebc")) + XCTAssertEqual( + RexProbe.sessionNames(for: [ + (id: "session:01a1e24f-a3e4-74ca-90c0-8cfddb282ebc", label: ""), + ]), + ["…282ebc"]) + } + + func testTheMintCarriesWhatTheUserTypedAsDataNeverAsScript() throws { + let label = "it's \"mine\"; os.exit() ]] --" + let command = RexProbe.mintCommand( + label: label, inDirectoryOf: nil, startingIn: nil, + typing: ["source ~/.venv/bin/activate", "claude 'fix it'"]) + // Never started by Multiplex, never a failed exec. + XCTAssertTrue(command.contains("REX_AUTOSTART=0 rex do -e ")) + XCTAssertTrue(command.contains("command -v rex >/dev/null 2>&1 || { echo MULTIPLEX_NO_REX; exit 0; }")) + XCTAssertTrue(command.hasSuffix("echo \"MULTIPLEX_REX_EXIT $?\"")) + + // The arguments are one shell word holding one JSON object. + let arguments = try XCTUnwrap(jsonArguments(of: command)) + XCTAssertEqual(arguments["label"], label) + // Each line is followed by Enter, in order: setup, then launch. + XCTAssertEqual( + arguments["input"], "source ~/.venv/bin/activate\rclaude 'fix it'\r") + XCTAssertNil(arguments["source"]) + // The script itself is constant: nothing typed reaches it. + let other = RexProbe.mintCommand( + label: "plain", inDirectoryOf: nil, startingIn: nil, typing: []) + XCTAssertEqual(script(of: command), script(of: other)) + XCTAssertNil(try XCTUnwrap(jsonArguments(of: other))["input"]) + } + + func testTheMintStartsWhereTheSourceSessionIsElseInTheNamedDirectory() throws { + let source = "session:01a1e24a-4b6a-7557-8707-32a02f197112" + // A source wins, and the explicit directory is then not consulted. + let sibling = RexProbe.mintCommand( + label: "api", inDirectoryOf: source, startingIn: "~/elsewhere", typing: []) + XCTAssertEqual(try XCTUnwrap(jsonArguments(of: sibling))["source"], source) + XCTAssertFalse(sibling.contains("MULTIPLEX_REX_CWD=")) + XCTAssertFalse(sibling.contains("elsewhere")) + + // Without one, the SHELL resolves the directory — the server takes + // `cwd` literally, tilde included — and hands over an absolute path, + // or nothing when it is not there. + let placed = RexProbe.mintCommand( + label: "api", inDirectoryOf: nil, startingIn: "~/work space", typing: []) + XCTAssertTrue(placed.contains( + "d=\"$HOME\"/'work space'; d=$(CDPATH= cd -- \"$d\" 2>/dev/null && pwd); ")) + XCTAssertTrue(placed.contains("MULTIPLEX_REX_CWD=\"$d\" REX_AUTOSTART=0 rex do -e ")) + XCTAssertNil(try XCTUnwrap(jsonArguments(of: placed))["source"]) + + // Neither: nothing is resolved and nothing is exported. + let home = RexProbe.mintCommand( + label: "api", inDirectoryOf: nil, startingIn: nil, typing: []) + XCTAssertFalse(home.contains("MULTIPLEX_REX_CWD=")) + } + + func testANewLabelIsReadableUniqueAndNeverEmpty() { + XCTAssertEqual(RexProbe.sessionLabel(base: " my work\u{07} "), "my work") + // An empty label would make the server invent one nobody predicted. + XCTAssertEqual(RexProbe.sessionLabel(base: " \n "), "session") + XCTAssertEqual(RexProbe.sessionLabel(base: String(repeating: "x", count: 300)).count, 120) + + XCTAssertEqual(RexProbe.uniqueSessionLabel(base: "api", existing: ["main"]), "api") + // Without case, as the wall counts labels. + XCTAssertEqual(RexProbe.uniqueSessionLabel(base: "api", existing: ["API"]), "api-2") + XCTAssertEqual( + RexProbe.uniqueSessionLabel(base: "api", existing: ["api", "api-2"]), "api-3") + } + + func testTheNewSessionSheetOffersRexWithoutMakingItTheDefault() throws { + var host = Host(name: "devbox", hostname: "127.0.0.1", username: "dev") + host.secondaryBackends = [.rex] + // No remembered agent: the suggestion is the backend's own default. + let suite = "app.multiplexterm.multiplex.tests.rex-mint.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defaults.removePersistentDomain(forName: suite) + var form = NewSessionFormState( + host: host, existingNames: [.tmux: ["main"], .rex: ["session"]], + preferences: NewSessionPreferences(defaults: defaults)) + XCTAssertEqual(form.backendChoices, [.tmux, .rex]) + // The sheet opens on the host's default. + XCTAssertEqual(form.backend, .tmux) + XCTAssertEqual(form.name, "main-2") + + form.selectBackend(.rex) + XCTAssertEqual(form.backend, .rex) + // An untouched suggestion follows the backend, by ITS namer and + // against ITS sessions. + XCTAssertEqual(form.name, "session-2") + // A tab inside an existing session stays herdr's shape. + XCTAssertTrue(form.tabTargetChoices.isEmpty) + } + + /// The `--args` word of a mint command, decoded. + private func jsonArguments(of command: String) -> [String: String]? { + guard let start = command.range(of: " --args '"), + let end = command.range(of: "' --json 2>/dev/null; ", options: .backwards) + else { return nil } + let quoted = String(command[start.upperBound.. String? { + guard let start = command.range(of: " do -e '"), + let end = command.range(of: "' --args '") + else { return nil } + return String(command[start.upperBound.. FleetSessionTileView { + let session = TmuxSession( + name: "work", windows: [], created: .distantPast, backend: backend) + let tile = FleetSessionTileView() + tile.configure(FleetSessionTileConfiguration( + hostID: UUID(), + session: session, + lines: [], + attention: nil, + usesTmuxAttentionFallback: false, + hasOpenTab: false, + sessionBackend: backend, + showsBackendIdentity: mixed, + compact: false, + selected: false, + duplicateAttachTitle: "Attach in New Window", + openTabAccessibilityText: "Open", + attach: {}, attachNewWindow: {}, newHerdrTab: {}, + copyHandoffCommand: {}, delete: {}, droppedSession: { _ in } + )) + return tile + } + + func testARexTileAttachesLikeAnyOtherAndOffersNoHandoffLine() throws { + let rex = tile(backend: .rex) + let label = try XCTUnwrap(rex.accessibilityLabel) + XCTAssertTrue(label.contains("on rex")) + XCTAssertTrue(label.hasSuffix("Attach")) + // There is no command that opens a Rex session in a host shell, so + // the handoff row is the one a Rex tile does not carry. + XCTAssertEqual( + rex.menuProvider?()?.children.map(\.title), + ["Attach in New Window", "Delete Session…"]) + + let tmux = tile(backend: .tmux) + XCTAssertEqual( + tmux.menuProvider?()?.children.map(\.title), + ["Attach in New Window", "Copy Command for Handoff", "Delete Session…"]) + } + + /// The wash must change HUE, not hierarchy, and must not be mistaken for + /// herdr's: blue over green over red, where mauve runs blue, red, green. + func testTheRexWashMatchesBezelsLightnessAndIsNotMauve() { + for style in [UIUserInterfaceStyle.light, .dark] { + let traits = UITraitCollection(userInterfaceStyle: style) + let bezel = TallyPalette.bezel.resolvedColor(with: traits) + let rex = TallyPalette.rexBezel.resolvedColor(with: traits) + XCTAssertNotEqual(rex, bezel, "\(style)") + XCTAssertNotEqual( + rex, TallyPalette.herdrBezel.resolvedColor(with: traits), "\(style)") + XCTAssertEqual( + luminance(of: rex), luminance(of: bezel), accuracy: 3 / 255, + "the rex wash must read as a different tint, not a brighter tile") + var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 + rex.getRed(&red, green: &green, blue: &blue, alpha: &alpha) + XCTAssertGreaterThan(blue, green, "\(style)") + XCTAssertGreaterThan(green, red, "\(style)") + } + XCTAssertEqual( + UIKitChassis.tileBezel(backend: .rex, tinted: false), UIKitChassis.bezel) + XCTAssertEqual( + UIKitChassis.tileBezel(backend: .tmux, tinted: true), UIKitChassis.bezel) + } + + private func luminance(of color: UIColor) -> CGFloat { + var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 + color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) + return 0.2126 * red + 0.7152 * green + 0.0722 * blue + } +} diff --git a/MultiplexTests/RexSessionTests.swift b/MultiplexTests/RexSessionTests.swift new file mode 100644 index 00000000..3819dacf --- /dev/null +++ b/MultiplexTests/RexSessionTests.swift @@ -0,0 +1,682 @@ +import XCTest +@testable import Multiplex + +/// `RexSession` end to end against an in-process Rex server: every byte +/// goes through the real WebSocket codec and wire formats, only the SSH +/// pipes are replaced. What this pins is ORDER — the part of the attach +/// that is load-bearing and that no pure test can see. +final class RexSessionTests: XCTestCase { + private let sessionID = "session:0000-aaaaaa" + + private func makeSession( + _ server: FakeRexServer, blockID: String? = nil + ) -> RexSession { + RexSession( + openPipe: { server.makePipe() }, + closeLink: { server.note("link closed") }, + sessionID: sessionID, blockID: blockID, clientVersion: "test" + ) + } + + /// Collects what the session hands the terminal and when it ends. + private final class Sink: @unchecked Sendable { + private let lock = NSLock() + private var chunks: [Data] = [] + private var closes: [String?] = [] + + func data(_ chunk: Data) { lock.withLock { chunks.append(chunk) } } + func closed(_ reason: String?) { lock.withLock { closes.append(reason) } } + var text: [String] { lock.withLock { chunks.map { String(decoding: $0, as: UTF8.self) } } } + var closeReasons: [String?] { lock.withLock { closes } } + } + + private func open( + _ session: RexSession, sink: Sink, cols: Int = 100, rows: Int = 30 + ) async throws { + try await session.open( + cols: cols, rows: rows, + onData: { sink.data($0) }, + onClose: { sink.closed($0) } + ) + } + + private func eventually( + _ condition: @escaping () -> Bool, file: StaticString = #filePath, line: UInt = #line + ) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } + XCTAssertTrue(condition(), "condition never held", file: file, line: line) + } + + // MARK: - Attach + + func testAttachClaimsAndSizesBeforeItAsksForTheScreenOrTheStream() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + XCTAssertEqual(server.calls, [ + "session.attach", + // Claim and size FIRST: the rendering and the stream below must + // describe the terminal at this tab's size. + "session.own_block", + "com.superlogical.terminal.resize 100x30", + "data.connect", + "com.superlogical.terminal.modes", + "com.superlogical.terminal.format", + ]) + // The hello never claims to be an app (see `RexWire.hello`). + XCTAssertEqual(server.helloKind, "other") + // The fronted block was chosen: active window, focused block. + XCTAssertEqual(server.attachedBlock, "block:front") + await session.close() + } + + func testTheSnapshotIsDroppedAndEarlyOutputIsDrawnAfterTheScreen() async throws { + let server = FakeRexServer() + // The server sends this the moment the stream opens — before the + // session has fetched, let alone drawn, the rendering. + server.earlyOutput = "early\r\n" + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + // RIS, then the rendering, then the held stream — never the + // Ghostty snapshot, and never output UNDER a later rendering. + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "early\r\n"]) + + server.sendOutput("later\r\n") + await eventually { sink.text.count == 3 } + XCTAssertEqual(sink.text.last, "later\r\n") + await session.close() + } + + func testANamedBlockIsAttachedWhileItExists() async throws { + let server = FakeRexServer() + let session = makeSession(server, blockID: "block:other") + try await open(session, sink: Sink()) + XCTAssertEqual(server.attachedBlock, "block:other") + await session.close() + + // One that has since closed falls back to the fronted block. + let fallback = FakeRexServer() + let second = makeSession(fallback, blockID: "block:gone") + try await open(second, sink: Sink()) + XCTAssertEqual(fallback.attachedBlock, "block:front") + await second.close() + } + + // MARK: - Switching terminals + + func testTheSwitchListNamesEveryTerminalAndMarksTheOneOnShow() async throws { + let server = FakeRexServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + let listed = await session.terminalChoices() + let choices = try XCTUnwrap(listed) + XCTAssertEqual(choices.map(\.tmuxID), ["block:other", "block:side", "block:front"]) + XCTAssertEqual(choices.map(\.isActive), [false, false, true]) + XCTAssertEqual(choices.map(\.name), ["one — shell", "two — shell", "two — shell"]) + await session.close() + } + + func testSwitchingRedrawsTheTabOnTheOtherTerminalWithoutEndingIt() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let attachCalls = server.calls.count + + server.screen = "OTHER" + await session.switchBlock(to: "block:other") + + // The old stream was closed properly, the old block given up, and + // the new one claimed, sized, streamed and drawn — the attach's own + // order, on the same control connection. + XCTAssertEqual(server.closeFramesReceived, [RexWire.dataPath]) + XCTAssertEqual(Array(server.calls.dropFirst(attachCalls)), [ + "session.disown_block block:front", + "session.own_block", + "com.superlogical.terminal.resize 100x30", + "data.connect", + "com.superlogical.terminal.modes", + "com.superlogical.terminal.format", + ]) + XCTAssertEqual(server.attachedBlock, "block:other") + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "\u{1B}cOTHER"]) + // The retired stream ending is NOT the tab ending. + XCTAssertTrue(sink.closeReasons.isEmpty) + + // The tab is live on the new terminal: output flows and typing + // goes to it. + server.sendOutput("from other\r\n") + await eventually { sink.text.last == "from other\r\n" } + try await session.write(Data("x".utf8)) + XCTAssertEqual(server.written, ["x"]) + XCTAssertEqual(server.lastWriteBlock, "block:other") + let listed = await session.terminalChoices() + let choices = try XCTUnwrap(listed) + XCTAssertEqual(choices.map(\.isActive), [true, false, false]) + + // Switching to the terminal already on show does nothing. + let before = server.calls.count + await session.switchBlock(to: "block:other") + XCTAssertEqual(server.calls.count, before) + await session.close() + } + + func testTheWorkingDirectoryFollowsTheTerminalOnShow() async throws { + let server = FakeRexServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + let front = await session.workingDirectory() + XCTAssertEqual(front, "/work/block:front") + await session.switchBlock(to: "block:other") + let other = await session.workingDirectory() + XCTAssertEqual(other, "/work/block:other") + await session.close() + // A closed tab has no answer — the $HOME fallback. + let closed = await session.workingDirectory() + XCTAssertNil(closed) + } + + // MARK: - Typing and sizing + + func testTypingReachesTheBlockInOrderAsText() async throws { + let server = FakeRexServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + + try await session.write(Data("ls\r".utf8)) + // A character split across two writes is sent whole. + let wide = Data("測".utf8) + try await session.write(wide.prefix(2)) + try await session.write(wide.suffix(1)) + try await session.write(Data([0x1B, 0x5B, 0x41])) + XCTAssertEqual(server.written, ["ls\r", "測", "\u{1B}[A"]) + + try await session.resize(cols: 120, rows: 40) + XCTAssertEqual(server.calls.last, "com.superlogical.terminal.resize 120x40") + await session.close() + } + + func testTypingClaimsTheBlockBackAfterAnotherClientTookIt() async throws { + let server = FakeRexServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + let before = server.calls.filter { $0 == "session.own_block" }.count + + // While this tab owns the block, typing claims nothing. + try await session.write(Data("a".utf8)) + XCTAssertEqual(server.calls.filter { $0 == "session.own_block" }.count, before) + + // The Rex app takes the block; the next keystroke takes it back and + // re-sizes it — the last client to type owns the size. + server.announceOwner("client:rex-app") + await eventually { server.eventsDelivered == 1 } + try await Task.sleep(for: .milliseconds(150)) + try await session.write(Data("b".utf8)) + XCTAssertEqual(server.calls.filter { $0 == "session.own_block" }.count, before + 1) + XCTAssertEqual(server.calls.suffix(3), [ + "session.own_block", + "com.superlogical.terminal.resize 100x30", + "com.superlogical.terminal.write", + ]) + await session.close() + } + + // MARK: - Full-screen programs + + func testATabAttachedDuringAFullScreenProgramRedrawsWhenItExits() async throws { + let server = FakeRexServer() + server.screenKind = "alternate" + server.screen = "VIM" + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + XCTAssertEqual(sink.text, ["\u{1B}cVIM"]) + + // The program leaves the alternate screen; the server can now + // render the shell history that was underneath. + server.screenKind = "primary" + server.screen = "HISTORY" + server.sendOutput("\u{1B}[?1049l$ ") + await eventually { sink.text.last == "\u{1B}cHISTORY" } + // The exit burst passed through, then ONE redraw replaced it. + XCTAssertEqual(sink.text, ["\u{1B}cVIM", "\u{1B}[?1049l$ ", "\u{1B}cHISTORY"]) + XCTAssertEqual( + server.calls.filter { $0 == "com.superlogical.terminal.format" }.count, 2) + + // Back on the primary screen there is nothing more to restore: a + // later exit sequence is just output. + server.sendOutput("\u{1B}[?1049l") + try await Task.sleep(for: .milliseconds(400)) + XCTAssertEqual( + server.calls.filter { $0 == "com.superlogical.terminal.format" }.count, 2) + await session.close() + } + + // MARK: - Ending + + func testABlockClosingEndsTheTabCleanlyAndSaysGoodbye() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + server.closeData(code: 4000, reason: "block closed") + await eventually { !sink.closeReasons.isEmpty } + // 4000 is a clean end — like a shell exiting, not an error. + XCTAssertEqual(sink.closeReasons, [nil]) + // The control connection got a close frame, so the server ends the + // client at once instead of keeping it "connection lost" a minute. + await eventually { server.closeFramesReceived.contains(RexWire.controlPath) } + await session.close() + XCTAssertEqual(server.notes, ["link closed"]) + } + + func testClosingTheTabClosesTheStreamBeforeTheControlConnection() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + await session.close() + + // Data first, with status 1000 (which ends the stream), then control. + XCTAssertEqual(server.closeFramesReceived, [RexWire.dataPath, RexWire.controlPath]) + XCTAssertEqual(server.notes, ["link closed"]) + // Closing is the tab's own doing — nobody is told it "ended". + XCTAssertTrue(sink.closeReasons.isEmpty) + // And is safe to repeat. + await session.close() + } + + func testAnAbnormalStreamCloseIsAnErrorTheTabCanShow() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + server.closeData(code: 1011, reason: "data provider failed") + await eventually { !sink.closeReasons.isEmpty } + XCTAssertEqual(sink.closeReasons.count, 1) + XCTAssertEqual(sink.closeReasons.first??.contains("data provider failed"), true) + await session.close() + } + + func testALinkThatDiesUnderALiveTabEndsItOnceWithTheReason() async throws { + // What iOS suspension does: the sockets die with no goodbye. The + // tab must END (once), because that close is what + // `SessionResumePolicy` hangs an automatic re-attach on. + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + server.dropLinks(SSHConnectionError.connectFailed("connection reset by peer")) + await eventually { !sink.closeReasons.isEmpty } + try await Task.sleep(for: .milliseconds(100)) + // Said as a lost connection — never the transport's own shorthand. + XCTAssertEqual(sink.closeReasons, ["The connection to the Rex server was lost."]) + // Nothing can be typed into a dead tab, and closing it is still safe. + do { + try await session.write(Data("x".utf8)) + XCTFail("a dead tab accepted input") + } catch {} + await session.close() + } + + // MARK: - Failing to attach + + func testASessionThatIsGoneFailsTheOpenWithAReadableReason() async { + let server = FakeRexServer() + server.attachError = ["code": "session_not_found", "message": "no such session", "status": 404] + let session = makeSession(server) + let sink = Sink() + do { + try await open(session, sink: sink) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, "This Rex session no longer exists.") + } + // A failed open is reported by the throw alone. + XCTAssertTrue(sink.closeReasons.isEmpty) + XCTAssertTrue(sink.text.isEmpty) + await session.close() + } + + func testASessionWithNoTerminalAndARefusedStreamBothFailTheOpen() async { + let empty = FakeRexServer() + empty.hasTerminals = false + do { + try await open(makeSession(empty), sink: Sink()) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, + "This Rex session has no terminal to open.") + } + + let refusing = FakeRexServer() + refusing.rejectReason = 0x02 + do { + try await open(makeSession(refusing), sink: Sink()) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message.contains( + "another connection already has this terminal"), + true) + } + } + + func testAPipeThatCannotStartCarriesTheCommandsOwnReason() async { + let session = RexSession( + openPipe: { + throw SSHConnectionError.connectFailed( + "Error: no Rex server is running, and REX_AUTOSTART=0 turns autostart off") + }, + closeLink: {}, + sessionID: sessionID, blockID: nil, clientVersion: "test" + ) + do { + try await open(session, sink: Sink()) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, + "Couldn't reach the Rex server. Error: no Rex server is running, " + + "and REX_AUTOSTART=0 turns autostart off") + } + } +} + +// MARK: - The in-process server + +/// A Rex server small enough to read: it answers the upgrade, the hello, +/// and the handful of methods an attach makes, and it streams what a test +/// tells it to. One instance serves both of a session's pipes. +private final class FakeRexServer: @unchecked Sendable { + private let lock = NSLock() + private var recordedCalls: [String] = [] + private var recordedWrites: [String] = [] + private var recordedNotes: [String] = [] + private var recordedCloses: [String] = [] + private var kind: String? + private var block: String? + private var writeBlock: String? + private var events = 0 + private var controlFeed: AsyncThrowingStream.Continuation? + private var dataFeed: AsyncThrowingStream.Continuation? + + // What a test configures before the attach. + var attachError: [String: Any]? + var hasTerminals = true + var rejectReason: UInt8? + var earlyOutput = "" + var screen = "SCREEN" + var screenKind = "primary" + let nonce: UInt64 = 0x1122_3344_5566_7788 + let clientID = "client:me" + + var calls: [String] { lock.withLock { recordedCalls } } + var written: [String] { lock.withLock { recordedWrites } } + var notes: [String] { lock.withLock { recordedNotes } } + var closeFramesReceived: [String] { lock.withLock { recordedCloses } } + var helloKind: String? { lock.withLock { kind } } + var attachedBlock: String? { lock.withLock { block } } + var lastWriteBlock: String? { lock.withLock { writeBlock } } + var eventsDelivered: Int { lock.withLock { events } } + + func note(_ text: String) { lock.withLock { recordedNotes.append(text) } } + + func makePipe() -> RemotePipe { + let (stream, feed) = AsyncThrowingStream.makeStream() + let connection = Connection(server: self, feed: feed) + return RemotePipe( + incoming: stream, + write: { connection.receive($0) }, + close: { feed.finish() } + ) + } + + // MARK: Driving the stream from a test + + func sendOutput(_ text: String) { + lock.withLock { dataFeed }?.yield(Self.frame(0x2, Data(text.utf8))) + } + + func closeData(code: UInt16, reason: String) { + let feed = lock.withLock { dataFeed } + feed?.yield(Self.frame( + 0x8, Data([UInt8(code >> 8), UInt8(code & 0xFF)]) + Data(reason.utf8))) + feed?.finish() + } + + /// Both pipes fail at once, as when the SSH connection under them dies. + func dropLinks(_ error: Error) { + let feeds = lock.withLock { [controlFeed, dataFeed] } + feeds.forEach { $0?.finish(throwing: error) } + } + + func announceOwner(_ owner: String) { + let event: [String: Any] = [ + "type": "event", "seq": 9, + "payload": [ + "type": "session_event", + "payload": [ + "session_id": "session:0000-aaaaaa", + "event": [ + "type": "block_owner_changed", + "payload": ["block_id": attachedBlock ?? "", "owner": owner], + ], + ], + ], + ] + lock.withLock { controlFeed }?.yield(Self.frame(0x1, Self.json(event))) + lock.withLock { events += 1 } + } + + // MARK: Frames + + /// An unmasked server frame. + static func frame(_ opcode: UInt8, _ payload: Data) -> Data { + var frame = Data([0x80 | opcode]) + if payload.count < 126 { + frame.append(UInt8(payload.count)) + } else { + frame.append(126) + frame.append(contentsOf: [UInt8(payload.count >> 8), UInt8(payload.count & 0xFF)]) + } + return frame + payload + } + + static func json(_ object: [String: Any]) -> Data { + (try? JSONSerialization.data(withJSONObject: object)) ?? Data() + } + + // MARK: One pipe + + private final class Connection: @unchecked Sendable { + private let server: FakeRexServer + private let feed: AsyncThrowingStream.Continuation + private let lock = NSLock() + private var head = Data() + private var path: String? + private var decoder = WebSocketCodec.Decoder() + + init(server: FakeRexServer, feed: AsyncThrowingStream.Continuation) { + self.server = server + self.feed = feed + } + + func receive(_ bytes: Data) { + lock.withLock { + if path == nil { + head.append(bytes) + guard let end = head.range(of: Data("\r\n\r\n".utf8)) else { return } + upgrade(String(decoding: head[.. String { + lines.first { $0.lowercased().hasPrefix(name.lowercased() + ":") } + .map { String($0.dropFirst(name.count + 1)).trimmingCharacters(in: .whitespaces) } + ?? "" + } + self.path = path + if path == RexWire.controlPath { + server.lock.withLock { server.controlFeed = feed } + } else { + server.lock.withLock { server.dataFeed = feed } + } + feed.yield(Data(""" + HTTP/1.1 101 Switching Protocols\r + Upgrade: websocket\r + Connection: Upgrade\r + Sec-Websocket-Accept: \(WebSocketCodec.acceptValue(forKey: header("Sec-WebSocket-Key")))\r + Sec-Websocket-Protocol: \(header("Sec-WebSocket-Protocol"))\r + \r + + """.utf8)) + } + + private func handle(_ message: WebSocketCodec.Message) { + switch message { + case .close: + server.lock.withLock { server.recordedCloses.append(path ?? "") } + case .text(let text) where path == RexWire.controlPath: + guard let object = (try? JSONSerialization.jsonObject(with: text)) as? [String: Any] + else { return } + control(object) + case .binary(let bytes) where path == RexWire.dataPath: + dataHello(bytes) + default: + break + } + } + + private func control(_ message: [String: Any]) { + if message["type"] as? String == "hello" { + let client = message["client"] as? [String: Any] + server.lock.withLock { server.kind = client?["kind"] as? String } + send([ + "type": "welcome", "protocol": RexWire.controlSubprotocol, + "client": ["id": server.clientID], + ]) + return + } + guard let id = message["id"] as? String, let method = message["method"] as? String + else { return } + let payload = message["payload"] as? [String: Any] ?? [:] + let args = payload["args"] as? [String: Any] ?? [:] + var record = method + var result: [String: Any] = [:] + var error: [String: Any]? + switch method { + case "session.attach": + error = server.attachError + result = ["client_id": server.clientID, "view": view()] + case "session.own_block": + let ids = payload["block_ids"] as? [String] ?? [] + server.lock.withLock { server.block = ids.first } + result = ["blocks": ids.map { ["block_id": $0, "owner": server.clientID] }] + case "session.disown_block": + let ids = payload["block_ids"] as? [String] ?? [] + record += " " + ids.joined(separator: ",") + result = ["blocks": ids.map { ["block_id": $0] }] + case "session.view": + result = view() + case "com.superlogical.terminal.process": + let id = payload["block_id"] as? String ?? "" + result = ["foreground": ["cwd": "/work/\(id)"], "child": ["cwd": "/home"]] + case "com.superlogical.terminal.resize": + record += " \(args["columns"] as? Int ?? 0)x\(args["rows"] as? Int ?? 0)" + case "data.connect": + result = ["ticket": "AAECAwQFBgcICQoLDA0ODw", "expires_in_ms": 60_000] + case "com.superlogical.terminal.modes": + result = ["screen": server.screenKind] + case "com.superlogical.terminal.format": + result = ["content": server.screen] + case "com.superlogical.terminal.write": + let text = args["data"] as? String ?? "" + server.lock.withLock { + server.recordedWrites.append(text) + server.writeBlock = payload["block_id"] as? String + } + result = ["bytes_written": text.utf8.count] + default: + error = ["code": "method_not_found", "message": method, "status": 404] + } + server.lock.withLock { server.recordedCalls.append(record) } + var response: [String: Any] = ["type": "response", "id": id, "seq": 0] + if let error { response["error"] = error } else { response["payload"] = result } + send(response) + } + + private func view() -> [String: Any] { + guard server.hasTerminals else { return ["windows": [[String: Any]]()] } + func block(_ id: String) -> [String: Any] { + ["block_id": id, "label": "shell", "creator_name": RexWire.terminalCreator] + } + return [ + "active_window_id": "window:2", + "windows": [ + [ + "window_id": "window:1", "label": "one", + "focused_block_id": "block:other", + "layers": [["blocks": [block("block:other")]]], + ], + [ + "window_id": "window:2", "label": "two", + "focused_block_id": "block:front", + "layers": [["blocks": [block("block:side"), block("block:front")]]], + ], + ], + ] + } + + private func dataHello(_ bytes: Data) { + guard bytes.first == 0x01, bytes.count == 17 else { return } + if let reason = server.rejectReason { + feed.yield(FakeRexServer.frame(0x2, Data([0x82, reason]))) + feed.yield(FakeRexServer.frame( + 0x8, Data([0x03, 0xF0]) + Data("data handshake rejected".utf8))) + feed.finish() + return + } + var welcome = [UInt8](repeating: 0, count: 32) + welcome[0] = 0x81 + for index in 0..<8 { + welcome[24 + index] = UInt8((server.nonce >> (8 * UInt64(index))) & 0xFF) + } + feed.yield(FakeRexServer.frame(0x2, Data(welcome))) + // A snapshot the emulator must never see, the `resize` that ends + // it, and whatever the program printed straight away. + let marker = "\u{1B}_rex1;\(server.nonce);" + let resize = #"{"type":"resize","cols":100,"rows":30,"owner":"client:me"}"# + feed.yield(FakeRexServer.frame( + 0x2, + Data("GHOSTSNP\u{1}\u{0}binary snapshot".utf8) + + Data((marker + resize + "\u{1B}\\").utf8) + + Data(server.earlyOutput.utf8))) + } + + private func send(_ object: [String: Any]) { + feed.yield(FakeRexServer.frame(0x1, FakeRexServer.json(object))) + } + } +} diff --git a/MultiplexTests/RexWireTests.swift b/MultiplexTests/RexWireTests.swift new file mode 100644 index 00000000..eed01e6e --- /dev/null +++ b/MultiplexTests/RexWireTests.swift @@ -0,0 +1,490 @@ +import XCTest +@testable import Multiplex + +/// Anchors `Bundle(for:)` fixture loading, the BindProtocolTests pattern. +private final class RexWireFixtureAnchor {} + +/// The pure half of attaching a Rex terminal: the WebSocket codec, the +/// control and data messages, and the terminal stream. The stream fixture is +/// 2322 bytes recorded off a live data connection (Rex 0.1.0-preview.19, +/// nonce 4078407816757279798): a 1962-byte Ghostty snapshot, a `resize`, +/// `tick 82`, a second `resize`, then three more lines. +final class RexWireTests: XCTestCase { + private let nonce: UInt64 = 4_078_407_816_757_279_798 + + private func streamFixture() throws -> Data { + let url = try XCTUnwrap( + Bundle(for: RexWireFixtureAnchor.self) + .url(forResource: "rex-terminal-stream-preview19", withExtension: "bin")) + return try Data(contentsOf: url) + } + + private func marked(_ json: String, nonce: UInt64? = nil) -> Data { + Data("\u{1B}_rex1;\(nonce ?? self.nonce);\(json)\u{1B}\\".utf8) + } + + // MARK: - WebSocket handshake + + func testTheUpgradeRequestAsksForTheSubprotocol() { + let request = String( + decoding: WebSocketCodec.upgradeRequest( + path: "/api/control", host: "rex", + subprotocol: "rex.control.v1", key: "dGhlIHNhbXBsZSBub25jZQ=="), + as: UTF8.self) + XCTAssertTrue(request.hasPrefix("GET /api/control HTTP/1.1\r\nHost: rex\r\n")) + XCTAssertTrue(request.contains("Sec-WebSocket-Protocol: rex.control.v1\r\n")) + XCTAssertTrue(request.contains("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n")) + XCTAssertTrue(request.hasSuffix("\r\n\r\n")) + // No extension is offered, so no frame may ever set a reserved bit. + XCTAssertFalse(request.contains("Sec-WebSocket-Extensions")) + } + + func testTheAcceptValueIsTheRFCsOwnExample() { + // RFC 6455 §1.3. + XCTAssertEqual( + WebSocketCodec.acceptValue(forKey: "dGhlIHNhbXBsZSBub25jZQ=="), + "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") + } + + private func upgradeResponse( + accept: String = "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", + subprotocol: String = "rex.control.v1" + ) -> String { + """ + HTTP/1.1 101 Switching Protocols\r + Connection: Upgrade\r + Sec-Websocket-Accept: \(accept)\r + Sec-Websocket-Protocol: \(subprotocol)\r + Upgrade: websocket\r + \r + + """ + } + + func testAnUpgradeIsReadAcrossChunksAndKeepsWhatFollows() throws { + let key = "dGhlIHNhbXBsZSBub25jZQ==" + let response = Data(upgradeResponse().utf8) + Data([0x81, 0x02, 0x68, 0x69]) + // Header names are case-insensitive: the server spells `Websocket`. + XCTAssertEqual( + try WebSocketCodec.readUpgradeResponse( + response.prefix(40), key: key, subprotocol: "rex.control.v1"), + .incomplete) + XCTAssertEqual( + try WebSocketCodec.readUpgradeResponse( + response, key: key, subprotocol: "rex.control.v1"), + .upgraded(remainder: Data([0x81, 0x02, 0x68, 0x69]))) + } + + func testAnUpgradeThatIsNotOursIsRefused() { + let key = "dGhlIHNhbXBsZSBub25jZQ==" + func read(_ text: String) throws -> WebSocketCodec.UpgradeReading { + try WebSocketCodec.readUpgradeResponse( + Data(text.utf8), key: key, subprotocol: "rex.control.v1") + } + XCTAssertThrowsError(try read(upgradeResponse(accept: "bm90IHRoZSBhbnN3ZXI="))) + XCTAssertThrowsError(try read(upgradeResponse(subprotocol: "rex.data.terminal.v1"))) + // What the server really answers a request with no upgrade headers. + XCTAssertThrowsError(try read( + "HTTP/1.1 426 Upgrade Required\r\nUpgrade: websocket\r\n\r\nWebSocket protocol violation" + )) { error in + XCTAssertEqual( + error as? WebSocketCodec.Failure, + .upgradeRefused(status: 426, body: "WebSocket protocol violation")) + } + XCTAssertThrowsError(try read("garbage\r\n\r\n")) + } + + // MARK: - WebSocket frames + + func testAClientFrameIsMaskedAndRoundTrips() throws { + let frame = WebSocketCodec.frame( + .text, payload: Data("Hello".utf8), maskKey: [0x37, 0xFA, 0x21, 0x3D]) + // RFC 6455 §5.7's masked "Hello". + XCTAssertEqual( + [UInt8](frame), + [0x81, 0x85, 0x37, 0xFA, 0x21, 0x3D, 0x7F, 0x9F, 0x4D, 0x51, 0x58]) + var decoder = WebSocketCodec.Decoder() + decoder.append(frame) + XCTAssertEqual(try decoder.next(), .text(Data("Hello".utf8))) + XCTAssertNil(try decoder.next()) + } + + func testLongPayloadsUseTheExtendedLengths() throws { + for size in [125, 126, 65_535, 65_536, 70_000] { + let payload = Data((0.. WebSocketCodec.Message? { + var decoder = WebSocketCodec.Decoder() + decoder.append(Data(bytes)) + return try decoder.next() + } + // A reserved bit (a compressed frame) with no extension negotiated. + XCTAssertThrowsError(try decode([0xC1, 0x01, 0x00])) + XCTAssertThrowsError(try decode([0x83, 0x00])) // unknown opcode + XCTAssertThrowsError(try decode([0x80, 0x01, 0x00])) // stray continuation + XCTAssertThrowsError(try decode([0x09, 0x00])) // fragmented ping + // A length this client refuses to buffer. + XCTAssertThrowsError(try decode([0x82, 0x7F, 0, 0, 0, 0, 0x40, 0, 0, 0])) + } + + // MARK: - Control messages + + func testTheHelloPinsTheRevisionAndStaysSmall() throws { + let hello = RexWire.hello(clientVersion: "1.5.2") + // The protocol caps a hello at 512 bytes. + XCTAssertLessThan(hello.count, 512) + let object = try XCTUnwrap( + JSONSerialization.jsonObject(with: hello) as? [String: Any]) + XCTAssertEqual(object["type"] as? String, "hello") + XCTAssertEqual(object["api_revision"] as? Int, 14) + // Never `app`: Rex aims client actions at "the one app client". + XCTAssertEqual((object["client"] as? [String: Any])?["kind"] as? String, "other") + } + + func testARequestIsByteStableAndABlockCallNestsItsArguments() { + XCTAssertEqual( + String(decoding: RexWire.request(id: "7", method: "session.list", payload: nil), + as: UTF8.self), + #"{"id":"7","method":"session.list","type":"request"}"#) + let write = RexWire.request( + id: "8", method: "com.superlogical.terminal.write", + payload: RexWire.blockPayload( + sessionID: "session:s", blockID: "block:b", args: ["data": "ls\u{1B}[A\r"])) + // The escape reaches the wire as a JSON escape, never a raw control. + XCTAssertEqual( + String(decoding: write, as: UTF8.self), + #"{"id":"8","method":"com.superlogical.terminal.write","# + + #""payload":{"args":{"data":"ls\u001b[A\r"},"block_id":"block:b","# + + #""session_id":"session:s"},"type":"request"}"#) + } + + func testInboundMessagesDecodeToWhatTheSessionActsOn() throws { + func decode(_ text: String) -> RexWire.Inbound? { + RexWire.decodeInbound(Data(text.utf8)) + } + // Verbatim from a live server. + guard case .welcome(let clientID)? = decode(""" + {"type":"welcome","protocol":"rex.control.v1","limits":{"max_message_bytes":1048576},\ + "client":{"id":"client:01a1e1d4-754f","reconnect_token":"CARtI14i"},\ + "api_revision":14,"api_server_revision":14} + """) + else { return XCTFail("welcome") } + XCTAssertEqual(clientID, "client:01a1e1d4-754f") + // A welcome for some other protocol is not a welcome. + XCTAssertNil(decode(#"{"type":"welcome","protocol":"rex.control.v2"}"#)) + + guard case .response(let id, .success(let payload))? = decode( + #"{"type":"response","id":"p2","seq":1,"payload":{"ticket":"2hsxxmMxRjpddNEsnIIRXA"}}"#) + else { return XCTFail("response") } + XCTAssertEqual(id, "p2") + XCTAssertEqual(payload["ticket"] as? String, "2hsxxmMxRjpddNEsnIIRXA") + + guard case .response(_, .failure(let error))? = decode(""" + {"type":"response","id":"2","seq":0,\ + "error":{"code":"not_found","message":"block not found","status":404}} + """) + else { return XCTFail("error response") } + XCTAssertEqual( + error, RexWire.ServerError(code: "not_found", message: "block not found", status: 404)) + + // A session event arrives doubly wrapped; the block's own event is + // what matters. + guard case .event(let type, let fields)? = decode(""" + {"type":"event","seq":3,"payload":{"type":"session_event","payload":{\ + "session_id":"session:s","event":{"type":"block_closed",\ + "payload":{"block_id":"block:b"}}}}} + """) + else { return XCTFail("event") } + XCTAssertEqual(type, "block_closed") + XCTAssertEqual(fields["block_id"] as? String, "block:b") + + // A type a newer server added is skipped, not an error. + guard case .unknown? = decode(#"{"type":"notice","text":"hi"}"#) + else { return XCTFail("unknown type") } + XCTAssertNil(decode("not json")) + } + + // MARK: - Choosing the block + + /// A `session.view` in the server's own shape: two windows, the second + /// active, with a non-terminal block among its blocks. + private func view() throws -> [String: Any] { + let json = """ + {"active_window_id":"window:2","windows":[ + {"window_id":"window:1","label":"editor","focused_block_id":"block:a","layers":[ + {"blocks":[ + {"block_id":"block:a","label":"shell","creator_name":"com.superlogical.terminal"}, + {"block_id":"block:b","label":"logs","creator_name":"com.superlogical.terminal"} + ]}]}, + {"window_id":"window:2","label":"","focused_block_id":"block:d","layers":[ + {"blocks":[ + {"block_id":"block:t","label":"tunnel","creator_name":"com.superlogical.tunnel"}, + {"block_id":"block:c","label":"agent","creator_name":"com.superlogical.terminal"}, + {"block_id":"block:d","label":"repl","creator_name":"com.superlogical.terminal"} + ]}]} + ]} + """ + return try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]) + } + + func testOnlyTerminalBlocksAreAttachableAndTheFrontedOneWins() throws { + let blocks = RexWire.terminalBlocks(inView: try view()) + // A tunnel block is not a terminal. + XCTAssertEqual(blocks.map(\.id), ["block:a", "block:b", "block:c", "block:d"]) + XCTAssertEqual(RexWire.attachTarget(in: blocks, preferring: nil)?.id, "block:d") + // A named block is honored while it exists… + XCTAssertEqual(RexWire.attachTarget(in: blocks, preferring: "block:b")?.id, "block:b") + // …and falls back to the fronted one once it is gone. + XCTAssertEqual(RexWire.attachTarget(in: blocks, preferring: "block:gone")?.id, "block:d") + XCTAssertNil(RexWire.attachTarget(in: [], preferring: nil)) + XCTAssertNil(RexWire.attachTarget( + in: RexWire.terminalBlocks(inView: [:]), preferring: nil)) + } + + func testSwitchTerminalRowsNameEachTerminalAndMarkTheOneOnShow() throws { + let blocks = RexWire.terminalBlocks(inView: try view()) + let choices = RexWire.terminalChoices(in: blocks, showing: "block:c") + XCTAssertEqual(choices.map(\.tmuxID), ["block:a", "block:b", "block:c", "block:d"]) + // A named window leads its terminals; an unnamed one is `window N`. + XCTAssertEqual( + choices.map(\.name), + ["editor — shell", "editor — logs", "window 2 — agent", "window 2 — repl"]) + XCTAssertEqual(choices.map(\.isActive), [false, false, true, false]) + XCTAssertEqual(choices.map(\.index), [1, 2, 3, 4]) + + // Rex's generated `Window ` label is not a name, and a + // terminal that only repeats its window adds nothing. + let generated = RexWire.terminalChoices( + in: [ + RexWire.Block( + id: "block:x", label: "", windowID: "window:0000-11112222", + windowLabel: "Window 11112222", windowPosition: 3, + isFocused: true, isFronted: true), + RexWire.Block( + id: "block:y", label: "Logs", windowID: "window:w", + windowLabel: "logs", windowPosition: 4, + isFocused: true, isFronted: false), + ], + showing: nil) + XCTAssertEqual(generated.map(\.name), ["window 3", "logs"]) + XCTAssertEqual(generated.map(\.isActive), [false, false]) + } + + func testTheWorkingDirectoryIsTheForegroundProcesssThenTheChilds() throws { + func directory(_ json: String) throws -> String? { + RexWire.workingDirectory(inProcess: try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])) + } + // Verbatim shape from a live server: an agent running in a shell. + XCTAssertEqual( + try directory(""" + {"last_exit":null,"child":{"pid":1,"name":"zsh","cwd":"/Users/dev"},\ + "foreground":{"pid":2,"name":"claude","cwd":"/Users/dev/src/api"},"home":"/Users/dev"} + """), + "/Users/dev/src/api") + XCTAssertEqual( + try directory(#"{"child":{"cwd":"/srv/app"},"foreground":null}"#), "/srv/app") + // Only a clean absolute path may be spliced into a shell line. + XCTAssertEqual( + try directory(#"{"foreground":{"cwd":"relative"},"child":{"cwd":"/ok"}}"#), "/ok") + XCTAssertNil(try directory(#"{"foreground":{"cwd":"/tmp/a\nb"}}"#)) + XCTAssertNil(try directory(#"{"last_exit":{"exit_code":0}}"#)) + } + + // MARK: - Data handshake + + func testTheHelloCarriesTheTicketsSixteenBytes() throws { + // base64url WITHOUT padding, as `data.connect` returns it. + let hello = try XCTUnwrap(RexWire.dataHello(ticket: "AAECAwQFBgcICQoLDA0ODw")) + XCTAssertEqual([UInt8](hello), [0x01] + (0..<16).map { UInt8($0) }) + // `-` and `_` are the URL alphabet. + XCTAssertNotNil(RexWire.dataHello(ticket: "-_-_-_-_-_-_-_-_-_-_-w")) + XCTAssertNil(RexWire.dataHello(ticket: "AAEC")) + XCTAssertNil(RexWire.dataHello(ticket: "not a ticket!")) + } + + func testAWelcomeYieldsItsLittleEndianNonce() { + var welcome = [UInt8](repeating: 0, count: 32) + welcome[0] = 0x81 + welcome[24...] = [0x76, 0xD3, 0x53, 0x6C, 0x2B, 0x74, 0x99, 0x38] + XCTAssertEqual( + RexWire.parseDataReply(Data(welcome)), .welcome(nonce: 0x3899_742B_6C53_D376)) + XCTAssertEqual(RexWire.parseDataReply(Data([0x82, 0x07])), .reject(reason: 7)) + // A welcome is exactly 32 bytes, and its nonce is never zero. + XCTAssertNil(RexWire.parseDataReply(Data(welcome.prefix(31)))) + XCTAssertNil(RexWire.parseDataReply(Data([0x81] + [UInt8](repeating: 0, count: 31)))) + XCTAssertNil(RexWire.parseDataReply(Data())) + } + + // MARK: - Terminal stream + + private func expectedEvents() -> [RexTerminalStream.Event] { + [ + .resize(cols: 80, rows: 24, owner: "client:01a1e1d4-7523-774b-917e-3547350b855e"), + .output(Data("tick 82\r\n".utf8)), + .resize(cols: 100, rows: 30, owner: "client:01a1e1d5-b2e0-75d4-ac80-8bf2099a6c09"), + .output(Data("tick 83\r\ntyped-by-probe\r\ntick 84\r\n".utf8)), + ] + } + + func testTheGhosttySnapshotIsDroppedAndOutputFollowsTheMessages() throws { + let fixture = try streamFixture() + XCTAssertEqual(String(decoding: fixture.prefix(8), as: UTF8.self), "GHOSTSNP") + var stream = RexTerminalStream(nonce: nonce) + XCTAssertFalse(stream.isLive) + XCTAssertEqual(stream.consume(fixture), expectedEvents()) + XCTAssertTrue(stream.isLive) + } + + func testTheStreamSurvivesAnyChunking() throws { + let fixture = try streamFixture() + for size in [1, 2, 7, 64, 1961, 1962, 1963, 2000] { + var stream = RexTerminalStream(nonce: nonce) + var events: [RexTerminalStream.Event] = [] + var offset = 0 + while offset < fixture.count { + let end = min(offset + size, fixture.count) + events += stream.consume(fixture.subdata(in: offset.. Bool { + var watch = AlternateScreenExitWatch() + return watch.sawExit(in: Data(text.utf8)) + } + XCTAssertTrue(saw("\u{1B}[?1049l")) + XCTAssertTrue(saw("bye\u{1B}[?1047l\r\n$ ")) + XCTAssertTrue(saw("\u{1B}[?47l")) + // One sequence may reset several modes. + XCTAssertTrue(saw("\u{1B}[?1;1049;2004l")) + // Entering it, other modes, and look-alikes are not an exit. + XCTAssertFalse(saw("\u{1B}[?1049h")) + XCTAssertFalse(saw("\u{1B}[?2004l\u{1B}[?25l")) + XCTAssertFalse(saw("\u{1B}[1049l")) + XCTAssertFalse(saw("plain text 1049l")) + XCTAssertFalse(saw("\u{1B}[?10490l")) + } + + func testAnExitSplitAcrossChunksIsStillNoticed() { + let sequence = Data("x\u{1B}[?1049ly".utf8) + for split in 1..' | `.** sshd runs exec requests through the account's login shell, and fish (exit @@ -271,6 +271,324 @@ HerdrProbe, session creation/targeting, or file attach/drop. so the new tab lands on screen, never where nobody is attached; an in-session create that fails alerts ("Couldn't Create Tab"), never a fallback mint. +- **Rex is shown, attached, and minted — never a host's default** + (`Host.SessionBackend.rex`; + `RexProbe` for the deck and the mint, `RexSession` for a tab; Rex 0.1.0-preview.19 / + API revision 14, measured 2026-11-16 against a throwaway server), + adapted as session→tile, window (a tab)→window, terminal block→pane. + - **Rex has no terminal client, so Multiplex is one.** No `rex attach` + exists and `rex block stream` answers `not implemented`: Rex sessions + are drawn by a native app over the server's WebSocket API + (`/api/control` `rex.control.v1` JSON; `/api/data` + `rex.data.terminal.v1` binary). A Rex tab therefore has no remote + command at all — it is the third `TerminalTransport`, beside the SSH + PTY and mosh. ⚠ The wire spec is NOT in the website docs — the server + serves its own (`GET /llms.txt` and `/api/help` on its socket; `rex api + list --json`). + - **`canBeDefault` is the one switch, and the record enforces it.** + ⚠ **Multiplex never starts a Rex server**, so a Rex session can be + created only while one is running. The default backend answers every + request that names no backend (New Session, the Signal check, external + actions) and must answer on an idle host — tmux and herdr bring their + server up with the first session — so Rex is never the primary: + `Host.sessionBackend`'s `didSet`, `init(from:)`, and `BackendSelection` + all demote it to a secondary, and the surfaces that choose a host's + DEFAULT leave it out (Host Settings' "New sessions run on", Add Host ▸ + BIND, the FAQ install bar — `defaultCases` / `defaultChoices`). + Everything else treats it as a backend like the others: the New Session + "Runs on" bar and the widget/Shortcut backend pick list offer it + (`monitoredBackends`), a Rex tab's `+ TAB` mints a Rex sibling, and + `multiplex://…&action=agent&backend=rex` mints on it. One gap: an + external `in=tab` launch aimed at a Rex session resolves to nothing and + mints fresh instead (`launchInSession` opens no window inside a Rex + session). What would change the rule is a decision to autostart, which + needs the unmeasured fact below. + ⚠ In that `didSet`, restore the primary BEFORE inserting the secondary: + `secondaryBackends`' own observer strips whatever the primary is at + that moment, and stripped the newcomer straight back out (caught by + `testRexIsNeverTheHostsPrimary`). + - **The mint is one exec** (`RexProbe.mintCommand` → `HostConnectionModel + .createRexSession`): `rex do -e --args --json` creates a + session holding one shell terminal (`session.create` with + `initial_windows`) and prints its id and stored label; the route is + `.rexAttach(name, id)`. + - **No autostart, by choice, not by measurement.** `rex new` would + start a server; the mint refuses and says so ("No Rex server is + running on …, and Multiplex doesn't start one" — + `SessionCreateFailure.serverNotRunning`). A server started from an + SSH login would be the one the host's Rex app then adopts, and how it + differs from one the app starts in the desktop session (keychain, + pasteboard, lifetime under systemd) was NOT measured. Do not flip + this without measuring it on a Mac and on Linux. + - ⚠ **What the user typed travels as `--args` JSON, never as script + text or `KEY=VALUE`.** Pairs are typed by spelling — `label=1e3` + arrived as the number 1000 — and anything spliced into the Lua would + be code. The script is a constant. + - **The script settles the label against the live list** (`api` taken → + `api-2`, compared without case, tmux's scheme): Rex itself creates a + second `api` without complaint, and both would then be shown with an + id tail (`sessionNames`) — the fresh tab's name would not match its + own tile. The label is cleaned the way a probed one is read + (`sessionLabel`), never empty (an empty one makes the server invent + `quiet-meadow`), and the stored label is read back after the create. + - **Setup script and launch line ride `initial_input`**, each followed + by a carriage return (Enter): the server types them into the fresh + shell before any client attaches — tmux's ordering, with nothing to + poll for. (This is what the earlier "Rex's model does not take a + setup script in one step" note got wrong.) + - ⚠ **`cwd` is taken literally.** `~` is not expanded and a directory + that does not exist silently starts in $HOME. So the exec's SHELL + resolves the Working Directory (`cd` + `pwd`, absolute or empty) and + hands it over in `MULTIPLEX_REX_CWD` — the Lua runs in the CLI + process, so `os.getenv` reads the exec's environment. A `+ TAB` + sibling starts where the source session's fronted terminal is + (`foreground.cwd`), which wins over an explicit directory; every miss + is $HOME. The tmux conf rider does not apply. + - **A backend set encodes sorted** (`KeyedEncodingContainer` overload in + `Host.swift`). With three backends `secondaryBackends` can hold two, + and `Set` iteration order is seeded per process — unsorted, every + launch rewrote `hosts.json` and the mirrored Keychain record. + - **The probe is one exec, one connection: `rex do -e --json`.** A + script is the only way to make many API calls on a single control + connection and get one document back — sessions, layouts, titles, + foreground processes, reported statuses, the fronted screen. Measured + 30 ms and 3 KB for three sessions (10 KB when a fronted block has deep + scrollback), which is tmux's weight, so `HostGuide.secondBackendCost` + holds. + - `session.view` and every block method answer `conflict` until the + connection is attached. **The probe uses `session.attach_all`, never + `session.attach`**: it does not join a session, so the probe is not + listed among its clients and no `client_connected` event fires every + five seconds. (A tab DOES join — `data.connect` and `own_block` + require it.) + - ⚠ **Every invocation carries `REX_AUTOSTART=0`** (`RexProbe + .rexCommand`; the bridge exports it). The CLI starts a personal + server when none is running; a probe, rider, or attach that did so + would leave a server on every host that merely has the binary. With + it off, no server exits 4 (the CLI's documented "unreachable") → + `.noServer`; any other nonzero exit is a failure that names the + status. The env switch, not `--autostart=false`, so a build predating + the flag still answers. + - `--json` is pretty-printed even when piped, and an empty Lua table + encodes as `{}` not `[]` (`LuaArray`). The exit line is the last the + command prints; JSON above it is indented and quoted, so a screen + cannot start a line with the marker. + - **The tail is read from the END, uncapped.** `format` returns screen + AND scrollback oldest-first, and its `max_bytes` counts JSON-encoded + bytes: a capped read of "the last 6144 bytes" stopped three lines + short on multibyte output. So `format(max_bytes: 1)` for the id and + total, then `blob_read(offset: total - 6144)` with no cap; a read + that started mid-screen drops its partial first line. + - **A label is not an identity.** Two sessions may share one and an + unnamed session gets a generated one (`floral-river`). The id + (`session:`) rides `TmuxSession.tmuxID` and is the only attach + and kill target — `rex kill work` with two `work`s refuses both + (exit 3), and `Mode.attach` is nil for a Rex record with no usable id. + Displayed names are made unique by `RexProbe.sessionNames`: a shared or + empty label is spelled with the id's tail (`work …8d7863`, the CLI's + own short form), for EVERY holder of the label — keeping the bare name + on the oldest would hand that name and its attention baseline to a + different session the day the oldest closes, and announce a turn that + never ended. An unnamed window's generated `Window ` label + gives way to its focused block's label (`shell`, `agent`) — Rex's + nearest analog of tmux naming a window after what runs in it — and to + `window N` only when that is empty too: the spine already leads with + N, and the first headless run read `1 WINDOW 1`. Only the exact + generated shape is replaced. A session whose programs all exited stays + listed with no windows (`0 WIN`, no spine) until someone closes it. + - **`rex` is not on an SSH exec's PATH on a Mac.** Rex adds it only for + terminals it opens itself. `RemoteCommandEnvironment.rexPathPrefix` + names the server copy the app installs (`~/Library/Application + Support/com.superlogical.rex/RexServer/Versions/Current/…`, which + leads because it does not depend on the bundle's name or location) and + the helper inside the app bundle; Linux/FreeBSD packages land in + `/usr/bin` and the unprivileged install in `~/.local/bin`. + - **Attention: reported status first, the tmux heuristics otherwise.** + Programs report idle / working / done / blocked / error through OSC + 7501, kept per block (`program_status`). Where any block reports, the + fold across EVERY block is the authority (blocked → NEEDS YOU with the + reported kind, `auth` read as a question; working → busy; `done` and + `error` → idle, the busy → idle edge that announces a turn once). Where + nothing reports, the fronted block is classified from its title and + screen exactly as a tmux tile is — and the tile's own background-pane + title pass applies too. Alert metadata borrows the fronted block's + agent and screen only when that block's records produced the verdict. + - The LIVE lamp is attached APP clients (`client.list` scoped to the + session, `kinds: ["app"]` — a Rex window showing it) OR this app's own + open tab. ⚠ **Multiplex says hello as kind `other`, never `app`** + (`RexWire.hello`): Rex's CLI and agent skill aim client actions (`rex + do pane.split`) at "the app client when exactly one is connected", and + a second self-declared app made every one of them ambiguous for as + long as a tab was attached. + - Discovery rides every primary probe (`rex ls -q`, one id per line) and + offers `+ REX · N` on the rail like herdr. The tile takes a cool-blue + wash at `bezel`'s lightness (`TallyPalette.rexBezel` — Rex publishes no + palette, so the hue is chosen to differ from herdr's mauve). Its menu + has no Copy Command for Handoff (no command opens a Rex session in a + host shell) and, on a session with more than one terminal, an **Open + Terminal** submenu. + - **A tab is ONE terminal block.** Rex's window is a split tree the + client draws; Multiplex does not draw it. A tile press attaches the + block the session is fronting (active window, focused block — + `RexWire.attachTarget`, decided at attach time); Open Terminal names + one (`.rexAttach(…, block:)`, label `session · window`), and a named + block that has since closed falls back to the fronted one. Tab + identity stays `(rex, session name)`, so the deck finds either kind. + - **The REX key's panel switches the tab's terminal** (`ShortcutPanel + Content.rex`; rows from `RexWire.terminalChoices`, `window — terminal` + in window order, the shown one marked ACTIVE). Rex has no prefix keys + to list, so the panel is the one thing a Rex tab needs it for: reaching + the session's other terminals without leaving the tab. + `RexSession.switchBlock` takes the new block, opens its stream, redraws + from `format`, then `disown_block`s the old one — which hands that + terminal's size back to the Rex app instead of leaving it at this + tab's. Each data stream carries a generation (`dataGeneration`): the + old stream's end must not read as the tab ending, and input typed + during the switch is dropped rather than sent to whichever block wins. + The choice survives a reconnect (`rexBlockOverride`). The rail key's + face comes from `SessionBackend.shortcutKeyCaption` — the three + `herdr ? "HRDR" : "TMUX"` sites it replaced drew a TMUX key on a Rex + tab. + - **A Rex tab has a working directory**: `com.superlogical.terminal + .process` → `foreground.cwd`, else the shell's (`RexWire + .workingDirectory`, asked over the tab's own control connection). FILE + drops land there and the file viewer opens there, as on tmux. (Unit + tested; not yet driven end to end.) + - **The link is two byte pipes on the tab's own SSH connection** + (`SSHConnection.openPipe`), each running `rex __internal dial-stdio` — + the stdin/stdout ↔ socket bridge Rex's own `ssh://` transport runs + remotely, which is why it finds the server unaided. ⚠ It is hidden + and unversioned; a rename surfaces as the CLI's "unknown command" on + the tab's ended line. (OpenSSH socket forwarding would be the + documented road; the vendored swift-nio-ssh has only `directTCPIP`.) + - **A pipe is a SHELL channel with no PTY, not an exec.** Citadel + 0.12.0's exec returns output only and keeps the channel, so nothing + can write stdin; its `withTTY` opens a login shell on plain pipes + (no line discipline — binary-safe), handed over with the PTY + handoff's own cross-shell `exec sh -c '…'` line. + - ⚠ **Nothing is written until the per-pipe marker comes back.** The + command echoes one first: it drops whatever a login script printed, + and it proves the `exec` happened — a shell reading its script from + a pipe may read ahead, and bytes sent early would be eaten as shell + input. A channel that ends before or after it throws the head of + the command's stderr, which is how "no Rex server is running" and + "rex: command not found" reach the tab. Verified against zsh and + sh; fish as a login shell is unverified. + - **`WebSocketCodec` + `RexWire` are the whole protocol, pure.** No + extension is offered (a data connection is never compressed, and the + control connection works without), revision 14 is pinned in the hello + (a newer server translates down to it), pings are answered in + `RexSocket`, and requests are matched by id with a 10 s timeout. + - **Attach order is load-bearing** (`RexSession.attach`): hello → + `session.attach` → **`own_block(take)` + `resize` first** → `data + .connect` → data HELLO/WELCOME → wait for the first server message → + `modes` + `format(vt)` → RIS + rendering → flush the held stream. + - ⚠ **The stream opens with a Ghostty binary snapshot + (`GHOSTSNP…`) SwiftTerm cannot read.** `RexTerminalStream` DROPS + it: its length is stated nowhere, but a `resize` message "comes + right after the snapshot", so everything before the first `ESC _ + rex1;;` is snapshot (the nonce is 64 random bits per stream, + which is what makes scanning binary for it sound; the same nonce is + why a program printing a look-alike is drawn as output). The screen + comes from `format`'s `vt` rendering instead — colors, cursor, + modes, scrollback, verified on a shell and on vim. + - Claim-and-size precedes both so the rendering and the stream + describe the terminal at THIS tab's size. + - **The two are not atomic and the gap errs toward repeating.** The + stream is opened first and held while `format` is fetched; output in + between is drawn twice rather than lost (lost bytes can leave a mode + wrong for the session; a repeated line is one line). An idle prompt + — the common attach — has nothing in the window. + - `extra_palette` is NOT requested (it repaints the tab in Rex's + theme); cursor, modes, scrolling region, style, charsets, keyboard, + kitty keyboard, and tab stops are. + - A rendering over 3 MB (a terminal keeps up to 64 MiB) is not + fetched: the attach draws a plain-text tail instead. + - ⚠ **Attached during a full-screen program, the tab redraws when it + exits.** While one is up `format` renders ONLY its screen — the shell + history underneath cannot be asked for — so the emulator's primary + screen starts empty, and quitting vim showed a bare prompt. + `AlternateScreenExitWatch` notices `CSI ? 1049/1047/47 l` and the + screen is fetched again. It waits for the terminal to go quiet first + (120 ms, capped at 800 ms): a shell prints its prompt within + milliseconds of the exit, and a rendering fetched during that burst + drew it twice (`$ $`). + - **Typing is `com.superlogical.terminal.write`, one call in flight.** + The server runs block methods concurrently, so two calls could land + out of order; whatever is typed meanwhile rides the next call as one + string. Its argument is JSON text, so `RexInputEncoder` holds a + split multi-byte character and replaces bytes that are not UTF-8. + - **The last client to type owns the size** (tmux's latest-client + rule): the Rex app can claim the block back (`block_owner_changed`); + the next keystroke here claims and re-sizes it. Until then the tab + shows another client's size — Multiplex does not letterbox. + - ⚠ **Say goodbye before cancelling the readers** (`teardown`). + Cancelling a reader tears its pipe down, and a connection that just + drops is kept by the server for 60 s — its client listed "connection + lost", its stream parked for a resume. The data connection closes + first with status 1000 (ends the stream), then the control connection + (ends the client at once). A data close of 4000 (`block closed`) or + 1000 is a clean end, like a shell exiting; resume is a fresh attach, + never the protocol's RESUME. + - **A link that breaks ends the tab like any transport's**, and + `SessionResumePolicy` treats it the same: suspension damage re-attaches + by itself when the app returns (verified on the iPad simulator — + backgrounded, both SSH connections killed, returned: a new client, + LIVE, output flowing); a drop in the foreground parks on RECONNECT. The + ended line says "The connection to the Rex server was lost." — a + broken pipe's own error under a LIVE tab is the transport's shorthand + (`Already closed` on the first headless run), which read as a second, + unrelated failure. During the attach the detail IS the reason and is + kept. The server lists the dropped client as "connection lost" for its + 60 s resume window; the fresh attach is a new client beside it. + - What a Rex tab does not have: a prefix-key list (the REX panel only + switches terminals), Copy Mode, HISTORY, the one-second helper-chip + probe (`detectActiveAgent` answers nil; the wall probe's record still + does), and mosh (no PTY for mosh-server to run — a Rex tab rides SSH + whatever the host prefers). + - Deliberately NOT built, with the reason each would need new facts to + reopen: + - **Drawing a window's splits.** Every terminal in a split needs its + own data stream — its own SSH channel and `dial-stdio` process, so + sshd's `MaxSessions` (10) caps a window near nine — and its own + emulator, and the terminal window assumes exactly one per tab + (`TerminalFocusArbiter`, the key rail, Copy Mode, the viewers, + keyboard avoidance). It would also claim the size of EVERY block in + the window from the Rex app at once. tmux and herdr tabs are not + drawn natively either — their multiplexer draws its own panes — so + this would be a layout engine for one backend. The app's own shape + already covers it: Switch Terminal inside a tab, Open Terminal for a + second tab or window. + - **The stream's RESUME.** A fresh attach restores screen, scrollback + and modes from `format`; RESUME would save one rendering fetch and + add a replay-window state machine. + - **Starting a Rex server**, and with it Rex as a default backend (see + the mint above). + - **A new window inside an existing Rex session** (`launchInSession`): + an external `in=tab` launch mints a fresh session instead. + - Polling `format` as a fake terminal was rejected outright. + - Headless: seed key `secondaryBackends: ["rex"]`, then + `MULTIPLEX_AUTO_ACTION_URL='multiplex://open?host=devbox&action=shell&session=&backend=rex'` + attaches (the `AUTO_ATTACH` env resolves names on the primary only). + Proof host-side: two `shell` sessions on one connection in the sshd + log, `rex client ls --all` listing `Multiplex … other`, `terminal + .size` naming it the owner; `debug.talkbacktype` + `debug + .talkbacksend` prove input, `rex send` proves output. + `MULTIPLEX_AUTO_REX_SWITCH=` presses row n of the REX panel once the + tab is live; `debug.tmuxshortcuts` opens the panel itself. `debug + .newtab` from a Rex tab mints a sibling (`rex ls` gains `-2`, + its `process` cwd is the source's). A link drop: kill the tab's + `sshd-session` (the newer of the app's two connections in `lsof -iTCP: + `). "No server": point the wrapper below at a socket path nothing + listens on and open `…&action=agent&backend=rex` — the mint fails + before anything is typed. To run without + touching real sessions: a throwaway server (`rex server run --listen + unix:// --state-dir --restore=false --config `, the path under macOS's 104-byte socket limit) and a second + user-mode sshd whose `SetEnv PATH=` leads with a `rex` wrapper that + adds `-S unix://`. ⚠ `REX_SERVER` does not isolate: a + socket path that does not exist is skipped and the CLI falls through + to the local default server. - **tmux attach needs a PTY**: the shell opens with ECHO off and `exec tmux attach-session …` is injected as the first stdin line; detach = close the channel. oh-my-zsh's update check steals queued stdin, so diff --git a/docs/agents/e2e-headless.md b/docs/agents/e2e-headless.md index 905fd050..d275e8ba 100644 --- a/docs/agents/e2e-headless.md +++ b/docs/agents/e2e-headless.md @@ -26,7 +26,11 @@ app.multiplexterm.multiplex`): `workingDirs` / `sessionScripts` / `newSessionTmuxConf` / `agentLaunchModels` feed the picker/script/conf/model paths; `secondaryBackends: ["herdr"]` imports a MIXED host (two probes on one - connection, both backends' tiles); `passphrase` + connection, both backends' tiles; `["rex"]` adds the Rex probe — on a + Mac running Rex it reads, and a tab attaches, that Mac's REAL sessions, + so use a throwaway server per `backends-and-probe.md` when that + matters); + `passphrase` stores the key passphrase in the Keychain so an encrypted `privateKey` proves the sealed-key connect path (probe logs `Accepted publickey`, no prompt); `"enabled": false` proves the never-dials promise against a @@ -46,6 +50,11 @@ app.multiplexterm.multiplex`): through the real surrender/adopt path (moved tabs keep connections). - `MULTIPLEX_AUTO_DROP=` — drops that file into the first tab (SFTP upload + typed path, the real drag path). +- `MULTIPLEX_AUTO_REX_SWITCH=` — on a Rex tab, presses row n (1-based) + of the REX panel's Switch Terminal list once the tab is live — the + headless stand-in for a press nothing else can make. Proof host-side: + `terminal.size` names the tab the owner of the NEW block and no longer of + the old one. - `MULTIPLEX_AUTO_ACTION_URL=multiplex://open?…` — submits the URL through the exact `onOpenURL` → router seam once per process; the headless widget stand-in (simctl openurl's first-run confirmation can't be clicked diff --git a/docs/store-metadata.md b/docs/store-metadata.md index 62d03188..34f66c79 100644 --- a/docs/store-metadata.md +++ b/docs/store-metadata.md @@ -105,6 +105,21 @@ Free surface added 2026-08-02 (unreleased; ships with the next binary): | Honest limits | No herdr API reports attached-client count or creation time, so those claims are omitted. The Claude HISTORY panel stays hidden on herdr tabs (herdr exposes no transcript identity), and tmux Copy Mode stays tmux's own — herdr tabs instead carry the shared Select Text mode, their own HRDR shortcut panel, and the same FILE attach/drop. Widget/Shortcut shell attach and Open Agent both work — an agent launch mints a herdr session, or lands inside an existing one as a new tab in the focused workspace / a new workspace | | Tier / privacy | Free, like tmux. No new permission or collection: probes and attaches still travel directly over the user's SSH connection. This does not change the Pro allocation, StoreKit catalog, paywall, IAP screenshot, or public screenshot set | +## Rex sessions + +Free surface added 2026-11-16 (unreleased; ships with the next binary): + +| Item | Facts | +| --- | --- | +| What it is | Rex (superlogical.com/rex) sessions on a host appear on the deck as tiles beside its tmux / herdr ones, and a tile attaches a Rex terminal as a tab. Rex ships no terminal client, so Multiplex speaks Rex's own protocol over the user's SSH connection — no PTY, no extra port | +| Selection | Never assumed. The deck rail offers `+ REX` when the host is holding Rex sessions, and Host Settings ▸ Backends lists it as a checkable backend. It is never a host's DEFAULT backend (the app does not start a Rex server, so it cannot promise a new session on an idle host), and Add Host ▸ BIND does not offer it | +| Wall model | One tile per Rex **session**, its windows (tabs) on the window spine and its terminal blocks as panes. The miniature is the fronted block's screen. Programs that report status through OSC 7501 drive RUNNING / NEEDS YOU directly; others are read from their title and screen like a tmux tile. Tiles take their own tint on the host, and VoiceOver hears "on rex" | +| Attach/close | A tile press attaches the terminal the session is showing; the tile menu's **Open Terminal** opens any other terminal of the session as its own tab. One tab is one terminal — a window's split layout is not drawn; the tab's **REX** key lists the session's terminals and switches the tab to another. The screen, colors, cursor and scrollback are restored on attach, and a tab whose link was lost to suspension re-attaches when the app returns. Delete Session closes the session. Widgets, Shortcuts, `multiplex://` links and alert banners can open a Rex session | +| New sessions | The New Session sheet's "Runs on" bar, a Rex tab's `+ TAB`, and the widget / Shortcut / `multiplex://…&backend=rex` agent launch create a Rex session — one shell terminal, in the chosen working directory (a `+ TAB` sibling starts where the tab's session is), with the setup script and launch line typed as on tmux. Only while a Rex server is running on the host: otherwise the app says so and creates nothing. No launch lands INSIDE an existing Rex session (a named Rex target gets a fresh session instead) | +| Requirements | Rex with a running server on the SSH host (measured against 0.1.0-preview.19, API revision 14 — Rex is in beta, and the attach relies on a Rex CLI command Rex does not document). The app never starts a Rex server | +| Honest limits | Rex cannot be a host's default backend, and nothing is created while no Rex server is running. The last client to type decides the terminal's size, so a Rex window showing the same terminal resizes with the tab. A Rex tab has no prefix-key list, Copy Mode or HISTORY; mosh hosts attach Rex tabs over SSH. Very large scrollback (over about 3 MB rendered) attaches with a plain-text tail instead of the full history | +| Tier / privacy | Free, like the other backends; attention alerts stay Pro. No new permission or collection: the probe and the attach travel over the user's SSH connection. This does not change the Pro allocation, StoreKit catalog, paywall, IAP screenshot, or public screenshot set. The store listing copy does not mention Rex yet | + ## Widgets, Shortcuts, and the URL scheme Free surfaces added 2026-07-18 (unreleased; ships with the next binary): diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index 0ce638c0..37ee00a4 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -1,3 +1,16 @@ NEW SINCE 1.5.2 +• Deck and terminal: a host that runs Rex (superlogical.com/rex) can now show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. When the host is holding Rex sessions a + REX chip appears on its rail; press it to start showing them, or check REX in Host Settings under Backends. Each tile shows the session's windows, the last lines of the screen in front, any agent it finds, and RUNNING or NEEDS YOU. Pressing a tile opens the terminal the session is showing, with its screen, colors and scrollback; a session with several terminals offers the others under Open Terminal in the tile's menu, and the REX key in a Rex tab switches the tab to another terminal of the session. New Session and + TAB can create a Rex session while a Rex server is running on the host (Multiplex does not start one); a host's default backend stays tmux or herdr. + +PLEASE TRY +1. On a host that runs Rex with at least one session open (a Mac with the Rex app works), wait for the + REX chip on the host's rail, press it and confirm: the Rex sessions should appear as tinted tiles beside the tmux ones, each with its window names and the last lines of its screen. Add or rename a window in Rex: the tile should follow within a few seconds. +2. Press a Rex tile: a terminal should open showing what that Rex terminal shows, colors and earlier output included. Type a command: it should run, and the same terminal in Rex should show it. Type in Rex: the tab should follow. +3. Open a full-screen program such as vim in a Rex terminal, then attach it from the deck: the tab should show the program. Quit the program: the earlier output should come back, with one prompt. +4. On a Rex session with a split or a second window, long-press its tile and choose Open Terminal: each terminal should be listed, and choosing one should open it as its own tab. +5. Exit the shell in a Rex terminal while it is attached: the tab should end with RECONNECT and CLOSE TAB, not an error. +6. Start an agent in a Rex terminal and let it work, then let it ask a question: the tile should show RUNNING, then NEEDS YOU while it waits. +7. In a Rex tab on a session with more than one terminal, press the REX key: the terminals should be listed with the current one marked ACTIVE, and choosing another should switch the tab to it. +8. On a host showing Rex sessions, press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. Press + TAB in a Rex tab and choose New Session: the new session should start in the same directory. With Rex not running on the host, the same press should say that no Rex server is running. +9. Lock the device for a minute with a Rex tab open, then return: the tab should reconnect by itself. +10. Open Host Settings and find Backends: REX should be checkable, and New sessions run on should never list it. Uncheck it: the Rex tiles should go away. Feedback: screenshot in TestFlight From 28f562449efb72721573b5c1e6e463dde6134b82 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Mon, 16 Nov 2026 13:26:05 +0800 Subject: [PATCH 03/13] Queue Rex keystrokes instead of awaiting each, and fold duplicated Rex code A cleanup pass over the Rex backend. Three things behave differently. A Rex tab's write now queues and returns; a drain task makes the calls. The input pump awaits each write, so a write that waited for the server's answer made every keystroke its own round trip, queued behind the last, and the batching the code described never happened. Whether a tab rides mosh is asked in one place (`ridesMosh`). A Rex tab rides SSH whatever the host prefers, but scrollback, FILE and the bar's MOSH badge read the host's preference directly: on a mosh host a Rex tab had no scrollback, no FILE, and a MOSH badge. Helper chips on a Rex tab follow the wall probe's record. They polled a focused-pane query that has no Rex answer and never left their first value. Duplication removed: - The Rex run is the SSH run with a different open step, not a copy. - RexOneShot was OneShotGate; the Rex attention fallback was the tmux verdict; the agent-name map was herdr's; base64url had a helper. - The "nobody named this window" rule lives once, in RexWire, for the deck's spine and a tab's Switch Terminal list. Session id vetting moved there too, so TerminalRoute no longer calls into a service. - One factory for attach modes, one sentence for a failed create, one spelling of the product's name ("Rex", not "rex", in the offer alert). - A mint no longer settles its label twice; the script's pass against the live list is the one that counts. Less work on the terminal's path: - The WebSocket decoder stopped copying the rest of its buffer after every frame, and frames are masked in place. - Stream output with no server message in it passes through uncopied. - The alternate-screen watch no longer allocates per ESC byte. - The two screen reads of an attach are asked together. Also gone: `reportsClientCount` and `shortcutBackend`, which nothing needed, and a no-op exec the file viewer made for a Rex tab. --- Multiplex/Models/Host.swift | 64 +++-- Multiplex/Models/HostGuide.swift | 8 +- Multiplex/Models/RexWire.swift | 83 ++++-- Multiplex/Models/TerminalRoute.swift | 25 +- Multiplex/Models/WebSocketCodec.swift | 46 ++-- Multiplex/Services/ConnectionHub.swift | 96 ++++--- Multiplex/Services/ExternalActionRouter.swift | 14 +- Multiplex/Services/FileViewerController.swift | 17 +- Multiplex/Services/HerdrProbe.swift | 16 +- Multiplex/Services/RexProbe.swift | 128 +++------ Multiplex/Services/RexSession.swift | 250 ++++++++---------- Multiplex/Services/SSHConnection.swift | 7 +- .../Services/TerminalSessionController.swift | 212 ++++++--------- Multiplex/Services/TmuxProbe.swift | 2 +- Multiplex/Services/WidgetStatePublisher.swift | 9 +- Multiplex/Views/Deck/FleetWall.swift | 41 ++- .../Views/Terminal/TerminalPaneUIKit.swift | 2 +- .../Views/Terminal/TerminalWindowUIKit.swift | 30 ++- Multiplex/Views/Terminal/UMDBarUIKit.swift | 2 +- MultiplexTests/RexProbeTests.swift | 11 +- MultiplexTests/RexSessionTests.swift | 80 +++++- docs/agents/backends-and-probe.md | 19 +- 22 files changed, 609 insertions(+), 553 deletions(-) diff --git a/Multiplex/Models/Host.swift b/Multiplex/Models/Host.swift index fa2185db..722ccbc0 100644 --- a/Multiplex/Models/Host.swift +++ b/Multiplex/Models/Host.swift @@ -51,27 +51,53 @@ struct Host: Identifiable, Codable, Hashable { /// run on" bars and the Bind pane offer. static let defaultCases = allCases.filter(\.canBeDefault) - /// Whether the probe can state how many clients a session has. - /// tmux answers `#{session_attached}`; herdr 0.7.5 / protocol 17 - /// exposes no attached-client surface at all (verified 2026-08-02 - /// across `session list --json`, `api snapshot`, `status --json`, - /// and the bundled API schema — only the socket-only - /// `client.window_title` reply leaks a `no_foreground_client` - /// reason, and no CLI verb reaches it), so its records carry - /// `clientCount == 0` whatever is really attached. Rex answers - /// `client.list` per session; the probe counts the attached APP - /// clients (a Rex window showing the session), never its own CLI. - var reportsClientCount: Bool { self != .herdr } + /// The product's name as prose spells it — tmux and herdr write + /// theirs lowercase, Rex does not. `rawValue` is the command. + var displayName: String { + switch self { + case .tmux, .herdr: rawValue + case .rex: "Rex" + } + } + + /// Whether a launch can land INSIDE an existing session, as a new + /// window or tab of it. Multiplex opens none inside a Rex session: + /// a launch aimed at one gets a fresh session instead. + var opensWindowsInSession: Bool { + switch self { + case .tmux, .herdr: true + case .rex: false + } + } + + /// Whether one exec can say which pane of a session is in front + /// and what runs in it — the helper chips' fast path between wall + /// probes. A Rex tab's terminal was chosen at attach and there is + /// no such query to make; the wall probe's record answers alone. + var hasFocusedPaneProbe: Bool { + switch self { + case .tmux, .herdr: true + case .rex: false + } + } /// Whether a session is live right now — said only where it can be - /// verified. tmux counts every client on the host. herdr can answer - /// for exactly one client: the one this app is, which is what an - /// open terminal tab means. A shell on the host attached to the same - /// herdr session therefore stays invisible; the tile understates - /// rather than guesses, the same choice its missing client count and - /// session age already make. Rex counts its APP clients, and this - /// app attaches as kind `other` on purpose (`RexWire.hello`), so its - /// own open tab is counted separately. + /// verified. tmux counts every client on the host + /// (`#{session_attached}`). herdr 0.7.5 / protocol 17 exposes no + /// attached-client surface at all (verified 2026-08-02 across + /// `session list --json`, `api snapshot`, `status --json`, and the + /// bundled API schema — only the socket-only `client.window_title` + /// reply leaks a `no_foreground_client` reason, and no CLI verb + /// reaches it), so its records carry `clientCount == 0` whatever is + /// really attached and it can answer for exactly one client: the + /// one this app is, which is what an open terminal tab means. A + /// shell on the host attached to the same herdr session therefore + /// stays invisible; the tile understates rather than guesses, the + /// same choice its missing session age already makes. Rex answers + /// `client.list` per session and the probe counts the attached APP + /// clients (a Rex window showing the session), never its own CLI; + /// this app attaches as kind `other` on purpose (`RexWire.hello`), + /// so its own open tab is counted separately. func isSessionLive(clientCount: Int, hasOpenTab: Bool) -> Bool { switch self { case .tmux: clientCount > 0 diff --git a/Multiplex/Models/HostGuide.swift b/Multiplex/Models/HostGuide.swift index 750d522d..c6019984 100644 --- a/Multiplex/Models/HostGuide.swift +++ b/Multiplex/Models/HostGuide.swift @@ -38,9 +38,9 @@ enum HostGuide { switch backend { case .tmux: tmuxInstall case .herdr: herdrInstall - // Rex is never the primary: no dead tile and no failed mint speaks - // for it, so there is no install road to hand over. (Its packages - // also come from a per-distribution repository, not one line.) + // Rex is never the primary, so no dead tile speaks for it, and its + // packages come from a per-distribution repository rather than one + // line: a mint that finds no `rex` says so without an install road. case .rex: [] } } @@ -77,7 +77,7 @@ enum HostGuide { ) -> String { // The product's name, not the binary's: this is about an app the // user opens, where `backendMissingMessage` is about a command. - let name = backend == .rex ? "Rex" : backend.rawValue + let name = backend.displayName return String(localized: """ No \(name) server is running on \(hostName), and Multiplex doesn’t \ start one. Start \(name) there, then try again. diff --git a/Multiplex/Models/RexWire.swift b/Multiplex/Models/RexWire.swift index 3cd3332a..f4511a6a 100644 --- a/Multiplex/Models/RexWire.swift +++ b/Multiplex/Models/RexWire.swift @@ -133,6 +133,45 @@ enum RexWire { return .event(type: type, fields: fields) } + // MARK: - Ids and labels + + /// A session id the app may splice into a command or bake into a + /// route: `session:` and a UUID's characters, nothing a shell could + /// reinterpret. What a parser reports is truth; what reaches a shell + /// line is vetted here. + static func bakeableSessionID(_ id: String) -> Bool { + let prefix = "session:" + guard id.hasPrefix(prefix), id.utf8.count <= 64 else { return false } + let rest = id.dropFirst(prefix.count) + return !rest.isEmpty && rest.unicodeScalars.allSatisfy { scalar in + (scalar >= "0" && scalar <= "9") + || (scalar >= "a" && scalar <= "f") + || (scalar >= "A" && scalar <= "F") + || scalar == "-" + } + } + + /// A label as the app can show it: control characters removed (a label + /// is user text and lands in a single-line row), ends trimmed. + static func displayLabel(_ label: String) -> String { + String(String.UnicodeScalarView(label.unicodeScalars.filter { + !CharacterSet.controlCharacters.contains($0) + })).trimmingCharacters(in: .whitespaces) + } + + /// A window's label if somebody chose it, nil if nobody did. + /// + /// A window nobody named carries a label generated from its own id + /// (`Window 262b0b23`, observed on preview.19) — noise wherever it is + /// shown. Only that exact shape counts as unnamed, so a label someone + /// chose is never second-guessed, and a server that generates labels + /// differently simply shows its own. The one statement of that shape: + /// the deck's spine and a tab's Switch Terminal list both ask here. + static func chosenWindowLabel(_ label: String, windowID: String) -> String? { + let label = displayLabel(label) + return label.isEmpty || label == "Window " + windowID.suffix(8) ? nil : label + } + // MARK: - Session view → the block to attach /// One terminal block a session shows, in window (tab) order. @@ -213,20 +252,17 @@ enum RexWire { /// The rows of a Rex tab's Switch Terminal list — every terminal of the /// session, in window order, as the shortcut panel's shared choice - /// record. A row reads `window — terminal`; a window nobody named (an - /// empty label, or Rex's generated `Window `) is `window N`, - /// and a terminal whose label says nothing more than its window is the - /// window alone. `isActive` marks the one this tab is showing. + /// record. A row reads `window — terminal`; a window nobody named + /// (`chosenWindowLabel`) is `window N`, and a terminal whose label says + /// nothing more than its window is the window alone. `isActive` marks + /// the one this tab is showing. static func terminalChoices( in blocks: [Block], showing blockID: String? ) -> [TmuxWindowChoice] { blocks.enumerated().map { offset, block in - let label = block.windowLabel.trimmingCharacters(in: .whitespaces) - let generated = "Window " + block.windowID.suffix(8) - let window = label.isEmpty || label == generated - ? String(localized: "window \(block.windowPosition)") - : label - let terminal = block.label.trimmingCharacters(in: .whitespaces) + let window = chosenWindowLabel(block.windowLabel, windowID: block.windowID) + ?? String(localized: "window \(block.windowPosition)") + let terminal = displayLabel(block.label) let name = terminal.isEmpty || terminal.caseInsensitiveCompare(window) == .orderedSame ? window : "\(window) — \(terminal)" @@ -241,11 +277,7 @@ enum RexWire { /// HELLO: `0x01`, then the ticket's 16 bytes. nil for a ticket that is /// not 16 bytes of base64url — never send a guess. static func dataHello(ticket: String) -> Data? { - var base64 = ticket - .replacingOccurrences(of: "-", with: "+") - .replacingOccurrences(of: "_", with: "/") - base64 += String(repeating: "=", count: (4 - base64.count % 4) % 4) - guard let bytes = Data(base64Encoded: base64), bytes.count == 16 else { return nil } + guard let bytes = Data(base64URLNoPad: ticket), bytes.count == 16 else { return nil } return Data([0x01]) + bytes } @@ -333,6 +365,12 @@ struct RexTerminalStream { var isLive: Bool { pastSnapshot } mutating func consume(_ chunk: Data) -> [Event] { + // The steady state — nothing held, and no message in or straddling + // this chunk: it is output exactly as it came, with no copy made. + if pastSnapshot, pending.isEmpty, chunk.range(of: marker) == nil, + Self.partialMarkerSuffix(of: chunk, marker: marker) == 0 { + return chunk.isEmpty ? [] : [.output(chunk)] + } pending.append(chunk) var events: [Event] = [] var output = Data() @@ -438,7 +476,7 @@ struct AlternateScreenExitWatch { /// True if `chunk` (continuing whatever came before) contains an /// alternate-screen exit. mutating func sawExit(in chunk: Data) -> Bool { - let bytes = [UInt8](carry + chunk) + let bytes = carry.isEmpty ? [UInt8](chunk) : [UInt8](carry) + [UInt8](chunk) carry = Data() var found = false var index = 0 @@ -447,16 +485,19 @@ struct AlternateScreenExitWatch { index += 1 continue } - // `ESC [ ?` then parameters, then a final byte. - let prefix: [UInt8] = [0x1B, 0x5B, 0x3F] + // `ESC [ ?` then parameters, then a final byte. Compared byte + // by byte: a redrawing full-screen program sends thousands of + // ESCs a second, each of which passes through here. let available = bytes.count - index - guard available >= prefix.count else { - if Array(bytes[index...]) == Array(prefix.prefix(available)) { + guard available >= 3 else { + // Cut short by the chunk's end: keep it if it could still + // become one. + if available == 1 || bytes[index + 1] == 0x5B { carry = Data(bytes[index...]) } break } - guard Array(bytes[index..<(index + 3)]) == prefix else { + guard bytes[index + 1] == 0x5B, bytes[index + 2] == 0x3F else { index += 1 continue } diff --git a/Multiplex/Models/TerminalRoute.swift b/Multiplex/Models/TerminalRoute.swift index 99c5528b..836e55c5 100644 --- a/Multiplex/Models/TerminalRoute.swift +++ b/Multiplex/Models/TerminalRoute.swift @@ -67,7 +67,7 @@ struct TerminalRoute: Codable, Hashable, Identifiable { case .herdr: return .herdrAttach(sessionName: sessionName) case .rex: - guard let sessionID, RexProbe.bakeableSessionID(sessionID) else { return nil } + guard let sessionID, RexWire.bakeableSessionID(sessionID) else { return nil } return .rexAttach(sessionName: sessionName, sessionID: sessionID) } } @@ -93,6 +93,21 @@ struct TerminalRoute: Codable, Hashable, Identifiable { backend: session.backend, sessionName: session.name, sessionID: session.tmuxID) } + + /// The mode for ONE terminal of a session, as its own tab — a Rex + /// tile's Open Terminal row. nil for a record with no usable ids, + /// and for a backend whose tab shows the whole session: its panes + /// are reached inside the tab, not opened one each. + static func attach(session: TmuxSession, window: TmuxWindow, pane: TmuxPane) -> Mode? { + guard session.backend == .rex, + RexWire.bakeableSessionID(session.tmuxID), !pane.tmuxID.isEmpty + else { return nil } + return .rexAttach( + sessionName: session.name, + sessionID: session.tmuxID, + block: RexBlockRef(id: pane.tmuxID, label: window.name) + ) + } } var id: UUID = UUID() @@ -192,14 +207,6 @@ struct TerminalRoute: Codable, Hashable, Identifiable { } } - /// The backend whose panel this tab carries — the rail's TMUX / HRDR / - /// REX key and the panel behind it (`ShortcutPanelContent.content`). - /// One accessor so the window bar and the pane rail cannot disagree; - /// the key's face is `SessionBackend.shortcutKeyCaption`, because a - /// two-way `herdr ? "HRDR" : "TMUX"` at each site once drew a TMUX key - /// on a Rex tab. - var shortcutBackend: Host.SessionBackend? { sessionBackend } - /// Complete multiplexer identity for control-plane work that outlives or /// sits beside this tab's interactive transport (for example a mosh tab /// summoning its independently connected file viewer). diff --git a/Multiplex/Models/WebSocketCodec.swift b/Multiplex/Models/WebSocketCodec.swift index c9876e55..16a8d26d 100644 --- a/Multiplex/Models/WebSocketCodec.swift +++ b/Multiplex/Models/WebSocketCodec.swift @@ -137,8 +137,9 @@ enum WebSocketCodec { maskKey: [UInt8] = (0..<4).map { _ in UInt8.random(in: .min ... .max) } ) -> Data { precondition(maskKey.count == 4) - var frame = Data([0x80 | opcode.rawValue]) let count = payload.count + var frame = Data(capacity: count + 14) + frame.append(0x80 | opcode.rawValue) switch count { case ..<126: frame.append(0x80 | UInt8(count)) @@ -152,7 +153,13 @@ enum WebSocketCodec { } } frame.append(contentsOf: maskKey) - frame.append(contentsOf: payload.enumerated().map { $0.element ^ maskKey[$0.offset % 4] }) + // Masked where it lands: a paste is megabytes, and a mapped copy + // of it is a second buffer and a closure call per byte. + let start = frame.count + frame.append(payload) + frame.withUnsafeMutableBytes { bytes in + for index in 0.. 0 { + buffer.removeSubrange(buffer.startIndex..<(buffer.startIndex + consumed)) + consumed = 0 + } buffer.append(bytes) } @@ -231,10 +247,10 @@ enum WebSocketCodec { /// Pops one whole frame off the buffer, or nil if it is not all here. private mutating func nextFrame() throws -> Frame? { - let bytes = buffer - guard bytes.count >= 2 else { return nil } - let base = bytes.startIndex - let first = bytes[base], second = bytes[base + 1] + let base = buffer.startIndex + consumed + let available = buffer.count - consumed + guard available >= 2 else { return nil } + let first = buffer[base], second = buffer[base + 1] guard first & 0x70 == 0 else { throw Failure.protocolViolation("reserved bits set with no extension negotiated") } @@ -244,13 +260,13 @@ enum WebSocketCodec { var offset = 2 var length = Int(second & 0x7F) if length == 126 { - guard bytes.count >= offset + 2 else { return nil } - length = Int(bytes[base + 2]) << 8 | Int(bytes[base + 3]) + guard available >= offset + 2 else { return nil } + length = Int(buffer[base + 2]) << 8 | Int(buffer[base + 3]) offset += 2 } else if length == 127 { - guard bytes.count >= offset + 8 else { return nil } + guard available >= offset + 8 else { return nil } var wide: UInt64 = 0 - for index in 0..<8 { wide = wide << 8 | UInt64(bytes[base + 2 + index]) } + for index in 0..<8 { wide = wide << 8 | UInt64(buffer[base + 2 + index]) } guard wide <= UInt64(WebSocketCodec.maxMessageBytes) else { throw Failure.messageTooLarge(Int(clamping: wide)) } @@ -265,16 +281,16 @@ enum WebSocketCodec { let masked = second & 0x80 != 0 var key: [UInt8] = [] if masked { - guard bytes.count >= offset + 4 else { return nil } - key = [UInt8](bytes[(base + offset)..<(base + offset + 4)]) + guard available >= offset + 4 else { return nil } + key = [UInt8](buffer[(base + offset)..<(base + offset + 4)]) offset += 4 } - guard bytes.count >= offset + length else { return nil } - var payload = Data(bytes[(base + offset)..<(base + offset + length)]) + guard available >= offset + length else { return nil } + var payload = Data(buffer[(base + offset)..<(base + offset + length)]) if masked { payload = Data(payload.enumerated().map { $0.element ^ key[$0.offset % 4] }) } - buffer = Data(bytes[(base + offset + length)...]) + consumed += offset + length return Frame(fin: first & 0x80 != 0, opcode: opcode, payload: payload) } } diff --git a/Multiplex/Services/ConnectionHub.swift b/Multiplex/Services/ConnectionHub.swift index 12e4d719..c4d3b02c 100644 --- a/Multiplex/Services/ConnectionHub.swift +++ b/Multiplex/Services/ConnectionHub.swift @@ -241,6 +241,17 @@ final class HostConnectionModel { } } } + + /// Why the last `createSession` returned nothing, as the one sentence + /// every surface shows: the mint's own reason when the link was + /// healthy, else the dead link's, else a generic one. + func sessionCreateFailureMessage(hostName: String) -> String { + if let failure = sessionCreateFailure { + return failure.message(hostName: hostName) + } + if case .failed(let reason) = phase { return reason } + return String(localized: "Couldn't create the session on \(hostName).") + } @ObservationIgnored private var lastRefreshed: Date? /// Observation-friendly summaries: views that only need liveness or a /// badge count should not subscribe to the full pane/process tree. @@ -435,11 +446,11 @@ final class HostConnectionModel { let connection else { return nil } - // A Rex tab has no one-exec "which pane is in front" query to make - // — its block was chosen at attach — and without this the tmux - // query below would run against a Rex session's name. nil means the - // fast path is unavailable; the wall probe's record still answers. - guard backend != .rex else { return nil } + // nil means the fast path is unavailable and the wall probe's + // record answers alone. Checked before anything below runs: what + // is not herdr there is tmux, and a tmux query must not be aimed at + // another backend's session name. + guard backend.hasFocusedPaneProbe else { return nil } activePaneProbeInFlight = true defer { activePaneProbeInFlight = false } @@ -1102,22 +1113,7 @@ final class HostConnectionModel { // the classifier that applies is the one that produced the record. switch session.backend { case .tmux: - let window = session.activeWindow - let agent = window?.activeAgent - let title = window?.activePane?.title ?? window?.paneTitle ?? "" - return AttentionVerdict( - // No detected agent, or an agent without verified attention - // signals, means no state (bells are still tracked). - state: AgentAttention.classifyVerified( - title: title, - tail: attentionTails[session.id] ?? [], - agent: agent - ), - agent: agent, - paneTitle: title, - hasBell: session.windows.contains(where: \.hasBell), - offersDialogSummary: true - ) + return titleAndScreenVerdict(for: session) case .herdr: let statuses = herdrPaneStatuses[session.id] ?? [:] let state = HerdrProbe.sessionAgentState(statuses.values) @@ -1167,22 +1163,34 @@ final class HostConnectionModel { offersDialogSummary: front ) } - // Nothing reported: read the fronted block the way a tmux tile - // is read, from its title and screen. Rex latches no bell. - return AttentionVerdict( - state: AgentAttention.classifyVerified( - title: title, - tail: attentionTails[session.id] ?? [], - agent: pane?.agent - ), - agent: pane?.agent, - paneTitle: title, - hasBell: false, - offersDialogSummary: true - ) + // Nothing reported: the fronted block is read exactly as a + // tmux tile is. (Rex latches no bell, so that term is false.) + return titleAndScreenVerdict(for: session) } } + /// The verdict for a session nothing reports on: its fronted pane's + /// title and screen, through the needle heuristics. tmux's only reading, + /// and Rex's when the program in front reports no status of its own. + private func titleAndScreenVerdict(for session: TmuxSession) -> AttentionVerdict { + let window = session.activeWindow + let agent = window?.activeAgent + let title = window?.activePane?.title ?? window?.paneTitle ?? "" + return AttentionVerdict( + // No detected agent, or an agent without verified attention + // signals, means no state (bells are still tracked). + state: AgentAttention.classifyVerified( + title: title, + tail: attentionTails[session.id] ?? [], + agent: agent + ), + agent: agent, + paneTitle: title, + hasBell: session.windows.contains(where: \.hasBell), + offersDialogSummary: true + ) + } + /// Re-derive the wall's KEYCHAIN LOCKED tip after a settled probe. /// Symptom first: only a Claude pane visibly parked on its sign-in /// screen (needle in the capture tail, agent confirmed on that pane) @@ -1354,7 +1362,9 @@ final class HostConnectionModel { /// without one, and every miss is $HOME. The source is resolved to its /// id against the latest probe — a name the probe no longer lists has /// no directory to offer, and the mint starts in $HOME rather than - /// guess. The tmux conf rider does not apply. + /// guess. The tmux conf rider does not apply. The label goes as asked: + /// the mint script settles it against the server's LIVE list, which a + /// pass over the last probe's names here could only second-guess. /// /// Throws what the exec throws, so a dead control link is reported as /// one by the caller. A healthy link that could not create the session @@ -1365,13 +1375,11 @@ final class HostConnectionModel { startingIn directory: String?, running script: String?, typing launch: String?, over connection: SSHConnection ) async throws -> TerminalRoute.Mode? { - let existing = sessions(on: .rex) let sourceID = sourceSession - .flatMap { name in existing.first { $0.name == name }?.tmuxID } - .flatMap { RexProbe.bakeableSessionID($0) ? $0 : nil } + .flatMap { name in sessions(on: .rex).first { $0.name == name }?.tmuxID } + .flatMap { RexWire.bakeableSessionID($0) ? $0 : nil } let command = RexProbe.mintCommand( - label: RexProbe.uniqueSessionLabel( - base: base, existing: existing.map(\.name)), + label: RexProbe.sessionLabel(base: base), inDirectoryOf: sourceID, startingIn: directory, typing: [script, launch].compactMap { $0 } @@ -1576,10 +1584,10 @@ final class HostConnectionModel { running script: String? = nil, typing launch: String? ) async -> TerminalRoute.Mode? { - // Multiplex opens no new window or tab inside a Rex session — a - // launch lands in a fresh one (`createSession`) — and the tmux - // verbs below must not aim at its name. - guard backend != .rex else { return nil } + // A backend with no window to open inside a session gets its + // launch in a fresh one (`createSession`); what is not herdr below + // is tmux, and tmux verbs must not aim at another backend's name. + guard backend.opensWindowsInSession else { return nil } resetConnectRetryBackoff() let reusedLink = connection != nil && phase == .connected do { diff --git a/Multiplex/Services/ExternalActionRouter.swift b/Multiplex/Services/ExternalActionRouter.swift index 5277a85f..97cb0a9f 100644 --- a/Multiplex/Services/ExternalActionRouter.swift +++ b/Multiplex/Services/ExternalActionRouter.swift @@ -306,7 +306,7 @@ enum ExternalActionPerformer { // target resolves to nothing and the launch falls through to a // fresh session — on Rex when the action named Rex. let candidates = openableSessions(model, backend: backend) - .filter { $0.backend != .rex } + .filter(\.backend.opensWindowsInSession) if case .existingSession(let name, let placement) = target, let session = candidates.first(where: { $0.name == name }) { guard let mode = await model.launchInSession( @@ -453,15 +453,9 @@ enum ExternalActionPerformer { // generic one) would send the user after the wrong thing. // createSession marks the host failed when the control link IS the // problem; reuse that reason when it exists. - let message: String - if let failure = model.sessionCreateFailure { - message = failure.message(hostName: host.name) - } else if case .failed(let reason) = model.phase { - message = reason - } else { - message = String(localized: "Couldn't create the session on \(host.name).") - } - context.presentFailure(ExternalActionFailure(hostName: host.name, message: message)) + context.presentFailure(ExternalActionFailure( + hostName: host.name, + message: model.sessionCreateFailureMessage(hostName: host.name))) } private static func failureMessage(for phase: HostConnectionModel.Phase, host: Host) -> String { diff --git a/Multiplex/Services/FileViewerController.swift b/Multiplex/Services/FileViewerController.swift index dda640c0..dfeea547 100644 --- a/Multiplex/Services/FileViewerController.swift +++ b/Multiplex/Services/FileViewerController.swift @@ -500,9 +500,8 @@ final class FileViewerController: AuxiliaryPaneController { /// keeps the active/focused pane. private func anchorPaneDirectory() async -> String? { guard let anchorSession, - let output = try? await withConnection({ - try await $0.exec(Self.anchorDirectoryCommand(for: anchorSession)) - }) + let command = Self.anchorDirectoryCommand(for: anchorSession), + let output = try? await withConnection({ try await $0.exec(command) }) else { return nil } return Self.parseAnchorDirectory( output, backend: anchorSession.backend, @@ -510,18 +509,18 @@ final class FileViewerController: AuxiliaryPaneController { ) } - static func anchorDirectoryCommand(for session: SessionKey) -> String { + /// nil where no exec can answer: a Rex block's directory lives behind + /// the server's API, not a command, so this viewer has no anchor to ask + /// for and opens at $HOME — the posture of a pane that will not answer, + /// without spending a connection on a no-op. + static func anchorDirectoryCommand(for session: SessionKey) -> String? { switch session.backend { case .tmux: TmuxProbe.pathAnchorCommand(sessionName: session.name) case .herdr: HerdrProbe.snapshotCommand(sessionName: session.name) case .rex: - // A Rex tab has no exec to ask where its block's program is - // (the answer lives behind the server's API, not a command). A - // no-op's empty answer parses to "no anchor": the $HOME - // fallback, the same posture as a pane that will not answer. - ":" + nil } } diff --git a/Multiplex/Services/HerdrProbe.swift b/Multiplex/Services/HerdrProbe.swift index 543bfe69..22225d5d 100644 --- a/Multiplex/Services/HerdrProbe.swift +++ b/Multiplex/Services/HerdrProbe.swift @@ -551,7 +551,7 @@ enum HerdrProbe { // is how a tile knows not to render this as an age, while // external actions and the widget still sort "most recent" // by it — herdr's own list order is the only order it states. - created: Date(timeIntervalSince1970: TimeInterval(index)), + created: syntheticCreated(position: index), tmuxID: entry.name, serverHost: "", // The one place a herdr record learns it is one. Everything @@ -562,10 +562,16 @@ enum HerdrProbe { ) } - /// True for the near-epoch stand-ins `session(entry:index:snapshot:)` - /// mints — herdr states no creation time, so a tile must render these - /// as no age at all. The one decoder of that encoding; keep them in - /// step. + /// The stand-in creation date for a backend that states none (herdr, + /// Rex): the session's place in the backend's own list, as seconds past + /// the epoch. The one encoder; `isSyntheticCreated` is its decoder. + static func syntheticCreated(position: Int) -> Date { + Date(timeIntervalSince1970: TimeInterval(position)) + } + + /// True for the near-epoch stand-ins `syntheticCreated` mints — the + /// backend states no creation time, so a tile must render these as no + /// age at all. The one decoder of that encoding; keep them in step. static func isSyntheticCreated(_ date: Date) -> Bool { date.timeIntervalSince1970 <= 86_400 } diff --git a/Multiplex/Services/RexProbe.swift b/Multiplex/Services/RexProbe.swift index 820bd55a..f62c2790 100644 --- a/Multiplex/Services/RexProbe.swift +++ b/Multiplex/Services/RexProbe.swift @@ -85,13 +85,21 @@ enum RexProbe { private static let serverUnreachableExit = 4 /// How much of the fronted screen each probe reads, from the end. Sized - /// to cover the tmux probe's 30 captured rows at a wide terminal; the - /// parser keeps `tailLines` of them. + /// to cover the tmux probe's captured rows at a wide terminal; the + /// parser keeps as many lines as that probe captures. private static let tailBytes = 6144 - private static let tailLines = 30 + private static let tailLines = TmuxProbe.captureDepth // MARK: - Probe command + /// A script without its source indentation: the same Lua, and a third + /// fewer bytes on an exec that runs every few seconds. + private static func compactLua(_ script: String) -> String { + script.split(separator: "\n") + .map { $0.drop(while: { $0 == " " }) } + .joined(separator: "\n") + } + /// The probe script. Lua, because `rex do` is the one way to make many /// API calls over a single connection and get one JSON document back. /// @@ -101,7 +109,7 @@ enum RexProbe { /// a herdr session without a snapshot is. /// /// Contains no single quote, so shell-quoting it is one pair of quotes. - private static let probeScript: String = """ + private static let probeScript: String = compactLua(""" local T = "com.superlogical.terminal." local out = { sessions = {} } rex.call("session.attach_all", { event_scope = "session" }) @@ -168,10 +176,7 @@ enum RexProbe { out.sessions[#out.sessions + 1] = item end return out - """ - .split(separator: "\n") - .map { $0.drop(while: { $0 == " " }) } - .joined(separator: "\n") + """) /// One exec round trip: presence, then the script's JSON, then the CLI's /// exit status — which is how "no server running" (4) is told apart from @@ -430,7 +435,7 @@ enum RexProbe { /// different session the day the older one is closed, and announce a /// turn that never ended. static func sessionNames(for entries: [(id: String, label: String)]) -> [String] { - let labels = entries.map { displayLabel($0.label) } + let labels = entries.map { RexWire.displayLabel($0.label) } var counts: [String: Int] = [:] for label in labels { counts[label.lowercased(), default: 0] += 1 } var seen = Set() @@ -451,14 +456,6 @@ enum RexProbe { } } - /// A label as a tile can show it: control characters removed (a label - /// is user text and lands in a single-line chassis row), ends trimmed. - private static func displayLabel(_ label: String) -> String { - String(String.UnicodeScalarView(label.unicodeScalars.filter { - !CharacterSet.controlCharacters.contains($0) - })).trimmingCharacters(in: .whitespaces) - } - /// The id's last six characters — the short form Rex's own listings /// print and accept as a target. private static func shortID(_ id: String) -> String { @@ -473,10 +470,10 @@ enum RexProbe { windows: windows(of: entry), clientCount: max(0, entry.clients ?? 0), // Rex states no creation time. The list is in creation order, - // so the position stands in — `HerdrProbe.isSyntheticCreated` - // is how a tile knows not to render it as an age, while "most - // recent" still sorts by it. - created: Date(timeIntervalSince1970: TimeInterval(index)), + // so the position stands in (`HerdrProbe.syntheticCreated`): a + // tile does not render it as an age, while "most recent" still + // sorts by it. + created: HerdrProbe.syntheticCreated(position: index), tmuxID: entry.id, serverHost: "", backend: .rex @@ -522,24 +519,19 @@ enum RexProbe { } } - /// A window nobody named carries a generated label built from its own - /// id (`Window 262b0b23`, observed on preview.19) — noise on a spine - /// line. Only that exact shape is replaced, so a label someone chose is - /// never second-guessed, and a server that generates labels differently - /// simply shows its own. - /// - /// The stand-in is the focused block's label (`shell`, or whatever the - /// block was named — `agent`, `logs`): the nearest thing Rex has to - /// tmux naming a window after what runs in it. `window N` is the last - /// resort only, because the spine already leads each line with N and - /// the first headless run read `1 WINDOW 1`. + /// A window's line on the spine. For one nobody named + /// (`RexWire.chosenWindowLabel`) the stand-in is the focused block's + /// label (`shell`, or whatever the block was named — `agent`, `logs`): + /// the nearest thing Rex has to tmux naming a window after what runs in + /// it. `window N` is the last resort only, because the spine already + /// leads each line with N and the first headless run read `1 WINDOW 1`. private static func windowName( _ window: WindowEntry, position: Int, focusedBlockLabel: String? ) -> String { - let label = displayLabel(window.label ?? "") - let generated = "Window " + window.id.suffix(8) - guard label.isEmpty || label == generated else { return label } - let blockLabel = displayLabel(focusedBlockLabel ?? "") + if let chosen = RexWire.chosenWindowLabel(window.label ?? "", windowID: window.id) { + return chosen + } + let blockLabel = RexWire.displayLabel(focusedBlockLabel ?? "") return blockLabel.isEmpty ? String(localized: "window \(position)") : blockLabel } @@ -611,43 +603,15 @@ enum RexProbe { return "\(window.name) — \(what)" } - /// The tab mode for one named terminal of a session — the menu row's - /// press. nil when the record carries no usable session id. - static func attachMode( - session: TmuxSession, window: TmuxWindow, pane: TmuxPane - ) -> TerminalRoute.Mode? { - guard bakeableSessionID(session.tmuxID), !pane.tmuxID.isEmpty else { return nil } - return .rexAttach( - sessionName: session.name, - sessionID: session.tmuxID, - block: RexBlockRef(id: pane.tmuxID, label: window.name) - ) - } - // MARK: - Session actions - /// A session id the app may splice into a command: `session:` and a - /// UUID's characters, nothing a shell could reinterpret. What the parser - /// reports is truth; what reaches a shell line is vetted here. - static func bakeableSessionID(_ id: String) -> Bool { - let prefix = "session:" - guard id.hasPrefix(prefix), id.utf8.count <= 64 else { return false } - let rest = id.dropFirst(prefix.count) - return !rest.isEmpty && rest.unicodeScalars.allSatisfy { scalar in - (scalar >= "0" && scalar <= "9") - || (scalar >= "a" && scalar <= "f") - || (scalar >= "A" && scalar <= "F") - || scalar == "-" - } - } - /// The deck tile's destructive close. Aimed at the session's ID, never /// its label: labels are shared, and `rex kill work` on a server with /// two of them refuses both. nil when the record carries no usable id — /// a tile restored from a snapshot always has one, so this is only a /// response that never named it. static func killCommand(for session: TmuxSession) -> String? { - guard bakeableSessionID(session.tmuxID) else { return nil } + guard RexWire.bakeableSessionID(session.tmuxID) else { return nil } return pathPrefix + "\(rexCommand) kill \(session.tmuxID.shellQuoted) >/dev/null 2>&1; true" } @@ -661,7 +625,7 @@ enum RexProbe { /// login-shell noise, a warning — is not a session. static func parseSessionIDs(_ lines: [some StringProtocol]) -> [String] { lines.map { $0.trimmingCharacters(in: .whitespaces) } - .filter(bakeableSessionID) + .filter(RexWire.bakeableSessionID) } // MARK: - New session @@ -678,7 +642,7 @@ enum RexProbe { /// label makes the server invent one (`quiet-meadow`), which nothing /// here could have predicted. static func sessionLabel(base: String) -> String { - let label = String(displayLabel(base).prefix(maxLabelLength)) + let label = String(RexWire.displayLabel(base).prefix(maxLabelLength)) .trimmingCharacters(in: .whitespaces) return label.isEmpty ? "session" : label } @@ -706,7 +670,7 @@ enum RexProbe { /// miss is $HOME — `TmuxProbe.newSessionCommand`'s own precedence. /// /// Contains no single quote, so shell-quoting it is one pair of quotes. - private static let mintScript: String = """ + private static let mintScript: String = compactLua(""" local T = "com.superlogical.terminal." local a = rex.args or {} local function text(v) if type(v) == "string" then return v end return "" end @@ -748,10 +712,7 @@ enum RexProbe { if s.session_id == made.session_id then label = text(s.label) end end return { ok = true, id = made.session_id, label = label } - """ - .split(separator: "\n") - .map { $0.drop(while: { $0 == " " }) } - .joined(separator: "\n") + """) /// Create a session with one shell terminal, over the control /// connection — the Rex arm of `HostConnectionModel.createSession`. @@ -828,11 +789,11 @@ enum RexProbe { return exitCode == serverUnreachableExit ? .noServer : .failed case .json(let json): guard let reply = try? JSONDecoder().decode(MintReply.self, from: Data(json.utf8)), - reply.ok == true, let id = reply.id, bakeableSessionID(id) + reply.ok == true, let id = reply.id, RexWire.bakeableSessionID(id) else { return .failed } // Spelled as `sessionNames` would spell a session that is alone // under its label — which the script just made true. - let label = displayLabel(reply.label ?? "") + let label = RexWire.displayLabel(reply.label ?? "") return .created(name: label.isEmpty ? "…" + shortID(id) : label, id: id) } } @@ -895,18 +856,13 @@ extension RexProbe.State { extension AgentKind { /// The `app` a program names itself with in an OSC 7501 report. The - /// protocol's own example is `claude-code`; every other spelling here - /// is the agent's command name, the only thing it can plausibly report. - /// Unrecognized apps (`cargo`, `terraform`) are programs, not agents. + /// protocol's own example is `claude-code`; any other spelling is the + /// agent's command name, the only thing it can plausibly report — the + /// names herdr reports too, so the two share one map and a new agent is + /// added once. Unrecognized apps (`cargo`, `terraform`) are programs, + /// not agents. init?(programStatusApp app: String) { - switch app.lowercased() { - case "claude-code", "claude": self = .claudeCode - case "codex": self = .codex - case "pi": self = .pi - case "grok": self = .grok - case "antigravity", "agy": self = .antigravity - case "hermes", "hermes-agent": self = .hermes - default: return nil - } + let name = app.lowercased() + self.init(herdrAgent: name == "claude-code" ? "claude" : name) } } diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift index 2f82e58c..d0e3e929 100644 --- a/Multiplex/Services/RexSession.swift +++ b/Multiplex/Services/RexSession.swift @@ -18,7 +18,7 @@ struct RexSocket: Sendable { try await pipe.write(WebSocketCodec.upgradeRequest( path: path, host: "rex", subprotocol: subprotocol, key: key)) try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - let upgraded = RexOneShot(continuation) + let upgraded = OneShotGate(continuation) let reader = Task { var head = Data() var isUpgraded = false @@ -36,7 +36,7 @@ struct RexSocket: Sendable { isUpgraded = true head = Data() decoder.append(remainder) - upgraded.succeed() + upgraded.open() } while let message = try decoder.next() { switch message { @@ -82,36 +82,6 @@ struct RexSocket: Sendable { } } -/// Resumes a continuation exactly once — the upgrade completing vs. the -/// pipe ending first. -private final class RexOneShot: @unchecked Sendable { - private let lock = NSLock() - private var continuation: CheckedContinuation? - - init(_ continuation: CheckedContinuation) { - self.continuation = continuation - } - - private func take() -> CheckedContinuation? { - lock.withLock { - let taken = continuation - continuation = nil - return taken - } - } - - func succeed() { - take()?.resume() - } - - /// False when the continuation had already been resumed. - func fail(_ error: Error) -> Bool { - guard let continuation = take() else { return false } - continuation.resume(throwing: error) - return true - } -} - /// A terminal tab attached to one Rex terminal block — the third /// `TerminalTransport`, beside the SSH PTY and mosh. /// @@ -200,15 +170,18 @@ actor RexSession: TerminalTransport { private(set) var blockID: String? private var owner: String? private var stream: RexTerminalStream? - /// Stream output that arrived before the bootstrap was drawn. - private var held = Data() - private var isBootstrapped = false + /// Stream output that arrived before the screen was drawn, kept to be + /// drawn after it. nil once the screen is up: output goes straight + /// through. + private var held: Data? = Data() /// Set while the emulator's primary screen is known to be incomplete — /// the bootstrap was rendered during a full-screen program. private var exitWatch: AlternateScreenExitWatch? private var lastOutput = ContinuousClock.now - private var isOpen = false - private var isClosed = false + /// `attaching` until `open` returns; `closed` is final, whichever side + /// ended it. + private enum Phase { case attaching, live, closed } + private var phase = Phase.attaching private var size: (cols: Int, rows: Int) = (80, 24) private var input = RexInputEncoder() private var pendingInput = "" @@ -262,7 +235,7 @@ actor RexSession: TerminalTransport { size = (cols, rows) do { try await attach() - isOpen = true + if phase == .attaching { phase = .live } } catch { let failure = Self.failure(from: error) await teardown(failing: failure) @@ -325,10 +298,8 @@ actor RexSession: TerminalTransport { /// lands in and a file viewer opens at. nil when the tab is not live or /// the server cannot say. func workingDirectory() async -> String? { - guard isOpen, !isClosed, let blockID, - let process = try? await call( - RexWire.terminalCreator + ".process", - RexWire.blockPayload(sessionID: sessionID, blockID: blockID)) + guard phase == .live, let blockID, + let process = try? await terminalCall("process", block: blockID) else { return nil } return RexWire.workingDirectory(inProcess: process) } @@ -339,7 +310,7 @@ actor RexSession: TerminalTransport { /// rows, with the one this tab shows marked. Read fresh each time the /// panel opens: windows come and go in Rex without telling the tab. func terminalChoices() async -> [TmuxWindowChoice]? { - guard isOpen, !isClosed, + guard phase == .live, let view = try? await call("session.view", ["session_id": sessionID]) else { return nil } return RexWire.terminalChoices( @@ -357,7 +328,7 @@ actor RexSession: TerminalTransport { /// ends the tab with the reason rather than leaving it on a dead /// stream; RECONNECT then attaches afresh. func switchBlock(to newID: String) async { - guard isOpen, !isClosed, !isSwitching, newID != blockID else { return } + guard phase == .live, !isSwitching, newID != blockID else { return } isSwitching = true defer { isSwitching = false } let previous = blockID @@ -373,7 +344,6 @@ actor RexSession: TerminalTransport { stream = nil reached.subtract([.dataWelcome, .live]) held = Data() - isBootstrapped = false exitWatch = nil pendingInput = "" input = RexInputEncoder() @@ -396,19 +366,19 @@ actor RexSession: TerminalTransport { /// rendering has been drawn, so nothing is drawn UNDER a rendering that /// was taken later, and nothing that arrived meanwhile is dropped. private func drawScreen(blockID: String) async { - isBootstrapped = false - let onAlternateScreen = await isOnAlternateScreen(blockID: blockID) - let screen = await bootstrapScreen(blockID: blockID) - guard !isClosed else { return } + held = held ?? Data() + // Two reads that depend on nothing of each other's, so they share + // one round trip. + async let alternate = isOnAlternateScreen(blockID: blockID) + async let rendering = bootstrapScreen(blockID: blockID) + let (onAlternateScreen, screen) = await (alternate, rendering) + guard phase != .closed else { return } // RIS first: a resumed tab still shows what the last run drew. onData?(Data([0x1B, 0x63]) + screen) exitWatch = onAlternateScreen ? AlternateScreenExitWatch() : nil - isBootstrapped = true - if !held.isEmpty { - let pending = held - held = Data() - deliver(pending) - } + let pending = held + held = nil + if let pending, !pending.isEmpty { deliver(pending) } } /// Stream output on its way to the emulator. The one place that also @@ -434,14 +404,14 @@ actor RexSession: TerminalTransport { /// terminal that never goes quiet is redrawn anyway after the cap. private func redrawOnceQuiet(blockID: String) async { let started = ContinuousClock.now - while !isClosed { + while phase != .closed { try? await Task.sleep(for: .milliseconds(60)) let now = ContinuousClock.now if now - lastOutput >= .milliseconds(120) || now - started >= .milliseconds(800) { break } } - guard !isClosed else { return } + guard phase != .closed else { return } await drawScreen(blockID: blockID) } @@ -449,9 +419,7 @@ actor RexSession: TerminalTransport { /// the server rather than read out of the rendering: `modes` states it /// outright. An answer that cannot be had reads as "no". private func isOnAlternateScreen(blockID: String) async -> Bool { - let modes = try? await call( - RexWire.terminalCreator + ".modes", - RexWire.blockPayload(sessionID: sessionID, blockID: blockID)) + let modes = try? await terminalCall("modes", block: blockID) return modes?["screen"] as? String == "alternate" } @@ -467,11 +435,14 @@ actor RexSession: TerminalTransport { .first { $0["block_id"] as? String == blockID } owner = mine?["owner"] as? String ?? clientID } - _ = try? await call( - RexWire.terminalCreator + ".resize", - RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, - args: ["columns": size.cols, "rows": size.rows])) + await sendSize(to: blockID) + } + + /// Applies at once while this client owns the block, and otherwise + /// waits server-side until it does — never a failure worth raising. + private func sendSize(to blockID: String) async { + _ = try? await terminalCall( + "resize", block: blockID, ["columns": size.cols, "rows": size.rows]) } /// The terminal's screen and scrollback as escape sequences SwiftTerm @@ -479,58 +450,50 @@ actor RexSession: TerminalTransport { /// rendering is too large to wait for, and to nothing at all — the /// stream alone — if the server will not render. private func bootstrapScreen(blockID: String) async -> Data { - let method = RexWire.terminalCreator + ".format" - guard let first = try? await call(method, RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, - args: [ - "format": "vt", - "extra_cursor": true, - "extra_modes": true, - "extra_scrolling_region": true, - "extra_style": true, - "extra_charsets": true, - "extra_keyboard": true, - "extra_kitty_keyboard": true, - "extra_tabstops": true, - "max_bytes": Self.bootstrapChunk, - ])) + guard let first = try? await terminalCall("format", block: blockID, [ + "format": "vt", + "extra_cursor": true, + "extra_modes": true, + "extra_scrolling_region": true, + "extra_style": true, + "extra_charsets": true, + "extra_keyboard": true, + "extra_kitty_keyboard": true, + "extra_tabstops": true, + "max_bytes": Self.bootstrapChunk, + ]) else { return Data() } - var text = first["content"] as? String ?? "" - guard let id = first["id"] as? Int else { return Data(text.utf8) } + var screen = Data((first["content"] as? String ?? "").utf8) + guard let id = first["id"] as? Int else { return screen } let total = first["total"] as? Int ?? .max guard total <= Self.bootstrapLimit else { return await plainTail(blockID: blockID) } - var offset = text.utf8.count - while offset < total { - guard let more = try? await call( - RexWire.terminalCreator + ".blob_read", - RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, - args: ["id": id, "offset": offset, "max_bytes": Self.bootstrapChunk])), - let piece = more["data"] as? String, !piece.isEmpty + // Offsets count the rendering's UTF-8 bytes, which is what `screen` + // holds. + while screen.count < total { + guard let more = try? await terminalCall("blob_read", block: blockID, [ + "id": id, "offset": screen.count, "max_bytes": Self.bootstrapChunk, + ]), let piece = more["data"] as? String, !piece.isEmpty else { break } - text += piece - offset += piece.utf8.count + screen.append(contentsOf: piece.utf8) if more["eof"] as? Bool == true { break } } - return Data(text.utf8) + return screen } /// The last screenful or so as plain text — no colors, but the user /// lands on what the terminal was showing rather than on nothing. Read /// from the END (`RexProbe` explains why a capped read stops short). private func plainTail(blockID: String) async -> Data { - let creator = RexWire.terminalCreator - guard let first = try? await call(creator + ".format", RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, - args: ["format": "text", "trim": true, "max_bytes": 1])), - let id = first["id"] as? Int, let total = first["total"] as? Int + guard let first = try? await terminalCall( + "format", block: blockID, ["format": "text", "trim": true, "max_bytes": 1]), + let id = first["id"] as? Int, let total = first["total"] as? Int else { return Data() } let offset = max(0, total - Self.plainTailBytes) - guard let rest = try? await call(creator + ".blob_read", RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, args: ["id": id, "offset": offset])), - let tail = rest["data"] as? String + guard let rest = try? await terminalCall( + "blob_read", block: blockID, ["id": id, "offset": offset]), + let tail = rest["data"] as? String else { return Data() } var lines = tail.split(separator: "\n", omittingEmptySubsequences: false) // A read that started mid-screen starts mid-line. @@ -540,28 +503,34 @@ actor RexSession: TerminalTransport { // MARK: - TerminalTransport + /// Queues the input and returns; it does not wait for the server. + /// + /// One write is in flight at a time — the server runs block methods + /// concurrently, so two calls could land out of order — and whatever is + /// typed meanwhile rides the next call as one string. Returning at once + /// is what lets that happen: the tab's input pump awaits each write, so + /// a write that waited for its answer would turn every keystroke into a + /// round trip of its own, queued behind the last. func write(_ data: Data) async throws { - guard isOpen, !isClosed else { throw Failure("not attached") } + guard phase == .live else { throw Failure("not attached") } // Mid-switch the screen on show is the terminal being left; a key // pressed then is dropped rather than typed into one not yet drawn. guard !isSwitching else { return } pendingInput += input.encode(data) - // One write in flight at a time: the server runs block methods - // concurrently, so two calls could land out of order. Whatever is - // typed meanwhile rides the next call as one string. - guard !isWriting else { return } + guard !isWriting, !pendingInput.isEmpty else { return } isWriting = true + Task { await self.drainInput() } + } + + private func drainInput() async { defer { isWriting = false } - while !pendingInput.isEmpty, !isClosed, let blockID { + while !pendingInput.isEmpty, phase == .live, let blockID { let text = pendingInput pendingInput = "" // Typing is what claims the size back from another client. if owner != clientID { await claimAndSize() } do { - _ = try await call( - RexWire.terminalCreator + ".write", - RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, args: ["data": text])) + _ = try await terminalCall("write", block: blockID, ["data": text]) } catch { Self.log.debug("write failed: \(String(describing: error), privacy: .public)") } @@ -570,21 +539,15 @@ actor RexSession: TerminalTransport { func resize(cols: Int, rows: Int) async throws { size = (cols, rows) - guard isOpen, !isClosed, let blockID else { return } - // Applies at once while this client owns the block, and otherwise - // waits server-side until it does — never a failure worth raising. - _ = try? await call( - RexWire.terminalCreator + ".resize", - RexWire.blockPayload( - sessionID: sessionID, blockID: blockID, - args: ["columns": cols, "rows": rows])) + guard phase == .live, let blockID else { return } + await sendSize(to: blockID) } /// Idempotent, and always closes the SSH connection the two pipes ride: /// a tab that ended on its own (`finish`) still has that link to drop. func close() async { - if !isClosed { - isClosed = true + if phase != .closed { + phase = .closed await teardown(failing: Failure("closed")) } await closeLink() @@ -592,9 +555,21 @@ actor RexSession: TerminalTransport { // MARK: - Requests - private func call( - _ method: String, _ payload: [String: Any]?, timeout: Double = 10 + /// How long the server gets to answer a request or reach a handshake + /// milestone. + private static let replyTimeout = Duration.seconds(10) + + /// One of the terminal's own methods (`com.superlogical.terminal.`) + /// on one block of this session. + private func terminalCall( + _ verb: String, block blockID: String, _ args: [String: Any] = [:] ) async throws -> [String: Any] { + try await call( + RexWire.terminalCreator + "." + verb, + RexWire.blockPayload(sessionID: sessionID, blockID: blockID, args: args)) + } + + private func call(_ method: String, _ payload: [String: Any]) async throws -> [String: Any] { guard let control else { throw Failure("not connected") } requestCount += 1 let id = "m\(requestCount)" @@ -602,7 +577,7 @@ actor RexSession: TerminalTransport { let reply: Reply = try await withCheckedThrowingContinuation { continuation in pending[id] = continuation timeouts[id] = Task { [weak self] in - do { try await Task.sleep(for: .seconds(timeout)) } catch { return } + do { try await Task.sleep(for: Self.replyTimeout) } catch { return } await self?.settle(id, .failure(Failure(String( localized: "The Rex server did not answer in time.")))) } @@ -624,10 +599,10 @@ actor RexSession: TerminalTransport { // MARK: - Milestones - private func wait(for milestone: Milestone, seconds: Double = 10) async throws { + private func wait(for milestone: Milestone) async throws { guard !reached.contains(milestone) else { return } let timer = Task { [weak self] in - do { try await Task.sleep(for: .seconds(seconds)) } catch { return } + do { try await Task.sleep(for: Self.replyTimeout) } catch { return } await self?.fail(milestone, Failure(String( localized: "The Rex server did not answer in time."))) } @@ -722,7 +697,7 @@ actor RexSession: TerminalTransport { guard generation == dataGeneration else { return } switch message { case .binary(let bytes): - guard var stream else { + guard stream != nil else { switch RexWire.parseDataReply(bytes) { case .welcome(let nonce)?: self.stream = RexTerminalStream(nonce: nonce) @@ -738,13 +713,14 @@ actor RexSession: TerminalTransport { } return } - let events = stream.consume(bytes) - self.stream = stream - if stream.isLive { reach(.live) } + // In place: a copy taken out and put back would share the + // stream's buffer and force it to be duplicated on every chunk. + let events = stream?.consume(bytes) ?? [] + if stream?.isLive == true { reach(.live) } for event in events { switch event { case .output(let output): - if isBootstrapped { deliver(output) } else { held.append(output) } + if held == nil { deliver(output) } else { held?.append(output) } case .resize, .childExited: // The size is this tab's own while it owns the block, // and a program's exit closes the block, which arrives @@ -778,8 +754,8 @@ actor RexSession: TerminalTransport { /// second, unrelated failure. During the attach the detail IS the /// reason ("no Rex server is running"), so it is kept. private func linkEnded(_ reason: String?, failed: Bool = false) { - guard !isClosed else { return } - guard isOpen else { + guard phase != .closed else { return } + guard phase == .live else { let failure = Failure(reason ?? String( localized: "The connection to the Rex server ended.")) for milestone in Array(waiters.keys) { fail(milestone, failure) } @@ -792,9 +768,11 @@ actor RexSession: TerminalTransport { } private func finish(_ reason: String?) { - guard !isClosed else { return } - isClosed = true - let notify = isOpen ? onClose : nil + guard phase != .closed else { return } + // Only a tab that went live has someone to tell; a failed attach + // is reported by `open` throwing. + let notify = phase == .live ? onClose : nil + phase = .closed Task { await self.teardown(failing: Failure(reason ?? "ended")) notify?(reason) diff --git a/Multiplex/Services/SSHConnection.swift b/Multiplex/Services/SSHConnection.swift index 927a42c9..7056da8c 100644 --- a/Multiplex/Services/SSHConnection.swift +++ b/Multiplex/Services/SSHConnection.swift @@ -995,8 +995,9 @@ private final class PipeWriter: @unchecked Sendable { } /// Resumes a continuation exactly once, from whichever side gets there first -/// (the PTY going live vs. the channel failing during setup). -private final class OneShotGate: @unchecked Sendable { +/// (the PTY going live vs. the channel failing during setup; a Rex socket's +/// upgrade completing vs. its pipe ending). +final class OneShotGate: @unchecked Sendable { private let lock = NSLock() private var continuation: CheckedContinuation? @@ -1012,7 +1013,7 @@ private final class OneShotGate: @unchecked Sendable { return taken } - /// PTY is live — resume the waiter. No-op if already resolved. + /// The channel is live — resume the waiter. No-op if already resolved. func open() { take()?.resume() } diff --git a/Multiplex/Services/TerminalSessionController.swift b/Multiplex/Services/TerminalSessionController.swift index b090243d..7338b5d7 100644 --- a/Multiplex/Services/TerminalSessionController.swift +++ b/Multiplex/Services/TerminalSessionController.swift @@ -72,12 +72,19 @@ final class TerminalSessionController { private var selectTextClampGeneration = 0 private var selectTextClampTask: Task? + /// Whether this tab's bytes ride mosh — THE transport question, asked + /// here by everything that depends on the answer (the run, scrollback, + /// FILE, the bar's MOSH badge). The host's preference, except on a Rex + /// tab: it has no PTY for mosh-server to run, so it rides SSH whatever + /// the host prefers. + var ridesMosh: Bool { host.useMosh && route.rexTarget == nil } + /// Local scrollback for this tab's terminal view; nil disables it. /// A transport capability, so it lives beside the transport choice: /// mosh syncs ONE live screen and anything archived above it is junk /// (stale frames from scroll-op diffs, resync resets, and resizes) — /// full record in docs/agents/mosh.md. - var localScrollbackLines: Int? { host.useMosh ? nil : 5000 } + var localScrollbackLines: Int? { ridesMosh ? nil : 5000 } /// The HISTORY surface: user prompts read from the agent's own session /// file on the host (see `AgentSessionHistory`). Present while the panel @@ -129,8 +136,10 @@ final class TerminalSessionController { /// windows — the adopting window re-parents this same view, so what's on /// screen survives a merge/split. Released with the controller on close. private(set) var terminalView: TerminalView? - /// The byte pipe under this tab — SSH PTY or mosh session. + /// The byte pipe under this tab — SSH PTY, mosh session, or Rex client. private var transport: (any TerminalTransport)? + /// The transport as the Rex client it is on a Rex tab; nil on any other. + private var rexSession: RexSession? { transport as? RexSession } /// The terminal a Rex tab was last switched to from its REX panel — /// preferred over the route's own block on the next transport run. private var rexBlockOverride: String? @@ -438,27 +447,19 @@ final class TerminalSessionController { generation: Int, output: TerminalOutputCoalescer ) async { - if let target = route.rexTarget { - // Before the mosh question: a Rex tab has no PTY for - // mosh-server to run, so it rides SSH whatever the host prefers. - await runRex( - sessionID: target.sessionID, - blockID: rexBlockOverride ?? target.blockID, - generation: generation, output: output) - } else if host.useMosh { + if ridesMosh { await runMosh(generation: generation, output: output) } else { await runSSH(generation: generation, output: output) } } - /// Rex: the tab's SSH connection carries no PTY at all — two byte pipes - /// to the Rex server instead, and `RexSession` speaking its protocol - /// over them. The connection stays this tab's exec surface, exactly as - /// on an SSH tab. - private func runRex( - sessionID: String, - blockID: String?, + /// The tab's own SSH connection, carrying one of two things: a PTY + /// running the route's remote command, or — on a Rex tab — no PTY at + /// all, just two byte pipes to the Rex server with `RexSession` + /// speaking its protocol over them. Either way the connection stays + /// this tab's exec surface. + private func runSSH( generation: Int, output: TerminalOutputCoalescer ) async { @@ -469,56 +470,74 @@ final class TerminalSessionController { await connection.close() return } - let session = RexSession( - connection: connection, - sessionID: sessionID, - blockID: blockID, - clientVersion: Bundle.main.object( - forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" - ) + let rex = route.rexTarget.map { target in + RexSession( + connection: connection, + sessionID: target.sessionID, + blockID: rexBlockOverride ?? target.blockID, + clientVersion: Bundle.main.object( + forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + ) + } + // Closing a Rex session closes the connection under it, so this is + // the one thing every exit below has to close. + let transport: any TerminalTransport = rex ?? connection self.connection = connection - transport = session + self.transport = transport do { try await connection.connect() try Task.checkCancellation() guard transportGeneration == generation, self.connection === connection else { - await session.close() + await transport.close() return } let openedSize = TerminalSize(cols: lastCols, rows: lastRows) - try await session.open( - cols: openedSize.cols, - rows: openedSize.rows, - onData: { data in - output.append(data) - }, - onClose: { [weak self] reason in - Task { @MainActor [weak self] in - self?.handleClose( - reason: reason, - generation: generation, - output: output - ) - } + let onData: @Sendable (Data) -> Void = { data in + output.append(data) + } + let onClose: @Sendable (String?) -> Void = { [weak self] reason in + Task { @MainActor [weak self] in + self?.handleClose( + reason: reason, + generation: generation, + output: output + ) } - ) + } + if let rex { + try await rex.open( + cols: openedSize.cols, rows: openedSize.rows, + onData: onData, onClose: onClose) + } else { + // Armed before the PTY opens so the first output chunk is + // already scanned; an rc-time oh-my-zsh update prompt + // swallows the injected handoff line and needs a re-type + // (ShellHandoff). + handoffWatch = route.remoteCommand == nil + ? nil + : ShellHandoff.UpdatePromptWatch() + try await connection.openShell( + command: route.remoteCommand, + cols: openedSize.cols, rows: openedSize.rows, + onData: onData, onClose: onClose) + } try Task.checkCancellation() guard transportGeneration == generation, self.connection === connection else { - await session.close() + await transport.close() return } - startTransportPumps(for: session, openedAt: openedSize) + startTransportPumps(for: transport, openedAt: openedSize) markLive() + startDirectShellMonitoring() #if DEBUG - debugAutoSwitchRexTerminal() + if rex != nil { debugAutoSwitchRexTerminal() } #endif } catch { - // Closes the SSH connection too — the session owns that link. - await session.close() + await transport.close() guard transportGeneration == generation, self.connection === connection else { return } @@ -528,79 +547,7 @@ final class TerminalSessionController { ?? String(localized: "Couldn't reach \(host.name). \(error.localizedDescription)") status = .ended(message) self.connection = nil - transport = nil - outputCoalescer = nil - considerAutomaticResume() - } - } - - private func runSSH( - generation: Int, - output: TerminalOutputCoalescer - ) async { - let secrets = await HostSecrets.loadOffMain(for: host) - guard transportGeneration == generation, !Task.isCancelled else { return } - let connection = SSHConnection(host: host, secrets: secrets) - guard transportGeneration == generation else { - await connection.close() - return - } - self.connection = connection - transport = connection - do { - try await connection.connect() - try Task.checkCancellation() - guard transportGeneration == generation, - self.connection === connection - else { - await connection.close() - return - } - let openedSize = TerminalSize(cols: lastCols, rows: lastRows) - // Armed before the PTY opens so the first output chunk is already - // scanned; an rc-time oh-my-zsh update prompt swallows the - // injected handoff line and needs a re-type (ShellHandoff). - handoffWatch = route.remoteCommand == nil - ? nil - : ShellHandoff.UpdatePromptWatch() - try await connection.openShell( - command: route.remoteCommand, - cols: openedSize.cols, - rows: openedSize.rows, - onData: { data in - output.append(data) - }, - onClose: { [weak self] reason in - Task { @MainActor [weak self] in - self?.handleClose( - reason: reason, - generation: generation, - output: output - ) - } - } - ) - try Task.checkCancellation() - guard transportGeneration == generation, - self.connection === connection - else { - await connection.close() - return - } - startTransportPumps(for: connection, openedAt: openedSize) - markLive() - startDirectShellMonitoring() - } catch { - await connection.close() - guard transportGeneration == generation, - self.connection === connection - else { return } - captureKeyPassphraseChallenge(from: error) - let message = (error as? SSHConnectionError)?.userMessage(host: host) - ?? String(localized: "Couldn't reach \(host.name). \(error.localizedDescription)") - status = .ended(message) - self.connection = nil - transport = nil + self.transport = nil outputCoalescer = nil handoffWatch = nil considerAutomaticResume() @@ -1100,15 +1047,16 @@ final class TerminalSessionController { else { return } selectTextClampGeneration &+= 1 let generation = selectTextClampGeneration - // A Rex tab shows exactly one terminal block, so there are no - // sibling panes to clamp a selection to, and no pane-rect query to - // make. The `.rex` arms below keep these switches total. - guard backend != .rex else { return } - let command = switch backend { + // nil where there is no pane-rect query to make: a Rex tab shows + // exactly one terminal block, so a selection has no sibling panes + // to be clamped away from. (The `.rex` arms further down only keep + // those switches total.) + let command: String? = switch backend { case .tmux: TmuxProbe.paneRectsCommand(sessionName: sessionName) case .herdr: HerdrProbe.snapshotCommand(sessionName: sessionName) - case .rex: ":" + case .rex: nil } + guard let command else { return } // Cancellation ends a superseded fetch at its next sleep — resize // re-enters here on every keyboard show/hide, and the generation // check alone would let each stale task finish its execs first. @@ -1289,8 +1237,8 @@ final class TerminalSessionController { /// The REX panel's Switch Terminal rows: every terminal of this tab's /// session, asked of the server over the tab's own control connection. func loadRexTerminalList() async -> [TmuxWindowChoice]? { - guard status == .live, let session = transport as? RexSession else { return nil } - return await session.terminalChoices() + guard status == .live, let rexSession else { return nil } + return await rexSession.terminalChoices() } /// Point this tab at another terminal of its session, in place. Unlike @@ -1300,9 +1248,9 @@ final class TerminalSessionController { /// back to the terminal the user was on, not the one the tab opened /// with. func selectRexTerminal(_ choice: TmuxWindowChoice) { - guard status == .live, let session = transport as? RexSession else { return } + guard status == .live, let rexSession else { return } rexBlockOverride = choice.tmuxID - Task { await session.switchBlock(to: choice.tmuxID) } + Task { await rexSession.switchBlock(to: choice.tmuxID) } } /// The shortcut panel's window list, read through the control path so @@ -1883,7 +1831,7 @@ final class TerminalSessionController { /// foreground cwd could be resolved. The chrome's FILE rule and the /// Talkback paperclip both read this. var canUploadFiles: Bool { - !host.useMosh && route.sessionBackend != nil + !ridesMosh && route.sessionBackend != nil } static let uploadUnavailableMessage = @@ -2059,7 +2007,7 @@ final class TerminalSessionController { // Rex answers over the tab's own control connection rather than // an exec, and — like herdr — hands the path home as data, so // the corral check is its own exec with it respliced. - guard let cwd = await (transport as? RexSession)?.workingDirectory() + guard let cwd = await rexSession?.workingDirectory() else { return (nil, false) } let check = (try? await connection.exec( TmuxProbe.gitWorktreeCheckCommand(directory: cwd) @@ -2394,7 +2342,7 @@ final class TerminalSessionController { ) case .rex: // One tab is one terminal, so the pressed cell is always its. - return await (transport as? RexSession)?.workingDirectory() + return await rexSession?.workingDirectory() case nil: return nil } diff --git a/Multiplex/Services/TmuxProbe.swift b/Multiplex/Services/TmuxProbe.swift index 8e5a9af6..bfa5d32c 100644 --- a/Multiplex/Services/TmuxProbe.swift +++ b/Multiplex/Services/TmuxProbe.swift @@ -1017,7 +1017,7 @@ enum TmuxProbe { /// Lines a tile shows; the parser keeps the trailing non-blank run. static let miniatureLines = 4 /// Scrollback depth requested per session. - private static let captureDepth = 30 + static let captureDepth = 30 /// Tile width clip — anything longer can't render in a tile anyway. private static let miniatureWidth = 56 diff --git a/Multiplex/Services/WidgetStatePublisher.swift b/Multiplex/Services/WidgetStatePublisher.swift index daa61fc6..8b5e19cf 100644 --- a/Multiplex/Services/WidgetStatePublisher.swift +++ b/Multiplex/Services/WidgetStatePublisher.swift @@ -105,10 +105,7 @@ enum WidgetStateBuilder { lastAttached: SessionKey?, miniatureLines: (TmuxSession) -> [String] ) -> WidgetHostState { - // A widget row is a session to OPEN and a pick list is where a NEW - // session can run; both are every monitored backend's. - let qualifiesBackend = host.showsBackendIdentity - return WidgetHostState( + WidgetHostState( id: host.id, name: host.name, address: host.address, @@ -119,7 +116,7 @@ enum WidgetStateBuilder { // Rows carry a backend only where it disambiguates. On // a single-backend host nil keeps every row — and every // link built from one — byte-identical to before. - qualifiesBackend: qualifiesBackend + qualifiesBackend: host.showsBackendIdentity ) }, probedAt: probedAt, @@ -133,7 +130,7 @@ enum WidgetStateBuilder { lastAttached: lastAttached.map { WidgetSessionRef( name: $0.name, - backendRaw: qualifiesBackend ? $0.backend.rawValue : nil + backendRaw: host.showsBackendIdentity ? $0.backend.rawValue : nil ) } ) diff --git a/Multiplex/Views/Deck/FleetWall.swift b/Multiplex/Views/Deck/FleetWall.swift index b829ebc8..79d9ee3b 100644 --- a/Multiplex/Views/Deck/FleetWall.swift +++ b/Multiplex/Views/Deck/FleetWall.swift @@ -678,21 +678,14 @@ final class FleetWallViewController: UIViewController { self?.focusOrAttach(host, session: session) }, openDuplicateSession: { [weak self] session in - guard let mode = TerminalRoute.Mode.attach(host: host, session: session) - else { - self?.presentCannotOpen(session, on: host) - return - } - self?.open(TerminalRoute(hostID: host.id, mode: mode)) + self?.open( + TerminalRoute.Mode.attach(host: host, session: session), + of: session, on: host) }, openSessionPane: { [weak self] session, window, pane in - guard let mode = RexProbe.attachMode( - session: session, window: window, pane: pane) - else { - self?.presentCannotOpen(session, on: host) - return - } - self?.open(TerminalRoute(hostID: host.id, mode: mode)) + self?.open( + TerminalRoute.Mode.attach(session: session, window: window, pane: pane), + of: session, on: host) }, requestNewSession: { [weak self] in self?.presentNewSession(on: host) }, requestNewHerdrTab: { [weak self] session in @@ -755,8 +748,8 @@ final class FleetWallViewController: UIViewController { /// press that changes what a host COSTS to monitor, and the copy states /// that plainly rather than letting the deck quietly get more expensive. private func confirmBackendOffer(_ backend: Host.SessionBackend, for host: Host) { - let name = backend.rawValue - let primary = host.sessionBackend.rawValue + let name = backend.displayName + let primary = host.sessionBackend.displayName var message = String(localized: """ \(host.name) is running \(name) as well as \(primary). \ Showing both \(HostGuide.secondBackendCost). @@ -909,7 +902,13 @@ final class FleetWallViewController: UIViewController { ) { return } - guard let mode = TerminalRoute.Mode.attach(host: host, session: session) else { + open(TerminalRoute.Mode.attach(host: host, session: session), of: session, on: host) + } + + /// Opens `session` in `mode`, or says why it cannot be opened when the + /// record had no mode to offer. + private func open(_ mode: TerminalRoute.Mode?, of session: TmuxSession, on host: Host) { + guard let mode else { presentCannotOpen(session, on: host) return } @@ -993,15 +992,7 @@ final class FleetWallViewController: UIViewController { private func presentCreateSessionFailure( on host: Host, model: HostConnectionModel ) { - let message: String - if let failure = model.sessionCreateFailure { - message = failure.message(hostName: host.name) - } else if case .failed(let reason) = model.phase { - message = reason - } else { - message = String( - localized: "Couldn't create the session on \(host.name).") - } + let message = model.sessionCreateFailureMessage(hostName: host.name) let alert = UIAlertController( title: String(localized: "Couldn't Create Session"), message: message, diff --git a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift index 0e3be043..63f31fa4 100644 --- a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift @@ -239,7 +239,7 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg bareChrome: configuration.bareChrome, keyRailHidden: configuration.keyRailHidden, isActive: configuration.isActive && configuration.focusAllowed, - shortcutBackend: configuration.controller?.route.shortcutBackend, + shortcutBackend: configuration.controller?.route.sessionBackend, keyCommandPlan: configuration.keyCommandPlan ) } diff --git a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift index a48207d5..9ece2795 100644 --- a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift @@ -1845,6 +1845,27 @@ final class TerminalWindowViewController: UIViewController, if agentChanged { renderNow() } await model.refreshAndWait(ifStaleFor: 4) + // The wall probe's verdict, as it stands now. All a backend with + // no focused-pane query ever has, and what an unfocused herdr + // window goes by between its own checks. + func followWallVerdict() { + let nextAgent = detectedAgent + if shownAgent != nextAgent { + hideAgentTask?.cancel() + shownAgent = nextAgent + renderNow() + } + } + + guard backend.hasFocusedPaneProbe else { + while !Task.isCancelled { + guard activeTab?.id == watchedTab.id else { return } + if UIApplication.shared.applicationState == .active { followWallVerdict() } + try? await Task.sleep(for: Self.focusedPaneProbeInterval) + } + return + } + if backend == .herdr { // The five-second wall probe remains the broad session/attention // authority. Between ticks, the one terminal that owns keyboard @@ -1867,12 +1888,7 @@ final class TerminalWindowViewController: UIViewController, if let detection { apply(detection) } } } else if UIApplication.shared.applicationState == .active { - let nextAgent = detectedAgent - if shownAgent != nextAgent { - hideAgentTask?.cancel() - shownAgent = nextAgent - renderNow() - } + followWallVerdict() } try? await Task.sleep(for: Self.focusedPaneProbeInterval) } @@ -2929,7 +2945,7 @@ extension TerminalWindowViewController { } : nil, fullScreenActive: fullScreenColumn, extraNewTabTarget: extraNewTabTarget, - shortcutBackend: activeTab?.shortcutBackend, + shortcutBackend: activeTab?.sessionBackend, style: vertical ? .verticalColumn : profile.style, deckControl: shell?.deckControl ?? .back, availableWidth: vertical ? column.width : umdAvailableWidth, diff --git a/Multiplex/Views/Terminal/UMDBarUIKit.swift b/Multiplex/Views/Terminal/UMDBarUIKit.swift index f580072a..5f7a9253 100644 --- a/Multiplex/Views/Terminal/UMDBarUIKit.swift +++ b/Multiplex/Views/Terminal/UMDBarUIKit.swift @@ -875,7 +875,7 @@ final class UMDBarViewController: UIViewController, private func statusCluster(_ state: UMDBarObservedState) -> UIView { var views: [UIView] = [] - if configuration.controller?.host.useMosh == true { + if configuration.controller?.ridesMosh == true { let mosh = UMDStateBadgeView( caption: "MOSH", accessibilityLabel: String(localized: "Connects over mosh") diff --git a/MultiplexTests/RexProbeTests.swift b/MultiplexTests/RexProbeTests.swift index b2ad185a..000741a7 100644 --- a/MultiplexTests/RexProbeTests.swift +++ b/MultiplexTests/RexProbeTests.swift @@ -284,7 +284,6 @@ final class RexProbeTests: XCTestCase { """)) let session = try XCTUnwrap(try sessions(probe).first) XCTAssertEqual(session.clientCount, 2) - XCTAssertTrue(Host.SessionBackend.rex.reportsClientCount) XCTAssertTrue(Host.SessionBackend.rex.isSessionLive( clientCount: session.clientCount, hasOpenTab: false)) // This app attaches as kind `other`, so its own tab is not in that @@ -329,8 +328,8 @@ final class RexProbeTests: XCTestCase { XCTAssertNil(RexProbe.killCommand(for: session)) session.tmuxID = "session:x; rm -rf ~" XCTAssertNil(RexProbe.killCommand(for: session)) - XCTAssertFalse(RexProbe.bakeableSessionID("work")) - XCTAssertFalse(RexProbe.bakeableSessionID("session:")) + XCTAssertFalse(RexWire.bakeableSessionID("work")) + XCTAssertFalse(RexWire.bakeableSessionID("session:")) } // MARK: Discovery @@ -452,13 +451,13 @@ final class RexProbeTests: XCTestCase { XCTAssertNil(route.moshRemoteCommand) XCTAssertFalse(route.usesTmux) // Its rail key opens the REX panel — never a TMUX one. - XCTAssertEqual(route.shortcutBackend, .rex) + XCTAssertEqual(route.sessionBackend, .rex) XCTAssertEqual(Host.SessionBackend.rex.shortcutKeyCaption, "REX") XCTAssertEqual(Host.SessionBackend.tmux.shortcutKeyCaption, "TMUX") XCTAssertEqual(Host.SessionBackend.herdr.shortcutKeyCaption, "HRDR") // The panel has no shortcut rows (Rex has no prefix-key client), // only the list that switches the tab's terminal. - let panel = ShortcutPanelContent.content(for: route.shortcutBackend) + let panel = ShortcutPanelContent.content(for: route.sessionBackend) XCTAssertEqual(panel, .rex) XCTAssertEqual(panel?.sections, []) XCTAssertEqual(panel?.switchSectionTitle, "Switch Terminal") @@ -504,7 +503,7 @@ final class RexProbeTests: XCTestCase { let window = session.windows[0] let pane = try XCTUnwrap(window.panes?.last) let mode = try XCTUnwrap( - RexProbe.attachMode(session: session, window: window, pane: pane)) + TerminalRoute.Mode.attach(session: session, window: window, pane: pane)) let route = TerminalRoute(hostID: UUID(), mode: mode) XCTAssertEqual(route.rexTarget?.sessionID, session.tmuxID) XCTAssertEqual(route.rexTarget?.blockID, "block:01a1e1e3-4810-7831-92b7-22087aff9bc8") diff --git a/MultiplexTests/RexSessionTests.swift b/MultiplexTests/RexSessionTests.swift index 3819dacf..56cd2aed 100644 --- a/MultiplexTests/RexSessionTests.swift +++ b/MultiplexTests/RexSessionTests.swift @@ -40,6 +40,13 @@ final class RexSessionTests: XCTestCase { ) } + /// The two reads a screen is drawn from, sorted. They share a round + /// trip, so which the server sees first is not the session's to say. + private static let screenReads = [ + "com.superlogical.terminal.format", + "com.superlogical.terminal.modes", + ] + private func eventually( _ condition: @escaping () -> Bool, file: StaticString = #filePath, line: UInt = #line ) async { @@ -57,16 +64,15 @@ final class RexSessionTests: XCTestCase { let sink = Sink() try await open(session, sink: sink) - XCTAssertEqual(server.calls, [ + XCTAssertEqual(Array(server.calls.prefix(4)), [ "session.attach", // Claim and size FIRST: the rendering and the stream below must // describe the terminal at this tab's size. "session.own_block", "com.superlogical.terminal.resize 100x30", "data.connect", - "com.superlogical.terminal.modes", - "com.superlogical.terminal.format", ]) + XCTAssertEqual(server.calls.dropFirst(4).sorted(), Self.screenReads) // The hello never claims to be an app (see `RexWire.hello`). XCTAssertEqual(server.helloKind, "other") // The fronted block was chosen: active window, focused block. @@ -136,14 +142,14 @@ final class RexSessionTests: XCTestCase { // the new one claimed, sized, streamed and drawn — the attach's own // order, on the same control connection. XCTAssertEqual(server.closeFramesReceived, [RexWire.dataPath]) - XCTAssertEqual(Array(server.calls.dropFirst(attachCalls)), [ + let switchCalls = Array(server.calls.dropFirst(attachCalls)) + XCTAssertEqual(Array(switchCalls.prefix(4)), [ "session.disown_block block:front", "session.own_block", "com.superlogical.terminal.resize 100x30", "data.connect", - "com.superlogical.terminal.modes", - "com.superlogical.terminal.format", ]) + XCTAssertEqual(switchCalls.dropFirst(4).sorted(), Self.screenReads) XCTAssertEqual(server.attachedBlock, "block:other") XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "\u{1B}cOTHER"]) // The retired stream ending is NOT the tab ending. @@ -154,7 +160,10 @@ final class RexSessionTests: XCTestCase { server.sendOutput("from other\r\n") await eventually { sink.text.last == "from other\r\n" } try await session.write(Data("x".utf8)) - XCTAssertEqual(server.written, ["x"]) + await eventually { + server.written == ["x"] + && server.calls.last == "com.superlogical.terminal.write" + } XCTAssertEqual(server.lastWriteBlock, "block:other") let listed = await session.terminalChoices() let choices = try XCTUnwrap(listed) @@ -195,13 +204,38 @@ final class RexSessionTests: XCTestCase { try await session.write(wide.prefix(2)) try await session.write(wide.suffix(1)) try await session.write(Data([0x1B, 0x5B, 0x41])) - XCTAssertEqual(server.written, ["ls\r", "測", "\u{1B}[A"]) + // A write queues and returns, so how the four were grouped into + // calls is timing. What is not: every byte once, in order, and no + // call carrying half a character. + await eventually { server.written.joined() == "ls\r測\u{1B}[A" } + XCTAssertFalse(server.written.contains { $0.contains("\u{FFFD}") }) try await session.resize(cols: 120, rows: 40) XCTAssertEqual(server.calls.last, "com.superlogical.terminal.resize 120x40") await session.close() } + func testWhatIsTypedWhileAWriteIsInFlightRidesTheNextOneTogether() async throws { + let server = FakeRexServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + + // The server sits on its answers, as a slow link does. + server.holdWriteReplies() + try await session.write(Data("a".utf8)) + await eventually { server.written == ["a"] } + // None of these waits for "a" to be answered... + try await session.write(Data("b".utf8)) + try await session.write(Data("c".utf8)) + try await session.write(Data("d".utf8)) + XCTAssertEqual(server.written, ["a"]) + + // ...and once it is, they go as one call, not three round trips. + server.releaseWriteReplies() + await eventually { server.written == ["a", "bcd"] } + await session.close() + } + func testTypingClaimsTheBlockBackAfterAnotherClientTookIt() async throws { let server = FakeRexServer() let session = makeSession(server) @@ -210,6 +244,7 @@ final class RexSessionTests: XCTestCase { // While this tab owns the block, typing claims nothing. try await session.write(Data("a".utf8)) + await eventually { server.written == ["a"] } XCTAssertEqual(server.calls.filter { $0 == "session.own_block" }.count, before) // The Rex app takes the block; the next keystroke takes it back and @@ -218,6 +253,10 @@ final class RexSessionTests: XCTestCase { await eventually { server.eventsDelivered == 1 } try await Task.sleep(for: .milliseconds(150)) try await session.write(Data("b".utf8)) + await eventually { + server.written == ["a", "b"] + && server.calls.last == "com.superlogical.terminal.write" + } XCTAssertEqual(server.calls.filter { $0 == "session.own_block" }.count, before + 1) XCTAssertEqual(server.calls.suffix(3), [ "session.own_block", @@ -411,6 +450,9 @@ private final class FakeRexServer: @unchecked Sendable { private var events = 0 private var controlFeed: AsyncThrowingStream.Continuation? private var dataFeed: AsyncThrowingStream.Continuation? + /// nil while write calls are answered as they arrive; otherwise the + /// answers a test is sitting on. + private var heldWriteReplies: [() -> Void]? // What a test configures before the attach. var attachError: [String: Any]? @@ -462,6 +504,20 @@ private final class FakeRexServer: @unchecked Sendable { feeds.forEach { $0?.finish(throwing: error) } } + /// Write calls are recorded as they arrive but go unanswered until + /// `releaseWriteReplies` — a link slow enough to type ahead of. + func holdWriteReplies() { + lock.withLock { heldWriteReplies = [] } + } + + func releaseWriteReplies() { + let held = lock.withLock { + defer { heldWriteReplies = nil } + return heldWriteReplies ?? [] + } + held.forEach { $0() } + } + func announceOwner(_ owner: String) { let event: [String: Any] = [ "type": "event", "seq": 9, @@ -624,7 +680,13 @@ private final class FakeRexServer: @unchecked Sendable { server.lock.withLock { server.recordedCalls.append(record) } var response: [String: Any] = ["type": "response", "id": id, "seq": 0] if let error { response["error"] = error } else { response["payload"] = result } - send(response) + let reply = response + let isHeld = method == "com.superlogical.terminal.write" && server.lock.withLock { + guard server.heldWriteReplies != nil else { return false } + server.heldWriteReplies?.append { [self] in send(reply) } + return true + } + if !isHeld { send(response) } } private func view() -> [String: Any] { diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index ca5213fa..eeefdb1a 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -482,7 +482,8 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. - **Attach order is load-bearing** (`RexSession.attach`): hello → `session.attach` → **`own_block(take)` + `resize` first** → `data .connect` → data HELLO/WELCOME → wait for the first server message → - `modes` + `format(vt)` → RIS + rendering → flush the held stream. + `modes` + `format(vt)` (two reads, asked together) → RIS + rendering → + flush the held stream. - ⚠ **The stream opens with a Ghostty binary snapshot (`GHOSTSNP…`) SwiftTerm cannot read.** `RexTerminalStream` DROPS it: its length is stated nowhere, but a `resize` message "comes @@ -518,6 +519,12 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. out of order; whatever is typed meanwhile rides the next call as one string. Its argument is JSON text, so `RexInputEncoder` holds a split multi-byte character and replaces bytes that are not UTF-8. + ⚠ `RexSession.write` QUEUES AND RETURNS; a drain task makes the calls. + The tab's input pump awaits each `transport.write`, so a write that + waited for the server's answer (the first shape) made every keystroke + its own round trip, queued behind the last, and the "rides the next + call" batching never happened — an SSH PTY write only enqueues bytes, + which is why the pump never had to care. - **The last client to type owns the size** (tmux's latest-client rule): the Rex app can claim the block back (`block_owner_changed`); the next keystroke here claims and re-sizes it. Until then the tab @@ -543,9 +550,13 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. 60 s resume window; the fresh attach is a new client beside it. - What a Rex tab does not have: a prefix-key list (the REX panel only switches terminals), Copy Mode, HISTORY, the one-second helper-chip - probe (`detectActiveAgent` answers nil; the wall probe's record still - does), and mosh (no PTY for mosh-server to run — a Rex tab rides SSH - whatever the host prefers). + probe (`SessionBackend.hasFocusedPaneProbe` is false, so the chips + follow the wall probe's record instead of polling for an answer that + is always nil), and mosh (no PTY for mosh-server to run — a Rex tab + rides SSH whatever the host prefers). ⚠ `TerminalSessionController + .ridesMosh` is the one statement of that last rule: scrollback, FILE + and the bar's MOSH badge read it, where reading `host.useMosh` raw + gave a Rex tab on a mosh host no scrollback, no FILE and a MOSH badge. - Deliberately NOT built, with the reason each would need new facts to reopen: - **Drawing a window's splits.** Every terminal in a split needs its From 0fd4b72d1204f762de930df5fb5269c4d22aafdd Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Mon, 16 Nov 2026 13:44:10 +0800 Subject: [PATCH 04/13] Show a Rex tab's agent bar for its own terminal The agent bar read the session's fronted pane (`activeAgent`). That is right for a tmux or herdr tab, which shows the whole session, and wrong for a Rex tab, which is one terminal: the bar left a tab still showing Claude Code as soon as the Rex app fronted another window, and never appeared on a tab opened or switched to a terminal that was not in front. A Rex tab now asks for the agent in the terminal it is showing (`TmuxSession.agent(inPane:)`), and finds its session by id rather than by a label another session can take. The controller learns the terminal when the attach settles on one (`rexBlockID`, which replaces the switch-only override), so a reconnect returns to it as well. This takes back part of the previous commit. The bar already followed the wall probe through the window's own observation, with its grace before hiding; the loop added for backends with no focused-pane query duplicated that and skipped the grace. Such a backend now runs no loop. Reproduced and checked on the Vision Pro simulator against a throwaway Rex server running a real `claude`: with another window fronted in Rex, a tab on the agent's terminal keeps its bar; a tab on a plain terminal shows none and gains it when switched to the agent's. --- Multiplex/Models/Host.swift | 3 +- Multiplex/Models/TmuxModels.swift | 12 +++++ .../Services/TerminalSessionController.swift | 17 +++++-- .../Views/Terminal/TerminalWindowUIKit.swift | 50 +++++++++---------- MultiplexTests/RexProbeTests.swift | 21 ++++++++ docs/agents/backends-and-probe.md | 36 ++++++++++--- fastlane/testflight-whats-new.txt | 1 + 7 files changed, 100 insertions(+), 40 deletions(-) diff --git a/Multiplex/Models/Host.swift b/Multiplex/Models/Host.swift index 722ccbc0..d173a07e 100644 --- a/Multiplex/Models/Host.swift +++ b/Multiplex/Models/Host.swift @@ -73,7 +73,8 @@ struct Host: Identifiable, Codable, Hashable { /// Whether one exec can say which pane of a session is in front /// and what runs in it — the helper chips' fast path between wall /// probes. A Rex tab's terminal was chosen at attach and there is - /// no such query to make; the wall probe's record answers alone. + /// no such query to make; the wall probe's record answers alone, + /// for that terminal (`TmuxSession.agent(inPane:)`). var hasFocusedPaneProbe: Bool { switch self { case .tmux, .herdr: true diff --git a/Multiplex/Models/TmuxModels.swift b/Multiplex/Models/TmuxModels.swift index 7c3569c3..3450e49d 100644 --- a/Multiplex/Models/TmuxModels.swift +++ b/Multiplex/Models/TmuxModels.swift @@ -188,6 +188,18 @@ struct TmuxSession: Identifiable, Hashable, Codable { var activeAgent: AgentKind? { activeWindow?.activeAgent } + /// The agent a tab's helper strip speaks for. A tab that shows the + /// whole session (tmux, herdr) follows `activeAgent`: its multiplexer + /// draws whichever pane is in front. A tab that IS one pane — a Rex tab + /// is one terminal — names it, and gets that pane's agent wherever the + /// session's focus has gone since: the Rex app fronting another window + /// must not take the strip off a tab still showing the agent. A named + /// pane the record does not list has no agent to report. + func agent(inPane paneID: String?) -> AgentKind? { + guard let paneID else { return activeAgent } + return windows.lazy.flatMap { $0.panes ?? [] } + .first { $0.tmuxID == paneID }?.agent + } /// Every detected agent pane, including background splits and inactive /// windows. FleetWall uses this broader view; helper chips intentionally /// continue to use `activeAgent`. diff --git a/Multiplex/Services/TerminalSessionController.swift b/Multiplex/Services/TerminalSessionController.swift index 7338b5d7..097364ca 100644 --- a/Multiplex/Services/TerminalSessionController.swift +++ b/Multiplex/Services/TerminalSessionController.swift @@ -140,9 +140,13 @@ final class TerminalSessionController { private var transport: (any TerminalTransport)? /// The transport as the Rex client it is on a Rex tab; nil on any other. private var rexSession: RexSession? { transport as? RexSession } - /// The terminal a Rex tab was last switched to from its REX panel — - /// preferred over the route's own block on the next transport run. - private var rexBlockOverride: String? + /// The terminal a Rex tab is showing: learned when the attach settles + /// on one, changed by its REX panel's Switch Terminal. nil until then, + /// and on every other kind of tab. Two readers: the next transport run + /// prefers it over the route's own block, so a reconnect comes back to + /// the terminal the user was on; and the window reads the tab's agent + /// from it — the session's fronted terminal is somebody else's choice. + private(set) var rexBlockID: String? /// SSH path only: the exec/SFTP surface (pane cwd, file drops). nil on /// mosh tabs — their bootstrap SSH connection is transient by design. private var connection: SSHConnection? @@ -474,7 +478,7 @@ final class TerminalSessionController { RexSession( connection: connection, sessionID: target.sessionID, - blockID: rexBlockOverride ?? target.blockID, + blockID: rexBlockID ?? target.blockID, clientVersion: Bundle.main.object( forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" ) @@ -510,6 +514,9 @@ final class TerminalSessionController { try await rex.open( cols: openedSize.cols, rows: openedSize.rows, onData: onData, onClose: onClose) + // Which terminal an unnamed attach landed on is the + // session's answer, known only now. + rexBlockID = await rex.blockID ?? rexBlockID } else { // Armed before the PTY opens so the first output chunk is // already scanned; an rc-time oh-my-zsh update prompt @@ -1249,7 +1256,7 @@ final class TerminalSessionController { /// with. func selectRexTerminal(_ choice: TmuxWindowChoice) { guard status == .live, let rexSession else { return } - rexBlockOverride = choice.tmuxID + rexBlockID = choice.tmuxID Task { await rexSession.switchBlock(to: choice.tmuxID) } } diff --git a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift index 9ece2795..7084cfcc 100644 --- a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift @@ -997,15 +997,23 @@ final class TerminalWindowViewController: UIViewController, let backend = activeTab.sessionBackend, host.monitors(backend) else { return nil } - let model = hub.model(for: host) - // One expression serves both backends on purpose: a herdr tile IS + let sessions = hub.model(for: host).sessions(on: backend) + // A Rex tab is ONE terminal of its session, and not necessarily the + // one the session is fronting — Open Terminal, Switch Terminal, or + // the Rex app showing another window — so the strip is that + // terminal's (`TmuxSession.agent(inPane:)`). Found by id: a Rex + // label is not an identity, and is respelled when another session + // takes the same one. + if let rex = activeTab.rexTarget { + return sessions.first { $0.tmuxID == rex.sessionID }? + .agent(inPane: activeController?.rexBlockID ?? rex.blockID) + } + // One expression serves tmux and herdr on purpose: a herdr tile IS // a whole session, and the probe writes its live focus into the // record (active window = focused workspace, active pane = the // session's one focus every client mirrors) — so following // `activeAgent` follows a workspace switch inside the TUI too. - return model.sessions(on: backend) - .first { $0.name == sessionName }? - .activeAgent + return sessions.first { $0.name == sessionName }?.activeAgent } private var resolvedTerminalTheme: TerminalTheme { // Prefer the pinned choice over the live traits: the observation @@ -1845,26 +1853,11 @@ final class TerminalWindowViewController: UIViewController, if agentChanged { renderNow() } await model.refreshAndWait(ifStaleFor: 4) - // The wall probe's verdict, as it stands now. All a backend with - // no focused-pane query ever has, and what an unfocused herdr - // window goes by between its own checks. - func followWallVerdict() { - let nextAgent = detectedAgent - if shownAgent != nextAgent { - hideAgentTask?.cancel() - shownAgent = nextAgent - renderNow() - } - } - - guard backend.hasFocusedPaneProbe else { - while !Task.isCancelled { - guard activeTab?.id == watchedTab.id else { return } - if UIApplication.shared.applicationState == .active { followWallVerdict() } - try? await Task.sleep(for: Self.focusedPaneProbeInterval) - } - return - } + // No fast path to run between wall probes: the wall's record is the + // only authority, and it already reaches the strip through the + // render's own observation of `detectedAgent` (with its grace + // before hiding). Polling here would ask a question with no answer. + guard backend.hasFocusedPaneProbe else { return } if backend == .herdr { // The five-second wall probe remains the broad session/attention @@ -1888,7 +1881,12 @@ final class TerminalWindowViewController: UIViewController, if let detection { apply(detection) } } } else if UIApplication.shared.applicationState == .active { - followWallVerdict() + let nextAgent = detectedAgent + if shownAgent != nextAgent { + hideAgentTask?.cancel() + shownAgent = nextAgent + renderNow() + } } try? await Task.sleep(for: Self.focusedPaneProbeInterval) } diff --git a/MultiplexTests/RexProbeTests.swift b/MultiplexTests/RexProbeTests.swift index 000741a7..92c952c8 100644 --- a/MultiplexTests/RexProbeTests.swift +++ b/MultiplexTests/RexProbeTests.swift @@ -491,6 +491,27 @@ final class RexProbeTests: XCTestCase { legacy, .rexAttach(sessionName: "api", sessionID: "session:0000-aaaaaa")) } + func testATabsAgentIsItsOwnTerminalsNotTheOneTheSessionFronts() throws { + let session = try XCTUnwrap( + try sessions(RexProbe.parseProbe(try fixture())).first) + // The session is fronting its editor window, where no agent runs; + // the agent is in another window. + XCTAssertNil(session.activeAgent) + let agentPane = try XCTUnwrap(session.windows[1].panes?.first) + // A tab on the agent's terminal speaks for the agent, whatever the + // Rex app is showing (seen live: fronting another window took the + // strip off a tab that was still on Claude Code). + XCTAssertEqual(session.agent(inPane: agentPane.tmuxID), .claudeCode) + // A tab on a plain terminal of the same session speaks for none. + let logsPane = try XCTUnwrap(session.windows[0].panes?.last) + XCTAssertNil(session.agent(inPane: logsPane.tmuxID)) + // A tab that names no terminal shows the whole session and follows + // its focus — tmux and herdr. + XCTAssertEqual(session.agent(inPane: nil), session.activeAgent) + // A terminal the record does not list has nothing to report. + XCTAssertNil(session.agent(inPane: "block:gone")) + } + func testOpenTerminalNamesEachTerminalAndTargetsItsBlock() throws { let session = try XCTUnwrap( try sessions(RexProbe.parseProbe(try fixture())).first) diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index eeefdb1a..d3deefaf 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -445,7 +445,7 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. tab's. Each data stream carries a generation (`dataGeneration`): the old stream's end must not read as the tab ending, and input typed during the switch is dropped rather than sent to whichever block wins. - The choice survives a reconnect (`rexBlockOverride`). The rail key's + The choice survives a reconnect (`rexBlockID`). The rail key's face comes from `SessionBackend.shortcutKeyCaption` — the three `herdr ? "HRDR" : "TMUX"` sites it replaced drew a TMUX key on a Rex tab. @@ -550,13 +550,33 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. 60 s resume window; the fresh attach is a new client beside it. - What a Rex tab does not have: a prefix-key list (the REX panel only switches terminals), Copy Mode, HISTORY, the one-second helper-chip - probe (`SessionBackend.hasFocusedPaneProbe` is false, so the chips - follow the wall probe's record instead of polling for an answer that - is always nil), and mosh (no PTY for mosh-server to run — a Rex tab - rides SSH whatever the host prefers). ⚠ `TerminalSessionController - .ridesMosh` is the one statement of that last rule: scrollback, FILE - and the bar's MOSH badge read it, where reading `host.useMosh` raw - gave a Rex tab on a mosh host no scrollback, no FILE and a MOSH badge. + probe (`SessionBackend.hasFocusedPaneProbe` is false: the wall probe's + record is the only authority, and it reaches the strip through the + window's own observation, so nothing polls), and mosh (no PTY for + mosh-server to run — a Rex tab rides SSH whatever the host prefers). + ⚠ `TerminalSessionController.ridesMosh` is the one statement of that + last rule: scrollback, FILE and the bar's MOSH badge read it, where + reading `host.useMosh` raw gave a Rex tab on a mosh host no + scrollback, no FILE and a MOSH badge. + - ⚠ **A Rex tab's agent bar is its OWN terminal's, not the session's + fronted one** (`TmuxSession.agent(inPane:)`, fed by + `TerminalSessionController.rexBlockID`; the session is found by id, + since a label is respelled when another session takes it). tmux and + herdr tabs show the whole session, so following the record's active + pane follows what the tab shows; a Rex tab is one terminal, and the + session's focus is whatever the Rex app last fronted. Read off the + active pane, the bar vanished from a tab still on Claude Code as soon + as Rex fronted another window, and never appeared on a tab opened or + switched to a terminal that was not in front (user-reported + 2026-11-16, reproduced with a real `claude` on a throwaway server). + `rexBlockID` is learned when the attach settles on a terminal and + changed by Switch Terminal; the next transport run prefers it too, so + a reconnect returns to the terminal the tab was on. + - Measured with Claude Code 2.1.325 (macOS native install) at its + folder-trust prompt: `process.foreground` is `name: "2.1.325"`, + `argv0: "claude"`; the title is the shell's (`claude`); `program + _status` has NO records. So it is the bare-semver rule in + `AgentSignature.classify` that names it there, not OSC 7501. - Deliberately NOT built, with the reason each would need new facts to reopen: - **Drawing a window's splits.** Every terminal in a split needs its diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index 37ee00a4..c76f3805 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -12,5 +12,6 @@ PLEASE TRY 8. On a host showing Rex sessions, press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. Press + TAB in a Rex tab and choose New Session: the new session should start in the same directory. With Rex not running on the host, the same press should say that no Rex server is running. 9. Lock the device for a minute with a Rex tab open, then return: the tab should reconnect by itself. 10. Open Host Settings and find Backends: REX should be checkable, and New sessions run on should never list it. Uncheck it: the Rex tiles should go away. +11. Open a Rex terminal where an agent such as Claude Code is running: the Agent Bar should show that agent's keys. Bring another window of the same session to the front in Rex: the bar should stay, because the tab is still on the agent's terminal. Feedback: screenshot in TestFlight From 2db8467a42bb70e12aa3aed385e765abdb959dec Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Fri, 20 Nov 2026 10:49:13 +0800 Subject: [PATCH 05/13] Light the TMUX / HRDR / REX key when the session has more to switch to The shortcut key opens a panel whose switch list may hold one row or ten, and nothing on the key said which. It now lights (primary ink and the signal border, the UMD chips' `prominent`; not the latch's fill, which means ON) while the list has somewhere else to go. `TmuxSession.hasSwitchChoices` states the rule: more than one window (herdr: workspace), or on Rex more than one terminal, since a Rex tab is one terminal and a single split window already has a second row. The window reads it off the wall probe's record (`probedSession(for:)`, which the agent bar's lookup now shares), so the key trails a new or closed window by up to one probe tick. Both rails re-ink the existing control rather than rebuild: the probe moves this while the key's own panel may be open (New Window is a row there), and a rebuilt UMD bar would pull the chip from under its popover. `shortcutHasChoices` therefore stays out of the bar's presentation key. Checked on the iPad simulator against the dev-sshd harness: a tab on the three-window `main` session shows the TMUX key lit. The unlit state, the in-place change and the Rex rule are covered by unit tests only; the REX key was not run against a live Rex server. --- Multiplex/Models/TmuxModels.swift | 8 ++++ Multiplex/Views/Terminal/SwiftTermView.swift | 4 ++ Multiplex/Views/Terminal/TerminalKeyBar.swift | 31 ++++++++++++-- .../Views/Terminal/TerminalPaneUIKit.swift | 4 ++ .../Views/Terminal/TerminalWindowUIKit.swift | 36 +++++++++++------ Multiplex/Views/Terminal/UMDBarUIKit.swift | 25 ++++++++++-- MultiplexTests/RexProbeTests.swift | 8 ++++ MultiplexTests/TerminalKeyBarUIKitTests.swift | 40 +++++++++++++++++++ MultiplexTests/TmuxProbeTests.swift | 3 ++ MultiplexTests/UMDBarUIKitTests.swift | 28 +++++++++++++ docs/agents/input-and-windows.md | 13 +++++- fastlane/testflight-whats-new.txt | 2 + 12 files changed, 182 insertions(+), 20 deletions(-) diff --git a/Multiplex/Models/TmuxModels.swift b/Multiplex/Models/TmuxModels.swift index 3450e49d..9c28e51a 100644 --- a/Multiplex/Models/TmuxModels.swift +++ b/Multiplex/Models/TmuxModels.swift @@ -212,6 +212,14 @@ struct TmuxSession: Identifiable, Hashable, Codable { var paneCount: Int { windows.reduce(0) { $0 + $1.paneCount } } + /// The shortcut panel's switch list has somewhere else to go — what + /// lights the TMUX / HRDR / REX key. The list is windows (herdr: + /// workspaces, which the probe writes as windows), except on Rex, where + /// a tab is ONE terminal and the list is every terminal of the session: + /// a single split window already has a second row. + var hasSwitchChoices: Bool { + (backend == .rex ? paneCount : windowCount) > 1 + } } extension TmuxSession { diff --git a/Multiplex/Views/Terminal/SwiftTermView.swift b/Multiplex/Views/Terminal/SwiftTermView.swift index 874b2635..116636fb 100644 --- a/Multiplex/Views/Terminal/SwiftTermView.swift +++ b/Multiplex/Views/Terminal/SwiftTermView.swift @@ -25,6 +25,8 @@ final class TerminalSurfaceView: UIView { /// Which multiplexer owns the rail's shortcut key (TMUX/HRDR); nil /// drops the key — plain shells and auxiliary panes have no panel. var shortcutBackend: Host.SessionBackend? + /// The session has several windows to switch between: the key lights. + var shortcutHasChoices = false /// The tier's Key Commands cap and paywall route for the rail's /// hold-CTRL panel. var keyCommandPlan: KeyCommandPlan = .unrestricted @@ -212,6 +214,7 @@ final class TerminalSurfaceView: UIView { keyBar.spendsBottomStrip = configuration.railOwnsBottomSafeArea keyBar.bareChrome = configuration.bareChrome keyBar.keyCommandPlan = configuration.keyCommandPlan + keyBar.shortcutHasChoices = configuration.shortcutHasChoices coordinator.keyBar = keyBar addSubview(view) addSubview(keyBar) @@ -360,6 +363,7 @@ final class TerminalSurfaceView: UIView { coordinator.setKeyRailHidden(configuration.keyRailHidden) coordinator.keyBar?.bareChrome = configuration.bareChrome coordinator.keyBar?.keyCommandPlan = configuration.keyCommandPlan + coordinator.keyBar?.shortcutHasChoices = configuration.shortcutHasChoices if fontChanged { coordinator.terminalMetricsDidChange() } diff --git a/Multiplex/Views/Terminal/TerminalKeyBar.swift b/Multiplex/Views/Terminal/TerminalKeyBar.swift index 3fa3a019..c9f2742c 100644 --- a/Multiplex/Views/Terminal/TerminalKeyBar.swift +++ b/Multiplex/Views/Terminal/TerminalKeyBar.swift @@ -23,6 +23,16 @@ final class TerminalTallyKeyControl: UIControl, UIDragInteractionDelegate { refreshAppearance() } } + /// State without a latch: the key has something to show (the shortcut + /// key of a session with several windows). Primary ink and the signal + /// border — the UMD chips' `prominent` — and never the latch's fill, + /// which says the key is ON. + var isLit = false { + didSet { + guard isLit != oldValue else { return } + refreshAppearance() + } + } var faceInset: CGFloat = 0 { didSet { setNeedsLayout() } } @@ -376,7 +386,9 @@ final class TerminalTallyKeyControl: UIControl, UIDragInteractionDelegate { private func refreshAppearance() { accessibilityTraits = isLatched ? [.button, .selected] : .button alpha = isDraggedAway ? 0.3 : isEnabled ? 1 : 0.45 - let foreground = isLatched ? UIKitChassis.chassis : UIKitChassis.signal2 + let foreground = isLatched + ? UIKitChassis.chassis + : isLit ? UIKitChassis.signal : UIKitChassis.signal2 textLabel.textColor = foreground symbolView.tintColor = foreground // PROTOTYPE(GLASS): resting key faces take the chip treatment — @@ -393,7 +405,7 @@ final class TerminalTallyKeyControl: UIControl, UIDragInteractionDelegate { ? UIKitChassis.signal2 : isHighlighted || isDropTarget ? UIKitChassis.bezelHi : restingFace // The drop target wears the signal border a tab cell does. - faceView.tallyBorderColor = isLatched || isDropTarget + faceView.tallyBorderColor = isLatched || isLit || isDropTarget ? UIKitChassis.signal2 : UIKitChassis.bezelHi } @@ -1166,6 +1178,17 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface } } + /// The tab's session has more than one window to switch between + /// (`TmuxSession.hasSwitchChoices`): the shortcut key lights. Re-inked + /// in place — the wall probe moves this, and a rebuilt row would drop a + /// press in flight. + var shortcutHasChoices = false { + didSet { + guard shortcutHasChoices != oldValue else { return } + shortcutKeyControl?.isLit = shortcutHasChoices + } + } + private weak var terminal: TerminalView? private weak var controller: TerminalSessionController? private let performShortcut: (ShortcutPanelItem) -> Void @@ -1546,7 +1569,9 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface switch slot { case .control: ctrlKeyControl = control case .talkback: talkKeyControl = control - case .shortcuts: shortcutKeyControl = control + case .shortcuts: + shortcutKeyControl = control + control.isLit = shortcutHasChoices default: break } } diff --git a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift index 63f31fa4..74d23920 100644 --- a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift @@ -23,6 +23,9 @@ struct TerminalPaneConfiguration { /// hold-CTRL panel (iPad/iPhone; the visionOS cluster gets it from the /// window directly). var keyCommandPlan: KeyCommandPlan = .unrestricted + /// The tab's session has several windows to switch between: the key + /// rail's shortcut key lights (`TmuxSession.hasSwitchChoices`). + var shortcutHasChoices = false var close: () -> Void } @@ -240,6 +243,7 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg keyRailHidden: configuration.keyRailHidden, isActive: configuration.isActive && configuration.focusAllowed, shortcutBackend: configuration.controller?.route.sessionBackend, + shortcutHasChoices: configuration.shortcutHasChoices, keyCommandPlan: configuration.keyCommandPlan ) } diff --git a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift index 7084cfcc..0fa8089a 100644 --- a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift @@ -984,36 +984,44 @@ final class TerminalWindowViewController: UIViewController, else { return nil } return notice } - private var detectedAgent: AgentKind? { - guard let activeTab else { return nil } - guard let sessionName = activeTab.sessionName else { - return activeController?.directShellAgent - } + /// The wall probe's record of a tab's session; nil for a plain shell. + private func probedSession(for tab: TerminalRoute) -> TmuxSession? { // Any backend this host MONITORS can answer — on a mixed host the // probe carries both, and a tab on the secondary deserves its agent // chips too. A tab whose backend the host no longer monitors gets // nothing rather than a same-named record from the other one. - guard let host = store.host(id: activeTab.hostID), - let backend = activeTab.sessionBackend, + guard let sessionName = tab.sessionName, + let host = store.host(id: tab.hostID), + let backend = tab.sessionBackend, host.monitors(backend) else { return nil } let sessions = hub.model(for: host).sessions(on: backend) + // A Rex session is found by id: a Rex label is not an identity, and + // is respelled when another session takes the same one. + if let rex = tab.rexTarget { + return sessions.first { $0.tmuxID == rex.sessionID } + } + return sessions.first { $0.name == sessionName } + } + private var detectedAgent: AgentKind? { + guard let activeTab else { return nil } + guard activeTab.sessionName != nil else { + return activeController?.directShellAgent + } + let session = probedSession(for: activeTab) // A Rex tab is ONE terminal of its session, and not necessarily the // one the session is fronting — Open Terminal, Switch Terminal, or // the Rex app showing another window — so the strip is that - // terminal's (`TmuxSession.agent(inPane:)`). Found by id: a Rex - // label is not an identity, and is respelled when another session - // takes the same one. + // terminal's (`TmuxSession.agent(inPane:)`). if let rex = activeTab.rexTarget { - return sessions.first { $0.tmuxID == rex.sessionID }? - .agent(inPane: activeController?.rexBlockID ?? rex.blockID) + return session?.agent(inPane: activeController?.rexBlockID ?? rex.blockID) } // One expression serves tmux and herdr on purpose: a herdr tile IS // a whole session, and the probe writes its live focus into the // record (active window = focused workspace, active pane = the // session's one focus every client mirrors) — so following // `activeAgent` follows a workspace switch inside the TUI too. - return sessions.first { $0.name == sessionName }?.activeAgent + return session?.activeAgent } private var resolvedTerminalTheme: TerminalTheme { // Prefer the pinned choice over the live traits: the observation @@ -2611,6 +2619,7 @@ extension TerminalWindowViewController { isActive: isActive, focusAllowed: terminalFocusAllowed, keyCommandPlan: keyCommandPlan, + shortcutHasChoices: probedSession(for: tab)?.hasSwitchChoices == true, close: { [weak self] in self?.closeTab(tab.id) } ) } @@ -2944,6 +2953,7 @@ extension TerminalWindowViewController { fullScreenActive: fullScreenColumn, extraNewTabTarget: extraNewTabTarget, shortcutBackend: activeTab?.sessionBackend, + shortcutHasChoices: activeTab.flatMap(probedSession(for:))?.hasSwitchChoices == true, style: vertical ? .verticalColumn : profile.style, deckControl: shell?.deckControl ?? .back, availableWidth: vertical ? column.width : umdAvailableWidth, diff --git a/Multiplex/Views/Terminal/UMDBarUIKit.swift b/Multiplex/Views/Terminal/UMDBarUIKit.swift index 5f7a9253..c1e853e1 100644 --- a/Multiplex/Views/Terminal/UMDBarUIKit.swift +++ b/Multiplex/Views/Terminal/UMDBarUIKit.swift @@ -47,6 +47,12 @@ struct UMDBarConfiguration { var extraNewTabTarget: TerminalRoute.NewTabTarget? /// Which multiplexer owns the shortcut chip (TMUX/HRDR); nil hides it. var shortcutBackend: Host.SessionBackend? + /// The active tab's session has several windows to switch between: the + /// shortcut chip turns prominent (`TmuxSession.hasSwitchChoices`). + /// Deliberately outside the presentation key — the wall probe moves it + /// while the chip's own panel may be open (New Window is a row there), + /// so the chip is re-inked in place, never rebuilt under its popover. + var shortcutHasChoices = false var style: UMDBarStyle var deckControl: ShellDeckControl var availableWidth: CGFloat? @@ -192,6 +198,9 @@ final class UMDBarViewController: UIViewController, private(set) var fileAttachController: FileAttachMenuViewController private weak var shortcutPopoverController: ShortcutPanelViewController? private weak var shortcutButtonView: UMDBarButton? + /// The shortcut chip in whichever shape the rail drew it (bar button or + /// column chip), for the in-place `shortcutHasChoices` re-ink. + private weak var shortcutChip: UMDChipBase? private weak var guideNavigationController: UINavigationController? private weak var guideFocusController: TerminalSessionController? private var resumesFocusAfterShortcutPanel = false @@ -242,6 +251,7 @@ final class UMDBarViewController: UIViewController, let previousKey = UMDBarPresentationKey(self.configuration) self.configuration = configuration let nextKey = UMDBarPresentationKey(configuration) + shortcutChip?.prominent = configuration.shortcutHasChoices guard previousKey != nextKey else { return } fileAttachController.update(controller: configuration.controller) guard isViewLoaded else { return } @@ -485,7 +495,7 @@ final class UMDBarViewController: UIViewController, let chip = UMDColumnChip( caption: backend.shortcutKeyCaption, systemImage: "command", - prominent: false, + prominent: configuration.shortcutHasChoices, accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) chip.accessibilityIdentifier = "umd.tmux" @@ -495,6 +505,7 @@ final class UMDBarViewController: UIViewController, self.showShortcutPanel(from: chip) }, for: .touchUpInside) shortcutButtonView = nil + shortcutChip = chip return chip case .overflow: let menu = makeOverflowMenu(overflowing: overflowing) @@ -860,7 +871,7 @@ final class UMDBarViewController: UIViewController, let button = UMDBarButton( caption: backend.shortcutKeyCaption, systemImage: "command", - prominent: false, + prominent: configuration.shortcutHasChoices, accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) button.accessibilityIdentifier = "umd.tmux" @@ -870,6 +881,7 @@ final class UMDBarViewController: UIViewController, self.showShortcutPanel(from: button) }, for: .touchUpInside) shortcutButtonView = button + shortcutChip = button return button } @@ -1882,7 +1894,14 @@ final class UMDSourceStripView: UIView { /// opaque on the glass bar for good). @MainActor class UMDChipBase: UIButton { - let prominent: Bool + /// Mutable for the one chip whose state moves under an open popover + /// (the shortcut chip); every other chip is rebuilt with its bar. + var prominent: Bool { + didSet { + guard prominent != oldValue else { return } + refreshColors() + } + } init(prominent: Bool, accessibilityLabel: String) { self.prominent = prominent diff --git a/MultiplexTests/RexProbeTests.swift b/MultiplexTests/RexProbeTests.swift index 92c952c8..09ae6d35 100644 --- a/MultiplexTests/RexProbeTests.swift +++ b/MultiplexTests/RexProbeTests.swift @@ -104,6 +104,14 @@ final class RexProbeTests: XCTestCase { let editor = work.windows[0] XCTAssertEqual(editor.paneCount, 2) + // The REX key's list is terminals, not windows: one split window + // alone is already somewhere else to go, where a tmux session with + // the same shape has only itself. + var split = work + split.windows = [editor] + XCTAssertTrue(split.hasSwitchChoices) + split.backend = .tmux + XCTAssertFalse(split.hasSwitchChoices) XCTAssertEqual(editor.panes?.map(\.isActive), [true, false]) XCTAssertEqual(editor.paneTitle, "vim README.md") XCTAssertEqual(editor.panes?.first?.command, "sleep") diff --git a/MultiplexTests/TerminalKeyBarUIKitTests.swift b/MultiplexTests/TerminalKeyBarUIKitTests.swift index d5418885..af1df376 100644 --- a/MultiplexTests/TerminalKeyBarUIKitTests.swift +++ b/MultiplexTests/TerminalKeyBarUIKitTests.swift @@ -142,6 +142,46 @@ final class TerminalKeyBarUIKitTests: XCTestCase { XCTAssertTrue(frames.allSatisfy { $0.width >= 24 }) } + func testShortcutKeyLightsWhenTheSessionHasChoices() throws { + let bar = TerminalKeyBar( + terminal: TerminalView(frame: CGRect(x: 0, y: 0, width: 1024, height: 200)), + controller: nil, + performShortcut: { _ in }, + finishTmuxCopyMode: {}, + shortcutBackend: .rex, + orderStore: KeyBarOrderStore(defaults: try isolatedDefaults()) + ) + bar.frame = CGRect(x: 0, y: 0, width: 1024, height: TerminalKeyBar.barHeight) + bar.layoutIfNeeded() + func key() throws -> TerminalTallyKeyControl { + try XCTUnwrap(bar.renderedKeys.first { + $0.accessibilityIdentifier == "terminal.keybar.tmux" + }) + } + let built = try key() + XCTAssertFalse(built.isLit) + + // Re-inked in place: the same control, so a press in flight survives + // the probe tick that found the second terminal. + bar.shortcutHasChoices = true + XCTAssertTrue(built.isLit) + XCTAssertFalse(built.isLatched, "lit is not the latch's fill") + + // A row rebuilt while lit (the keyboard lock adds RET) comes back lit. + bar.applyObservedState(TerminalKeyBarObservedState( + hardwareKeyboardConnected: false, + keyboardLocked: true, + isDictating: false, + talkbackOpen: false, + arranging: false, + order: KeyBarOrder.standard + )) + bar.layoutIfNeeded() + let rebuilt = try key() + XCTAssertFalse(rebuilt === built) + XCTAssertTrue(rebuilt.isLit) + } + func testNativeRailBuildsTallyControlsWithoutAHostedView() throws { let terminal = TerminalView( frame: CGRect(x: 0, y: 0, width: 420, height: 200) diff --git a/MultiplexTests/TmuxProbeTests.swift b/MultiplexTests/TmuxProbeTests.swift index aa89ecac..44417b4d 100644 --- a/MultiplexTests/TmuxProbeTests.swift +++ b/MultiplexTests/TmuxProbeTests.swift @@ -27,6 +27,9 @@ final class TmuxProbeTests: XCTestCase { XCTAssertFalse(sessions[1].isAttached) XCTAssertEqual(sessions[1].windowCount, 1) + // What lights the TMUX key: a second window to switch to. + XCTAssertTrue(main.hasSwitchChoices) + XCTAssertFalse(sessions[1].hasSwitchChoices) } func testEmptyOutputMeansNoServer() { diff --git a/MultiplexTests/UMDBarUIKitTests.swift b/MultiplexTests/UMDBarUIKitTests.swift index f5fec221..fe1525ea 100644 --- a/MultiplexTests/UMDBarUIKitTests.swift +++ b/MultiplexTests/UMDBarUIKitTests.swift @@ -60,6 +60,32 @@ final class UMDBarUIKitTests: XCTestCase { XCTAssertNil(control("umd.tmux", in: none.view)) } + func testShortcutChipTurnsProminentWhenTheSessionHasChoices() throws { + let controller = UMDBarViewController(configuration: configuration()) + controller.loadViewIfNeeded() + func chip() throws -> UMDChipBase { + try XCTUnwrap(control("umd.tmux", in: controller.view) as? UMDChipBase) + } + let built = try chip() + XCTAssertFalse(built.prominent) + + // The wall probe finds a second window: the SAME chip re-inks — its + // panel may be open over it, so the bar must not rebuild. + controller.update(configuration: configuration(shortcutHasChoices: true)) + XCTAssertTrue(built.prominent) + XCTAssertTrue(try chip() === built) + + controller.update(configuration: configuration()) + XCTAssertFalse(built.prominent) + + // A bar built for a session that already has several starts lit. + let lit = UMDBarViewController(configuration: configuration( + shortcutHasChoices: true + )) + lit.loadViewIfNeeded() + XCTAssertEqual((control("umd.tmux", in: lit.view) as? UMDChipBase)?.prominent, true) + } + func testRegularActionRouterAndDirectButtonsPreserveEveryCallback() throws { let first = UUID() let second = UUID() @@ -646,6 +672,7 @@ final class UMDBarUIKitTests: XCTestCase { fullScreenActive: Bool = false, extraNewTabTarget: TerminalRoute.NewTabTarget? = nil, shortcutBackend: Host.SessionBackend? = .tmux, + shortcutHasChoices: Bool = false, style: UMDBarStyle = .regular, deckControl: ShellDeckControl = .back, availableWidth: CGFloat? = nil, @@ -671,6 +698,7 @@ final class UMDBarUIKitTests: XCTestCase { fullScreenActive: fullScreenActive, extraNewTabTarget: extraNewTabTarget, shortcutBackend: shortcutBackend, + shortcutHasChoices: shortcutHasChoices, style: style, deckControl: deckControl, availableWidth: availableWidth, diff --git a/docs/agents/input-and-windows.md b/docs/agents/input-and-windows.md index d66b8136..b24d28ae 100644 --- a/docs/agents/input-and-windows.md +++ b/docs/agents/input-and-windows.md @@ -89,7 +89,18 @@ routing, tab moves, keyboard avoidance, or secret fields. HRDR — four mono characters, so every tier and cutoff holds unchanged — and both open the shared `ShortcutPanelViewController`, whose content (`ShortcutPanelContent.tmux`/`.herdr`) is the ONE place a backend's - shortcut set lives. Pane cycling (both backends) and herdr tab cycling are + shortcut set lives. The key LIGHTS (primary ink + signal border, the + UMD chips' `prominent`; never the latch's fill, which means ON) while + the session's switch list has somewhere else to go — + `TmuxSession.hasSwitchChoices`: more than one window (herdr: workspace), + or on Rex more than one TERMINAL, since a Rex tab is one terminal and a + single split window already has a second row. The fact comes from the + wall probe's record (`probedSession(for:)` in the window), so it trails + a new window by up to one ~5 s tick, and it is re-inked IN PLACE on both + rails: the probe moves it while the key's own panel may be open (New + Window is a row there), and a rebuilt UMD bar would pull the chip out + from under its popover — which is why `shortcutHasChoices` stays out of + `UMDBarPresentationKey`. Pane cycling (both backends) and herdr tab cycling are deliberately absent because those targets are already directly tappable; tmux Last Window is absent because the live switch list targets a window directly. The panel root scrolls when a phone popover clamps diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index c76f3805..79b8757a 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -1,5 +1,6 @@ NEW SINCE 1.5.2 • Deck and terminal: a host that runs Rex (superlogical.com/rex) can now show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. When the host is holding Rex sessions a + REX chip appears on its rail; press it to start showing them, or check REX in Host Settings under Backends. Each tile shows the session's windows, the last lines of the screen in front, any agent it finds, and RUNNING or NEEDS YOU. Pressing a tile opens the terminal the session is showing, with its screen, colors and scrollback; a session with several terminals offers the others under Open Terminal in the tile's menu, and the REX key in a Rex tab switches the tab to another terminal of the session. New Session and + TAB can create a Rex session while a Rex server is running on the host (Multiplex does not start one); a host's default backend stays tmux or herdr. +• Terminal: the TMUX, HRDR or REX key now lights up when the session has more than one window to switch between (for Rex, more than one terminal), so you can tell there is somewhere else to go without opening the panel. PLEASE TRY 1. On a host that runs Rex with at least one session open (a Mac with the Rex app works), wait for the + REX chip on the host's rail, press it and confirm: the Rex sessions should appear as tinted tiles beside the tmux ones, each with its window names and the last lines of its screen. Add or rename a window in Rex: the tile should follow within a few seconds. @@ -13,5 +14,6 @@ PLEASE TRY 9. Lock the device for a minute with a Rex tab open, then return: the tab should reconnect by itself. 10. Open Host Settings and find Backends: REX should be checkable, and New sessions run on should never list it. Uncheck it: the Rex tiles should go away. 11. Open a Rex terminal where an agent such as Claude Code is running: the Agent Bar should show that agent's keys. Bring another window of the same session to the front in Rex: the bar should stay, because the tab is still on the agent's terminal. +12. Attach a tmux session that has one window: the TMUX key should look like the other keys. Add a second window from the TMUX panel: within a few seconds the key should turn brighter with a stronger border, and go back when that window is closed. A Rex tab should do the same with the REX key when its session gains a second terminal. Feedback: screenshot in TestFlight From 3fbc4891128ff2c73a6b379729dedcd6e487d32d Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Fri, 20 Nov 2026 11:33:32 +0800 Subject: [PATCH 06/13] Stop a Rex tab's emulator from answering queries the Rex server answers A Rex terminal open in Multiplex and in the Rex app at once flickered in the app: the two clients kept trading the terminal's size. The Rex server keeps the terminal and answers its queries itself. The tab's SwiftTerm reads the same output and answered too, and that answer went out as a terminal.write, which is also what claims the size. So a tab nobody was touching took the terminal back whenever the program asked something, and a program that asks on every resize made it a loop. The program also read each reply twice. SwiftTerm handed the host one send() for what a person did and for what the terminal said by itself, so the fork now marks the first kind (Terminal.isSendingUserInput) and the iOS view routes the rest to a new TerminalViewDelegate.sendTerminalReport, which defaults to send(). A Rex tab drops those; keys, mouse events and prompt clicks still go and still claim. Other tabs are unchanged. Measured against a throwaway server with a stand-in client that reclaims the block whenever it loses it: 82 owner changes in 0.6 s before, and after only the stand-in's own take, with no terminal.write from the idle tab. Typing in the tab still takes the size. --- Multiplex/Services/RexSession.swift | 6 ++++ .../Services/TerminalSessionController.swift | 19 +++++++++++ Multiplex/Views/Terminal/SwiftTermView.swift | 10 ++++++ MultiplexTests/KeyChordEncodingTests.swift | 6 ++++ MultiplexTests/TerminalRemoteMouseTests.swift | 24 ++++++++++++++ .../Apple/TerminalViewDelegate.swift | 15 +++++++++ .../Sources/SwiftTerm/Terminal.swift | 32 +++++++++++++++---- .../SwiftTerm/iOS/iOSTerminalView.swift | 9 +++++- docs/agents/backends-and-probe.md | 29 +++++++++++++++++ docs/agents/swiftterm-fork.md | 15 +++++++++ fastlane/testflight-whats-new.txt | 1 + 11 files changed, 159 insertions(+), 7 deletions(-) diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift index d0e3e929..f764b55b 100644 --- a/Multiplex/Services/RexSession.swift +++ b/Multiplex/Services/RexSession.swift @@ -109,6 +109,12 @@ struct RexSocket: Sendable { /// - **The last client to type owns the size**, as with tmux's latest-client /// rule. Another client (the Rex app) can claim the block back; the next /// keystroke here claims it again and re-sizes it. +/// - **Only what a person does is written.** `write` is what claims, so +/// nothing may reach it that the emulator said by itself. The server +/// parses the terminal's output too and answers its queries there; the +/// emulator's own answers are stopped before this transport +/// (`TerminalSessionController.sendTerminalReport`). Sent on, each one +/// was a second answer in the program's input and a claim nobody made. /// - **The palette is the app's.** `extra_palette` is not requested: it /// would repaint the tab in Rex's theme. /// - **A tab attached during a full-screen program redraws when it exits.** diff --git a/Multiplex/Services/TerminalSessionController.swift b/Multiplex/Services/TerminalSessionController.swift index 097364ca..36d57403 100644 --- a/Multiplex/Services/TerminalSessionController.swift +++ b/Multiplex/Services/TerminalSessionController.swift @@ -943,6 +943,25 @@ final class TerminalSessionController { // MARK: Terminal view events + /// What the emulator said by itself — an answer to a query in the + /// output (device attributes, cursor position, a color), or a report of + /// its own focus or size — rather than anything a person did. + /// + /// On a PTY that is input like any other: this emulator is the only + /// terminal the program has. A Rex terminal lives on the Rex server, + /// which parses the same output and answers it there, so none of it is + /// forwarded. Forwarding did two things, both measured: the program + /// read every answer twice, and — since a write is what claims a Rex + /// terminal's size (`RexSession`) — a tab nobody was touching took the + /// terminal back from whoever was using it in Rex, each time the + /// program asked something. A program that asks on every resize made + /// that a loop: the two clients traded the size for as long as the + /// other kept claiming it. + func sendTerminalReport(_ data: Data) { + guard route.rexTarget == nil else { return } + sendInput(data) + } + func sendInput(_ data: Data) { guard status == .live else { return } // While the jump search pages the remote transcript, a keystroke diff --git a/Multiplex/Views/Terminal/SwiftTermView.swift b/Multiplex/Views/Terminal/SwiftTermView.swift index 116636fb..c2fb29e8 100644 --- a/Multiplex/Views/Terminal/SwiftTermView.swift +++ b/Multiplex/Views/Terminal/SwiftTermView.swift @@ -803,6 +803,16 @@ final class TerminalSurfaceView: UIView { } } + /// The fork's second road (`sendTerminalReport`): what the emulator + /// said by itself, kept apart from what a person did so the + /// controller can decide whether this tab's far side wants it. + func sendTerminalReport(source: TerminalView, data: ArraySlice) { + let bytes = Data(data) + MainActor.assumeIsolated { + controller.sendTerminalReport(bytes) + } + } + func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) { MainActor.assumeIsolated { controller.terminalResized(cols: newCols, rows: newRows) diff --git a/MultiplexTests/KeyChordEncodingTests.swift b/MultiplexTests/KeyChordEncodingTests.swift index 4bccd492..101c3e90 100644 --- a/MultiplexTests/KeyChordEncodingTests.swift +++ b/MultiplexTests/KeyChordEncodingTests.swift @@ -8,6 +8,9 @@ import XCTest @MainActor final class CapturingTerminalDelegate: NSObject, TerminalViewDelegate { var sent: [[UInt8]] = [] + /// Set to keep what the terminal says by itself out of `sent`, the way + /// a host does whose far side answers queries on its own. + var reports: [[UInt8]]? /// A fresh terminal view wired to a fresh capturing delegate. static func makeTerminal() -> (TerminalView, CapturingTerminalDelegate) { @@ -23,6 +26,9 @@ final class CapturingTerminalDelegate: NSObject, TerminalViewDelegate { func send(source: TerminalView, data: ArraySlice) { sent.append(Array(data)) } + func sendTerminalReport(source: TerminalView, data: ArraySlice) { + if reports == nil { sent.append(Array(data)) } else { reports?.append(Array(data)) } + } func scrolled(source: TerminalView, position: Double) {} func requestOpenLink(source: TerminalView, link: String, params: [String: String]) {} func rangeChanged(source: TerminalView, startY: Int, endY: Int) {} diff --git a/MultiplexTests/TerminalRemoteMouseTests.swift b/MultiplexTests/TerminalRemoteMouseTests.swift index ce5fcfbf..a17b1739 100644 --- a/MultiplexTests/TerminalRemoteMouseTests.swift +++ b/MultiplexTests/TerminalRemoteMouseTests.swift @@ -64,6 +64,30 @@ final class TerminalRemoteMouseTests: XCTestCase { ]) } + /// The split a Rex tab depends on (`TerminalSessionController + /// .sendTerminalReport`): what the terminal says by itself — a query's + /// answer, the focus state it reports the moment reporting is switched + /// on — leaves by one road, and a person's mouse event by the other. + /// Both used to arrive as `send`, where nothing could tell them apart. + func testWhatTheTerminalSaysByItselfTravelsApartFromAMouseEvent() { + let (terminal, delegate) = sgrTracking() + delegate.reports = [] + terminal.longPressMouseDragFilter = { _, _ in true } + + terminal.feed(text: "\u{1B}[c\u{1B}[6n\u{1B}[?1004h") + XCTAssertTrue(terminal.beginRemoteMouseDrag(at: terminal.pointForCell(col: 5, row: 2))) + terminal.endRemoteMouseDrag(at: terminal.pointForCell(col: 5, row: 2)) + waitForSends(delegate, count: 2) + + XCTAssertEqual(text(delegate), ["\u{1B}[<0;6;3M", "\u{1B}[<0;6;3m"]) + let reports = (delegate.reports ?? []).map { String(decoding: $0, as: UTF8.self) } + XCTAssertEqual(reports.count, 3) + XCTAssertEqual(reports.first?.last, "c") // device attributes + XCTAssertEqual(reports.dropFirst().first, "\u{1B}[1;1R") + // Focus, said the moment reporting is switched on — whichever it is. + XCTAssertTrue(["\u{1B}[I", "\u{1B}[O"].contains(reports.last ?? "")) + } + func testDeclinedCellKeepsTheLongPressLocal() { let (terminal, delegate) = sgrTracking() terminal.longPressMouseDragFilter = { _, _ in false } diff --git a/Vendor/SwiftTerm/Sources/SwiftTerm/Apple/TerminalViewDelegate.swift b/Vendor/SwiftTerm/Sources/SwiftTerm/Apple/TerminalViewDelegate.swift index aa2e386b..33f98d21 100644 --- a/Vendor/SwiftTerm/Sources/SwiftTerm/Apple/TerminalViewDelegate.swift +++ b/Vendor/SwiftTerm/Sources/SwiftTerm/Apple/TerminalViewDelegate.swift @@ -183,10 +183,25 @@ public protocol TerminalViewDelegate: AnyObject { /// Updates can be combined before delivery. Text is untrusted plain text. func programStatusChanged(source: TerminalView, records: [TerminalProgramStatus]) + /// Multiplex patch: bytes the terminal produced by itself rather than a + /// person — an answer to a query in the output it was fed (device + /// attributes, cursor position, a color), or a report of its own focus, + /// visibility, size or color scheme. What a person typed, clicked or + /// pasted arrives through `send`. + /// + /// Defaults to `send`, which is right wherever this terminal is the + /// only one the program has. A host whose far side keeps a terminal of + /// its own and answers there must not forward these as well. + func sendTerminalReport(source: TerminalView, data: ArraySlice) + } public extension TerminalViewDelegate { func programStatusChanged(source: TerminalView, records: [TerminalProgramStatus]) {} + + func sendTerminalReport(source: TerminalView, data: ArraySlice) { + send(source: source, data: data) + } } #endif diff --git a/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift b/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift index f084cc76..0f7096d3 100644 --- a/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift +++ b/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift @@ -2851,6 +2851,24 @@ open class Terminal { /// paste, and programmatic input. public func sendUserInput(_ data: ArraySlice) { registerUserInput(data) + sendAsUserInput(data) + } + + /// Multiplex patch: true while the bytes being handed to the delegate + /// are a person's — a mouse event, a prompt click, input routed through + /// `sendUserInput` — and false for everything the terminal says by + /// itself: an answer to a query in its output, or a report of its own + /// focus, visibility, size or color scheme. + /// + /// Both kinds leave through the one `send(source:data:)`, so a delegate + /// that must tell them apart reads this inside that call. A host whose + /// far side already runs a terminal (a multiplexer server that answers + /// queries itself) forwards the first kind and not the second. + public private(set) var isSendingUserInput = false + + private func sendAsUserInput(_ data: ArraySlice) { + isSendingUserInput = true + defer { isSendingUserInput = false } tdel?.send(source: self, data: data) } @@ -3301,7 +3319,7 @@ open class Terminal { } private func sendRepeatedSemanticSequence(_ data: [UInt8]) { - tdel?.send(source: self, data: data[...]) + sendAsUserInput(data[...]) } // MARK: OSC 133 stream handling (R2, R4) @@ -8640,8 +8658,9 @@ open class Terminal { */ public func sendEvent (buttonFlags: Int, x: Int, y: Int, pixelX: Int, pixelY: Int) { - sendResponse(mouseEventBytes(buttonFlags: buttonFlags, x: x, y: y, - pixelX: pixelX, pixelY: pixelY)) + // Multiplex patch: a mouse event is the person's, not a response. + sendAsUserInput(mouseEventBytes(buttonFlags: buttonFlags, x: x, y: y, + pixelX: pixelX, pixelY: pixelY)[...]) } /// Encodes a response without invoking the delegate. Owners can copy it @@ -8658,9 +8677,10 @@ open class Terminal { private func sendMousePacket(buttonFlags: Int, release: Bool, originalButton: Int, x: Int, y: Int, pixelX: Int, pixelY: Int) { - sendResponse(mousePacketBytes(buttonFlags: buttonFlags, release: release, - originalButton: originalButton, x: x, y: y, - pixelX: pixelX, pixelY: pixelY)) + // Multiplex patch: a mouse event is the person's, not a response. + sendAsUserInput(mousePacketBytes(buttonFlags: buttonFlags, release: release, + originalButton: originalButton, x: x, y: y, + pixelX: pixelX, pixelY: pixelY)[...]) } private func mousePacketBytes(buttonFlags: Int, release: Bool, originalButton: Int, diff --git a/Vendor/SwiftTerm/Sources/SwiftTerm/iOS/iOSTerminalView.swift b/Vendor/SwiftTerm/Sources/SwiftTerm/iOS/iOSTerminalView.swift index dc8e5383..c66f66af 100644 --- a/Vendor/SwiftTerm/Sources/SwiftTerm/iOS/iOSTerminalView.swift +++ b/Vendor/SwiftTerm/Sources/SwiftTerm/iOS/iOSTerminalView.swift @@ -2538,9 +2538,16 @@ open class TerminalView: UIScrollView, UITextInputTraits, UIKeyInput, UIScrollVi nonisolated open func send(source: Terminal, data: ArraySlice) { let capturedData = Array(data) + // Multiplex patch: read now — the flag is only true for the length + // of this call, and the delivery below happens later, on main. + let isUserInput = source.isSendingUserInput onMain { [weak self] in guard let self else { return } - self.terminalDelegate?.send(source: self, data: capturedData[...]) + if isUserInput { + self.terminalDelegate?.send(source: self, data: capturedData[...]) + } else { + self.terminalDelegate?.sendTerminalReport(source: self, data: capturedData[...]) + } } } diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index d3deefaf..2b030dc0 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -529,6 +529,35 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. rule): the Rex app can claim the block back (`block_owner_changed`); the next keystroke here claims and re-sizes it. Until then the tab shows another client's size — Multiplex does not letterbox. + - ⚠ **Nothing the emulator says by itself reaches a Rex terminal** + (`TerminalSessionController.sendTerminalReport`). The server keeps the + terminal and answers its queries there — measured with no client + attached: `CSI c` and `CSI 6n` both came back to the program. SwiftTerm + reads the same output and answers too, and that answer used to go out + as a `write`: the program read every reply twice, and because a write + is what claims, a tab nobody was touching took the terminal's size + back whenever the program asked something. A program that asks on + every resize closed the loop — reported as the same terminal in the + Rex app flickering, and reproduced with a stand-in client that + reclaims when it loses the block: 82 owner changes in 0.6 s before, + 1 (the stand-in's own) after. So on a Rex tab the emulator's answers + AND its reports (focus, in-band size, color scheme) are dropped; + mouse events and prompt clicks are a person's and still go. + - Focus reports go with the rest on purpose. Only this client knows + its own focus, but so does every other client of the terminal, and + a tab that reported "unfocused" as the user looked away would say + it for a terminal still in use in Rex. Whether the Rex app reports + focus itself is unmeasured. + - The split is a fork seam (`Terminal.isSendingUserInput`, + `TerminalViewDelegate.sendTerminalReport`, see + `swiftterm-fork.md`): both kinds used to leave SwiftTerm through + the one `send`. + - To re-measure: a script in the terminal that prints `CSI 6n` from a + `WINCH` trap and logs its stdin, then a second control connection + that `own_block(take)`s and resizes. The server's log lists every + `terminal.write` — with the tab idle there must be none. + - Still claimed without a keystroke: the attach itself, so an + automatic reconnect takes the size once. - ⚠ **Say goodbye before cancelling the readers** (`teardown`). Cancelling a reader tears its pipe down, and a connection that just drops is kept by the server for 60 s — its client listed "connection diff --git a/docs/agents/swiftterm-fork.md b/docs/agents/swiftterm-fork.md index 1f738478..78b5e9ab 100644 --- a/docs/agents/swiftterm-fork.md +++ b/docs/agents/swiftterm-fork.md @@ -247,6 +247,21 @@ input encoding, or terminal rendering. ~2–4 fps under streaming load with the row cache warm (rows rebuilt 0/58) — the stall is the sim's present path, not the renderer; only a real-device A/B against the CG damage-strip path counts. + - **The terminal's own bytes leave by a second road.** Upstream hands + the host one `send` for everything: what a person typed or clicked, + and what the terminal says by itself (answers to queries in its + output; focus, visibility, in-band size and color-scheme reports). + `Terminal.isSendingUserInput` is true only inside the sends that are + a person's (`sendUserInput`, `sendEvent` and the mouse packet, the + prompt-click cursor walk), the iOS view reads it in `send(source: Terminal, …)` + before hopping to main, and routes the rest to + `TerminalViewDelegate.sendTerminalReport` — which defaults to `send`, + so a delegate that does not care sees no change. A Rex tab drops + them (`backends-and-probe.md`). Keyboard input never passes through + the terminal, so it was always `send`. Pinned by + `TerminalRemoteMouseTests`. Mouse packets used to leave through + `sendResponse`; re-check that on a bump, or mouse input would be + classed as a report and a Rex tab would lose its clicks. - The visible screen's links are enumerable (`Terminal .visibleLinkMatches` + `TerminalView.visibleLinkRegions`, the inverse of `calculateTapHit`) — what visionOS gaze hover stands on. diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index 79b8757a..eff9a741 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -15,5 +15,6 @@ PLEASE TRY 10. Open Host Settings and find Backends: REX should be checkable, and New sessions run on should never list it. Uncheck it: the Rex tiles should go away. 11. Open a Rex terminal where an agent such as Claude Code is running: the Agent Bar should show that agent's keys. Bring another window of the same session to the front in Rex: the bar should stay, because the tab is still on the agent's terminal. 12. Attach a tmux session that has one window: the TMUX key should look like the other keys. Add a second window from the TMUX panel: within a few seconds the key should turn brighter with a stronger border, and go back when that window is closed. A Rex tab should do the same with the REX key when its session gains a second terminal. +13. Open the same Rex terminal in Rex on the Mac and in a Rex tab, then work in it on the Mac without touching the tab: the Mac's terminal should keep its size and not flicker. Typing in the tab should still take the size. Feedback: screenshot in TestFlight From 624abe7fedd2cfbca8bc60b34c2836a5d96fb84a Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Fri, 20 Nov 2026 18:17:03 +0800 Subject: [PATCH 07/13] Keep a Rex tab free of another screen's and another size's characters Two ways a Rex tab ended up with stray characters, both reproduced against a throwaway Rex server. Switching the tab between two terminals that each run a full-screen program left the first one's screen under the second. Every redraw of a Rex tab is RIS plus a rendering, and SwiftTerm's RIS did not empty the alternate screen: the buffer is emptied only on the way out of it, and is not blanked on the way back in once it has rows. With two stand-in full-screen programs the whole first screen stayed. The fork's reset now clears the alternate buffer too. A shell on either side hid it, which is why the first switch tests passed. While another client held a terminal at a different size, the tab went on parsing its output at the pane's own grid. Since the tab stopped answering the terminal's queries, nothing claims the size back until someone types, so this lasted as long as the Mac was the one in use. The stream says what size the terminal is and whose; a size that is another client's is now followed. The session holds the stream, waits for the repaint a resize sets off to go quiet, has the emulator take the grid, and draws the screen again, without replaying the held bytes the rendering already contains. The pane gives SwiftTerm the grid by giving it the frame: text shrinks until the grid fits, and the room left over comes off the trailing and bottom edges. The grids reported on the way are never sent on as the tab's own. Typing in the tab still claims the size, and the pane is its own again. Redraws now run one at a time; two sharing a hold let the first release the stream under the second. --- Multiplex/Models/RexWire.swift | 57 ++++++ Multiplex/Models/TerminalGrid.swift | 59 ++++++ Multiplex/Services/RexSession.swift | 157 +++++++++++++-- .../Services/TerminalSessionController.swift | 56 +++++- Multiplex/Views/Terminal/SwiftTermView.swift | 185 ++++++++++++++++-- MultiplexTests/RexSessionTests.swift | 126 +++++++++++- MultiplexTests/RexWireTests.swift | 55 ++++++ MultiplexTests/TerminalFullResetTests.swift | 54 +++++ MultiplexTests/TerminalGridFitTests.swift | 85 ++++++++ .../Sources/SwiftTerm/Terminal.swift | 8 + docs/agents/backends-and-probe.md | 57 +++++- docs/agents/swiftterm-fork.md | 16 ++ fastlane/testflight-whats-new.txt | 20 +- 13 files changed, 877 insertions(+), 58 deletions(-) create mode 100644 Multiplex/Models/TerminalGrid.swift create mode 100644 MultiplexTests/TerminalFullResetTests.swift create mode 100644 MultiplexTests/TerminalGridFitTests.swift diff --git a/Multiplex/Models/RexWire.swift b/Multiplex/Models/RexWire.swift index f4511a6a..4050a195 100644 --- a/Multiplex/Models/RexWire.swift +++ b/Multiplex/Models/RexWire.swift @@ -318,6 +318,63 @@ enum RexWire { default: "reason \(reason)" } } + + // MARK: Picking a held stream up again + + /// Where to resume a held stream whose first `offset` bytes are known + /// to be in a rendering already — `offset` itself, unless that cut + /// falls inside an escape sequence or a multi-byte character, in which + /// case its start. Resumed mid-sequence, the rest of it is drawn as + /// text (`8;5;12m`); backing up repeats at most one sequence instead. + /// + /// Also asked of a cut at the very end: the bytes that complete an + /// unfinished sequence are then the next to arrive. + static func resumeOffset(in data: Data, from offset: Int) -> Int { + let bytes = [UInt8](data) + let cut = min(max(0, offset), bytes.count) + guard cut > 0 else { return 0 } + let floor = max(0, cut - resumeLookback) + if let escape = bytes[floor.. max(0, cut - 4), bytes[lead] & 0xC0 == 0x80 { lead -= 1 } + let length: Int = switch bytes[lead] { + case 0xC0...0xDF: 2 + case 0xE0...0xEF: 3 + case 0xF0...0xF7: 4 + default: 1 + } + return lead + length > cut ? lead : cut + } + + /// How far back a cut looks for the escape it may have split. Longer + /// than any sequence but a window title or a hyperlink, and one of + /// those cut in two is a title lost, not characters on the screen. + private static let resumeLookback = 256 + + /// Whether `sequence`, which starts at an ESC and holds no other, + /// already has its final byte. + private static func isCompleteSequence(_ sequence: ArraySlice) -> Bool { + let body = sequence.dropFirst() + guard let introducer = body.first else { return false } + let rest = body.dropFirst() + switch introducer { + case UInt8(ascii: "["): + return rest.contains { (0x40...0x7E).contains($0) } + case UInt8(ascii: "]"), UInt8(ascii: "P"), UInt8(ascii: "_"), + UInt8(ascii: "^"), UInt8(ascii: "X"): + // A string ends at BEL, or at an ST whose own ESC would have + // been the last one found. + return rest.contains(0x07) + case 0x20...0x2F: + return rest.contains { $0 >= 0x30 } + default: + return true + } + } } /// Splits a Rex terminal stream into what the terminal emulator should draw diff --git a/Multiplex/Models/TerminalGrid.swift b/Multiplex/Models/TerminalGrid.swift new file mode 100644 index 00000000..b2fa06ef --- /dev/null +++ b/Multiplex/Models/TerminalGrid.swift @@ -0,0 +1,59 @@ +import CoreGraphics + +/// A terminal's size in cells. +struct TerminalGrid: Equatable, Sendable { + var cols: Int + var rows: Int +} + +/// Fitting someone else's grid into this tab's pane. +/// +/// A Rex terminal has ONE size, its owner's. While another client owns it — +/// the Rex app on the Mac, the moment someone works there — a tab still has +/// to draw it, and an emulator can only draw a terminal correctly at that +/// terminal's own grid. So the tab takes the grid as given and makes it +/// fit: the text shrinks until the whole grid is inside the pane, and +/// whatever room is left over stays empty to the right and below. Typing in +/// the tab claims the size back and the pane is its own again. +enum TerminalGridFit { + /// Text never shrinks below this; a grid still too large at it runs + /// off the pane's right and bottom edges rather than becoming specks. + static let minimumFontSize: CGFloat = 5 + + /// The largest font size, in half points and no larger than the tab's + /// own, at which `grid` fits `available`. `cellPerPoint` is one cell's + /// size at a 1 pt font — cell size is close to linear in font size, and + /// the caller checks the result against the real cell and steps down. + static func fontSize( + for grid: TerminalGrid, in available: CGSize, + cellPerPoint: CGSize, preferred: CGFloat + ) -> CGFloat { + guard grid.cols > 0, grid.rows > 0, + cellPerPoint.width > 0, cellPerPoint.height > 0 + else { return preferred } + let widest = available.width / (CGFloat(grid.cols) * cellPerPoint.width) + let tallest = available.height / (CGFloat(grid.rows) * cellPerPoint.height) + let fitting = (min(widest, tallest) * 2).rounded(.down) / 2 + return max(min(preferred, minimumFontSize), min(preferred, fitting)) + } + + /// The frame that makes an emulator measure exactly `grid`: the cells + /// plus one physical pixel each way, which keeps the division that + /// turns points back into cells from landing one short. + static func frameSize( + for grid: TerminalGrid, cell: CGSize, displayScale: CGFloat + ) -> CGSize { + let safety = 1 / max(displayScale, 1) + return CGSize( + width: CGFloat(grid.cols) * cell.width + safety, + height: CGFloat(grid.rows) * cell.height + safety) + } + + /// Whether `grid` fits `available` at this cell size. + static func fits( + _ grid: TerminalGrid, cell: CGSize, in available: CGSize, displayScale: CGFloat + ) -> Bool { + let frame = frameSize(for: grid, cell: cell, displayScale: displayScale) + return frame.width <= available.width && frame.height <= available.height + } +} diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift index f764b55b..a6d32d32 100644 --- a/Multiplex/Services/RexSession.swift +++ b/Multiplex/Services/RexSession.swift @@ -109,6 +109,12 @@ struct RexSocket: Sendable { /// - **The last client to type owns the size**, as with tmux's latest-client /// rule. Another client (the Rex app) can claim the block back; the next /// keystroke here claims it again and re-sizes it. +/// - **The emulator's grid is the terminal's, not always this tab's.** A +/// terminal has one size, its owner's. While another client owns it the +/// stream says what that size is (`resize`), and the emulator is given +/// that grid (`onGrid`) and its screen drawn again — output laid out for +/// 170 columns and parsed at 132 left stray characters all over the tab +/// (user-reported, reproduced with a stand-in client holding the block). /// - **Only what a person does is written.** `write` is what claims, so /// nothing may reach it that the emulator said by itself. The server /// parses the terminal's output too and answers its queries there; the @@ -184,6 +190,14 @@ actor RexSession: TerminalTransport { /// the bootstrap was rendered during a full-screen program. private var exitWatch: AlternateScreenExitWatch? private var lastOutput = ContinuousClock.now + /// The grid the terminal has while it is someone else's to size — what + /// the stream last said. nil while its size is this tab's own. + private var terminalGrid: TerminalGrid? + /// What the emulator was last told (`onGrid`); nil is its own grid. + private var shownGrid: TerminalGrid? + /// One redraw at a time: each waits for the one before it. + private var drawing: Task? + private var isResyncing = false /// `attaching` until `open` returns; `closed` is final, whichever side /// ended it. private enum Phase { case attaching, live, closed } @@ -200,6 +214,7 @@ actor RexSession: TerminalTransport { private var onData: (@Sendable (Data) -> Void)? private var onClose: (@Sendable (String?) -> Void)? + private var onGrid: (@Sendable (TerminalGrid?) async -> Void)? init( openPipe: @escaping @Sendable () async throws -> RemotePipe, @@ -231,13 +246,20 @@ actor RexSession: TerminalTransport { /// Attaches and returns once the terminal's current screen has been /// handed to `onData`. `onClose` fires at most once, later, when the /// block or the link ends on its own (nil for a clean end). + /// + /// `onGrid` names the grid the emulator must have before the bytes that + /// follow are drawn: another client's while that client owns the + /// terminal's size, nil for the tab's own again. It is awaited — the + /// screen is not sent until it returns. func open( cols: Int, rows: Int, onData: @Sendable @escaping (Data) -> Void, - onClose: @Sendable @escaping (String?) -> Void + onClose: @Sendable @escaping (String?) -> Void, + onGrid: @Sendable @escaping (TerminalGrid?) async -> Void = { _ in } ) async throws { self.onData = onData self.onClose = onClose + self.onGrid = onGrid size = (cols, rows) do { try await attach() @@ -350,6 +372,9 @@ actor RexSession: TerminalTransport { stream = nil reached.subtract([.dataWelcome, .live]) held = Data() + // The size on record is the terminal being left's; the new stream + // opens by saying its own. + terminalGrid = nil exitWatch = nil pendingInput = "" input = RexInputEncoder() @@ -366,25 +391,122 @@ actor RexSession: TerminalTransport { } } + /// How much of the held stream a redraw draws after the rendering. + private enum Replay { + /// All of it. The attach's rule: nothing says where in the held + /// bytes the rendering was taken, so it errs toward repeating. + case everything + /// Only what arrived after the rendering was asked for. Whatever + /// came before that is in the rendering for certain, and the redraw + /// that asks for this has waited for the terminal to go quiet. + case sinceRequest + } + /// Renders the terminal's current screen into the emulator, then lets /// the stream through. Stream output is held from the moment this is /// called (the attach holds it from the start) to the moment the /// rendering has been drawn, so nothing is drawn UNDER a rendering that /// was taken later, and nothing that arrived meanwhile is dropped. - private func drawScreen(blockID: String) async { + /// + /// Redraws run one at a time. Two at once shared one hold: the first to + /// finish let the stream through, and the second then wiped whatever + /// had been drawn since its own rendering was taken. + private func drawScreen(blockID: String, replay: Replay = .everything) async { + held = held ?? Data() + let generation = dataGeneration + let previous = drawing + let task = Task { + await previous?.value + await self.performDraw(blockID: blockID, replay: replay, generation: generation) + } + drawing = task + await task.value + } + + private func performDraw(blockID: String, replay: Replay, generation: Int) async { + // A switch since this was asked for: the screen now belongs to + // another terminal, whose own redraw follows. + guard phase != .closed, generation == dataGeneration else { return } held = held ?? Data() + await adoptTerminalGrid() + let asked = held?.count ?? 0 // Two reads that depend on nothing of each other's, so they share // one round trip. async let alternate = isOnAlternateScreen(blockID: blockID) async let rendering = bootstrapScreen(blockID: blockID) let (onAlternateScreen, screen) = await (alternate, rendering) - guard phase != .closed else { return } + guard phase != .closed, generation == dataGeneration else { return } // RIS first: a resumed tab still shows what the last run drew. onData?(Data([0x1B, 0x63]) + screen) exitWatch = onAlternateScreen ? AlternateScreenExitWatch() : nil - let pending = held + let pending = held ?? Data() held = nil - if let pending, !pending.isEmpty { deliver(pending) } + let rest = replay == .everything + ? pending + : pending.dropFirst(RexWire.resumeOffset(in: pending, from: asked)) + if !rest.isEmpty { deliver(Data(rest)) } + // The size changed again while the rendering was on its way. + if terminalGrid != shownGrid, !isResyncing { + held = Data() + Task { await self.resync() } + } + } + + // MARK: - Another client's size + + /// The stream said what size the terminal is. While this client owns + /// the block that is the tab's own size and nothing changes; otherwise + /// it is whatever its owner made it, and the emulator has to follow. + private func noteTerminalSize(cols: Int, rows: Int, owner: String?) { + let isOwn = (owner != nil && owner == clientID) || (cols == size.cols && rows == size.rows) + terminalGrid = isOwn ? nil : TerminalGrid(cols: cols, rows: rows) + // While the screen is still to be drawn (attach, switch, a redraw + // already holding) that redraw reads the grid itself. + guard terminalGrid != shownGrid, held == nil else { return } + // Everything from here on was written for the new size. + held = Data() + Task { await self.resync() } + } + + /// Gives the emulator the terminal's grid and draws the screen again at + /// it, once the burst a resize sets off has passed — the program + /// repaints on SIGWINCH, and a rendering taken mid-repaint would have + /// the rest of it drawn on top a second time. + /// + /// It redraws even when the size has gone back by then: what was + /// written in between was laid out for a grid the emulator never had. + private func resync() async { + guard !isResyncing else { return } + isResyncing = true + defer { isResyncing = false } + repeat { + held = held ?? Data() + await waitForQuiet() + // A switch draws the new terminal itself, and the hold is its. + guard phase != .closed, !isSwitching, let blockID else { return } + await drawScreen(blockID: blockID, replay: .sinceRequest) + } while phase != .closed && !isSwitching && terminalGrid != shownGrid + } + + private func adoptTerminalGrid() async { + while terminalGrid != shownGrid, phase != .closed { + let grid = terminalGrid + await onGrid?(grid) + shownGrid = grid + } + } + + /// Returns once the terminal has written nothing for a moment, or + /// after the cap for one that never stops. + private func waitForQuiet() async { + let started = ContinuousClock.now + while phase != .closed { + try? await Task.sleep(for: .milliseconds(60)) + let now = ContinuousClock.now + if now - lastOutput >= .milliseconds(120) || now - started >= .milliseconds(800) { + break + } + } } /// Stream output on its way to the emulator. The one place that also @@ -409,14 +531,7 @@ actor RexSession: TerminalTransport { /// terminal has gone quiet, leaves nothing in the window to repeat. A /// terminal that never goes quiet is redrawn anyway after the cap. private func redrawOnceQuiet(blockID: String) async { - let started = ContinuousClock.now - while phase != .closed { - try? await Task.sleep(for: .milliseconds(60)) - let now = ContinuousClock.now - if now - lastOutput >= .milliseconds(120) || now - started >= .milliseconds(800) { - break - } - } + await waitForQuiet() guard phase != .closed else { return } await drawScreen(blockID: blockID) } @@ -726,11 +841,17 @@ actor RexSession: TerminalTransport { for event in events { switch event { case .output(let output): - if held == nil { deliver(output) } else { held?.append(output) } - case .resize, .childExited: - // The size is this tab's own while it owns the block, - // and a program's exit closes the block, which arrives - // as the stream's close. Neither needs acting on here. + if held == nil { + deliver(output) + } else { + held?.append(output) + lastOutput = .now + } + case .resize(let cols, let rows, let owner): + noteTerminalSize(cols: cols, rows: rows, owner: owner) + case .childExited: + // A program's exit closes the block, which arrives as + // the stream's close. break } } diff --git a/Multiplex/Services/TerminalSessionController.swift b/Multiplex/Services/TerminalSessionController.swift index 36d57403..7eb6f65f 100644 --- a/Multiplex/Services/TerminalSessionController.swift +++ b/Multiplex/Services/TerminalSessionController.swift @@ -167,6 +167,18 @@ final class TerminalSessionController { private var handoffWatch: ShellHandoff.UpdatePromptWatch? private var lastCols = 80 private var lastRows = 24 + /// Rex only: the grid of the terminal on show while another client + /// owns its size (`RexSession`'s `onGrid`). The pane lays the emulator + /// out at it; nil is the pane's own grid. + private(set) var gridPin: TerminalGrid? + /// The pane's side of `gridPin`. It must have the emulator at the new + /// grid by the time it returns — the screen drawn next is for it. + var onGridPinChanged: (() -> Void)? + /// The last grid the pane measured for itself: what this tab asks a + /// terminal to be. `lastCols`/`lastRows` are whatever the emulator has, + /// which under a pin is somebody else's size. + private var ownSize: TerminalSize? + private var isSettlingGridPin = false private var started = false private var transportGeneration = 0 /// Session-volume counters drained by the stats pump. Written on the @@ -432,6 +444,8 @@ final class TerminalSessionController { private func beginTransportRun() { transportGeneration &+= 1 let generation = transportGeneration + // A new run attaches at this tab's own size. + setGridPin(nil) let output = TerminalOutputCoalescer { [weak self] bytes in guard let self, self.transportGeneration == generation else { return } self.feed(bytes) @@ -497,7 +511,7 @@ final class TerminalSessionController { await transport.close() return } - let openedSize = TerminalSize(cols: lastCols, rows: lastRows) + let openedSize = ownSize ?? TerminalSize(cols: lastCols, rows: lastRows) let onData: @Sendable (Data) -> Void = { data in output.append(data) } @@ -513,7 +527,17 @@ final class TerminalSessionController { if let rex { try await rex.open( cols: openedSize.cols, rows: openedSize.rows, - onData: onData, onClose: onClose) + onData: onData, onClose: onClose, + onGrid: { [weak self] grid in + await MainActor.run { [weak self] in + guard let self, self.transportGeneration == generation + else { return } + // What was written for the old grid is parsed + // at the old grid. + output.flush() + self.setGridPin(grid) + } + }) // Which terminal an unnamed attach landed on is the // session's answer, known only now. rexBlockID = await rex.blockID ?? rexBlockID @@ -931,11 +955,31 @@ final class TerminalSessionController { startResizePump(for: transport) // Layout may have changed while the handshake/open call was awaiting; // reconcile once with the newest geometry before normal coalescing. - if lastCols != size.cols || lastRows != size.rows { + if gridPin == nil, lastCols != size.cols || lastRows != size.rows { resizeContinuation?.yield(TerminalSize(cols: lastCols, rows: lastRows)) } } + /// Gives the emulator another client's grid, or its own back. + /// + /// The pane changes the text size and the frame to do it, and each of + /// those makes SwiftTerm report a grid on the way — none of them the + /// tab's own, so none is sent on. Once the pane has settled back on its + /// own grid, that one is: the window may have been resized meanwhile. + private func setGridPin(_ grid: TerminalGrid?) { + guard grid != gridPin else { return } + gridPin = grid + isSettlingGridPin = true + onGridPinChanged?() + isSettlingGridPin = false + // With no pane to lay out, the emulator is still at the grid it + // was given and `ownSize` already holds the tab's last own one. + guard grid == nil, onGridPinChanged != nil else { return } + let own = TerminalSize(cols: lastCols, rows: lastRows) + ownSize = own + if status == .live { resizeContinuation?.yield(own) } + } + private func stopTransportPumps() { stopInputPump() stopResizePump() @@ -1830,8 +1874,12 @@ final class TerminalSessionController { guard cols != lastCols || rows != lastRows else { return } lastCols = cols lastRows = rows + // A grid taken from another client is the emulator's, not this + // tab's ask: the far side is never told it. + let isOwn = gridPin == nil && !isSettlingGridPin + if isOwn { ownSize = TerminalSize(cols: cols, rows: rows) } guard status == .live else { return } - resizeContinuation?.yield(TerminalSize(cols: cols, rows: rows)) + if isOwn { resizeContinuation?.yield(TerminalSize(cols: cols, rows: rows)) } // A resize relayouts the multiplexer's panes, so a select-text clamp // fetched for the old geometry is wrong — refetch (the generation // counter drops the stale answer if resizes storm). diff --git a/Multiplex/Views/Terminal/SwiftTermView.swift b/Multiplex/Views/Terminal/SwiftTermView.swift index e9f4c6c0..d5be1a06 100644 --- a/Multiplex/Views/Terminal/SwiftTermView.swift +++ b/Multiplex/Views/Terminal/SwiftTermView.swift @@ -121,7 +121,10 @@ final class TerminalSurfaceView: UIView { TerminalFocusArbiter.installScribbleGate(on: view) view.renderUpdatesEnabled = configuration.isActive apply(configuration.theme, to: view) - if view.font.pointSize != configuration.fontSize { + coordinator.preferredFontSize = configuration.fontSize + // An adopted view showing another client's grid keeps the text + // size that grid was fitted at; the first layout fits it here. + if controller.gridPin == nil, view.font.pointSize != configuration.fontSize { view.font = .monospacedSystemFont( ofSize: configuration.fontSize, weight: .regular @@ -163,6 +166,14 @@ final class TerminalSurfaceView: UIView { #if os(visionOS) addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false + let terminalTrailing = view.trailingAnchor.constraint( + equalTo: trailingAnchor, + constant: -Self.terminalInsets.right + ) + let terminalBottom = view.bottomAnchor.constraint( + equalTo: bottomAnchor, + constant: -Self.terminalInsets.bottom + ) NSLayoutConstraint.activate([ view.topAnchor.constraint( equalTo: topAnchor, @@ -172,15 +183,10 @@ final class TerminalSurfaceView: UIView { equalTo: leadingAnchor, constant: Self.terminalInsets.left ), - view.trailingAnchor.constraint( - equalTo: trailingAnchor, - constant: -Self.terminalInsets.right - ), - view.bottomAnchor.constraint( - equalTo: bottomAnchor, - constant: -Self.terminalInsets.bottom - ), + terminalTrailing, + terminalBottom, ]) + coordinator.installGridEdges(trailing: terminalTrailing, bottom: terminalBottom) // Gaze hover for links: the overlay is a subview of the terminal // (its touches keep feeding the terminal's own pan recognizers) and // survives merge/split with it — reuse the one already riding an @@ -283,6 +289,7 @@ final class TerminalSurfaceView: UIView { terminalLeadingConstraint: terminalLeading, terminalTrailingConstraint: terminalTrailing ) + coordinator.installGridEdges(trailing: terminalTrailing, bottom: terminalBottom) coordinator.keyBarHeightConstraint = keyBarHeight coordinator.setRailOwnsBottomSafeArea(configuration.railOwnsBottomSafeArea) coordinator.setKeyRailHidden(configuration.keyRailHidden) @@ -308,6 +315,11 @@ final class TerminalSurfaceView: UIView { } controller.bind(view) + // Replace, never stack: a moved tab's hook still names the pane it + // left. + controller.onGridPinChanged = { [weak coordinator] in + coordinator?.applyGridPin(synchronously: true) + } if configuration.isActive { DispatchQueue.main.async { TerminalFocusArbiter.claim(view) @@ -340,12 +352,20 @@ final class TerminalSurfaceView: UIView { } } #endif - let fontChanged = view.font.pointSize != configuration.fontSize + // While the grid is another client's the text size is whatever + // fits it; the tab's own size comes back with its own grid. + let fontChanged = coordinator.preferredFontSize != configuration.fontSize + || (controller.gridPin == nil && view.font.pointSize != configuration.fontSize) + coordinator.preferredFontSize = configuration.fontSize if fontChanged { - view.font = .monospacedSystemFont( - ofSize: configuration.fontSize, - weight: .regular - ) + if controller.gridPin == nil { + view.font = .monospacedSystemFont( + ofSize: configuration.fontSize, + weight: .regular + ) + } else { + coordinator.applyGridPin(synchronously: false) + } } if coordinator.appliedTheme != configuration.theme { apply(configuration.theme, to: view) @@ -376,6 +396,8 @@ final class TerminalSurfaceView: UIView { #if !os(visionOS) coordinator.containerDidLayout() #endif + // The pane changed size under a grid that is not its own: fit again. + coordinator.applyGridPin(synchronously: false) } /// Colors change live — SwiftTerm's setters queue a full redraw, so an @@ -448,6 +470,128 @@ final class TerminalSurfaceView: UIView { self.controller = controller } + // MARK: Another client's grid (Rex) + + /// The tab's own text size — what the emulator goes back to when + /// the grid is its own again. + var preferredFontSize: CGFloat = 0 + /// The two edges a foreign grid pulls in, and where they rest + /// without one. Everything else that moves these edges (bottom + /// chrome, side safe areas) writes the resting value and calls + /// `applyGridEdges`, so the two never overwrite each other. + private var gridTrailingConstraint: NSLayoutConstraint? + private var gridBottomConstraint: NSLayoutConstraint? + private var restingTrailing: CGFloat = 0 + private var restingBottom: CGFloat = 0 + /// Room left beside and below a fitted grid (negative when even + /// the smallest text cannot fit it and it runs off the pane). + private var gridSlack = CGSize.zero + /// What the current fit was solved for; an unchanged pane is not + /// solved again on every layout pass. + private var gridFitKey: GridFitKey? + + private struct GridFitKey: Equatable { + var grid: TerminalGrid + var available: CGSize + var preferred: CGFloat + } + + func installGridEdges(trailing: NSLayoutConstraint, bottom: NSLayoutConstraint) { + gridTrailingConstraint = trailing + gridBottomConstraint = bottom + restingTrailing = trailing.constant + restingBottom = bottom.constant + gridSlack = .zero + gridFitKey = nil + } + + private func applyGridEdges() { + let trailing = restingTrailing - gridSlack.width + let bottom = restingBottom - gridSlack.height + if gridTrailingConstraint?.constant != trailing { + gridTrailingConstraint?.constant = trailing + } + if gridBottomConstraint?.constant != bottom { + gridBottomConstraint?.constant = bottom + } + } + + /// Lays the emulator out at the grid of a terminal another client + /// owns the size of (`TerminalSessionController.gridPin`), or back + /// at the pane's own. + /// + /// SwiftTerm measures its grid from its frame and its font, so the + /// grid is given by giving it exactly that frame: the text shrinks + /// until the grid fits the pane (`TerminalGridFit`), and the room + /// left over is taken off the trailing and bottom edges. Nothing + /// in the fork changes, and its frame-is-the-grid arithmetic — + /// scrolling, hit testing, the caret — stays true. + /// + /// `synchronously` is for the controller's call: the screen that + /// follows is drawn for this grid, so the grid has to be in place + /// when it returns. From a layout pass it only asks for another. + func applyGridPin(synchronously: Bool) { + guard let view = terminalView, let container = view.superview, + gridTrailingConstraint != nil, preferredFontSize > 0 + else { return } + func relayout() { + if synchronously { container.layoutIfNeeded() } else { container.setNeedsLayout() } + } + func setFontSize(_ size: CGFloat) { + guard abs(view.font.pointSize - size) > 0.01 else { return } + view.font = .monospacedSystemFont(ofSize: size, weight: .regular) + } + guard let grid = controller.gridPin else { + guard gridFitKey != nil || gridSlack != .zero else { return } + gridFitKey = nil + gridSlack = .zero + setFontSize(preferredFontSize) + applyGridEdges() + relayout() + return + } + if synchronously { container.layoutIfNeeded() } + let available = CGSize( + width: view.bounds.width + gridSlack.width, + height: view.bounds.height + gridSlack.height) + guard available.width > 0, available.height > 0 else { return } + let key = GridFitKey(grid: grid, available: available, preferred: preferredFontSize) + guard key != gridFitKey else { return } + let scale = max(view.traitCollection.displayScale, 1) + func cell() -> CGSize? { + let dimensions = view.terminalDimensions + guard dimensions.cols > 0, dimensions.rows > 0 else { return nil } + let optimal = view.getOptimalFrameSize() + return CGSize( + width: optimal.width / CGFloat(dimensions.cols), + height: optimal.height / CGFloat(dimensions.rows)) + } + guard let measured = cell(), view.font.pointSize > 0 else { return } + var size = TerminalGridFit.fontSize( + for: grid, in: available, + cellPerPoint: CGSize( + width: measured.width / view.font.pointSize, + height: measured.height / view.font.pointSize), + preferred: preferredFontSize) + setFontSize(size) + // Cell size is only nearly linear in font size (it is snapped + // to pixels): check the real cell and step down. + while let fitted = cell(), + size > TerminalGridFit.minimumFontSize, + !TerminalGridFit.fits(grid, cell: fitted, in: available, displayScale: scale) { + size = max(TerminalGridFit.minimumFontSize, size - 0.5) + setFontSize(size) + } + guard let fitted = cell() else { return } + let frame = TerminalGridFit.frameSize(for: grid, cell: fitted, displayScale: scale) + gridSlack = CGSize( + width: available.width - frame.width, + height: available.height - frame.height) + gridFitKey = key + applyGridEdges() + relayout() + } + #if !os(visionOS) weak var keyBar: TerminalKeyBar? private(set) var railOwnsBottomSafeArea = false @@ -558,10 +702,10 @@ final class TerminalSurfaceView: UIView { } func updateBottomChromeHeight(_ height: CGFloat) { - guard let constraint = terminalBottomConstraint, - constraint.constant != -height + guard terminalBottomConstraint != nil, restingBottom != -height else { return } - constraint.constant = -height + restingBottom = -height + applyGridEdges() avoidingContainer?.layoutIfNeeded() } @@ -570,17 +714,18 @@ final class TerminalSurfaceView: UIView { /// pane. Both change the grid's clearance without rebuilding it. func updateContentSafeArea(_ safeArea: UIEdgeInsets) { guard let leadingConstraint = terminalLeadingConstraint, - let trailingConstraint = terminalTrailingConstraint + terminalTrailingConstraint != nil else { return } let leadingConstant = TerminalSurfaceView.terminalInsets.left + safeArea.left let trailingConstant = -(TerminalSurfaceView.terminalInsets.right + safeArea.right) guard leadingConstraint.constant != leadingConstant - || trailingConstraint.constant != trailingConstant + || restingTrailing != trailingConstant else { return } leadingConstraint.constant = leadingConstant - trailingConstraint.constant = trailingConstant + restingTrailing = trailingConstant + applyGridEdges() avoidingContainer?.layoutIfNeeded() } diff --git a/MultiplexTests/RexSessionTests.swift b/MultiplexTests/RexSessionTests.swift index 56cd2aed..0a647cbf 100644 --- a/MultiplexTests/RexSessionTests.swift +++ b/MultiplexTests/RexSessionTests.swift @@ -25,6 +25,11 @@ final class RexSessionTests: XCTestCase { private var closes: [String?] = [] func data(_ chunk: Data) { lock.withLock { chunks.append(chunk) } } + /// The emulator's grid changing hands, in line with what is drawn. + func grid(_ grid: TerminalGrid?) { + let text = grid.map { "GRID \($0.cols)x\($0.rows)" } ?? "GRID own" + lock.withLock { chunks.append(Data(text.utf8)) } + } func closed(_ reason: String?) { lock.withLock { closes.append(reason) } } var text: [String] { lock.withLock { chunks.map { String(decoding: $0, as: UTF8.self) } } } var closeReasons: [String?] { lock.withLock { closes } } @@ -36,7 +41,8 @@ final class RexSessionTests: XCTestCase { try await session.open( cols: cols, rows: rows, onData: { sink.data($0) }, - onClose: { sink.closed($0) } + onClose: { sink.closed($0) }, + onGrid: { sink.grid($0) } ) } @@ -266,6 +272,102 @@ final class RexSessionTests: XCTestCase { await session.close() } + // MARK: - Another client's size + + func testAnotherClientsSizeIsGivenToTheEmulatorBeforeTheScreenIsDrawnAgain() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN"]) + + // The Rex app takes the terminal at its own size, and the program + // repaints for it straight away. + server.screen = "WIDE" + server.sendResize(cols: 170, rows: 50, owner: "client:rex-app") + server.sendOutput("REPAINT") + await eventually { sink.text.last == "\u{1B}cWIDE" } + // The grid first, then the screen at it — and the repaint, which + // arrived before the rendering was asked for and so is in it, is + // not drawn a second time on top. + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "GRID 170x50", "\u{1B}cWIDE"]) + // Following is all it does: the size is not asked back. + XCTAssertEqual(server.calls.filter { $0 == "session.own_block" }.count, 1) + XCTAssertEqual( + server.calls.filter { $0.hasPrefix("com.superlogical.terminal.resize") }.count, 1) + + server.sendOutput("later") + await eventually { sink.text.last == "later" } + + // Typing here takes the terminal back; the stream then says it is + // this tab's size again and the emulator returns to its own grid. + server.screen = "OWN" + server.sendResize(cols: 100, rows: 30, owner: server.clientID) + await eventually { sink.text.last == "\u{1B}cOWN" } + XCTAssertEqual(Array(sink.text.suffix(2)), ["GRID own", "\u{1B}cOWN"]) + await session.close() + } + + func testThisTabsOwnResizesNeverMoveTheEmulatorsGrid() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + // A window drag: the stream reports sizes this client set, some of + // them already overtaken by the next one. + try await session.resize(cols: 120, rows: 40) + server.sendResize(cols: 110, rows: 35, owner: server.clientID) + server.sendResize(cols: 120, rows: 40, owner: server.clientID) + // Another client that happens to want this tab's size changes + // nothing either. + server.sendResize(cols: 120, rows: 40, owner: "client:rex-app") + server.sendOutput("after") + await eventually { sink.text.last == "after" } + try await Task.sleep(for: .milliseconds(400)) + + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "after"]) + XCTAssertEqual( + server.calls.filter { $0 == "com.superlogical.terminal.format" }.count, 1) + await session.close() + } + + func testASizeThatGoesBackBeforeTheRedrawIsStillDrawnAgainAtTheTabsOwnGrid() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + // Taken and given back inside the quiet wait. The emulator's grid + // has nowhere to go, but what the program wrote in between was + // laid out for 170 columns: it is replaced, not drawn. + server.screen = "BACK" + server.sendResize(cols: 170, rows: 50, owner: "client:rex-app") + server.sendOutput("one") + server.sendResize(cols: 100, rows: 30, owner: server.clientID) + server.sendOutput("two") + await eventually { sink.text.count == 2 } + try await Task.sleep(for: .milliseconds(300)) + + XCTAssertEqual(sink.text, ["\u{1B}cSCREEN", "\u{1B}cBACK"]) + XCTAssertEqual( + server.calls.filter { $0 == "com.superlogical.terminal.format" }.count, 2) + await session.close() + } + + func testATerminalAlreadyAtAnotherClientsSizeIsAttachedAtThatGrid() async throws { + let server = FakeRexServer() + // The claim did not hold: by the time the stream opens the Rex app + // has the terminal again. + server.openingSize = (170, 50, "client:rex-app") + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + XCTAssertEqual(sink.text, ["GRID 170x50", "\u{1B}cSCREEN"]) + await session.close() + } + // MARK: - Full-screen programs func testATabAttachedDuringAFullScreenProgramRedrawsWhenItExits() async throws { @@ -461,6 +563,8 @@ private final class FakeRexServer: @unchecked Sendable { var earlyOutput = "" var screen = "SCREEN" var screenKind = "primary" + /// The size the stream opens by stating, and whose it is. + var openingSize: (cols: Int, rows: Int, owner: String) = (100, 30, "client:me") let nonce: UInt64 = 0x1122_3344_5566_7788 let clientID = "client:me" @@ -491,6 +595,19 @@ private final class FakeRexServer: @unchecked Sendable { lock.withLock { dataFeed }?.yield(Self.frame(0x2, Data(text.utf8))) } + /// The stream's own word that the terminal changed size, and whose + /// size it now is. + func sendResize(cols: Int, rows: Int, owner: String) { + lock.withLock { dataFeed }?.yield(Self.frame( + 0x2, Data(Self.resizeMessage(nonce: nonce, cols: cols, rows: rows, owner: owner).utf8))) + } + + static func resizeMessage(nonce: UInt64, cols: Int, rows: Int, owner: String) -> String { + "\u{1B}_rex1;\(nonce);" + + #"{"type":"resize","cols":\#(cols),"rows":\#(rows),"owner":"\#(owner)"}"# + + "\u{1B}\\" + } + func closeData(code: UInt16, reason: String) { let feed = lock.withLock { dataFeed } feed?.yield(Self.frame( @@ -728,12 +845,13 @@ private final class FakeRexServer: @unchecked Sendable { feed.yield(FakeRexServer.frame(0x2, Data(welcome))) // A snapshot the emulator must never see, the `resize` that ends // it, and whatever the program printed straight away. - let marker = "\u{1B}_rex1;\(server.nonce);" - let resize = #"{"type":"resize","cols":100,"rows":30,"owner":"client:me"}"# + let opening = server.openingSize feed.yield(FakeRexServer.frame( 0x2, Data("GHOSTSNP\u{1}\u{0}binary snapshot".utf8) - + Data((marker + resize + "\u{1B}\\").utf8) + + Data(FakeRexServer.resizeMessage( + nonce: server.nonce, cols: opening.cols, rows: opening.rows, + owner: opening.owner).utf8) + Data(server.earlyOutput.utf8))) } diff --git a/MultiplexTests/RexWireTests.swift b/MultiplexTests/RexWireTests.swift index eed01e6e..3c41bb62 100644 --- a/MultiplexTests/RexWireTests.swift +++ b/MultiplexTests/RexWireTests.swift @@ -359,6 +359,61 @@ final class RexWireTests: XCTestCase { XCTAssertNil(RexWire.parseDataReply(Data())) } + // MARK: - Picking a held stream up again + + func testACleanCutResumesWhereItWasMade() { + let data = Data("one\r\n\u{1B}[31mtwo\u{1B}[0m\r\nthree".utf8) + // After a line, after a finished sequence, in plain text. + for offset in [5, 10, 13, 17, 21] { + XCTAssertEqual(RexWire.resumeOffset(in: data, from: offset), offset, "\(offset)") + } + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 0), 0) + // Out of range is clamped, not trapped on. + XCTAssertEqual(RexWire.resumeOffset(in: data, from: -4), 0) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 999), data.count) + XCTAssertEqual(RexWire.resumeOffset(in: Data(), from: 3), 0) + } + + func testACutInsideAnEscapeSequenceBacksUpToItsStart() { + // "ab" ESC [ 3 8 ; 5 ; 1 2 m "cd": the sequence starts at 2 and its + // final byte is at 11. + let data = Data("ab\u{1B}[38;5;12mcd".utf8) + for offset in 3...11 { + XCTAssertEqual(RexWire.resumeOffset(in: data, from: offset), 2, "\(offset)") + } + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 12), 12) + // The same question of a cut at the very end of what has arrived. + XCTAssertEqual(RexWire.resumeOffset(in: data.prefix(9), from: 9), 2) + + // A lone ESC, a charset designator missing its final byte, and an + // OSC still waiting for its terminator. + XCTAssertEqual(RexWire.resumeOffset(in: Data("ab\u{1B}".utf8), from: 3), 2) + XCTAssertEqual(RexWire.resumeOffset(in: Data("ab\u{1B}(B".utf8), from: 4), 2) + XCTAssertEqual(RexWire.resumeOffset(in: Data("ab\u{1B}(B".utf8), from: 5), 5) + let title = Data("ab\u{1B}]0;title\u{07}cd".utf8) + XCTAssertEqual(RexWire.resumeOffset(in: title, from: 8), 2) + XCTAssertEqual(RexWire.resumeOffset(in: title, from: 11), 2) + XCTAssertEqual(RexWire.resumeOffset(in: title, from: 12), 12) + // An ST's own ESC: the string before it is whole, the ST is not. + let hyperlink = Data("\u{1B}]8;;x\u{1B}\\y".utf8) + XCTAssertEqual(RexWire.resumeOffset(in: hyperlink, from: 7), 6) + XCTAssertEqual(RexWire.resumeOffset(in: hyperlink, from: 8), 8) + } + + func testACutInsideACharacterBacksUpToItsLeadByte() { + // "a" + 測 (3 bytes) + "b" + 😀 (4 bytes). + let data = Data("a測b😀".utf8) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 1), 1) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 2), 1) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 3), 1) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 4), 4) + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 5), 5) + for offset in 6...8 { + XCTAssertEqual(RexWire.resumeOffset(in: data, from: offset), 5, "\(offset)") + } + XCTAssertEqual(RexWire.resumeOffset(in: data, from: 9), 9) + } + // MARK: - Terminal stream private func expectedEvents() -> [RexTerminalStream.Event] { diff --git a/MultiplexTests/TerminalFullResetTests.swift b/MultiplexTests/TerminalFullResetTests.swift new file mode 100644 index 00000000..1d1539e2 --- /dev/null +++ b/MultiplexTests/TerminalFullResetTests.swift @@ -0,0 +1,54 @@ +import SwiftTerm +import XCTest + +/// The fork's full reset (`Multiplex patch` in `Terminal.setup`): RIS +/// empties the alternate screen as well as the normal one. +/// +/// A Rex tab redraws from a rendering behind an RIS — on attach, when the +/// tab switches to another terminal of its session, when the terminal's +/// size changes hands. Upstream's reset left the alternate buffer's rows in +/// place, and a buffer that has rows is not blanked on the way back in, so +/// switching from one full-screen program to another drew the second over +/// the first (user-reported 2026-11-20: stray characters after switching +/// between two Rex terminals, both running an agent). +final class TerminalFullResetTests: XCTestCase { + private func row(_ terminal: Terminal, _ index: Int) -> String { + (terminal.getLine(row: index)?.translateToString() ?? "") + // An untouched cell reads as NUL, an erased one as a space. + .trimmingCharacters(in: CharacterSet(charactersIn: " \0")) + } + + func testAFullResetEmptiesTheAlternateScreenToo() { + let terminal = Terminal( + delegate: SilentTerminalDelegate(), + options: TerminalOptions(cols: 40, rows: 6, scrollback: 100) + ) + // One full-screen program paints every row… + terminal.feed(text: "\u{1b}[?1049h\u{1b}[2J\u{1b}[H") + for index in 1...6 { + terminal.feed(text: "\u{1b}[\(index);1HFIRST PROGRAM ROW \(index)") + } + XCTAssertEqual(row(terminal, 0), "FIRST PROGRAM ROW 1") + + // …the tab is redrawn for another, which paints one cell. + terminal.feed(text: "\u{1b}c\u{1b}[?1049h\u{1b}[3;5HSECOND") + + XCTAssertEqual( + (0..<6).map { row(terminal, $0) }, + ["", "", "SECOND", "", "", ""]) + } + + /// The normal screen and its scrollback were always reset; pinned here + /// so the patch above cannot be "fixed" by trading one for the other. + func testAFullResetStillEmptiesTheNormalScreenAndItsScrollback() { + let terminal = Terminal( + delegate: SilentTerminalDelegate(), + options: TerminalOptions(cols: 40, rows: 4, scrollback: 100) + ) + for index in 1...12 { terminal.feed(text: "line \(index)\r\n") } + terminal.feed(text: "\u{1b}cfresh") + + XCTAssertEqual(terminal.buffer.yDisp, 0) + XCTAssertEqual((0..<4).map { row(terminal, $0) }, ["fresh", "", "", ""]) + } +} diff --git a/MultiplexTests/TerminalGridFitTests.swift b/MultiplexTests/TerminalGridFitTests.swift new file mode 100644 index 00000000..4ed89aa6 --- /dev/null +++ b/MultiplexTests/TerminalGridFitTests.swift @@ -0,0 +1,85 @@ +import CoreGraphics +import XCTest +@testable import Multiplex + +/// Fitting a terminal another client sized into this tab's pane +/// (`TerminalGridFit`): the text shrinks until the whole grid is inside, +/// never grows past the tab's own size, and the frame handed to the +/// emulator measures back to exactly the grid. +final class TerminalGridFitTests: XCTestCase { + /// A monospaced cell at 1 pt, close to the system font's. + private let perPoint = CGSize(width: 0.6, height: 1.2) + private let pane = CGSize(width: 1056, height: 704) // 132 x 44 at 13.33 pt + + func testAGridThatAlreadyFitsKeepsTheTabsOwnTextSize() { + let size = TerminalGridFit.fontSize( + for: TerminalGrid(cols: 100, rows: 30), in: pane, + cellPerPoint: perPoint, preferred: 13) + XCTAssertEqual(size, 13) + } + + func testALargerGridShrinksTheTextToTheTighterDimensionInHalfPoints() { + // 170 columns need 1056 / (170 * 0.6) = 10.35 pt; 50 rows would + // allow 11.7. The width decides, rounded DOWN to a half point. + let size = TerminalGridFit.fontSize( + for: TerminalGrid(cols: 170, rows: 50), in: pane, + cellPerPoint: perPoint, preferred: 13) + XCTAssertEqual(size, 10) + + let tall = TerminalGridFit.fontSize( + for: TerminalGrid(cols: 80, rows: 100), in: pane, + cellPerPoint: perPoint, preferred: 13) + XCTAssertEqual(tall, 5.5) // 704 / (100 * 1.2) = 5.87 + } + + func testTextStopsShrinkingAtTheFloorAndNeverGrowsPastTheTabsOwn() { + let huge = TerminalGridFit.fontSize( + for: TerminalGrid(cols: 1000, rows: 300), in: pane, + cellPerPoint: perPoint, preferred: 13) + XCTAssertEqual(huge, TerminalGridFit.minimumFontSize) + + // A tab whose own text is already below the floor keeps it. + let tiny = TerminalGridFit.fontSize( + for: TerminalGrid(cols: 1000, rows: 300), in: pane, + cellPerPoint: perPoint, preferred: 4) + XCTAssertEqual(tiny, 4) + + // Unusable measurements change nothing. + XCTAssertEqual(TerminalGridFit.fontSize( + for: TerminalGrid(cols: 0, rows: 50), in: pane, + cellPerPoint: perPoint, preferred: 13), 13) + XCTAssertEqual(TerminalGridFit.fontSize( + for: TerminalGrid(cols: 170, rows: 50), in: pane, + cellPerPoint: .zero, preferred: 13), 13) + } + + func testTheFrameMeasuresBackToExactlyTheGrid() { + let grid = TerminalGrid(cols: 170, rows: 50) + for scale: CGFloat in [1, 2, 3] { + // Cells as the emulator snaps them: whole pixels. + let cell = CGSize( + width: (6.21 * scale).rounded() / scale, + height: ceil(12.4 * scale) / scale) + let frame = TerminalGridFit.frameSize(for: grid, cell: cell, displayScale: scale) + // SwiftTerm's own arithmetic (`processSizeChange`). + XCTAssertEqual(Int(frame.width / cell.width), 170, "scale \(scale)") + XCTAssertEqual(Int(frame.height / cell.height), 50, "scale \(scale)") + // And not a pixel more than one over. + XCTAssertLessThanOrEqual( + frame.width - CGFloat(grid.cols) * cell.width, 1 / scale + 0.0001) + } + } + + func testFitsComparesTheWholeFrameAgainstThePane() { + let grid = TerminalGrid(cols: 170, rows: 50) + XCTAssertTrue(TerminalGridFit.fits( + grid, cell: CGSize(width: 6, height: 12), in: pane, displayScale: 2)) + // 170 * 6.25 = 1062.5 > 1056. + XCTAssertFalse(TerminalGridFit.fits( + grid, cell: CGSize(width: 6.25, height: 12), in: pane, displayScale: 2)) + // Exactly the cells but no room for the safety pixel. + XCTAssertFalse(TerminalGridFit.fits( + TerminalGrid(cols: 176, rows: 50), cell: CGSize(width: 6, height: 12), + in: pane, displayScale: 2)) + } +} diff --git a/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift b/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift index 0f7096d3..b3824759 100644 --- a/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift +++ b/Vendor/SwiftTerm/Sources/SwiftTerm/Terminal.swift @@ -1344,6 +1344,14 @@ open class Terminal { clearProgramStatus() resetNormalBuffer() activateNormalBuffer(clearAlt: false) + // Multiplex patch: a full reset empties the alternate screen + // too. It is otherwise emptied only on the way out of it + // (1047/1049), and `fillViewportRows` leaves a buffer that + // already has rows alone — so after RIS during a full-screen + // program, the next program to enter the alternate screen was + // drawn over the last one's cells. + clearKittyImages(in: altBuffer, isAlternateBuffer: true) + altBuffer.clear () resetSemanticPromptState(clearingScreenMarks: true) } else { normalBuffer.resize(newCols: cols, newRows: rows) diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index 2b030dc0..144297a3 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -527,8 +527,61 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. which is why the pump never had to care. - **The last client to type owns the size** (tmux's latest-client rule): the Rex app can claim the block back (`block_owner_changed`); - the next keystroke here claims and re-sizes it. Until then the tab - shows another client's size — Multiplex does not letterbox. + the next keystroke here claims and re-sizes it. Until then the + terminal has the other client's size, and the tab draws it AT that + size (next bullet). + - ⚠ **The emulator's grid follows the terminal's, not the pane's.** A + terminal has one size, its owner's; the stream says what it is + (`resize`, with the owner). Ignored — the first shape, "Multiplex does + not letterbox" — the tab parsed output laid out for 170 columns at 132 + and filled with stray characters the moment the Rex app held the + terminal at another size (reproduced with a stand-in client; and since + the tab stopped answering queries, above, nothing claims the size back + until someone types). Now a size that is another client's + (`RexSession.noteTerminalSize`: not this client's, not this tab's own + dimensions) is followed: + - `RexSession` holds the stream from that `resize` on, waits for the + repaint a SIGWINCH sets off to go quiet (the alternate-screen wait: + 120 ms, capped at 800), has the emulator take the grid (`onGrid`, + awaited), then draws the screen again from `format`. Held bytes + that arrived before the rendering was asked for are in it and are + NOT drawn again (`Replay.sinceRequest`; `RexWire.resumeOffset` + keeps the cut off the middle of an escape sequence or a character) + — replaying them, the attach's rule, drew the program's repaint + twice. The attach keeps its own rule: it has no quiet wait to lean + on. + - Redraws run one at a time (`drawScreen` chains them). Two sharing + one hold let the first release the stream under the second. + - The pane gives SwiftTerm the grid by giving it the FRAME + (`TerminalSurfaceView.Coordinator.applyGridPin`, `TerminalGridFit`, + pure + tested): text shrinks in half points, never below 5 pt and + never above the tab's own, until the grid fits; what is left over + comes off the trailing and bottom edges. The fork is untouched and + its frame-is-the-grid arithmetic stays true. A fork-side "pinned + grid" was rejected: the view's scroll geometry, hit testing and + caret all divide the frame by the cell. + - The grids SwiftTerm reports on the way (`sizeChanged` for each font + and frame step) are not this tab's ask and are never sent + (`TerminalSessionController.gridPin`, `isSettlingGridPin`); the + tab's own last grid is kept (`ownSize`) for the next attach. + - It ends when this client owns the block again — typing claims it, + or the other client leaves and the server hands it back — because + the stream then reports a size whose owner is this client. + - Only FOLLOWING: the tab never takes the size back by itself. That + was the flicker. + - To re-measure: a second control connection that `own_block(take)`s + and resizes to something larger than the pane, then type in the + terminal from that side (`rex send`). The tab must match `rex + capture` cell for cell. Not exercised: the real Rex app as the + other client, and a tab whose pane is off screen when the size + changes hands (its emulator is laid out when it next appears, after + the rendering was drawn). + - ⚠ **Every redraw is RIS + a rendering, and RIS has to empty BOTH + screens.** Upstream SwiftTerm's did not empty the alternate one, so + the REX key's switch from one full-screen program to another (two + agents — the common case) drew the second over the first; fixed in + the fork (`swiftterm-fork.md`, `TerminalFullResetTests`). A shell on + either side hid it, which is why the first switch tests passed. - ⚠ **Nothing the emulator says by itself reaches a Rex terminal** (`TerminalSessionController.sendTerminalReport`). The server keeps the terminal and answers its queries there — measured with no client diff --git a/docs/agents/swiftterm-fork.md b/docs/agents/swiftterm-fork.md index 78b5e9ab..97854669 100644 --- a/docs/agents/swiftterm-fork.md +++ b/docs/agents/swiftterm-fork.md @@ -262,6 +262,22 @@ input encoding, or terminal rendering. `TerminalRemoteMouseTests`. Mouse packets used to leave through `sendResponse`; re-check that on a bump, or mouse input would be classed as a report and a Rex tab would lose its clicks. + - **A full reset empties the alternate screen too** + (`Terminal.setup(isReset:)`). Upstream's RIS replaces the normal + buffer and steps back to it with `activateNormalBuffer(clearAlt: + false)`; the alternate buffer is otherwise emptied only on the way + OUT of it (1047/1049), and `fillViewportRows` returns at once for a + buffer that already has rows. So after an RIS sent while a + full-screen program was up, the next `?1049h` showed that program's + cells again and whatever drew next drew over them. Nothing a + well-behaved program does hits this — it is what a HOST does when it + redraws a tab from scratch, which a Rex tab does behind every RIS + (`backends-and-probe.md`): switching from one terminal running an + agent to another left the first one's screen under the second + (user-reported 2026-11-20; with two stand-in full-screen programs + the whole first screen stayed). The reset now also clears the + alternate buffer and its kitty images. Pinned by + `TerminalFullResetTests`; mosh's resync reset rides the same path. - The visible screen's links are enumerable (`Terminal .visibleLinkMatches` + `TerminalView.visibleLinkRegions`, the inverse of `calculateTapHit`) — what visionOS gaze hover stands on. diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index 82c0d11b..7ab9e662 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -1,24 +1,24 @@ NEW SINCE 1.5.2 • iPhone Duo: the side column's buttons now move down when a Live Activity (a delivery, a timer, a call) pushes the clock and Wi-Fi symbols down the column, instead of sitting under them. They move back up when it ends. • iPad: with the keyboard locked, Apple Pencil no longer writes on the terminal. A stroke now taps, selects, and scrolls like a finger. Unlocked, the Pencil still handwrites text. -• Deck and terminal: a host that runs Rex (superlogical.com/rex) can now show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. When the host has Rex sessions a + REX chip appears on its rail; press it, or check REX in Host Settings under Backends. A session with several terminals offers the others under Open Terminal in the tile's menu, and the REX key in a Rex tab switches between them. New Session and + TAB can create a Rex session while a Rex server is running on the host (Multiplex does not start one); a host's default backend stays tmux or herdr. +• Deck and terminal: a host that runs Rex (superlogical.com/rex) can now show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. When the host has Rex sessions a + REX chip appears on its rail; press it, or check REX in Host Settings under Backends. A session's other terminals are under Open Terminal in the tile's menu, and the REX key in a Rex tab switches between them. New Session and + TAB can create a Rex session while a Rex server is running on the host; a host's default backend stays tmux or herdr. While the Rex app holds a terminal at another size, the tab shows it at that size, in smaller text if needed, until you type in the tab. • Terminal: the TMUX, HRDR or REX key now lights up when the session has more than one window (for Rex, terminal) to switch between. PLEASE TRY 1. On iPhone Duo, open or closed and upright, attach a session, then start a Live Activity in another app (a timer works) and come back: DECK and the buttons below it should start under the clock and Wi-Fi symbols, none hidden behind them. End the activity: the buttons should move back up. 2. On iPad with Apple Pencil, hold the keyboard key to lock it, then drag the Pencil across the terminal: it should scroll or select, with no handwriting ink and no text typed. Unlock: writing with the Pencil should type again. -3. On a host that runs Rex with a session open (the Mac app works), wait for the + REX chip on the host's rail and press it: the Rex sessions should appear as tinted tiles beside the tmux ones, with window names and the last lines of the screen. Rename a window in Rex: the tile should follow within a few seconds. -4. Press a Rex tile: a terminal should open showing what that Rex terminal shows, colors and earlier output included. Type a command: it should run, and Rex should show it. Type in Rex: the tab should follow. +3. On a host running Rex with a session open (the Mac app works), press the + REX chip on the host's rail: the Rex sessions should appear as tinted tiles with window names and the last lines of the screen. +4. Press a Rex tile: a terminal should open showing what that Rex terminal shows, colors and earlier output included. Type a command: it should run, and Rex should show it. 5. Open vim in a Rex terminal, then attach it from the deck: the tab should show it. Quit vim: the earlier output should come back, with one prompt. -6. On a Rex session with a split or a second window, long-press its tile and choose Open Terminal: choosing a terminal should open it as its own tab. +6. Long-press the tile of a Rex session with a split or second window and choose Open Terminal: the chosen terminal should open as its own tab. 7. Exit the shell in an attached Rex terminal: the tab should end with RECONNECT and CLOSE TAB, not an error. 8. Start an agent in a Rex terminal, then let it ask a question: the tile should show RUNNING, then NEEDS YOU. -9. In a Rex tab on a session with several terminals, press the REX key: the current one should be marked ACTIVE, and choosing another should switch the tab. -10. Press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. + TAB then New Session in a Rex tab should start in the same directory. With no Rex server running on the host, it should say so. +9. In a Rex tab on a session with several terminals, press the REX key and choose another: the tab should switch to it. Switch between two terminals that each run an agent or vim: nothing of the first should be left on the second. +10. Press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. + TAB then New Session in a Rex tab should start in the same directory. With no Rex server running, it should say so. 11. Lock the device for a minute with a Rex tab open: on return the tab should reconnect by itself. -12. In Host Settings under Backends, REX should be checkable, and New sessions run on should never list it. Uncheck it: the Rex tiles should go away. -13. Open a Rex terminal running an agent: the Agent Bar should show that agent's keys, and stay when another window of the session comes to the front in Rex. -14. Attach a tmux session with one window, then add a second from the TMUX panel: the TMUX key should turn brighter, and go back when the window is closed. The REX key should do the same for a second terminal. -15. Open the same Rex terminal in Rex on the Mac and in a Rex tab, then work on the Mac without touching the tab: the Mac's terminal should keep its size and not flicker. Typing in the tab should still take the size. +12. In Host Settings under Backends, uncheck REX: the Rex tiles should go away. New sessions run on should never list REX. +13. Open a Rex terminal running an agent: the Agent Bar should show its keys, and stay when another window of the session comes to the front in Rex. +14. Attach a tmux session with one window, then add a second from the TMUX panel: the TMUX key should turn brighter, and go back when the window is closed. +15. Open the same Rex terminal in Rex on the Mac and in a Rex tab, then work on the Mac without touching the tab: the Mac's terminal should keep its size and not flicker, and the tab should show the same screen at the Mac's size, never garbled. Type in the tab: it should take the size and its own text size back. Feedback: screenshot in TestFlight From 7f022ee07295693507438b718c19a094a94624df Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Mon, 23 Nov 2026 14:49:13 +0800 Subject: [PATCH 08/13] Put the Rex backend behind an experimental switch Rex speaks a preview server's protocol, which moved from API revision 14 to 18 within a week, so nobody should meet it by accident. Settings gains an Experimental section with a "Rex sessions" switch, off by default. The switch is per device and a host's record is not: `secondaryBackends` keeps `rex` whatever the switch says, because records sync and another device may have it on. The gate sits where the record is read (`SessionBackend.isAvailable`, asked by `monitoredBackends`, `monitors` and `showsBackendIdentity`), so the probe loop, tiles, New Session, widgets and external actions follow without checks of their own. The discovery riders and Host Settings' check bar list backends directly and use `availableCases`; the check bar carries a hidden checked `rex` through an edit. Nothing observes the switch: the hub re-reads the host on every refresh. `MULTIPLEX_REX=1` forces it on; the unit-test scheme sets it so tests that build Rex hosts do not depend on a simulator's defaults. Also records why a Rex tab cannot ride mosh yet and what to re-measure: Rex ships no terminal client (`rex block stream` still answers "not implemented" on preview.21), and a throwaway PTY client run by a real mosh-server met four traps that are now written down for whoever builds it once upstream does. --- AGENTS.md | 3 +- Multiplex/Localizable.xcstrings | 48 ++++++++++++++++ Multiplex/Models/ExperimentalFeatures.swift | 46 ++++++++++++++++ Multiplex/Models/Host.swift | 41 +++++++++++++- Multiplex/Services/ConnectionHub.swift | 6 +- Multiplex/Views/Deck/AddHostSheet.swift | 14 ++++- Multiplex/Views/Settings/SettingsView.swift | 25 +++++++++ .../ExperimentalFeaturesTests.swift | 54 ++++++++++++++++++ MultiplexTests/SettingsUIKitTests.swift | 2 + docs/agents/backends-and-probe.md | 55 ++++++++++++++++++- docs/agents/e2e-headless.md | 4 ++ docs/agents/mosh.md | 5 ++ fastlane/testflight-whats-new.txt | 12 ++-- project.yml | 5 ++ 14 files changed, 304 insertions(+), 16 deletions(-) create mode 100644 Multiplex/Models/ExperimentalFeatures.swift create mode 100644 MultiplexTests/ExperimentalFeaturesTests.swift diff --git a/AGENTS.md b/AGENTS.md index ba28e8d3..e2ffb34e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,6 @@ Multiplex — a spatial SSH terminal built around remote **tmux** (with herdr -as an optional second backend, and Rex sessions shown, attached and created); +as an optional second backend, and — experimental, behind a Settings switch — +Rex sessions shown, attached and created); visionOS-first, iPadOS alongside. The deck is a fleet-wide monitor wall: every host probes concurrently, every session renders as a live capture-pane tile, and each attach opens its own terminal diff --git a/Multiplex/Localizable.xcstrings b/Multiplex/Localizable.xcstrings index 74893e5e..db92b986 100644 --- a/Multiplex/Localizable.xcstrings +++ b/Multiplex/Localizable.xcstrings @@ -1750,6 +1750,22 @@ } } }, + "Experimental" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "実験的な機能" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "實驗性功能" + } + } + } + }, "Open Terminal" : { "localizations" : { "ja" : { @@ -1814,6 +1830,38 @@ } } }, + "Rex sessions" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexセッション" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex 工作階段" + } + } + } + }, + "Shows the sessions of a host that runs Rex (superlogical.com/rex) and attaches their terminals as tabs. Rex is a preview and can change under Multiplex. Once on, a host with Rex sessions offers + REX on its rail, and REX appears in Host Settings under Backends. Turning it off hides them at the deck's next refresh; hosts keep their setting." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rex(superlogical.com/rex)を実行しているホストのセッションを表示し、そのターミナルをタブとしてアタッチします。Rexはプレビュー版のため、Multiplexが対応する前に変更されることがあります。オンにすると、Rexセッションのあるホストは + REX をDeckに表示し、「ホスト設定」の「バックエンド」にREXが表示されます。オフにすると、Deckの次回更新時に非表示になります。ホストの設定は保持されます。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "顯示執行 Rex(superlogical.com/rex)的主機上的工作階段,並把其中的終端機連接成分頁。Rex 仍是預覽版,可能在 Multiplex 跟上之前就有變動。開啟後,有 Rex 工作階段的主機會在 Deck 上顯示 + REX,「主機設定」的「後端」下也會出現 REX。關閉後,這些項目會在 Deck 下次重新整理時隱藏;主機本身的設定會保留。" + } + } + } + }, "terminal %lld" : { "localizations" : { "ja" : { diff --git a/Multiplex/Models/ExperimentalFeatures.swift b/Multiplex/Models/ExperimentalFeatures.swift new file mode 100644 index 00000000..7ce8187b --- /dev/null +++ b/Multiplex/Models/ExperimentalFeatures.swift @@ -0,0 +1,46 @@ +import Foundation + +/// Features that ship behind a switch in Settings ▸ Experimental, off until +/// the user turns them on. +/// +/// The Rex backend is the first: it speaks a preview server's wire protocol +/// (`RexSession`), which has already moved under it between two measurements +/// a week apart, so nobody meets it by accident. +/// +/// ⚠ The switch is a fact about THIS device, never about a host. A host's +/// record keeps `rex` in `secondaryBackends` whatever the switch says — the +/// record syncs, and another device may have the feature on — and the gate +/// is applied where the record is read (`Host.SessionBackend.isAvailable`, +/// which `Host.monitoredBackends` and `monitors(_:)` ask). Turning the +/// switch off therefore hides Rex everywhere and forgets nothing. +/// +/// `MULTIPLEX_REX=1` forces it on regardless of the stored choice — harness +/// runs and the unit-test scheme set it (`project.yml`), so a test that +/// builds a Rex host never depends on a simulator's defaults. +enum ExperimentalFeatures { + static let rexBackendKey = "MultiplexRexBackend" + + /// Read once: the environment cannot change under a running process, and + /// `ProcessInfo.environment` builds a dictionary on every call — this is + /// asked per tile per render. + private static let rexBackendForced = + isForced(environment: ProcessInfo.processInfo.environment) + + static var isRexBackendEnabled: Bool { + rexBackendForced || UserDefaults.standard.bool(forKey: rexBackendKey) + } + + static func isRexBackendEnabled( + defaults: UserDefaults, environment: [String: String] + ) -> Bool { + isForced(environment: environment) || defaults.bool(forKey: rexBackendKey) + } + + static func setRexBackendEnabled(_ enabled: Bool, defaults: UserDefaults = .standard) { + defaults.set(enabled, forKey: rexBackendKey) + } + + private static func isForced(environment: [String: String]) -> Bool { + environment["MULTIPLEX_REX"] == "1" + } +} diff --git a/Multiplex/Models/Host.swift b/Multiplex/Models/Host.swift index d173a07e..35413ed7 100644 --- a/Multiplex/Models/Host.swift +++ b/Multiplex/Models/Host.swift @@ -47,6 +47,28 @@ struct Host: Identifiable, Codable, Hashable { /// still shown, attached, created and closed like any other's. var canBeDefault: Bool { self != .rex } + /// Whether this backend sits behind a Settings ▸ Experimental + /// switch (`ExperimentalFeatures`). + var isExperimental: Bool { self == .rex } + + /// Whether this device shows the backend at all. The one gate for + /// an experimental backend: a host's record may list it (records + /// sync, and the switch is per device), and every reader that asks + /// what a host monitors goes through `Host.monitoredBackends` or + /// `monitors(_:)`, which ask this. + var isAvailable: Bool { isAvailable(rexEnabled: ExperimentalFeatures.isRexBackendEnabled) } + + func isAvailable(rexEnabled: Bool) -> Bool { + switch self { + case .tmux, .herdr: true + case .rex: rexEnabled + } + } + + /// The backends this device offers — what Host Settings lists and + /// discovery asks about. + static var availableCases: [SessionBackend] { allCases.filter(\.isAvailable) } + /// The backends a host's default can be — what the "New sessions /// run on" bars and the Bind pane offer. static let defaultCases = allCases.filter(\.canBeDefault) @@ -356,9 +378,18 @@ struct Host: Identifiable, Codable, Hashable { /// iterates. Order is load-bearing: the primary's block leads the wall, /// and the primary alone answers reachability, minting, and the Signal /// check. + /// + /// A listed backend this device has switched off + /// (`SessionBackend.isAvailable`) is left out here and stays in the + /// record. var monitoredBackends: [SessionBackend] { + monitoredBackends(rexEnabled: ExperimentalFeatures.isRexBackendEnabled) + } + + func monitoredBackends(rexEnabled: Bool) -> [SessionBackend] { [sessionBackend] + SessionBackend.allCases.filter { $0 != sessionBackend && secondaryBackends.contains($0) + && $0.isAvailable(rexEnabled: rexEnabled) } } @@ -368,7 +399,8 @@ struct Host: Identifiable, Codable, Hashable { /// here, and answering with the other one's namesake would attach the /// wrong multiplexer. func monitors(_ backend: SessionBackend) -> Bool { - backend == sessionBackend || secondaryBackends.contains(backend) + backend == sessionBackend + || (secondaryBackends.contains(backend) && backend.isAvailable) } /// Whether tiles must say which multiplexer they came from. The single @@ -379,8 +411,11 @@ struct Host: Identifiable, Codable, Hashable { /// two array allocations — this is read once per tile per render and /// once per session per widget publish. The set never holds the primary /// (`secondaryBackends`' `didSet`), so non-empty is exactly "more than - /// one monitored backend". - var showsBackendIdentity: Bool { !secondaryBackends.isEmpty } + /// one monitored backend" — once the ones this device has switched off + /// are left out, which only a host that lists any pays for. + var showsBackendIdentity: Bool { + !secondaryBackends.isEmpty && secondaryBackends.contains(where: \.isAvailable) + } /// The configured launch models for one agent, picker-ready. func launchModels(for agent: AgentKind) -> [String] { diff --git a/Multiplex/Services/ConnectionHub.swift b/Multiplex/Services/ConnectionHub.swift index c4d3b02c..95a9ecf4 100644 --- a/Multiplex/Services/ConnectionHub.swift +++ b/Multiplex/Services/ConnectionHub.swift @@ -272,7 +272,9 @@ final class HostConnectionModel { /// acted on automatically; the press is the whole design. var offeredBackends: [BackendDiscovery.Result] { let monitored = Set(host.monitoredBackends) - return Host.SessionBackend.allCases.compactMap { backend in + // `availableCases`: a result found before an experimental backend + // was switched off is not an offer any more. + return Host.SessionBackend.availableCases.compactMap { backend in guard !monitored.contains(backend), let result = discovery[backend], result.offersSessions @@ -581,7 +583,7 @@ final class HostConnectionModel { // Discovery rides the primary probe for every backend this host // does NOT already monitor. A monitored one gets a full probe of // its own below, which would make the rider redundant work. - let discovering = Set(Host.SessionBackend.allCases) + let discovering = Set(Host.SessionBackend.availableCases) .subtracting(host.monitoredBackends) let secondaries = host.monitoredBackends.dropFirst() diff --git a/Multiplex/Views/Deck/AddHostSheet.swift b/Multiplex/Views/Deck/AddHostSheet.swift index 9c5155ea..633d4d48 100644 --- a/Multiplex/Views/Deck/AddHostSheet.swift +++ b/Multiplex/Views/Deck/AddHostSheet.swift @@ -1677,7 +1677,12 @@ final class AddHostViewController: UIViewController, UITextFieldDelegate, // MARK: Backend /// Every backend this host shows tiles for — the checked set. - private var enabledBackends: Set { form.enabledBackends } + /// The checked backends this device shows. One it has switched off + /// (`SessionBackend.isAvailable`) stays in the form, and so in the + /// record, without a check box or a line of copy. + private var enabledBackends: Set { + form.enabledBackends.filter(\.isAvailable) + } private var backendDetail: String { let enabled = enabledBackends @@ -1719,7 +1724,7 @@ final class AddHostViewController: UIViewController, UITextFieldDelegate, let checks = AddHostCheckBar( // The button face uppercases; pass the natural spelling so // VoiceOver reads "tmux", not the letters T-M-U-X. - choices: Host.SessionBackend.allCases.map { ($0.rawValue, $0) }, + choices: Host.SessionBackend.availableCases.map { ($0.rawValue, $0) }, selection: enabledBackends ) { [weak self] backends in self?.setEnabledBackends(backends) @@ -1785,7 +1790,10 @@ final class AddHostViewController: UIViewController, UITextFieldDelegate, /// Apply a new checked set, keeping the current default where it is still /// checked — `setBackends` promotes a survivor when it isn't. private func setEnabledBackends(_ backends: Set) { - updateTestSensitive { $0.backendSelection.setEnabled(backends) } + // The bar only knows the backends it lists: one that is checked in + // the record and hidden on this device is carried through. + let hidden = form.enabledBackends.filter { !$0.isAvailable } + updateTestSensitive { $0.backendSelection.setEnabled(backends.union(hidden)) } renderBackend() renderTestSection() } diff --git a/Multiplex/Views/Settings/SettingsView.swift b/Multiplex/Views/Settings/SettingsView.swift index c83b5e87..987ed351 100644 --- a/Multiplex/Views/Settings/SettingsView.swift +++ b/Multiplex/Views/Settings/SettingsView.swift @@ -246,6 +246,7 @@ final class SettingsViewController: UIViewController { ), makeWindowModeSection(), makeRendererSection(), + makeExperimentalSection(), makeScreenSection(), voiceInputSection, makeConnectionStatsSection(), @@ -493,6 +494,30 @@ final class SettingsViewController: UIViewController { ) } + /// Features that are off until asked for (`ExperimentalFeatures`). The + /// switch is read wherever a host's backends are, so nothing here has to + /// tell the deck: its next refresh asks again. + private func makeExperimentalSection() -> UIView { + let control = SettingsBooleanRow( + title: String(localized: "Rex sessions"), + isOn: ExperimentalFeatures.isRexBackendEnabled + ) { enabled in + ExperimentalFeatures.setRexBackendEnabled(enabled) + } + control.accessibilityIdentifier = "settings.experimental.rex" + return SettingsSectionView( + title: String(localized: "Experimental"), + detail: String(localized: """ + Shows the sessions of a host that runs Rex (superlogical.com/rex) and attaches \ + their terminals as tabs. Rex is a preview and can change under Multiplex. Once \ + on, a host with Rex sessions offers + REX on its rail, and REX appears in Host \ + Settings under Backends. Turning it off hides them at the deck's next refresh; \ + hosts keep their setting. + """), + rows: [control] + ) + } + /// iPhone and iPad: Vision Pro's display never idles out under the user. private func makeScreenSection() -> UIView? { #if os(visionOS) diff --git a/MultiplexTests/ExperimentalFeaturesTests.swift b/MultiplexTests/ExperimentalFeaturesTests.swift new file mode 100644 index 00000000..b1572143 --- /dev/null +++ b/MultiplexTests/ExperimentalFeaturesTests.swift @@ -0,0 +1,54 @@ +import XCTest +@testable import Multiplex + +/// The Rex backend is off until switched on, and the switch hides it without +/// touching a host's record. +final class ExperimentalFeaturesTests: XCTestCase { + private func makeDefaults() -> UserDefaults { + let name = "ExperimentalFeaturesTests.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + addTeardownBlock { defaults.removePersistentDomain(forName: name) } + return defaults + } + + func testRexIsOffUntilSwitchedOn() { + let defaults = makeDefaults() + XCTAssertFalse( + ExperimentalFeatures.isRexBackendEnabled(defaults: defaults, environment: [:])) + ExperimentalFeatures.setRexBackendEnabled(true, defaults: defaults) + XCTAssertTrue( + ExperimentalFeatures.isRexBackendEnabled(defaults: defaults, environment: [:])) + ExperimentalFeatures.setRexBackendEnabled(false, defaults: defaults) + XCTAssertFalse( + ExperimentalFeatures.isRexBackendEnabled(defaults: defaults, environment: [:])) + } + + func testTheEnvironmentForcesRexOnWhateverIsStored() { + let defaults = makeDefaults() + XCTAssertTrue(ExperimentalFeatures.isRexBackendEnabled( + defaults: defaults, environment: ["MULTIPLEX_REX": "1"])) + XCTAssertFalse(ExperimentalFeatures.isRexBackendEnabled( + defaults: defaults, environment: ["MULTIPLEX_REX": "0"])) + } + + func testOnlyRexIsExperimental() { + XCTAssertEqual(Host.SessionBackend.allCases.filter(\.isExperimental), [.rex]) + XCTAssertTrue(Host.SessionBackend.tmux.isAvailable(rexEnabled: false)) + XCTAssertTrue(Host.SessionBackend.herdr.isAvailable(rexEnabled: false)) + XCTAssertFalse(Host.SessionBackend.rex.isAvailable(rexEnabled: false)) + XCTAssertTrue(Host.SessionBackend.rex.isAvailable(rexEnabled: true)) + } + + func testAHostThatListsRexIsNotMonitoredForItWhileTheSwitchIsOff() throws { + var host = Host(name: "devbox", hostname: "devbox.local", username: "dev") + host.secondaryBackends = [.herdr, .rex] + + XCTAssertEqual(host.monitoredBackends(rexEnabled: true), [.tmux, .herdr, .rex]) + XCTAssertEqual(host.monitoredBackends(rexEnabled: false), [.tmux, .herdr]) + + // The record is untouched: it syncs, and the switch is per device. + XCTAssertEqual(host.secondaryBackends, [.herdr, .rex]) + let decoded = try JSONDecoder().decode(Host.self, from: JSONEncoder().encode(host)) + XCTAssertEqual(decoded.secondaryBackends, [.herdr, .rex]) + } +} diff --git a/MultiplexTests/SettingsUIKitTests.swift b/MultiplexTests/SettingsUIKitTests.swift index b474fb56..3a4f7968 100644 --- a/MultiplexTests/SettingsUIKitTests.swift +++ b/MultiplexTests/SettingsUIKitTests.swift @@ -60,6 +60,7 @@ final class SettingsUIKitTests: XCTestCase { "Your themes", ] + windowMode + [ "Terminal renderer", + "Experimental", ] + screen + [ "Voice input", "Connection stats", @@ -78,6 +79,7 @@ final class SettingsUIKitTests: XCTestCase { XCTAssertTrue(rendered.contains("MOSH TRANSPORT")) XCTAssertTrue(rendered.contains("AGENT HELPERS")) XCTAssertTrue(rendered.contains("Metal renderer")) + XCTAssertTrue(rendered.contains("Rex sessions")) XCTAssertTrue( rendered.contains("NOT INSTALLED") || rendered.contains("Noise reduction"), "Voice input shows the model's state or its switch" diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index 144297a3..d6c5da32 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -274,8 +274,28 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. - **Rex is shown, attached, and minted — never a host's default** (`Host.SessionBackend.rex`; `RexProbe` for the deck and the mint, `RexSession` for a tab; Rex 0.1.0-preview.19 / - API revision 14, measured 2026-11-16 against a throwaway server), + API revision 14, measured 2026-11-16 against a throwaway server — the + app still announces revision 14, and a client making the same calls + attached, typed, resized and streamed against preview.21 / revision 18 on + 2026-11-23), adapted as session→tile, window (a tab)→window, terminal block→pane. + - **Experimental: off until switched on in Settings ▸ Experimental** + (`ExperimentalFeatures.isRexBackendEnabled`, default off). ⚠ The switch + is per DEVICE and the record is per host: `secondaryBackends` keeps + `rex` whatever the switch says (records sync; another device may have + it on), and the gate sits where the record is read — + `SessionBackend.isAvailable`, asked by `Host.monitoredBackends`, + `monitors(_:)` and `showsBackendIdentity`. Everything downstream (probe + loop, tiles, New Session's "Runs on", widgets, `backend=rex` actions) + reads those, so none of it has a check of its own. Two surfaces list + backends directly and use `availableCases` instead: the discovery riders + (`ConnectionHub` — no `rex` exec on a host while it is off) and Host + Settings' check bar, which carries a hidden checked `rex` through an + edit rather than dropping it. Nothing observes the switch: the hub + re-reads the host every refresh, so it takes effect within one (~5 s). + A Rex tab already open keeps running. `MULTIPLEX_REX=1` forces it on — + the unit-test scheme sets it (`project.yml`), and a harness run that + seeds `secondaryBackends: ["rex"]` needs it too. - **Rex has no terminal client, so Multiplex is one.** No `rex attach` exists and `rex block stream` answers `not implemented`: Rex sessions are drawn by a native app over the server's WebSocket API @@ -636,6 +656,39 @@ HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. record is the only authority, and it reaches the strip through the window's own observation, so nothing polls), and mosh (no PTY for mosh-server to run — a Rex tab rides SSH whatever the host prefers). + - **TODO, waiting on upstream: mosh for a Rex tab needs a Rex + terminal client to run in mosh-server's PTY, and Rex ships none.** + Re-measured 2026-11-23 (0.1.0-preview.21 / API revision 18, mosh + 1.4.0): `rex block stream BLOCK [DATA_REF]` exists and still answers + `not implemented`; there is no `rex attach`; a `rex do` Lua script + cannot stand in (the terminal creator lists no events, and the output + is a second WebSocket the script cannot open). mosh itself syncs a + screen, not bytes, so `RexSession`'s two WebSockets cannot ride it. + Revisit when `rex block stream ` stops answering `not + implemented` — and check first whether it is a terminal client at + all or a one-way dump of the data stream (the `DATA_REF` argument + suggests the latter, which changes nothing here). + A throwaway PTY client (a Python port of the attach, run by a real + mosh-server, read through a real mosh-client) drew, typed and resized + correctly and met four things any such client has to handle: + 1. **Queries are answered twice.** mosh-server's emulator answers + DA/DSR in the output too, on the client's stdin, which a naive + client writes into the terminal (`62;22c;1R62c;1R` at the prompt, + and a size claim nobody made). Dropping queries from the output + before the PTY left one answer — the Rex server's. + 2. **No alternate screen.** After `:q` the vim frame stays; the + client must redraw (RIS + `format`) on every `?1049l`, as + `AlternateScreenExitWatch` does for one case today. + 3. **Another client's size has no way back to the app.** The client + sees the stream's `resize`, but a mosh tab's grid is the app's; the + grid pin above needs a side channel (unmeasured). + 4. **No scrollback, and nothing replaces it**: a mosh tab has none + (`mosh.md`), and a Rex tab has no Copy Mode or HISTORY. + Also unbuilt: the REX key's switch, which rides the control + connection a mosh tab would not have. Not a prerequisite, and cheaper + for the same complaint (a slow re-attach on a bad link): the + protocol's RESUME, which continues a dropped stream within 60 s + without a redraw — today a resume is always a fresh attach. ⚠ `TerminalSessionController.ridesMosh` is the one statement of that last rule: scrollback, FILE and the bar's MOSH badge read it, where reading `host.useMosh` raw gave a Rex tab on a mosh host no diff --git a/docs/agents/e2e-headless.md b/docs/agents/e2e-headless.md index d275e8ba..64f34b3f 100644 --- a/docs/agents/e2e-headless.md +++ b/docs/agents/e2e-headless.md @@ -50,6 +50,10 @@ app.multiplexterm.multiplex`): through the real surrender/adopt path (moved tabs keep connections). - `MULTIPLEX_AUTO_DROP=` — drops that file into the first tab (SFTP upload + typed path, the real drag path). +- `MULTIPLEX_REX=1` — turns the experimental Rex backend on whatever + Settings ▸ Experimental says (`ExperimentalFeatures`). Required by every + Rex recipe: without it a seeded `secondaryBackends: ["rex"]` is kept in + the record and not monitored. - `MULTIPLEX_AUTO_REX_SWITCH=` — on a Rex tab, presses row n (1-based) of the REX panel's Switch Terminal list once the tab is live — the headless stand-in for a press nothing else can make. Proof host-side: diff --git a/docs/agents/mosh.md b/docs/agents/mosh.md index 53239d05..85067fc6 100644 --- a/docs/agents/mosh.md +++ b/docs/agents/mosh.md @@ -32,6 +32,11 @@ Load-bearing decisions split from AGENTS.md. still ride the ordered terminal pump. mosh tabs have no exec surface: FILE is hidden and pane drops are refused with a message, never silently dropped. +- **A Rex tab never rides mosh** (`TerminalSessionController.ridesMosh`): + mosh-server needs a program to run in its PTY and Rex ships no terminal + client. Waiting on upstream's `rex block stream`; the measured traps for + whoever builds it are in `backends-and-probe.md` (Rex section, "TODO, + waiting on upstream"). - **A mosh tab has NO local scrollback** (`TerminalSessionController.localScrollbackLines` answers nil for mosh — a transport capability, owned beside the transport choice — and diff --git a/fastlane/testflight-whats-new.txt b/fastlane/testflight-whats-new.txt index 7ab9e662..03beeb1f 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -1,23 +1,23 @@ NEW SINCE 1.5.2 • iPhone Duo: the side column's buttons now move down when a Live Activity (a delivery, a timer, a call) pushes the clock and Wi-Fi symbols down the column, instead of sitting under them. They move back up when it ends. • iPad: with the keyboard locked, Apple Pencil no longer writes on the terminal. A stroke now taps, selects, and scrolls like a finger. Unlocked, the Pencil still handwrites text. -• Deck and terminal: a host that runs Rex (superlogical.com/rex) can now show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. When the host has Rex sessions a + REX chip appears on its rail; press it, or check REX in Host Settings under Backends. A session's other terminals are under Open Terminal in the tile's menu, and the REX key in a Rex tab switches between them. New Session and + TAB can create a Rex session while a Rex server is running on the host; a host's default backend stays tmux or herdr. While the Rex app holds a terminal at another size, the tab shows it at that size, in smaller text if needed, until you type in the tab. +• Experimental, off until you turn on Rex sessions in Settings under Experimental: a host that runs Rex (superlogical.com/rex) can show its Rex sessions as tiles, and a tile attaches the Rex terminal as a tab. A host with Rex sessions gets a + REX chip on its rail; press it, or check REX in Host Settings under Backends. A session's other terminals are under Open Terminal in the tile's menu, and the REX key in a Rex tab switches between them. New Session and + TAB can create a Rex session while a Rex server runs on the host; a host's default stays tmux or herdr. While the Rex app holds a terminal at another size, the tab shows it at that size, in smaller text if needed, until you type in the tab. • Terminal: the TMUX, HRDR or REX key now lights up when the session has more than one window (for Rex, terminal) to switch between. PLEASE TRY 1. On iPhone Duo, open or closed and upright, attach a session, then start a Live Activity in another app (a timer works) and come back: DECK and the buttons below it should start under the clock and Wi-Fi symbols, none hidden behind them. End the activity: the buttons should move back up. 2. On iPad with Apple Pencil, hold the keyboard key to lock it, then drag the Pencil across the terminal: it should scroll or select, with no handwriting ink and no text typed. Unlock: writing with the Pencil should type again. -3. On a host running Rex with a session open (the Mac app works), press the + REX chip on the host's rail: the Rex sessions should appear as tinted tiles with window names and the last lines of the screen. -4. Press a Rex tile: a terminal should open showing what that Rex terminal shows, colors and earlier output included. Type a command: it should run, and Rex should show it. +3. In Settings under Experimental, turn on Rex sessions. On a host running Rex with a session open (the Mac app works), press the + REX chip on the host's rail: the Rex sessions should appear as tinted tiles. +4. Press a Rex tile: a terminal should open showing what that Rex terminal shows, colors and earlier output included. Type a command: it should run. 5. Open vim in a Rex terminal, then attach it from the deck: the tab should show it. Quit vim: the earlier output should come back, with one prompt. 6. Long-press the tile of a Rex session with a split or second window and choose Open Terminal: the chosen terminal should open as its own tab. -7. Exit the shell in an attached Rex terminal: the tab should end with RECONNECT and CLOSE TAB, not an error. +7. Exit the shell in a Rex tab: it should end with RECONNECT and CLOSE TAB, not an error. 8. Start an agent in a Rex terminal, then let it ask a question: the tile should show RUNNING, then NEEDS YOU. 9. In a Rex tab on a session with several terminals, press the REX key and choose another: the tab should switch to it. Switch between two terminals that each run an agent or vim: nothing of the first should be left on the second. 10. Press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. + TAB then New Session in a Rex tab should start in the same directory. With no Rex server running, it should say so. 11. Lock the device for a minute with a Rex tab open: on return the tab should reconnect by itself. -12. In Host Settings under Backends, uncheck REX: the Rex tiles should go away. New sessions run on should never list REX. -13. Open a Rex terminal running an agent: the Agent Bar should show its keys, and stay when another window of the session comes to the front in Rex. +12. In Host Settings under Backends, uncheck REX: the Rex tiles should go away. Check it again, then turn Rex sessions off in Settings: within a few seconds they should go away again. +13. Open a Rex terminal running an agent: the Agent Bar should show its keys. 14. Attach a tmux session with one window, then add a second from the TMUX panel: the TMUX key should turn brighter, and go back when the window is closed. 15. Open the same Rex terminal in Rex on the Mac and in a Rex tab, then work on the Mac without touching the tab: the Mac's terminal should keep its size and not flicker, and the tab should show the same screen at the Mac's size, never garbled. Type in the tab: it should take the size and its own text size back. diff --git a/project.yml b/project.yml index 7d299cf2..5f2c47e6 100644 --- a/project.yml +++ b/project.yml @@ -77,6 +77,11 @@ schemes: MultiplexTests: [test] test: config: Debug + # The Rex backend is off until switched on in Settings ▸ Experimental + # (`ExperimentalFeatures`); the tests that build Rex hosts must not + # depend on what a simulator's defaults say. + environmentVariables: + MULTIPLEX_REX: "1" targets: - MultiplexTests # Real-touch UI tests (XCUITest): the one route that drives a gesture From d359f23d409569a0485d2dbb2c01d605c22c2315 Mon Sep 17 00:00:00 2001 From: Jhen-Jie Hong Date: Thu, 26 Nov 2026 11:30:54 +0800 Subject: [PATCH 09/13] Draw a Rex tab's panes natively A Rex tab showed one terminal of its session and reached the others through a list. It now draws the whole Rex window it was opened on: one emulator per terminal block, laid out as the server's split tree, with a frame around the pane the keyboard is on. Dragging the line between two panes resizes them, and the REX panel's rows split the focused pane right or down, zoom it, close it, or open a new Rex tab. Nothing above the transport is Rex's. `PaneLayout` is the app's own pane tree and its geometry; `PanedTerminalTransport` is what a backend that hands its panes out one stream each looks like to a tab; `TerminalScreen` is one emulator endpoint, of which a tab has one, or one per pane; and `PaneSplitView` sits where the single emulator view sat, so keyboard avoidance, bottom chrome and the key rail are shared. "The terminal" of a tab is its active screen's view, so the chrome that read it follows the focus from pane to pane without a second version. tmux, herdr, shell and mosh tabs keep the single-emulator path. docs/agents/panes.md records the seam and what a second backend (tmux control mode, herdr) would have to do; neither was measured or built. `RexSession` now holds one control connection and one data connection per terminal. The layout is the server's: the tab asks (`session.new_split`, `resize_pane`, `block.close`, `new_window`) and hears the answer in the view like any other client's change. Measured against a throwaway server at the pinned API revision: - A pane is laid out before its terminal is opened, because a screen is rendered for the size it will be drawn at. - The tab's focus is its own. `focus_block`, and `focus: true` on a new split or window, also make that window the session's active one, which is the tab the Rex app on the host is showing. - Zoom is the tab's own for the same reason: the server's cannot be aimed at the tab's focused pane without moving the session. The hidden panes keep their size and their output. - A drag sends only the newest ratio, and the server's answer to an earlier one no longer pulls the line back. - Typing claims every pane another client holds. A pane another client just made is drawn at its owner's size until then. - The line is dragged by a press with no delay. A pan recognizer lost the first twenty points of a drag. Attaching now takes the size of every pane of the window, not of one terminal. Each pane is an SSH channel, so sshd's MaxSessions caps a tab near nine panes; one that cannot be opened says so in its own pane. Rows of the switch list that would read the same are counted, since a window split three ways is three shells with one label. A panel row with no key behind it shows no empty keycap. Real touches (the tap that moves focus, the finger on a line) are covered by `RexPanesUITests`, outside the unit scheme and CI: it needs a Rex server. --- AGENTS.md | 15 +- Multiplex/Localizable.xcstrings | 194 +++- Multiplex/Models/HostGuide.swift | 9 +- Multiplex/Models/PaneLayout.swift | 285 +++++ Multiplex/Models/RexWire.swift | 193 ++- Multiplex/Models/ShortcutPanelContent.swift | 66 +- Multiplex/Models/TerminalRoute.swift | 20 +- Multiplex/Models/TmuxModels.swift | 17 +- .../Services/PanedTerminalTransport.swift | 54 + Multiplex/Services/RexSession.swift | 991 +++++++++++----- Multiplex/Services/TerminalScreen.swift | 223 ++++ .../Services/TerminalSessionController.swift | 824 ++++++++----- Multiplex/Views/Deck/FleetWall.swift | 12 +- Multiplex/Views/Settings/SettingsView.swift | 10 +- Multiplex/Views/Terminal/ShortcutPanel.swift | 10 +- Multiplex/Views/Terminal/SwiftTermView.swift | 397 +++++-- Multiplex/Views/Terminal/TerminalKeyBar.swift | 54 +- .../Terminal/TerminalPaneSplitView.swift | 330 ++++++ .../Views/Terminal/TerminalPaneUIKit.swift | 50 + .../Views/Terminal/TerminalWindowUIKit.swift | 12 +- .../Terminal/TouchDownGestureRecognizer.swift | 20 + MultiplexTests/PaneLayoutTests.swift | 169 +++ MultiplexTests/RexProbeTests.swift | 20 +- MultiplexTests/RexSessionTests.swift | 1032 ++++++++++++++--- MultiplexTests/RexWireTests.swift | 149 +++ MultiplexTests/ShortcutPanelUIKitTests.swift | 27 + .../TerminalPaneSplitUIKitTests.swift | 523 +++++++++ MultiplexTests/TerminalWindowUIKitTests.swift | 6 +- MultiplexUITests/RexPanesUITests.swift | 87 ++ docs/agents/architecture.md | 23 +- docs/agents/backends-and-probe.md | 254 ++-- docs/agents/e2e-headless.md | 9 + docs/agents/input-and-windows.md | 6 +- docs/agents/panes.md | 182 +++ fastlane/testflight-whats-new.txt | 32 +- 35 files changed, 5244 insertions(+), 1061 deletions(-) create mode 100644 Multiplex/Models/PaneLayout.swift create mode 100644 Multiplex/Services/PanedTerminalTransport.swift create mode 100644 Multiplex/Services/TerminalScreen.swift create mode 100644 Multiplex/Views/Terminal/TerminalPaneSplitView.swift create mode 100644 Multiplex/Views/Terminal/TouchDownGestureRecognizer.swift create mode 100644 MultiplexTests/PaneLayoutTests.swift create mode 100644 MultiplexTests/TerminalPaneSplitUIKitTests.swift create mode 100644 MultiplexUITests/RexPanesUITests.swift create mode 100644 docs/agents/panes.md diff --git a/AGENTS.md b/AGENTS.md index e2ffb34e..e1a1e745 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,10 +64,12 @@ One UIKit scene runtime (`MultiplexSceneDelegate` + ornament API needs a View): a classic Deck window + N terminal windows, or one adaptive single-window Shell. A terminal window is ordered tabs, each a `TerminalRoute`; `TerminalWorkspace` owns the tab controllers so merge/split -move live shells. `ConnectionHub` runs one probe connection per host (one -exec round-trip per monitored backend, ~5 s); `TerminalFocusArbiter` is the -app-wide single owner of keyboard focus; hosts + secrets sync via iCloud -Keychain. Full annotated component map: `docs/agents/architecture.md`. +move live shells. A tab is one emulator, except on a backend that hands its +panes out one stream each (Rex): that tab draws the panes itself. +`ConnectionHub` runs one probe connection per host (one exec round-trip per +monitored backend, ~5 s); `TerminalFocusArbiter` is the app-wide single +owner of keyboard focus; hosts + secrets sync via iCloud Keychain. Full +annotated component map: `docs/agents/architecture.md`. Layer rule: **Views → Services → Models**; Models have no UIKit/SwiftTerm imports. `TmuxProbe`, `TerminalRoute`, and the models are pure and are where @@ -91,12 +93,15 @@ approaches. Don't re-litigate a recorded decision without new facts. and tab moves, keyboard avoidance, secret fields, held-backspace filler. - `links-and-viewers.md` — link/path confirmation, ⌗ viewport, ▤ file viewer. - `backends-and-probe.md` — tmux invocation facts, mixed tmux+herdr hosts, - the herdr adaptation, the Rex adaptation (probe, attach, mint), session creation + the herdr adaptation, the Rex adaptation (probe, attach, panes, mint), session creation (setup scripts, per-host tmux conf, systemd-run), file attach/drop. - `agent-helpers.md` — CLI-agent detection, helper chips, launch model override, keychain-locked tip, HISTORY/jump. - `lifecycle-and-attention.md` — disabled hosts, session resume, keep screen on, background keep-alive + `BGAppRefreshTask`, attention alerts and notification rules. +- `panes.md` — native panes: the pane tree, the paned transport seam, one + emulator per pane, focus and keyboard rules, what a second backend (tmux + control mode, herdr) would have to do. - `mosh.md` — the clean-room mosh transport. - `bind-host.md` — Bind Host flow + `mpx` CLI distribution. - `sync-and-widgets.md` — iCloud Keychain sync, widgets/Shortcuts/external diff --git a/Multiplex/Localizable.xcstrings b/Multiplex/Localizable.xcstrings index db92b986..a7dc9ddf 100644 --- a/Multiplex/Localizable.xcstrings +++ b/Multiplex/Localizable.xcstrings @@ -1670,18 +1670,18 @@ } } }, - "A Rex tile opens one terminal: the one its session is showing. New Rex sessions need Rex already running on the host, so Rex is never the default." : { + "A Rex tile opens the window its session is showing, with its panes. New Rex sessions need Rex already running on the host, so Rex is never the default." : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Rexタイルは、そのセッションが表示しているターミナルを1つ開きます。新しいRexセッションを作成するには、ホストでRexがすでに実行されている必要があるため、Rexが新規セッションのデフォルトの実行先になることはありません。" + "value" : "Rexタイルは、そのセッションが表示しているウインドウをペインごと開きます。新しいRexセッションを作成するには、ホストでRexがすでに実行されている必要があるため、Rexが新規セッションのデフォルトの実行先になることはありません。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "Rex 方塊會開啟一個終端機:也就是該工作階段目前顯示的那一個。主機上必須已有 Rex 在執行,才能建立新的 Rex 工作階段,因此 Rex 不會是新工作階段的預設後端。" + "value" : "Rex 方塊會開啟該工作階段目前顯示的視窗,窗格一併顯示。主機上必須已有 Rex 在執行,才能建立新的 Rex 工作階段,因此 Rex 不會是新工作階段的預設後端。" } } } @@ -1846,18 +1846,18 @@ } } }, - "Shows the sessions of a host that runs Rex (superlogical.com/rex) and attaches their terminals as tabs. Rex is a preview and can change under Multiplex. Once on, a host with Rex sessions offers + REX on its rail, and REX appears in Host Settings under Backends. Turning it off hides them at the deck's next refresh; hosts keep their setting." : { + "Shows the sessions of a host that runs Rex (superlogical.com/rex) and opens their windows as tabs, panes included. Rex is a preview and can change under Multiplex. Once on, a host with Rex sessions offers + REX on its rail, and REX appears in Host Settings under Backends. Turning it off hides them at the deck's next refresh; hosts keep their setting." : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Rex(superlogical.com/rex)を実行しているホストのセッションを表示し、そのターミナルをタブとしてアタッチします。Rexはプレビュー版のため、Multiplexが対応する前に変更されることがあります。オンにすると、Rexセッションのあるホストは + REX をDeckに表示し、「ホスト設定」の「バックエンド」にREXが表示されます。オフにすると、Deckの次回更新時に非表示になります。ホストの設定は保持されます。" + "value" : "Rex(superlogical.com/rex)を実行しているホストのセッションを表示し、そのウインドウをペインごとタブとして開きます。Rexはプレビュー版のため、Multiplexが対応する前に変更されることがあります。オンにすると、Rexセッションのあるホストは + REX をDeckに表示し、「ホスト設定」の「バックエンド」にREXが表示されます。オフにすると、Deckの次回更新時に非表示になります。ホストの設定は保持されます。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "顯示執行 Rex(superlogical.com/rex)的主機上的工作階段,並把其中的終端機連接成分頁。Rex 仍是預覽版,可能在 Multiplex 跟上之前就有變動。開啟後,有 Rex 工作階段的主機會在 Deck 上顯示 + REX,「主機設定」的「後端」下也會出現 REX。關閉後,這些項目會在 Deck 下次重新整理時隱藏;主機本身的設定會保留。" + "value" : "顯示執行 Rex(superlogical.com/rex)的主機上的工作階段,並把其中的視窗連同窗格開成標籤頁。Rex 仍是預覽版,可能在 Multiplex 跟上之前就有變動。開啟後,有 Rex 工作階段的主機會在 Deck 上顯示 + REX,「主機設定」的「後端」下也會出現 REX。關閉後,這些項目會在 Deck 下次重新整理時隱藏;主機本身的設定會保留。" } } } @@ -3176,6 +3176,38 @@ } } }, + "Between left and right panes" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "左右のペインの間" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "左右窗格之間" + } + } + } + }, + "Between top and bottom panes" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "上下のペインの間" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "上下窗格之間" + } + } + } + }, "Binary files differ." : { "localizations" : { "ja" : { @@ -5006,6 +5038,22 @@ } } }, + "Couldn't close the pane. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ペインを閉じられませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法關閉窗格。%@" + } + } + } + }, "Couldn't connect to %@: %@" : { "localizations" : { "en" : { @@ -5152,6 +5200,38 @@ } } }, + "Couldn't open a new tab. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "新規タブを開けませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法開啟新的標籤頁。%@" + } + } + } + }, + "Couldn't open this terminal. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このターミナルを開けませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法開啟這個終端機。%@" + } + } + } + }, "Couldn't reach %@ (%@)." : { "localizations" : { "en" : { @@ -5288,6 +5368,22 @@ } } }, + "Couldn't split the pane. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ペインを分割できませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法分割窗格。%@" + } + } + } + }, "Couldn’t seal the key with that passphrase — nothing was enrolled." : { "localizations" : { "ja" : { @@ -11394,6 +11490,22 @@ } } }, + "Pane divider" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ペインの区切り線" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "窗格分隔線" + } + } + } + }, "PANE MENU" : { "localizations" : { "ja" : { @@ -13664,6 +13776,22 @@ } } }, + "Show all panes" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "すべてのペインを表示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "顯示所有窗格" + } + } + } + }, "Show connection stats" : { "localizations" : { "ja" : { @@ -13760,18 +13888,18 @@ } } }, - "Show Rex terminals" : { + "Show Rex panes and terminals" : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "Rexのターミナルを表示" + "value" : "Rexのペインとターミナルを表示" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "顯示 Rex 終端機" + "value" : "顯示 Rex 窗格與終端機" } } } @@ -14363,6 +14491,22 @@ } } }, + "Split Down" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "下に分割" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "向下分割" + } + } + } + }, "Split Left / Right" : { "localizations" : { "ja" : { @@ -14379,6 +14523,22 @@ } } }, + "Split Right" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "右に分割" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "向右分割" + } + } + } + }, "Split Top / Bottom" : { "localizations" : { "ja" : { @@ -16259,6 +16419,22 @@ } } }, + "The terminal closed before it could be opened." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナルは開く前に閉じられました。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "終端機在開啟前就已關閉。" + } + } + } + }, "The terminal's canvas, text, and insertion cursor." : { "localizations" : { "ja" : { diff --git a/Multiplex/Models/HostGuide.swift b/Multiplex/Models/HostGuide.swift index c6019984..0e9ca3d7 100644 --- a/Multiplex/Models/HostGuide.swift +++ b/Multiplex/Models/HostGuide.swift @@ -108,11 +108,12 @@ enum HostGuide { /// What showing Rex sessions means, said wherever they can be switched /// on — the rail's offer confirmation and Host Settings' Backend detail - /// — so neither promises more than the app does: one terminal per tab, - /// and new sessions only where a Rex server is already running, which - /// is also why it is missing from the default's choices right below. + /// — so neither promises more than the app does: one Rex window per + /// tab, and new sessions only where a Rex server is already running, + /// which is also why it is missing from the default's choices right + /// below. static let rexSessionsNote = String(localized: """ - A Rex tile opens one terminal: the one its session is showing. \ + A Rex tile opens the window its session is showing, with its panes. \ New Rex sessions need Rex already running on the host, so Rex is \ never the default. """) diff --git a/Multiplex/Models/PaneLayout.swift b/Multiplex/Models/PaneLayout.swift new file mode 100644 index 00000000..ca1ce090 --- /dev/null +++ b/Multiplex/Models/PaneLayout.swift @@ -0,0 +1,285 @@ +import CoreGraphics + +/// One pane of a tab that draws its backend's panes itself, named by the +/// backend's own id for it: a Rex block id today; a tmux `%7` or a herdr +/// pane id for a backend that hands its panes out one stream each. +struct PaneID: Hashable, Sendable, CustomStringConvertible { + var rawValue: String + + init(_ rawValue: String) { + self.rawValue = rawValue + } + + var description: String { rawValue } +} + +/// How a tab's panes divide its space: a binary tree of splits with a pane +/// at every leaf. +/// +/// This is the app's own shape, not any backend's. Rex's layout is this +/// tree already. A backend whose splits hold more than two children (a tmux +/// row of three panes) nests them — `a | (b | c)` — and states each ratio +/// from its cell counts; nothing here assumes the ratios came from a +/// person. +/// +/// Pure: the geometry below turns a tree and a rectangle into frames, and a +/// drag back into a ratio. Who may change a ratio, and how, is the +/// transport's business (`PaneCommand`). +indirect enum PaneLayout: Equatable, Sendable { + case pane(PaneID) + case split(Split) + + /// Which way a split divides its space. Named for what is on screen: + /// the backends disagree about which of these is "horizontal" (Rex and + /// tmux say it of panes side by side; herdr of panes stacked). + enum Axis: Equatable, Sendable { + /// `before` on the left, `after` on the right. + case sideBySide + /// `before` above `after`. + case stacked + } + + struct Split: Equatable, Sendable { + /// The backend's name for this split; the same split keeps it from + /// one layout to the next, which is what lets a drag in progress + /// survive a layout that arrives meanwhile. + var id: String + var axis: Axis + /// The fraction of the split's space `before` gets. + var ratio: Double + var before: PaneLayout + var after: PaneLayout + } + + /// A ratio is kept this far from either end, whatever a backend or a + /// drag says: a pane of no width cannot be dragged back open. + static let ratioBounds: ClosedRange = 0.05...0.95 + + /// Every pane, in reading order: `before` ahead of `after`. + var panes: [PaneID] { + switch self { + case .pane(let id): [id] + case .split(let split): split.before.panes + split.after.panes + } + } + + func contains(_ pane: PaneID) -> Bool { + switch self { + case .pane(let id): id == pane + case .split(let split): split.before.contains(pane) || split.after.contains(pane) + } + } + + var firstPane: PaneID { + switch self { + case .pane(let id): id + case .split(let split): split.before.firstPane + } + } + + func split(withID id: String) -> Split? { + guard case .split(let split) = self else { return nil } + if split.id == id { return split } + return split.before.split(withID: id) ?? split.after.split(withID: id) + } + + /// This layout with one split's ratio replaced; unchanged when no split + /// has that id. + func settingRatio(_ ratio: Double, ofSplit id: String) -> PaneLayout { + guard case .split(var split) = self else { return self } + if split.id == id { + split.ratio = min(max(ratio, Self.ratioBounds.lowerBound), Self.ratioBounds.upperBound) + } else { + split.before = split.before.settingRatio(ratio, ofSplit: id) + split.after = split.after.settingRatio(ratio, ofSplit: id) + } + return .split(split) + } + + /// The pane focus goes to when `pane` closes: its nearest neighbour in + /// the tree, the way a closed split hands its space to its sibling. nil + /// when `pane` is the only one, or is not in the layout. + func neighbor(ofClosing pane: PaneID) -> PaneID? { + guard case .split(let split) = self else { return nil } + if split.before == .pane(pane) { return split.after.firstPane } + if split.after == .pane(pane) { return split.before.panes.last } + return split.before.neighbor(ofClosing: pane) ?? split.after.neighbor(ofClosing: pane) + } +} + +// MARK: - Geometry + +/// Where a layout's panes and the lines between them sit in a rectangle. +struct PaneLayoutFrames: Equatable { + /// The line between a split's two sides. + struct Divider: Equatable { + var splitID: String + var axis: PaneLayout.Axis + /// The line as drawn. + var frame: CGRect + /// The whole of the split it divides: what a drag's position is a + /// fraction of. + var extent: CGRect + } + + var panes: [PaneID: CGRect] = [:] + var dividers: [Divider] = [] +} + +extension PaneLayout { + /// The narrowest a drag may leave a pane, along the split's axis. A + /// terminal a few cells wide is not one anybody can read, and its + /// program is told that size. + static let minimumPaneLength: CGFloat = 72 + + /// Lays the tree out in `bounds`, a divider `dividerThickness` wide + /// between the two sides of every split. Edges land on physical pixels: + /// a pane's frame is what its emulator measures its grid from, and a + /// fractional edge blurs the line drawn beside it. + func frames( + in bounds: CGRect, dividerThickness: CGFloat, displayScale: CGFloat + ) -> PaneLayoutFrames { + var frames = PaneLayoutFrames() + place( + in: bounds, thickness: dividerThickness, + scale: max(displayScale, 1), into: &frames) + return frames + } + + private func place( + in bounds: CGRect, thickness: CGFloat, scale: CGFloat, + into frames: inout PaneLayoutFrames + ) { + switch self { + case .pane(let id): + frames.panes[id] = bounds + case .split(let split): + let length = split.axis == .sideBySide ? bounds.width : bounds.height + let usable = max(0, length - thickness) + let before = ((usable * CGFloat(split.ratio)) * scale).rounded() / scale + let first: CGRect + let line: CGRect + let second: CGRect + switch split.axis { + case .sideBySide: + first = CGRect( + x: bounds.minX, y: bounds.minY, width: before, height: bounds.height) + line = CGRect( + x: first.maxX, y: bounds.minY, width: min(thickness, length), + height: bounds.height) + second = CGRect( + x: line.maxX, y: bounds.minY, width: max(0, bounds.maxX - line.maxX), + height: bounds.height) + case .stacked: + first = CGRect( + x: bounds.minX, y: bounds.minY, width: bounds.width, height: before) + line = CGRect( + x: bounds.minX, y: first.maxY, width: bounds.width, + height: min(thickness, length)) + second = CGRect( + x: bounds.minX, y: line.maxY, width: bounds.width, + height: max(0, bounds.maxY - line.maxY)) + } + split.before.place(in: first, thickness: thickness, scale: scale, into: &frames) + frames.dividers.append(PaneLayoutFrames.Divider( + splitID: split.id, axis: split.axis, frame: line, extent: bounds)) + split.after.place(in: second, thickness: thickness, scale: scale, into: &frames) + } + } + + /// The ratio that puts a divider's centre at `position` along its + /// split's axis. Both sides keep `minimumPaneLength` while the split is + /// large enough to give it to them, and `ratioBounds` always. + static func ratio( + forDividerAt position: CGFloat, in extent: CGRect, axis: Axis, + dividerThickness: CGFloat + ) -> Double { + let start = axis == .sideBySide ? extent.minX : extent.minY + let length = axis == .sideBySide ? extent.width : extent.height + let usable = length - dividerThickness + guard usable > 0 else { return 0.5 } + var before = position - start - dividerThickness / 2 + if usable >= minimumPaneLength * 2 { + before = min(max(before, minimumPaneLength), usable - minimumPaneLength) + } + let ratio = Double(before / usable) + return min(max(ratio, ratioBounds.lowerBound), ratioBounds.upperBound) + } +} + +// MARK: - What a transport says, and is asked + +/// How a paned transport says its tab's panes are arranged. +struct PaneArrangement: Equatable, Sendable { + var layout: PaneLayout + /// Where the tab's focus should go, when the backend has a reason to + /// move it: the pane an attach lands on, a pane this tab just made, the + /// one that takes over from a pane that closed. nil leaves the tab's + /// focus where the person put it. + var focus: PaneID? +} + +/// What a tab can ask of a transport that draws its panes natively. The +/// transport answers by changing the backend; the tab hears the result as +/// the next `PaneArrangement`, like a change made anywhere else. +enum PaneCommand: Equatable, Sendable { + /// A new pane beside `pane`: to its right, or below it. + case split(PaneID, PaneLayout.Axis) + /// End the pane and whatever runs in it. + case close(PaneID) + /// Move the line between a split's two sides. + case setRatio(Double, splitID: String) + /// The person is on this pane now. What a backend makes of that is its + /// own: one with a shared focus moves it, one without only remembers. + case focus(PaneID) + /// Another window of the session — a tab draws one at a time — holding + /// one new pane that starts where `from`'s program is. The tab moves to + /// it: the next arrangement is the new window's. + case newWindow(from: PaneID) +} + +/// The rows of a native-pane tab's shortcut panel — what `TmuxShortcut` +/// and `HerdrShortcut` are for a tab whose multiplexer draws its own panes, +/// minus the key bindings: these act on the pane that has the tab's focus, +/// through `PaneCommand` — except the zoom, which no backend is asked for. +enum PaneShortcut: String, CaseIterable, Identifiable, Sendable { + case splitRight + case splitDown + case zoomPane + case closePane + case newWindow + + var id: Self { self } + + /// The row's name where a backend has no word of its own for it. A + /// backend that does (Rex calls a window a tab) names the row itself + /// (`ShortcutPanelItem.init(_:title:reference:)`). + var title: String { + switch self { + case .splitRight: String(localized: "Split Right") + case .splitDown: String(localized: "Split Down") + case .zoomPane: String(localized: "Toggle Pane Zoom") + case .closePane: String(localized: "Close Pane") + case .newWindow: String(localized: "New Window") + } + } + + /// Closing ends a program, so the panel asks twice — the confirmed + /// closes' rule on every backend. + var requiresDoubleActivation: Bool { self == .closePane } + + var bindingLabel: String { requiresDoubleActivation ? "2×" : "" } + + /// What the row asks the backend to do with `pane`. nil for the zoom: + /// drawing one pane over the others is the tab's own doing + /// (`TerminalSessionController.togglePaneZoom`). + func command(on pane: PaneID) -> PaneCommand? { + switch self { + case .splitRight: .split(pane, .sideBySide) + case .splitDown: .split(pane, .stacked) + case .zoomPane: nil + case .closePane: .close(pane) + case .newWindow: .newWindow(from: pane) + } + } +} diff --git a/Multiplex/Models/RexWire.swift b/Multiplex/Models/RexWire.swift index 4050a195..8eb559ae 100644 --- a/Multiplex/Models/RexWire.swift +++ b/Multiplex/Models/RexWire.swift @@ -1,8 +1,9 @@ import Foundation -/// The Rex server's wire protocol, as far as attaching one terminal needs it: -/// the control connection's JSON messages, the data connection's binary -/// handshake, and the terminal stream. Pure — `RexSession` owns the sockets. +/// The Rex server's wire protocol, as far as a tab drawing one window's +/// terminals needs it: the control connection's JSON messages, the session +/// view and its layout tree, the data connection's binary handshake, and +/// the terminal stream. Pure — `RexSession` owns the sockets. /// /// Written against API revision 14 (Rex 0.1.0-preview.19, 2026-11-16). The /// authority is the server's own `GET /llms.txt`, not the website docs; what @@ -186,6 +187,8 @@ enum RexWire { var isFocused: Bool /// In the session's active window. var isFronted: Bool + /// The client its size follows; nil for none. + var owner: String? } /// Every terminal block of a `session.view` (or the `view` inside a @@ -209,7 +212,8 @@ enum RexWire { windowLabel: window["label"] as? String ?? "", windowPosition: offset + 1, isFocused: id == focused, - isFronted: windowID == activeWindow + isFronted: windowID == activeWindow, + owner: block["owner"] as? String )) } } @@ -229,6 +233,169 @@ enum RexWire { ?? blocks.first } + // MARK: - Session view → the panes a tab draws + + static let shellFlavor = terminalCreator + ".shell" + + /// The part of a session's view one tab draws: ONE layer of one window, + /// as the app's own pane tree. A pane's id is its block's. + struct Layer: Equatable, Sendable { + var windowID: String + var layerID: String + var layout: PaneLayout + /// The window's focused block, when it is one of this layer's + /// terminals — where Rex itself would type. + var focusedBlockID: String? + } + + /// The layer holding `blockID` — where a tab pointed at that terminal + /// draws. nil when no window shows it as a terminal. + static func layer(holding blockID: String, inView view: [String: Any]) -> Layer? { + layers(inView: view, preferring: blockID) + .first { $0.layout.contains(PaneID(blockID)) } + } + + /// The layer a tab was already drawing, as `view` now has it. nil once + /// the window or the layer is gone, or holds no terminal any more. + static func layer( + windowID: String, layerID: String, preferring blockID: String?, + inView view: [String: Any] + ) -> Layer? { + layers(inView: view, preferring: blockID) + .first { $0.windowID == windowID && $0.layerID == layerID } + } + + /// Every layer of `view` that holds a terminal, as a pane tree of its + /// TERMINAL blocks. Any other kind of block has no stream this client + /// can draw: its leaf is cut out and what was beside it takes the room. + /// A window's tiled layer and each floating layer are separate entries — + /// a tab draws one of them, filling its own space (`bounds` is where a + /// floating layer sits over a Rex window, which a tab has no use for). + private static func layers( + inView view: [String: Any], preferring blockID: String? + ) -> [Layer] { + var found: [Layer] = [] + for window in view["windows"] as? [[String: Any]] ?? [] { + guard let windowID = window["window_id"] as? String else { continue } + let focused = window["focused_block_id"] as? String + for layer in window["layers"] as? [[String: Any]] ?? [] { + guard let layerID = layer["layer_id"] as? String else { continue } + let terminals = (layer["blocks"] as? [[String: Any]] ?? []).compactMap { block in + block["creator_name"] as? String == terminalCreator + ? block["block_id"] as? String : nil + } + guard !terminals.isEmpty else { continue } + let layout: PaneLayout? + if let tree = layer["layout"] as? [String: Any] { + layout = paneLayout(tree, terminals: Set(terminals)) + } else { + // A layer that names its terminals but not how they are + // arranged (no server measured leaves the layout out): + // one of them, alone, rather than an arrangement + // invented here. + layout = .pane(PaneID( + blockID.flatMap { terminals.contains($0) ? $0 : nil } ?? terminals[0])) + } + guard let layout else { continue } + found.append(Layer( + windowID: windowID, layerID: layerID, layout: layout, + focusedBlockID: focused.flatMap { + layout.contains(PaneID($0)) ? $0 : nil + })) + } + } + return found + } + + /// One node of a layer's `layout`: a block, or a split of two nodes. + /// A direction this client does not know is drawn side by side, as the + /// protocol asks. + private static func paneLayout( + _ node: [String: Any], terminals: Set + ) -> PaneLayout? { + if let block = node["block_id"] as? String { + return terminals.contains(block) ? .pane(PaneID(block)) : nil + } + guard let split = node["split"] as? [String: Any] else { return nil } + let before = (split["before"] as? [String: Any]) + .flatMap { paneLayout($0, terminals: terminals) } + let after = (split["after"] as? [String: Any]) + .flatMap { paneLayout($0, terminals: terminals) } + guard let before, let after else { return before ?? after } + guard let id = split["split_id"] as? String else { return before } + let ratio = (split["ratio"] as? NSNumber)?.doubleValue ?? 0.5 + return .split(PaneLayout.Split( + id: id, + axis: split["direction"] as? String == "vertical" ? .stacked : .sideBySide, + ratio: min( + max(ratio, PaneLayout.ratioBounds.lowerBound), + PaneLayout.ratioBounds.upperBound), + before: before, after: after)) + } + + // MARK: - Changing a layout + + /// `session.new_split`: one new shell beside `anchorID` — to its right, + /// or below it — taking half its space. + /// + /// `focus` stays false on purpose. Focusing also makes the block's + /// window the session's active one, which is what the Rex app on the + /// host is showing; a tab's own focus is the tab's (`PaneCommand + /// .focus`). `cwd` is taken literally by the server (`RexProbe`), so it + /// is only ever a path the server itself reported. + static func newSplitPayload( + sessionID: String, anchorID: String, axis: PaneLayout.Axis, cwd: String? + ) -> [String: Any] { + var block: [String: Any] = ["flavor": shellFlavor] + if let cwd { block["options"] = ["cwd": cwd] } + return [ + "session_id": sessionID, + "anchor_id": anchorID, + "direction": direction(axis), + "side": "after", + "layout": ["block": block], + "focus": false, + ] + } + + /// `session.new_window`: a new window — a tab, in Rex's own app — + /// holding one shell. + /// + /// `focus` is false for the reason `newSplitPayload`'s is: true (the + /// default) makes the new window the session's active one, and the Rex + /// app on the host would flip to it. Measured: with false the session's + /// `active_window_id` stays where it was, and the block is still its + /// maker's. + static func newWindowPayload(sessionID: String, cwd: String?) -> [String: Any] { + var block: [String: Any] = ["flavor": shellFlavor] + if let cwd { block["options"] = ["cwd": cwd] } + return [ + "session_id": sessionID, + "layout": ["block": block], + "focus": false, + ] + } + + /// `session.resize_pane`: the server finds the split from a block on + /// each side of it. Any pair works — the split is the only one with one + /// of them on each side — so the first pane of each side names it. + static func resizePanePayload( + sessionID: String, split: PaneLayout.Split, ratio: Double + ) -> [String: Any] { + [ + "session_id": sessionID, + "direction": direction(split.axis), + "before_block_id": split.before.firstPane.rawValue, + "after_block_id": split.after.firstPane.rawValue, + "ratio": ratio, + ] + } + + /// Rex's word for an axis: `horizontal` puts the two sides side by side. + private static func direction(_ axis: PaneLayout.Axis) -> String { + axis == .sideBySide ? "horizontal" : "vertical" + } + // MARK: - Working directory /// Where a terminal's program is, out of a `com.superlogical.terminal @@ -255,20 +422,30 @@ enum RexWire { /// record. A row reads `window — terminal`; a window nobody named /// (`chosenWindowLabel`) is `window N`, and a terminal whose label says /// nothing more than its window is the window alone. `isActive` marks - /// the one this tab is showing. + /// the one the tab's keyboard is on. + /// + /// Rows that would read the same are counted: a window split three ways + /// is three shells called `shell`, and the tab draws all three, so the + /// list has to say which is which — `shell`, `shell 2`, `shell 3`, in + /// the layout's reading order, which is the order the panes are in on + /// screen. static func terminalChoices( in blocks: [Block], showing blockID: String? ) -> [TmuxWindowChoice] { - blocks.enumerated().map { offset, block in + var seen: [String: Int] = [:] + return blocks.enumerated().map { offset, block in let window = chosenWindowLabel(block.windowLabel, windowID: block.windowID) ?? String(localized: "window \(block.windowPosition)") let terminal = displayLabel(block.label) - let name = terminal.isEmpty || terminal.caseInsensitiveCompare(window) == .orderedSame + let base = terminal.isEmpty || terminal.caseInsensitiveCompare(window) == .orderedSame ? window : "\(window) — \(terminal)" + let count = (seen[base.lowercased()] ?? 0) + 1 + seen[base.lowercased()] = count return TmuxWindowChoice( tmuxID: block.id, index: offset + 1, - isActive: block.id == blockID, name: name) + isActive: block.id == blockID, + name: count == 1 ? base : "\(base) \(String(count))") } } diff --git a/Multiplex/Models/ShortcutPanelContent.swift b/Multiplex/Models/ShortcutPanelContent.swift index 1f1084a9..663b191e 100644 --- a/Multiplex/Models/ShortcutPanelContent.swift +++ b/Multiplex/Models/ShortcutPanelContent.swift @@ -11,6 +11,9 @@ struct ShortcutPanelItem: Equatable, Sendable, Identifiable { enum Payload: Equatable, Sendable { case tmux(TmuxShortcut) case herdr(HerdrShortcut) + /// A row of a tab that draws its backend's panes itself: performed + /// on the pane the tab's keyboard is on, through the transport. + case pane(PaneShortcut) } var payload: Payload @@ -63,6 +66,27 @@ struct ShortcutPanelItem: Equatable, Sendable, Identifiable { symbolName = nil accessibilityIdentifier = "herdrShortcut.\(shortcut.rawValue)" } + + /// `reference` is the backend's own name for what the row does, shown + /// as the row's supporting text the way a tmux command or a herdr + /// action name is; `title` is the backend's word for the row where it + /// has one. + init(_ shortcut: PaneShortcut, title: String? = nil, reference: String) { + payload = .pane(shortcut) + self.title = title ?? shortcut.title + command = reference + bindingLabel = shortcut.bindingLabel + requiresDoubleActivation = shortcut.requiresDoubleActivation + // Every row changes what the tab shows: a new pane, the neighbour + // of a closed one, one pane alone, another window. + keepsPanelOpen = false + // The switch list marks the terminal the keyboard is on, and a + // split, a close and a new window all move it. + invalidatesSwitchChoices = shortcut != .zoomPane + promptsForName = false + symbolName = nil + accessibilityIdentifier = "paneShortcut.\(shortcut.rawValue)" + } } struct ShortcutPanelSection: Equatable, Sendable { @@ -126,15 +150,39 @@ struct ShortcutPanelContent: Equatable, Sendable { ) /// Rex has no prefix-key client — Multiplex IS the client — so its panel - /// carries no shortcut rows at all. What it carries is the one thing a - /// Rex tab cannot otherwise do from inside itself: a tab shows ONE - /// terminal of its session, and this lists the others and switches the - /// tab to one in place (`RexSession.switchBlock`). The header's trailing - /// slot says so where the others state their prefix. + /// has no bindings to list. Its rows act on the tab's own panes + /// (`PaneShortcut`): split the pane the keyboard is on, zoom it, close + /// it, or open a new Rex tab — a window, in the server's word and in + /// every other part of this app — beside the one the tab is drawing. + /// Below them, every terminal of the session: one among the panes on + /// show takes the keyboard, one in another Rex window brings that + /// window's panes into the tab (`RexSession.showTerminal`). The + /// header's trailing slot says whose pane the rows act on, where the + /// others state their prefix. static let rex = ShortcutPanelContent( - headerTitle: "REX TERMINALS", - prefixLabel: "SWITCHES THIS TAB", - sections: [], + headerTitle: "REX PANES", + prefixLabel: "ACTS ON THE FOCUSED PANE", + sections: [ + ShortcutPanelSection( + title: String(localized: "Panes"), + accessibilityIdentifier: "rexGroup.Panes", + items: [ + ShortcutPanelItem(.splitRight, reference: "new_split horizontal"), + ShortcutPanelItem(.splitDown, reference: "new_split vertical"), + ShortcutPanelItem(.zoomPane, reference: "in this tab only"), + ShortcutPanelItem(.closePane, reference: "block.close"), + ] + ), + ShortcutPanelSection( + title: String(localized: "Tabs"), + accessibilityIdentifier: "rexGroup.Tabs", + items: [ + ShortcutPanelItem( + .newWindow, title: String(localized: "New Tab"), + reference: "session.new_window"), + ] + ), + ], switchSectionTitle: String(localized: "Switch Terminal"), switchSectionAccessibilityIdentifier: "rexTerminalSection", switchChoiceAccessibilityPrefix: "rexTerminal.", @@ -168,7 +216,7 @@ extension Host.SessionBackend { switch self { case .tmux: String(localized: "Show tmux shortcuts") case .herdr: String(localized: "Show herdr shortcuts") - case .rex: String(localized: "Show Rex terminals") + case .rex: String(localized: "Show Rex panes and terminals") } } } diff --git a/Multiplex/Models/TerminalRoute.swift b/Multiplex/Models/TerminalRoute.swift index 836e55c5..6800cf3f 100644 --- a/Multiplex/Models/TerminalRoute.swift +++ b/Multiplex/Models/TerminalRoute.swift @@ -17,14 +17,15 @@ struct TerminalRoute: Codable, Hashable, Identifiable { /// presses too. A real terminal like `.attach`: restores across /// launches, resumes per `SessionResumePolicy`. case herdrAttach(sessionName: String) - /// Attach one terminal block of a Rex session. Unlike tmux and herdr - /// there is no client to run in a PTY: the tab speaks Rex's own - /// protocol (`RexSession`), so this mode has no remote command at - /// all. `sessionName` is the tile's display name — the identity the + /// Attach one window of a Rex session, its terminal blocks drawn as + /// the tab's own panes. Unlike tmux and herdr there is no client to + /// run in a PTY: the tab speaks Rex's own protocol (`RexSession`), + /// so this mode has no remote command at all. `sessionName` is the tile's display name — the identity the /// deck and the tab strip match on — while `sessionID` is the only /// thing the server can be asked for (a Rex label is not unique). /// `block` names one terminal of the session (the tile menu's Open - /// Terminal rows); nil means the one the session is fronting, + /// Terminal rows) — the tab draws that terminal's window with the + /// keyboard on it; nil means the one the session is fronting, /// decided at attach time, which is what a tile press opens. A real /// terminal like `.attach`: restores across launches, resumes per /// `SessionResumePolicy` — a named block that has since closed falls @@ -94,10 +95,11 @@ struct TerminalRoute: Codable, Hashable, Identifiable { sessionID: session.tmuxID) } - /// The mode for ONE terminal of a session, as its own tab — a Rex - /// tile's Open Terminal row. nil for a record with no usable ids, - /// and for a backend whose tab shows the whole session: its panes - /// are reached inside the tab, not opened one each. + /// The mode for a tab pointed at ONE terminal of a session — a Rex + /// tile's Open Terminal row: the tab opens on that terminal's + /// window. nil for a record with no usable ids, and for a backend + /// whose tab shows the whole session: its panes are reached inside + /// the tab, not opened one each. static func attach(session: TmuxSession, window: TmuxWindow, pane: TmuxPane) -> Mode? { guard session.backend == .rex, RexWire.bakeableSessionID(session.tmuxID), !pane.tmuxID.isEmpty diff --git a/Multiplex/Models/TmuxModels.swift b/Multiplex/Models/TmuxModels.swift index 9c28e51a..c1f9fccb 100644 --- a/Multiplex/Models/TmuxModels.swift +++ b/Multiplex/Models/TmuxModels.swift @@ -189,12 +189,13 @@ struct TmuxSession: Identifiable, Hashable, Codable { activeWindow?.activeAgent } /// The agent a tab's helper strip speaks for. A tab that shows the - /// whole session (tmux, herdr) follows `activeAgent`: its multiplexer - /// draws whichever pane is in front. A tab that IS one pane — a Rex tab - /// is one terminal — names it, and gets that pane's agent wherever the - /// session's focus has gone since: the Rex app fronting another window - /// must not take the strip off a tab still showing the agent. A named - /// pane the record does not list has no agent to report. + /// whole session through its multiplexer (tmux, herdr) follows + /// `activeAgent`: the multiplexer draws whichever pane is in front. A + /// tab that draws its panes itself — a Rex tab — names the one its + /// keyboard is on, and gets that pane's agent wherever the session's + /// focus has gone since: the Rex app fronting another window must not + /// take the strip off a tab still on the agent. A named pane the record + /// does not list has no agent to report. func agent(inPane paneID: String?) -> AgentKind? { guard let paneID else { return activeAgent } return windows.lazy.flatMap { $0.panes ?? [] } @@ -215,8 +216,8 @@ struct TmuxSession: Identifiable, Hashable, Codable { /// The shortcut panel's switch list has somewhere else to go — what /// lights the TMUX / HRDR / REX key. The list is windows (herdr: /// workspaces, which the probe writes as windows), except on Rex, where - /// a tab is ONE terminal and the list is every terminal of the session: - /// a single split window already has a second row. + /// the list is every terminal of the session: a single split window + /// already has a second row. var hasSwitchChoices: Bool { (backend == .rex ? paneCount : windowCount) > 1 } diff --git a/Multiplex/Services/PanedTerminalTransport.swift b/Multiplex/Services/PanedTerminalTransport.swift new file mode 100644 index 00000000..549b3dbd --- /dev/null +++ b/Multiplex/Services/PanedTerminalTransport.swift @@ -0,0 +1,54 @@ +import Foundation + +/// A tab's link to a backend that hands its panes out separately — one byte +/// stream each — and leaves drawing them to the app. +/// +/// The other transports (`TerminalTransport`: an SSH PTY, mosh) carry ONE +/// stream, and a multiplexer on the far side composes its panes into it. A +/// paned transport carries no composed screen at all: it says how the panes +/// are arranged (`PaneArrangement`), streams each pane's output apart, and +/// takes input and a size per pane. The tab gives every pane its own +/// emulator (`TerminalScreen`) and lays them out itself (`PaneSplitView`). +/// +/// Nothing here is Rex's. `RexSession` is the first conformer; what a second +/// one would map onto it: +/// - **tmux control mode** (`tmux -CC`): `%output %` is `output`, +/// `%layout-change` an arrangement, `send-keys -t % -H` a write, +/// `split-window` / `kill-pane` / `resize-pane` the commands. tmux sizes +/// its panes itself from the client's whole size, so that adapter would +/// answer `resize(pane:)` by summing to a `refresh-client -C`, and pin +/// every pane to the grid tmux gives it through `grid` — the same road a +/// Rex terminal takes while another client owns its size. +/// - **herdr**, once it serves pane streams: pane ids, a split tree and +/// close/split verbs are in its snapshot API already. +protocol PanedTerminalTransport: Actor { + /// What was typed into one pane. Queues and returns, like every + /// transport's write: the tab's input pump awaits each call. + func write(_ data: Data, to pane: PaneID) async throws + /// The grid the tab measured for one pane. + func resize(pane: PaneID, cols: Int, rows: Int) async throws + /// Change the backend's layout. The result is not returned: it arrives + /// as the next arrangement, as a change made by anyone else would. + func perform(_ command: PaneCommand) async throws + func close() async +} + +/// What a paned transport tells its tab. Every closure may be called from +/// any isolation. +struct PaneEvents: Sendable { + /// The panes and how they are arranged — at the attach, and whenever + /// that changes. The tab lays them out and answers with the grid it + /// measured for each; the transport waits for that before it opens a + /// new pane's stream, because a screen is fetched for the size it will + /// be drawn at. + var arrange: @Sendable (PaneArrangement) async -> [PaneID: TerminalGrid] + /// One pane's output, in order. + var output: @Sendable (PaneID, Data) -> Void + /// The grid a pane's emulator must have before the bytes that follow + /// are drawn: one the backend dictates, or nil for the pane's own + /// again. Awaited — nothing more is sent for that pane until it + /// returns. + var grid: @Sendable (PaneID, TerminalGrid?) async -> Void + /// The link ended on its own, at most once; nil for a clean end. + var close: @Sendable (String?) -> Void +} diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift index a6d32d32..813e6c0f 100644 --- a/Multiplex/Services/RexSession.swift +++ b/Multiplex/Services/RexSession.swift @@ -82,55 +82,73 @@ struct RexSocket: Sendable { } } -/// A terminal tab attached to one Rex terminal block — the third -/// `TerminalTransport`, beside the SSH PTY and mosh. +/// A terminal tab attached to one window of a Rex session — the app's first +/// `PanedTerminalTransport`. /// /// Rex has no terminal client to run in a PTY (see `RexProbe`), so this IS -/// the client: it speaks the server's WebSocket API through two byte pipes -/// on the tab's SSH connection (`SSHConnection.openPipe` running `rex +/// the client: it speaks the server's WebSocket API through byte pipes on +/// the tab's SSH connection (`SSHConnection.openPipe` running `rex /// __internal dial-stdio`, the bridge Rex's own `ssh://` transport uses). /// -/// - The **control** connection attaches to the session, claims the block, -/// sizes it, and carries every keystroke as a -/// `com.superlogical.terminal.write` call. -/// - The **data** connection carries the block's output, one way. +/// - ONE **control** connection attaches to the session, reads its view, +/// claims and sizes terminals, carries every keystroke as a +/// `com.superlogical.terminal.write` call, and changes the layout. +/// - One **data** connection PER TERMINAL carries that terminal's output, +/// one way. A window of five panes is six pipes. +/// +/// A tab draws one layer of one window: the layer holding the terminal it +/// was opened on (`RexWire.Layer`). Its panes are that layer's terminal +/// blocks, a pane's id its block's. The layout is the server's — this side +/// asks (`perform`) and then hears the answer in the view like any other +/// client's change. /// /// What is deliberate here: -/// - **The screen is bootstrapped from `format`, not from the stream.** The +/// - **Each screen is bootstrapped from `format`, not from the stream.** A /// stream opens with a Ghostty binary snapshot SwiftTerm cannot read /// (`RexTerminalStream` drops it), so the starting screen comes from the -/// `vt` rendering instead. The block is claimed and sized BEFORE either -/// is asked for, so both describe the terminal at this tab's size. +/// `vt` rendering instead. The terminal is claimed and sized BEFORE either +/// is asked for, so both describe it at its pane's size — which is why the +/// tab is asked to lay the panes out first (`PaneEvents.arrange`). /// - **The two are not atomic, and the gap errs toward repeating.** The /// stream is opened first and held while `format` is fetched: output the /// program wrote in between is drawn twice (once inside the rendering, /// once from the stream) rather than lost. Lost bytes can leave a mode /// wrong for the rest of the session; a repeated line is one line. -/// - **The last client to type owns the size**, as with tmux's latest-client -/// rule. Another client (the Rex app) can claim the block back; the next -/// keystroke here claims it again and re-sizes it. -/// - **The emulator's grid is the terminal's, not always this tab's.** A +/// - **The last client to type owns the sizes**, as with tmux's +/// latest-client rule. Another client (the Rex app) can claim a terminal +/// back; the next keystroke here claims every terminal the tab draws and +/// re-sizes each to its pane. All of them, because the tab draws them as +/// one window: a pane left at another client's size beside one at this +/// tab's is a layout nobody chose. +/// - **An emulator's grid is its terminal's, not always its pane's.** A /// terminal has one size, its owner's. While another client owns it the /// stream says what that size is (`resize`), and the emulator is given -/// that grid (`onGrid`) and its screen drawn again — output laid out for -/// 170 columns and parsed at 132 left stray characters all over the tab -/// (user-reported, reproduced with a stand-in client holding the block). +/// that grid (`PaneEvents.grid`) and its screen drawn again — output laid +/// out for 170 columns and parsed at 132 left stray characters all over +/// the tab (user-reported, reproduced with a stand-in client holding the +/// block). /// - **Only what a person does is written.** `write` is what claims, so /// nothing may reach it that the emulator said by itself. The server /// parses the terminal's output too and answers its queries there; the /// emulator's own answers are stopped before this transport /// (`TerminalSessionController.sendTerminalReport`). Sent on, each one /// was a second answer in the program's input and a claim nobody made. +/// - **The tab's focus is the tab's.** Which pane has the keyboard here is +/// never written to the server: `session.focus_block` also makes the +/// block's window the session's active one, which is what the Rex app on +/// the host is showing. `PaneCommand.focus` is only remembered — it +/// decides which layer the tab keeps drawing and where focus goes when +/// that pane closes. /// - **The palette is the app's.** `extra_palette` is not requested: it /// would repaint the tab in Rex's theme. -/// - **A tab attached during a full-screen program redraws when it exits.** -/// While one is up, `format` renders only its screen — the shell history -/// underneath cannot be asked for — so the emulator's primary screen -/// starts empty and leaving vim showed a bare prompt (seen on the first -/// headless run). `AlternateScreenExitWatch` notices the exit and the -/// screen is fetched again, under the same hold-then-flush rule as the -/// attach. -actor RexSession: TerminalTransport { +/// - **A terminal attached during a full-screen program redraws when it +/// exits.** While one is up, `format` renders only its screen — the shell +/// history underneath cannot be asked for — so the emulator's primary +/// screen starts empty and leaving vim showed a bare prompt (seen on the +/// first headless run). `AlternateScreenExitWatch` notices the exit and +/// the screen is fetched again, under the same hold-then-flush rule as +/// the attach. +actor RexSession: PanedTerminalTransport { /// A reason a person can read — the tab's ended line. struct Failure: Error, Equatable { var message: String @@ -151,10 +169,10 @@ actor RexSession: TerminalTransport { private static let bootstrapLimit = 3_000_000 private static let plainTailBytes = 16 * 1024 - /// Opens one byte pipe to the Rex server's socket; called twice per - /// attach (control, then data). A closure rather than the connection - /// itself so the whole session can be driven by an in-process server - /// under test. + /// Opens one byte pipe to the Rex server's socket: once for the control + /// connection, then once per terminal. A closure rather than the + /// connection itself so the whole session can be driven by an + /// in-process server under test. private let openPipe: @Sendable () async throws -> RemotePipe /// Drops whatever the pipes ride on — the tab's SSH connection. private let closeLink: @Sendable () async -> Void @@ -163,9 +181,7 @@ actor RexSession: TerminalTransport { private let clientVersion: String private var control: RexSocket? - private var data: RexSocket? private var controlReader: Task? - private var dataReader: Task? private struct Reply: @unchecked Sendable { var payload: [String: Any] @@ -174,47 +190,98 @@ actor RexSession: TerminalTransport { private var timeouts: [String: Task] = [:] private var requestCount = 0 - private enum Milestone: Hashable { case welcome, dataWelcome, live } + /// A point a handshake has to reach. The two a stream has are named by + /// its terminal's serial, so a milestone of an earlier stream of the + /// same block can never be mistaken for this one's. + private enum Milestone: Hashable { + case welcome + case dataWelcome(Int) + case live(Int) + } private var reached: Set = [] private var waiters: [Milestone: CheckedContinuation] = [:] private var clientID: String? - private(set) var blockID: String? - private var owner: String? - private var stream: RexTerminalStream? - /// Stream output that arrived before the screen was drawn, kept to be - /// drawn after it. nil once the screen is up: output goes straight - /// through. - private var held: Data? = Data() - /// Set while the emulator's primary screen is known to be incomplete — - /// the bootstrap was rendered during a full-screen program. - private var exitWatch: AlternateScreenExitWatch? - private var lastOutput = ContinuousClock.now - /// The grid the terminal has while it is someone else's to size — what - /// the stream last said. nil while its size is this tab's own. - private var terminalGrid: TerminalGrid? - /// What the emulator was last told (`onGrid`); nil is its own grid. - private var shownGrid: TerminalGrid? - /// One redraw at a time: each waits for the one before it. - private var drawing: Task? - private var isResyncing = false /// `attaching` until `open` returns; `closed` is final, whichever side /// ended it. private enum Phase { case attaching, live, closed } private var phase = Phase.attaching - private var size: (cols: Int, rows: Int) = (80, 24) - private var input = RexInputEncoder() - private var pendingInput = "" - private var isWriting = false - private var isSwitching = false - /// Bumped whenever the data connection is replaced. A reader reports - /// with the generation it was started under, so a retired stream's - /// last words are recognised as that and dropped. - private var dataGeneration = 0 - - private var onData: (@Sendable (Data) -> Void)? - private var onClose: (@Sendable (String?) -> Void)? - private var onGrid: (@Sendable (TerminalGrid?) async -> Void)? + private var events: PaneEvents? + + /// One terminal the tab draws: its stream, and everything about putting + /// that stream on its emulator. A reference so the many steps that + /// suspend can keep mutating the one record; it never leaves the actor. + private final class Terminal { + let id: String + /// Tells this stream of the block from an earlier one — a pane that + /// left the tab and came back is a new terminal here. + let serial: Int + /// The grid this tab asks the terminal to be: its pane's. + var size: TerminalGrid + var socket: RexSocket? + var reader: Task? + var stream: RexTerminalStream? + /// Stream output that arrived before the screen was drawn, kept to + /// be drawn after it. nil once the screen is up: output goes + /// straight through. + var held: Data? = Data() + /// Set while the emulator's primary screen is known to be + /// incomplete — the bootstrap was rendered during a full-screen + /// program. + var exitWatch: AlternateScreenExitWatch? + var lastOutput = ContinuousClock.now + /// The grid the terminal has while it is someone else's to size — + /// what the stream last said. nil while its size is this tab's own. + var terminalGrid: TerminalGrid? + /// What the emulator was last told (`PaneEvents.grid`); nil is its + /// own grid. + var shownGrid: TerminalGrid? + /// One redraw at a time: each waits for the one before it. + var drawing: Task? + var isResyncing = false + var owner: String? + var input = RexInputEncoder() + var pendingInput = "" + var isWriting = false + /// Nothing more will come from it or go to it: its program exited, + /// its block closed, or its stream could not be opened. + var hasEnded = false + + init(id: String, serial: Int, size: TerminalGrid) { + self.id = id + self.serial = serial + self.size = size + } + } + + private var terminals: [String: Terminal] = [:] + private var terminalSerial = 0 + /// The window and layer the tab draws. + private var shown: (windowID: String, layerID: String)? + private var layout: PaneLayout? + private var viewRevision = -1 + /// The oldest view worth adopting: the revision the server gave in + /// answer to this tab's own last change. A view read before that + /// answer can still arrive after it, and would undo the change on + /// screen until the next one put it back. + private var floorRevision = -1 + /// The grid the tab last measured for a pane, kept even before the + /// terminal is known here: a pane is laid out — and measured — before + /// its terminal is opened. + private var requestedSizes: [String: TerminalGrid] = [:] + /// The pane the tab's keyboard is on (`PaneCommand.focus`). + private var focusedBlockID: String? + /// A terminal this tab just made, to be focused when the view shows it. + private var pendingFocus: String? + /// A terminal the tab was asked to show, wherever in the session it is. + private var retarget: String? + private var wantsViewRefresh = false + private var isRefreshingView = false + /// Ratios this tab asked for that the server has not answered yet. Until + /// it has, they stand in for the view's: the answer to an earlier ask + /// would otherwise drag a divider back under the finger. + private var pendingRatios: [String: Double] = [:] + private var isSendingRatios = false init( openPipe: @escaping @Sendable () async throws -> RemotePipe, @@ -228,7 +295,7 @@ actor RexSession: TerminalTransport { self.clientVersion = clientVersion } - /// The app's form: both pipes ride `connection`, each running the Rex + /// The app's form: every pipe rides `connection`, each running the Rex /// CLI's stdio bridge, and closing the session closes the connection. init( connection: SSHConnection, sessionID: String, blockID: String?, @@ -243,27 +310,18 @@ actor RexSession: TerminalTransport { // MARK: - Opening - /// Attaches and returns once the terminal's current screen has been - /// handed to `onData`. `onClose` fires at most once, later, when the - /// block or the link ends on its own (nil for a clean end). - /// - /// `onGrid` names the grid the emulator must have before the bytes that - /// follow are drawn: another client's while that client owns the - /// terminal's size, nil for the tab's own again. It is awaited — the - /// screen is not sent until it returns. - func open( - cols: Int, rows: Int, - onData: @Sendable @escaping (Data) -> Void, - onClose: @Sendable @escaping (String?) -> Void, - onGrid: @Sendable @escaping (TerminalGrid?) async -> Void = { _ in } - ) async throws { - self.onData = onData - self.onClose = onClose - self.onGrid = onGrid - size = (cols, rows) + /// Attaches and returns once every terminal of the window has been + /// drawn — or failed to open; one that failed says so in its own pane. + /// The attach itself fails only when none could be opened. + /// `events.close` fires at most once, later, when the window or the + /// link ends on its own. + func open(events: PaneEvents) async throws { + self.events = events do { try await attach() if phase == .attaching { phase = .live } + // A change that arrived mid-attach waited for it to finish. + if wantsViewRefresh { scheduleViewRefresh() } } catch { let failure = Self.failure(from: error) await teardown(failing: failure) @@ -282,115 +340,343 @@ actor RexSession: TerminalTransport { let attached = try await call("session.attach", ["session_id": sessionID]) if let id = attached["client_id"] as? String { clientID = id } - let blocks = RexWire.terminalBlocks( - inView: attached["view"] as? [String: Any] ?? [:]) - guard let block = RexWire.attachTarget(in: blocks, preferring: preferredBlockID) else { + let view = attached["view"] as? [String: Any] ?? [:] + guard let target = RexWire.attachTarget( + in: RexWire.terminalBlocks(inView: view), preferring: preferredBlockID), + let layer = RexWire.layer(holding: target.id, inView: view) + else { throw Failure(String(localized: "This Rex session has no terminal to open.")) } - try await showBlock(block.id) + let failures = await show(layer, focusing: target.id, in: view) + // A pane that could not be opened beside ones that could is that + // pane's news. With nothing opened there is no tab to show it in. + if failures.count == layer.layout.panes.count, + let failure = failures[target.id] ?? failures.values.first { + throw failure + } + for (id, failure) in failures { report(failure, inTerminal: id) } } - /// Points the tab at one terminal block: claim and size it, open its - /// stream, draw its screen. The attach's second half, and the whole of - /// a switch. - private func showBlock(_ blockID: String) async throws { - self.blockID = blockID - // Claim and size first: the rendering and the stream below must - // both describe the terminal at THIS tab's size. - await claimAndSize() + // MARK: - The view - let ticket = try await call("data.connect", [ - "session_id": sessionID, - "block_id": blockID, - "data_ref_id": "terminal", - "subprotocol": RexWire.terminalSubprotocol, - ]) - guard let hello = (ticket["ticket"] as? String).flatMap(RexWire.dataHello) else { - throw Failure(String(localized: "The Rex server issued no usable stream ticket.")) + /// The server's view of the session changed, or something here needs it + /// read again. One reader at a time; a change during a read is read + /// after it. + private func scheduleViewRefresh() { + wantsViewRefresh = true + guard phase == .live, !isRefreshingView else { return } + isRefreshingView = true + Task { await self.refreshView() } + } + + private func refreshView() async { + defer { isRefreshingView = false } + while wantsViewRefresh, phase == .live { + wantsViewRefresh = false + guard let view = try? await call("session.view", ["session_id": sessionID]), + phase == .live + else { return } + // Older than this tab's own last change: the read that follows + // that change is already asked for. + if let revision = view["revision"] as? Int, revision < floorRevision { continue } + let target = retarget + retarget = nil + let layer = target.flatMap { RexWire.layer(holding: $0, inView: view) } + ?? shown.flatMap { + RexWire.layer( + windowID: $0.windowID, layerID: $0.layerID, + preferring: focusedBlockID, inView: view) + } + guard let layer else { + // The window this tab drew has closed, or its last terminal + // has — a clean end, like a shell exiting. + finish(nil) + return + } + let failures = await show(layer, focusing: target, in: view) + for (id, failure) in failures { report(failure, inTerminal: id) } } - let data = try await RexSocket.open( - over: try await openPipe(), - path: RexWire.dataPath, subprotocol: RexWire.terminalSubprotocol) - self.data = data - try await data.send(.binary, hello) - startDataReader(data) - try await wait(for: .dataWelcome) - // The snapshot has passed once the first server message arrives; - // only then is the terminal's state settled enough to render. - try await wait(for: .live) - - await drawScreen(blockID: blockID) - } - - /// The directory the terminal on show is working in — what a file drop - /// lands in and a file viewer opens at. nil when the tab is not live or - /// the server cannot say. - func workingDirectory() async -> String? { - guard phase == .live, let blockID, - let process = try? await terminalCall("process", block: blockID) + } + + /// Makes `layer` what the tab draws: tells the tab how its panes are + /// arranged, lets go of terminals that left, and opens the ones that + /// are new. Returns the new terminals that could not be opened. + /// + /// Never runs twice at once — the attach calls it before the tab is + /// live, the view reader after — so what it read before suspending is + /// still true when it resumes. + private func show( + _ layer: RexWire.Layer, focusing wanted: String?, in view: [String: Any] + ) async -> [String: Failure] { + if let revision = view["revision"] as? Int { viewRevision = max(viewRevision, revision) } + shown = (layer.windowID, layer.layerID) + let previous = layout + var next = layer.layout + for (splitID, ratio) in pendingRatios { + next = next.settingRatio(ratio, ofSplit: splitID) + } + let ids = next.panes.map(\.rawValue) + let gone = terminals.keys.filter { !ids.contains($0) } + let added = ids.filter { terminals[$0] == nil } + let blocks = RexWire.terminalBlocks(inView: view) + + // Focus moves only for a reason: a terminal the tab asked for, one + // it just made, or the one it was on having gone. + var focus = wanted.flatMap { ids.contains($0) ? $0 : nil } + if focus == nil, let pendingFocus, ids.contains(pendingFocus) { + focus = pendingFocus + } + if focus == nil, focusedBlockID.map({ !ids.contains($0) }) ?? true { + let neighbor = focusedBlockID + .flatMap { previous?.neighbor(ofClosing: PaneID($0))?.rawValue } + .flatMap { ids.contains($0) ? $0 : nil } + focus = neighbor ?? layer.focusedBlockID ?? next.firstPane.rawValue + } + if let focus { + focusedBlockID = focus + if pendingFocus == focus { pendingFocus = nil } + } + + // Most view changes are not about the layout at all (every change + // of owner is one); those say nothing to the tab. + guard next != previous || focus != nil || !added.isEmpty || !gone.isEmpty + else { return [:] } + layout = next + let measured = await events?.arrange( + PaneArrangement(layout: next, focus: focus.map(PaneID.init))) ?? [:] + guard phase != .closed else { return [:] } + + for id in gone { await retire(id) } + // A terminal that only left this tab's window is given up as well + // as left: owning it is what makes it follow this tab's size, and + // the client still showing it gets its own back. One that closed + // is not named — a single unknown id fails the whole call. + let existing = Set(blocks.map(\.id)) + let released = gone.filter(existing.contains).sorted() + if !released.isEmpty { + _ = try? await call("session.disown_block", [ + "session_id": sessionID, "block_ids": released, + ]) + } + + var opening: [(id: String, serial: Int)] = [] + for id in added where terminals[id] == nil { + terminalSerial += 1 + // What the pane's pump said since it was laid out is newer than + // what the layout pass returned. + let size = requestedSizes[id] ?? measured[PaneID(id)] + ?? TerminalGrid(cols: 80, rows: 24) + terminals[id] = Terminal(id: id, serial: terminalSerial, size: size) + opening.append((id, terminalSerial)) + } + guard !opening.isEmpty else { return [:] } + // Claim and size first: the rendering and the stream each terminal + // is opened with must both describe it at its pane's size. + // + // Claimed: what the tab was pointed at (the attach, a switch), what + // is already this client's — a terminal it just made, which the + // server hands its maker — and what is nobody's. A pane ANOTHER + // client holds is not: the tab only follows there, and draws it at + // its owner's size until someone types here (`drainInput`). + let theirs = Set(blocks.filter { $0.owner != nil && $0.owner != clientID }.map(\.id)) + await claim(opening.map(\.id).filter { wanted != nil || !theirs.contains($0) }) + return await withTaskGroup(of: (String, Failure?).self) { group in + for (id, serial) in opening { + group.addTask { (id, await self.openStream(id, serial)) } + } + var failures: [String: Failure] = [:] + for await (id, failure) in group { + if let failure { failures[id] = failure } + } + return failures + } + } + + /// The terminal `id` names, if it is still the one `serial` was. + private func current(_ id: String, _ serial: Int) -> Terminal? { + guard phase != .closed, let terminal = terminals[id], terminal.serial == serial + else { return nil } + return terminal + } + + /// Opens one terminal's stream and draws its screen. Returns why it + /// could not; nil when it is up, or is no longer wanted. + private func openStream(_ id: String, _ serial: Int) async -> Failure? { + do { + let ticket = try await call("data.connect", [ + "session_id": sessionID, + "block_id": id, + "data_ref_id": "terminal", + "subprotocol": RexWire.terminalSubprotocol, + ]) + guard let hello = (ticket["ticket"] as? String).flatMap(RexWire.dataHello) else { + throw Failure(String(localized: "The Rex server issued no usable stream ticket.")) + } + let socket = try await RexSocket.open( + over: try await openPipe(), + path: RexWire.dataPath, subprotocol: RexWire.terminalSubprotocol) + guard let terminal = current(id, serial) else { + await socket.close() + return nil + } + terminal.socket = socket + try await socket.send(.binary, hello) + startDataReader(socket, id: id, serial: serial) + try await wait(for: .dataWelcome(serial)) + // The snapshot has passed once the first server message + // arrives; only then is the terminal's state settled enough to + // render. + try await wait(for: .live(serial)) + await drawScreen(id, serial) + return nil + } catch { + guard let terminal = current(id, serial) else { return nil } + terminal.hasEnded = true + let socket = terminal.socket + terminal.socket = nil + await socket?.close() + terminal.reader?.cancel() + return Self.failure(from: error) + } + } + + /// Says in a terminal's own pane why it could not be opened. The tab + /// stays: its other panes are fine, and RECONNECT is not on offer while + /// it is live — closing and reopening the tab attaches afresh. + private func report(_ failure: Failure, inTerminal id: String) { + let text = String(localized: "Couldn't open this terminal. \(failure.message)") + events?.output(PaneID(id), Data("\u{1B}c".utf8) + Data(text.utf8)) + } + + /// Lets go of a terminal the tab no longer draws. + private func retire(_ id: String) async { + guard let terminal = terminals.removeValue(forKey: id) else { return } + requestedSizes[id] = nil + let failure = Failure("closed") + for milestone in [Milestone.dataWelcome(terminal.serial), .live(terminal.serial)] { + reached.remove(milestone) + fail(milestone, failure) + } + terminal.hasEnded = true + let socket = terminal.socket + terminal.socket = nil + // Status 1000 ends the stream rather than parking it for a resume. + await socket?.close() + terminal.reader?.cancel() + } + + /// The directory one terminal is working in — what a file drop lands in + /// and a file viewer opens at. nil when the tab is not live or the + /// server cannot say. + func workingDirectory(of pane: PaneID) async -> String? { + guard phase == .live, terminals[pane.rawValue] != nil, + let process = try? await terminalCall("process", block: pane.rawValue) else { return nil } return RexWire.workingDirectory(inProcess: process) } - // MARK: - Switching terminals + // MARK: - The session's other terminals /// Every terminal of the session, as the REX panel's Switch Terminal - /// rows, with the one this tab shows marked. Read fresh each time the - /// panel opens: windows come and go in Rex without telling the tab. + /// rows, with the one this tab's keyboard is on marked. Read fresh each + /// time the panel opens: windows come and go in Rex without telling the + /// tab. func terminalChoices() async -> [TmuxWindowChoice]? { guard phase == .live, let view = try? await call("session.view", ["session_id": sessionID]) else { return nil } return RexWire.terminalChoices( - in: RexWire.terminalBlocks(inView: view), showing: blockID) + in: RexWire.terminalBlocks(inView: view), showing: focusedBlockID) } - /// Points this tab at another terminal of the same session, in place: - /// the control connection and the tab stay, only the stream and the - /// screen change. - /// - /// The old block is given up as well as left. Owning a block is what - /// makes it follow this tab's size, and a terminal nobody here is - /// looking at any more has no business keeping it — the Rex window - /// showing it gets its own size back. A switch that cannot complete - /// ends the tab with the reason rather than leaving it on a dead - /// stream; RECONNECT then attaches afresh. - func switchBlock(to newID: String) async { - guard phase == .live, !isSwitching, newID != blockID else { return } - isSwitching = true - defer { isSwitching = false } - let previous = blockID - - // Retire the old stream. The generation bump is what keeps its - // reader's parting "ended" from being read as the TAB ending. - dataGeneration += 1 - let oldData = data - data = nil - await oldData?.close() - dataReader?.cancel() - dataReader = nil - stream = nil - reached.subtract([.dataWelcome, .live]) - held = Data() - // The size on record is the terminal being left's; the new stream - // opens by saying its own. - terminalGrid = nil - exitWatch = nil - pendingInput = "" - input = RexInputEncoder() - - if let previous { - _ = try? await call("session.disown_block", [ - "session_id": sessionID, "block_ids": [previous], - ]) - } + /// Points the tab at a terminal of its session, wherever it is: one of + /// the panes on show takes the focus; one in another window brings that + /// window's panes in, in place — the control connection and the tab + /// stay. One that has since closed changes nothing. + func showTerminal(_ blockID: String) { + guard phase == .live else { return } + retarget = blockID + scheduleViewRefresh() + } + + // MARK: - Changing the layout + + func perform(_ command: PaneCommand) async throws { + guard phase == .live else { throw Failure("not attached") } do { - try await showBlock(newID) + switch command { + case .focus(let pane): + if terminals[pane.rawValue] != nil { focusedBlockID = pane.rawValue } + case .split(let pane, let axis): + // A new shell starts where the one it was split from is, + // as tmux's and herdr's splits do here. + let cwd = await workingDirectory(of: pane) + let made = try await call("session.new_split", RexWire.newSplitPayload( + sessionID: sessionID, anchorID: pane.rawValue, axis: axis, cwd: cwd)) + pendingFocus = (made["block_ids"] as? [String])?.first + noteOwnChange(made) + case .close(let pane): + let closed = try await call("block.close", [ + "session_id": sessionID, "block_id": pane.rawValue, + ]) + noteOwnChange(closed) + case .newWindow(let pane): + let cwd = await workingDirectory(of: pane) + let made = try await call("session.new_window", RexWire.newWindowPayload( + sessionID: sessionID, cwd: cwd)) + // The tab goes where its new terminal is: the next view + // read brings that window in, as Switch Terminal would. + if let block = (made["block_ids"] as? [String])?.first { retarget = block } + noteOwnChange(made) + case .setRatio(let ratio, let splitID): + guard layout?.split(withID: splitID) != nil else { return } + pendingRatios[splitID] = ratio + layout = layout?.settingRatio(ratio, ofSplit: splitID) + guard !isSendingRatios else { return } + isSendingRatios = true + Task { await self.sendRatios() } + } } catch { - finish(Self.failure(from: error).message) + throw Self.failure(from: error) } } + /// The server answered a change this tab made: the view is worth reading + /// again, and nothing older than the answer is. + private func noteOwnChange(_ result: [String: Any]) { + if let revision = result["revision"] as? Int { + floorRevision = max(floorRevision, revision) + } + scheduleViewRefresh() + } + + /// One `resize_pane` in flight at a time, each carrying the newest + /// ratio asked for: a drag asks many times a second and only where the + /// divider is NOW matters. + private func sendRatios() async { + defer { isSendingRatios = false } + var sent: [String: Double] = [:] + while phase == .live, + let next = pendingRatios.first(where: { sent[$0.key] != $0.value }) { + guard let split = layout?.split(withID: next.key) else { + pendingRatios[next.key] = nil + continue + } + sent[next.key] = next.value + let answer = try? await call("session.resize_pane", RexWire.resizePanePayload( + sessionID: sessionID, split: split, ratio: next.value)) + if let revision = answer?["revision"] as? Int { + floorRevision = max(floorRevision, revision) + } + } + // Everything asked for has been answered: the server's word stands + // again, including where it refused. + pendingRatios.removeAll() + scheduleViewRefresh() + } + + // MARK: - Drawing a screen + /// How much of the held stream a redraw draws after the rendering. private enum Replay { /// All of it. The attach's rule: nothing says where in the held @@ -402,70 +688,73 @@ actor RexSession: TerminalTransport { case sinceRequest } - /// Renders the terminal's current screen into the emulator, then lets - /// the stream through. Stream output is held from the moment this is - /// called (the attach holds it from the start) to the moment the + /// Renders a terminal's current screen into its emulator, then lets the + /// stream through. Stream output is held from the moment this is called + /// (an opening terminal holds it from the start) to the moment the /// rendering has been drawn, so nothing is drawn UNDER a rendering that /// was taken later, and nothing that arrived meanwhile is dropped. /// - /// Redraws run one at a time. Two at once shared one hold: the first to - /// finish let the stream through, and the second then wiped whatever - /// had been drawn since its own rendering was taken. - private func drawScreen(blockID: String, replay: Replay = .everything) async { - held = held ?? Data() - let generation = dataGeneration - let previous = drawing + /// Redraws of one terminal run one at a time. Two at once shared one + /// hold: the first to finish let the stream through, and the second + /// then wiped whatever had been drawn since its own rendering was taken. + private func drawScreen(_ id: String, _ serial: Int, replay: Replay = .everything) async { + guard let terminal = current(id, serial) else { return } + terminal.held = terminal.held ?? Data() + let previous = terminal.drawing let task = Task { await previous?.value - await self.performDraw(blockID: blockID, replay: replay, generation: generation) + await self.performDraw(id, serial, replay: replay) } - drawing = task + terminal.drawing = task await task.value } - private func performDraw(blockID: String, replay: Replay, generation: Int) async { - // A switch since this was asked for: the screen now belongs to - // another terminal, whose own redraw follows. - guard phase != .closed, generation == dataGeneration else { return } - held = held ?? Data() - await adoptTerminalGrid() - let asked = held?.count ?? 0 + private func performDraw(_ id: String, _ serial: Int, replay: Replay) async { + // Retired since this was asked for: there is no emulator to draw on. + guard let terminal = current(id, serial) else { return } + terminal.held = terminal.held ?? Data() + await adoptTerminalGrid(terminal) + let asked = terminal.held?.count ?? 0 // Two reads that depend on nothing of each other's, so they share // one round trip. - async let alternate = isOnAlternateScreen(blockID: blockID) - async let rendering = bootstrapScreen(blockID: blockID) + async let alternate = isOnAlternateScreen(blockID: id) + async let rendering = bootstrapScreen(blockID: id) let (onAlternateScreen, screen) = await (alternate, rendering) - guard phase != .closed, generation == dataGeneration else { return } + guard current(id, serial) != nil else { return } // RIS first: a resumed tab still shows what the last run drew. - onData?(Data([0x1B, 0x63]) + screen) - exitWatch = onAlternateScreen ? AlternateScreenExitWatch() : nil - let pending = held ?? Data() - held = nil + events?.output(PaneID(id), Data([0x1B, 0x63]) + screen) + terminal.exitWatch = onAlternateScreen ? AlternateScreenExitWatch() : nil + let pending = terminal.held ?? Data() + terminal.held = nil let rest = replay == .everything ? pending : pending.dropFirst(RexWire.resumeOffset(in: pending, from: asked)) - if !rest.isEmpty { deliver(Data(rest)) } + if !rest.isEmpty { deliver(Data(rest), from: terminal) } // The size changed again while the rendering was on its way. - if terminalGrid != shownGrid, !isResyncing { - held = Data() - Task { await self.resync() } + if terminal.terminalGrid != terminal.shownGrid, !terminal.isResyncing { + terminal.held = Data() + Task { await self.resync(id, serial) } } } // MARK: - Another client's size /// The stream said what size the terminal is. While this client owns - /// the block that is the tab's own size and nothing changes; otherwise + /// the block that is its pane's own size and nothing changes; otherwise /// it is whatever its owner made it, and the emulator has to follow. - private func noteTerminalSize(cols: Int, rows: Int, owner: String?) { - let isOwn = (owner != nil && owner == clientID) || (cols == size.cols && rows == size.rows) - terminalGrid = isOwn ? nil : TerminalGrid(cols: cols, rows: rows) - // While the screen is still to be drawn (attach, switch, a redraw - // already holding) that redraw reads the grid itself. - guard terminalGrid != shownGrid, held == nil else { return } + private func noteTerminalSize( + cols: Int, rows: Int, owner: String?, of terminal: Terminal + ) { + let isOwn = (owner != nil && owner == clientID) + || (cols == terminal.size.cols && rows == terminal.size.rows) + terminal.terminalGrid = isOwn ? nil : TerminalGrid(cols: cols, rows: rows) + // While the screen is still to be drawn (an opening terminal, a + // redraw already holding) that redraw reads the grid itself. + guard terminal.terminalGrid != terminal.shownGrid, terminal.held == nil else { return } // Everything from here on was written for the new size. - held = Data() - Task { await self.resync() } + terminal.held = Data() + let id = terminal.id, serial = terminal.serial + Task { await self.resync(id, serial) } } /// Gives the emulator the terminal's grid and draws the screen again at @@ -475,35 +764,36 @@ actor RexSession: TerminalTransport { /// /// It redraws even when the size has gone back by then: what was /// written in between was laid out for a grid the emulator never had. - private func resync() async { - guard !isResyncing else { return } - isResyncing = true - defer { isResyncing = false } + private func resync(_ id: String, _ serial: Int) async { + guard let terminal = current(id, serial), !terminal.isResyncing else { return } + terminal.isResyncing = true + defer { terminal.isResyncing = false } repeat { - held = held ?? Data() - await waitForQuiet() - // A switch draws the new terminal itself, and the hold is its. - guard phase != .closed, !isSwitching, let blockID else { return } - await drawScreen(blockID: blockID, replay: .sinceRequest) - } while phase != .closed && !isSwitching && terminalGrid != shownGrid + terminal.held = terminal.held ?? Data() + await waitForQuiet(terminal) + guard current(id, serial) != nil else { return } + await drawScreen(id, serial, replay: .sinceRequest) + } while current(id, serial) != nil && terminal.terminalGrid != terminal.shownGrid } - private func adoptTerminalGrid() async { - while terminalGrid != shownGrid, phase != .closed { - let grid = terminalGrid - await onGrid?(grid) - shownGrid = grid + private func adoptTerminalGrid(_ terminal: Terminal) async { + while terminal.terminalGrid != terminal.shownGrid, + current(terminal.id, terminal.serial) != nil { + let grid = terminal.terminalGrid + await events?.grid(PaneID(terminal.id), grid) + terminal.shownGrid = grid } } /// Returns once the terminal has written nothing for a moment, or /// after the cap for one that never stops. - private func waitForQuiet() async { + private func waitForQuiet(_ terminal: Terminal) async { let started = ContinuousClock.now - while phase != .closed { + while current(terminal.id, terminal.serial) != nil { try? await Task.sleep(for: .milliseconds(60)) let now = ContinuousClock.now - if now - lastOutput >= .milliseconds(120) || now - started >= .milliseconds(800) { + if now - terminal.lastOutput >= .milliseconds(120) + || now - started >= .milliseconds(800) { break } } @@ -511,12 +801,13 @@ actor RexSession: TerminalTransport { /// Stream output on its way to the emulator. The one place that also /// watches for a full-screen program exiting, when that matters. - private func deliver(_ output: Data) { - onData?(output) - lastOutput = .now - guard exitWatch?.sawExit(in: output) == true, let blockID else { return } - exitWatch = nil - Task { await self.redrawOnceQuiet(blockID: blockID) } + private func deliver(_ output: Data, from terminal: Terminal) { + events?.output(PaneID(terminal.id), output) + terminal.lastOutput = .now + guard terminal.exitWatch?.sawExit(in: output) == true else { return } + terminal.exitWatch = nil + let id = terminal.id, serial = terminal.serial + Task { await self.redrawOnceQuiet(id, serial) } } /// A full-screen program just exited: wait for the burst that follows @@ -530,10 +821,10 @@ actor RexSession: TerminalTransport { /// burst through first, to be replaced by a rendering taken once the /// terminal has gone quiet, leaves nothing in the window to repeat. A /// terminal that never goes quiet is redrawn anyway after the cap. - private func redrawOnceQuiet(blockID: String) async { - await waitForQuiet() - guard phase != .closed else { return } - await drawScreen(blockID: blockID) + private func redrawOnceQuiet(_ id: String, _ serial: Int) async { + guard let terminal = current(id, serial) else { return } + await waitForQuiet(terminal) + await drawScreen(id, serial) } /// Whether a full-screen program currently owns the terminal. Asked of @@ -544,26 +835,36 @@ actor RexSession: TerminalTransport { return modes?["screen"] as? String == "alternate" } - /// Makes this client the block's owner and gives it this tab's size. - /// Best effort: a refusal leaves the terminal at someone else's size, - /// which is wrong-looking but not fatal. - private func claimAndSize() async { - guard let blockID else { return } - if let claimed = try? await call("session.own_block", [ - "session_id": sessionID, "block_ids": [blockID], "mode": "take", - ]) { - let mine = (claimed["blocks"] as? [[String: Any]])? - .first { $0["block_id"] as? String == blockID } - owner = mine?["owner"] as? String ?? clientID + /// Makes this client the owner of `ids` and gives each terminal its + /// pane's size. Best effort: a refusal leaves a terminal at someone + /// else's size, which is wrong-looking but not fatal. + private func claim(_ ids: [String]) async { + guard !ids.isEmpty else { return } + let claimed = try? await call("session.own_block", [ + "session_id": sessionID, "block_ids": ids, "mode": "take", + ]) + // One id that is no longer a block fails the whole call and claims + // nothing — a pane closing as another is typed into. Each alone, + // then, so the rest are still claimed. + if claimed == nil, ids.count > 1 { + for id in ids { await claim([id]) } + return + } + for entry in claimed?["blocks"] as? [[String: Any]] ?? [] { + guard let id = entry["block_id"] as? String else { continue } + terminals[id]?.owner = entry["owner"] as? String ?? clientID + } + for id in ids { + if let terminal = terminals[id] { await sendSize(to: terminal) } } - await sendSize(to: blockID) } /// Applies at once while this client owns the block, and otherwise /// waits server-side until it does — never a failure worth raising. - private func sendSize(to blockID: String) async { + private func sendSize(to terminal: Terminal) async { _ = try? await terminalCall( - "resize", block: blockID, ["columns": size.cols, "rows": size.rows]) + "resize", block: terminal.id, + ["columns": terminal.size.cols, "rows": terminal.size.rows]) } /// The terminal's screen and scrollback as escape sequences SwiftTerm @@ -622,50 +923,62 @@ actor RexSession: TerminalTransport { return Data(lines.joined(separator: "\r\n").utf8) } - // MARK: - TerminalTransport + // MARK: - PanedTerminalTransport /// Queues the input and returns; it does not wait for the server. /// - /// One write is in flight at a time — the server runs block methods - /// concurrently, so two calls could land out of order — and whatever is - /// typed meanwhile rides the next call as one string. Returning at once - /// is what lets that happen: the tab's input pump awaits each write, so - /// a write that waited for its answer would turn every keystroke into a - /// round trip of its own, queued behind the last. - func write(_ data: Data) async throws { + /// One write per terminal is in flight at a time — the server runs + /// block methods concurrently, so two calls could land out of order — + /// and whatever is typed meanwhile rides the next call as one string. + /// Returning at once is what lets that happen: the tab's input pump + /// awaits each write, so a write that waited for its answer would turn + /// every keystroke into a round trip of its own, queued behind the last. + func write(_ data: Data, to pane: PaneID) async throws { guard phase == .live else { throw Failure("not attached") } - // Mid-switch the screen on show is the terminal being left; a key - // pressed then is dropped rather than typed into one not yet drawn. - guard !isSwitching else { return } - pendingInput += input.encode(data) - guard !isWriting, !pendingInput.isEmpty else { return } - isWriting = true - Task { await self.drainInput() } - } - - private func drainInput() async { - defer { isWriting = false } - while !pendingInput.isEmpty, phase == .live, let blockID { - let text = pendingInput - pendingInput = "" - // Typing is what claims the size back from another client. - if owner != clientID { await claimAndSize() } + // A pane whose program has gone takes nothing; neither does one the + // view has not brought in yet. + guard let terminal = terminals[pane.rawValue], !terminal.hasEnded else { return } + terminal.pendingInput += terminal.input.encode(data) + guard !terminal.isWriting, !terminal.pendingInput.isEmpty else { return } + terminal.isWriting = true + let id = terminal.id, serial = terminal.serial + Task { await self.drainInput(id, serial) } + } + + private func drainInput(_ id: String, _ serial: Int) async { + guard let terminal = current(id, serial) else { return } + defer { terminal.isWriting = false } + while !terminal.pendingInput.isEmpty, phase == .live, + current(id, serial) != nil, !terminal.hasEnded { + let text = terminal.pendingInput + terminal.pendingInput = "" + // Typing is what claims the sizes back from another client — + // every terminal the tab draws, the one typed into first. + if terminal.owner != clientID { + let others = terminals.values + .filter { $0.id != id && !$0.hasEnded && $0.owner != clientID } + .map(\.id).sorted() + await claim([id] + others) + } do { - _ = try await terminalCall("write", block: blockID, ["data": text]) + _ = try await terminalCall("write", block: id, ["data": text]) } catch { Self.log.debug("write failed: \(String(describing: error), privacy: .public)") } } } - func resize(cols: Int, rows: Int) async throws { - size = (cols, rows) - guard phase == .live, let blockID else { return } - await sendSize(to: blockID) + func resize(pane: PaneID, cols: Int, rows: Int) async throws { + let grid = TerminalGrid(cols: cols, rows: rows) + requestedSizes[pane.rawValue] = grid + guard let terminal = terminals[pane.rawValue] else { return } + terminal.size = grid + guard phase != .closed, !terminal.hasEnded else { return } + await sendSize(to: terminal) } - /// Idempotent, and always closes the SSH connection the two pipes ride: - /// a tab that ended on its own (`finish`) still has that link to drop. + /// Idempotent, and always closes the SSH connection the pipes ride: a + /// tab that ended on its own (`finish`) still has that link to drop. func close() async { if phase != .closed { phase = .closed @@ -779,76 +1092,96 @@ actor RexSession: TerminalTransport { } private func handleEvent(_ type: String, _ fields: [String: Any]) { - guard fields["block_id"] as? String == blockID else { return } switch type { + case "session_view_changed": + // Only the revision rides the event, and events can arrive out + // of order: one at or below the view on hand is old news. + if let revision = fields["revision"] as? Int, revision <= viewRevision { return } + scheduleViewRefresh() case "block_owner_changed": // nil when the event names no owner — the next keystroke then // claims the block again, which is the safe reading. - owner = fields["owner"] as? String + guard let id = fields["block_id"] as? String else { return } + terminals[id]?.owner = fields["owner"] as? String case "block_closed": - finish(nil) + guard let id = fields["block_id"] as? String, let terminal = terminals[id] + else { return } + terminal.hasEnded = true + // Its place in the layout goes with the next view. + scheduleViewRefresh() default: break } } - // MARK: - Data connection + // MARK: - Data connections - private func startDataReader(_ socket: RexSocket) { - let generation = dataGeneration - dataReader = Task { [weak self] in + private func startDataReader(_ socket: RexSocket, id: String, serial: Int) { + terminals[id]?.reader = Task { [weak self] in do { for try await message in socket.messages { - await self?.handleData(message, generation: generation) + await self?.handleData(message, id, serial) } - await self?.dataLinkEnded(nil, generation: generation) + await self?.dataLinkEnded(nil, id, serial) } catch { await self?.dataLinkEnded( - Self.failure(from: error).message, failed: true, generation: generation) + Self.failure(from: error).message, failed: true, id, serial) } } } - private func dataLinkEnded(_ reason: String?, failed: Bool = false, generation: Int) { - guard generation == dataGeneration else { return } + /// A terminal's stream stopped without a closing frame. Before the + /// stream was up that is this terminal failing to open; after, it is + /// the link under the whole tab — every pipe rides the one connection. + private func dataLinkEnded( + _ reason: String?, failed: Bool = false, _ id: String, _ serial: Int + ) { + guard let terminal = current(id, serial), !terminal.hasEnded else { return } + guard reached.contains(.live(serial)) else { + let failure = Failure(reason ?? String( + localized: "The connection to the Rex server ended.")) + fail(.dataWelcome(serial), failure) + fail(.live(serial), failure) + return + } linkEnded(reason, failed: failed) } - private func handleData(_ message: WebSocketCodec.Message, generation: Int) { - guard generation == dataGeneration else { return } + private func handleData(_ message: WebSocketCodec.Message, _ id: String, _ serial: Int) { + guard let terminal = current(id, serial), !terminal.hasEnded else { return } switch message { case .binary(let bytes): - guard stream != nil else { + guard terminal.stream != nil else { switch RexWire.parseDataReply(bytes) { case .welcome(let nonce)?: - self.stream = RexTerminalStream(nonce: nonce) - reach(.dataWelcome) + terminal.stream = RexTerminalStream(nonce: nonce) + reach(.dataWelcome(serial)) case .reject(let reason)?: - fail(.dataWelcome, Failure(String(localized: """ + fail(.dataWelcome(serial), Failure(String(localized: """ The Rex server refused the terminal stream: \ \(RexWire.rejectDescription(reason)). """))) case nil: - fail(.dataWelcome, Failure(String( + fail(.dataWelcome(serial), Failure(String( localized: "The Rex server answered the stream handshake unreadably."))) } return } // In place: a copy taken out and put back would share the // stream's buffer and force it to be duplicated on every chunk. - let events = stream?.consume(bytes) ?? [] - if stream?.isLive == true { reach(.live) } + let events = terminal.stream?.consume(bytes) ?? [] + if terminal.stream?.isLive == true { reach(.live(serial)) } for event in events { switch event { case .output(let output): - if held == nil { - deliver(output) + if terminal.held == nil { + deliver(output, from: terminal) } else { - held?.append(output) - lastOutput = .now + terminal.held?.append(output) + terminal.lastOutput = .now } case .resize(let cols, let rows, let owner): - noteTerminalSize(cols: cols, rows: rows, owner: owner) + noteTerminalSize(cols: cols, rows: rows, owner: owner, of: terminal) case .childExited: // A program's exit closes the block, which arrives as // the stream's close. @@ -857,11 +1190,26 @@ actor RexSession: TerminalTransport { } case .close(let code, let reason): // 4000 is "block closed" and 1000 a stream that simply ended — - // both a clean end, like a shell exiting. + // both a clean end, like a shell exiting. The pane goes when + // the view no longer has its block; the tab, when that was the + // last one. if code == 4000 || code == 1000 || code == nil { - finish(nil) - } else { + terminal.hasEnded = true + let ended = Failure(String( + localized: "The terminal closed before it could be opened.")) + fail(.dataWelcome(serial), ended) + fail(.live(serial), ended) + scheduleViewRefresh() + } else if reached.contains(.live(serial)) { finish(String(localized: "Rex closed the terminal stream: \(reason).")) + } else { + // A stream that never came up — refused at its handshake, + // say, in which case that reason is already on its way out + // of `openStream`. This terminal's failure, not the tab's. + let failure = Failure(String( + localized: "Rex closed the terminal stream: \(reason).")) + fail(.dataWelcome(serial), failure) + fail(.live(serial), failure) } case .text, .ping, .pong: break @@ -898,7 +1246,7 @@ actor RexSession: TerminalTransport { guard phase != .closed else { return } // Only a tab that went live has someone to tell; a failed attach // is reported by `open` throwing. - let notify = phase == .live ? onClose : nil + let notify = phase == .live ? events?.close : nil phase = .closed Task { await self.teardown(failing: Failure(reason ?? "ended")) @@ -909,22 +1257,29 @@ actor RexSession: TerminalTransport { private func teardown(failing failure: Failure) async { for milestone in Array(waiters.keys) { fail(milestone, failure) } for id in Array(pending.keys) { settle(id, .failure(failure)) } - let data = self.data, control = self.control - self.data = nil + let streams = terminals.values.sorted { $0.serial < $1.serial } + let sockets = streams.compactMap(\.socket) + let control = self.control + for terminal in streams { + terminal.socket = nil + terminal.hasEnded = true + } self.control = nil // Say goodbye BEFORE the readers are cancelled: cancelling a reader // tears its pipe down, and a connection that just drops is kept by // the server for a minute — its client listed as "connection lost", // its stream parked for a resume nobody will send (seen on the - // first headless run). The data connection goes first, with status - // 1000, which ends the stream; a control connection closed with a + // first headless run). The data connections go first, with status + // 1000, which ends each stream; a control connection closed with a // close frame ends its client at once. - await data?.close() + for socket in sockets { await socket.close() } await control?.close() controlReader?.cancel() - dataReader?.cancel() controlReader = nil - dataReader = nil + for terminal in streams { + terminal.reader?.cancel() + terminal.reader = nil + } } /// Turns whatever the layers below threw into one readable sentence. diff --git a/Multiplex/Services/TerminalScreen.swift b/Multiplex/Services/TerminalScreen.swift new file mode 100644 index 00000000..a0c37d98 --- /dev/null +++ b/Multiplex/Services/TerminalScreen.swift @@ -0,0 +1,223 @@ +import Foundation +import SwiftTerm + +/// One emulator of a terminal tab, and the plumbing between it and the far +/// side: the SwiftTerm view, the output on its way in, the ordered pumps +/// for input and size on their way out, and the grid it is held to. +/// +/// A tab has exactly one — `paneID` nil — unless its transport hands its +/// panes out separately (`PanedTerminalTransport`), in which case it has +/// one per pane and `TerminalSessionController` moves `terminalView` between +/// them with the tab's focus. Everything the controller does to "the +/// terminal" it does to its active screen, so a paned tab needed no second +/// version of the chrome above it. +/// +/// What a screen writes to is two closures, so it does not know which kind +/// of transport it belongs to. +@MainActor +final class TerminalScreen { + /// The pane this screen draws; nil for a tab's only screen. + let paneID: PaneID? + + /// Strongly owned (SwiftTerm's delegate back-reference is weak): the + /// view carries the terminal buffer and scrollback, and tabs move + /// between windows — the adopting window re-parents this same view, so + /// what's on screen survives a merge/split. + private(set) var terminalView: TerminalView? + private var pendingOutput: [UInt8] = [] + /// One short-delay drain per transport run replaces a MainActor Task + /// and a Data→Array copy for every network chunk. Parsing remains on + /// the main actor because SwiftTerm's view/delegate/display machinery + /// is UIKit. + var outputCoalescer: TerminalOutputCoalescer? + /// Pinged after every coalesced output flush reaches the terminal — + /// visionOS's gaze link-hover overlay debounces its region rebuild + /// behind this, so affordances follow the screen without polling. + var onOutputFlushed: (() -> Void)? + + /// Whatever grid the emulator has — under a pin, somebody else's. + private(set) var cols = 80 + private(set) var rows = 24 + /// The grid of the terminal on show while the far side dictates it (a + /// Rex terminal another client owns the size of). The surface lays the + /// emulator out at it; nil is the surface's own grid. + private(set) var gridPin: TerminalGrid? + /// The surface's side of `gridPin`. It must have the emulator at the + /// new grid by the time it returns — the screen drawn next is for it. + var onGridPinChanged: (() -> Void)? + /// The last grid the surface measured for itself: what this screen + /// asks its terminal to be. + private(set) var ownSize: TerminalGrid? + private var isSettlingGridPin = false + /// The title the program last set (OSC 0/2). + var title = "" + + private var inputTask: Task? + private var inputContinuation: AsyncStream.Continuation? + private var resizeTask: Task? + private var resizeContinuation: AsyncStream.Continuation? + + init(paneID: PaneID? = nil) { + self.paneID = paneID + } + + /// The grid a transport opens this screen's terminal at. + var openingSize: TerminalGrid { + ownSize ?? TerminalGrid(cols: cols, rows: rows) + } + + var hasPumps: Bool { inputContinuation != nil } + + // MARK: Output + + /// Takes the view a surface made (or adopted from another window) and + /// draws whatever arrived before there was one. + func attach(_ view: TerminalView) { + terminalView = view + if !pendingOutput.isEmpty { + view.feed(byteArray: pendingOutput[...]) + pendingOutput.removeAll() + } + } + + func feed(_ bytes: [UInt8]) { + guard let terminalView else { + pendingOutput.append(contentsOf: bytes) + return + } + terminalView.feed(byteArray: bytes[...]) + onOutputFlushed?() + } + + // MARK: Pumps + + /// Keystrokes flow through one AsyncStream consumed by a single task — + /// yield order is preserved, unlike a Task spawned per keystroke, and + /// the terminal thread never waits on the network. + /// + /// Resize callbacks can arrive for every layout pass while a window is + /// dragged. Only the newest dimensions are kept and one ordered task + /// talks to the transport, rather than an unbounded task per callback. + func startPumps( + write: @escaping @Sendable (Data) async throws -> Void, + resize: @escaping @Sendable (TerminalGrid) async throws -> Void, + openedAt size: TerminalGrid + ) { + stopPumps() + let (input, inputContinuation) = AsyncStream.makeStream(of: Data.self) + self.inputContinuation = inputContinuation + inputTask = Task { + for await chunk in input { + try? await write(chunk) + } + } + let (sizes, resizeContinuation) = AsyncStream.makeStream( + of: TerminalGrid.self, + bufferingPolicy: .bufferingNewest(1) + ) + self.resizeContinuation = resizeContinuation + resizeTask = Task { + for await size in sizes { + try? await resize(size) + } + } + // Layout may have changed while the handshake/open call was + // awaiting; reconcile once with the newest geometry before normal + // coalescing. + if gridPin == nil, cols != size.cols || rows != size.rows { + resizeContinuation.yield(TerminalGrid(cols: cols, rows: rows)) + } + } + + func stopPumps() { + inputContinuation?.finish() + inputContinuation = nil + inputTask?.cancel() + inputTask = nil + resizeContinuation?.finish() + resizeContinuation = nil + resizeTask?.cancel() + resizeTask = nil + } + + /// Joins the ordered input pump. False when there is none — the caller + /// has bytes that must not be dropped (the handoff re-type) and writes + /// them itself. + @discardableResult + func send(_ data: Data) -> Bool { + guard let inputContinuation else { return false } + inputContinuation.yield(data) + return true + } + + // MARK: Size + + /// The emulator measured a grid; false when it is the one it had. The + /// far side is told only a grid that is this screen's own ask — one + /// taken from another client is the emulator's, not this tab's — and + /// only while there is a far side: the pumps live exactly as long as + /// the transport does. + @discardableResult + func resized(cols: Int, rows: Int) -> Bool { + guard cols != self.cols || rows != self.rows else { return false } + self.cols = cols + self.rows = rows + if gridPin == nil, !isSettlingGridPin { + let size = TerminalGrid(cols: cols, rows: rows) + ownSize = size + resizeContinuation?.yield(size) + } + return true + } + + /// Gives the emulator another client's grid, or its own back. + /// + /// The surface changes the text size and the frame to do it, and each + /// of those makes SwiftTerm report a grid on the way — none of them the + /// screen's own, so none is sent on. Once the surface has settled back + /// on its own grid, that one is: the window may have been resized + /// meanwhile. + func setGridPin(_ grid: TerminalGrid?) { + guard grid != gridPin else { return } + gridPin = grid + isSettlingGridPin = true + onGridPinChanged?() + isSettlingGridPin = false + // With no surface to lay out, the emulator is still at the grid it + // was given and `ownSize` already holds the screen's last own one. + guard grid == nil, onGridPinChanged != nil else { return } + let own = TerminalGrid(cols: cols, rows: rows) + ownSize = own + resizeContinuation?.yield(own) + } + + /// The emulator's visible rows as text, and whether a full-screen + /// program has it. Copied reads: the terminal lives behind SwiftTerm's + /// lock, and its parse runs on the feed thread. + func snapshot() -> (lines: [String], isAlternate: Bool) { + guard let terminalView else { return ([], false) } + let rows = max(0, terminalView.terminalDimensions.rows) + let lines = terminalView.visibleRowsText(0..