diff --git a/AGENTS.md b/AGENTS.md index ab4bc6e6..934aae63 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: @@ -62,10 +63,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 @@ -89,12 +92,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, session creation (setup scripts, per-host tmux conf, - systemd-run), file attach/drop. + 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/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..17995492 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" : { @@ -1507,143 +1529,511 @@ "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%1$@のシェル(%2$@)はMultiplexのコマンドを拒否しました(終了コード%3$@):%4$@" + "value" : "%1$@のシェル(%2$@)はMultiplexのコマンドを拒否しました(終了コード%3$@):%4$@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ 的 shell(%2$@)拒絕了 Multiplex 的指令(結束代碼 %3$@):%4$@" + } + } + } + }, + "%lld additions, %lld deletions" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$lld additions, %2$lld deletions" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld行追加、%lld行削除" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "新增 %lld 行,刪除 %lld 行" + } + } + } + }, + "%lld KEY COMMANDS" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld件のキーコマンド" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 個按鍵指令" + } + } + } + }, + "%lld sessions" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lldセッション" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 個工作階段" + } + } + } + }, + "%lld tabs" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lldタブ" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 個標籤頁" + } + } + } + }, + "%lld windows and %lld panes" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$lld windows and %2$lld panes" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lldウインドウ、%lldペイン" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 個視窗和 %lld 個窗格" + } + } + } + }, + "%lld windows, %lld panes. %@%@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$lld windows, %2$lld panes. %3$@%4$@" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lldウインドウ、%lldペイン。%@%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%lld 個視窗,%lld 個窗格。%@%@" + } + } + } + }, + "+ New Session" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "+ 新規セッション" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "+ 新增工作階段" + } + } + } + }, + "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タイルは、そのセッションが表示しているウインドウをペインごと開きます。新しい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" : "%1$@ 的 shell(%2$@)拒絕了 Multiplex 的指令(結束代碼 %3$@):%4$@" + "value" : "Rex 伺服器沒有發出可用的串流票證。" } } } }, - "%lld additions, %lld deletions" : { + "The Rex server refused the connection (%@)." : { "localizations" : { - "en" : { - "stringUnit" : { - "state" : "new", - "value" : "%1$lld additions, %2$lld deletions" - } - }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lld行追加、%lld行削除" + "value" : "Rexサーバーが接続を拒否しました(%@)。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "新增 %lld 行,刪除 %lld 行" + "value" : "Rex 伺服器拒絕了連線(%@)。" } } } }, - "%lld KEY COMMANDS" : { + "The Rex server refused the terminal stream: %@." : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lld件のキーコマンド" + "value" : "Rexサーバーがターミナルストリームを拒否しました:%@。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 個按鍵指令" + "value" : "Rex 伺服器拒絕了終端機串流:%@。" } } } }, - "%lld sessions" : { + "The Rex server refused: %@" : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lldセッション" + "value" : "Rexサーバーが拒否しました:%@" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 個工作階段" + "value" : "Rex 伺服器拒絕了要求:%@" } } } }, - "%lld tabs" : { + "This Rex session has no terminal to open." : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lldタブ" + "value" : "このRexセッションには開けるターミナルがありません。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 個標籤頁" + "value" : "這個 Rex 工作階段沒有可開啟的終端機。" } } } }, - "%lld windows and %lld panes" : { + "This Rex session no longer exists." : { "localizations" : { - "en" : { - "stringUnit" : { - "state" : "new", - "value" : "%1$lld windows and %2$lld panes" - } - }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lldウインドウ、%lldペイン" + "value" : "このRexセッションはもう存在しません。" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 個視窗和 %lld 個窗格" + "value" : "這個 Rex 工作階段已不存在。" } } } }, - "%lld windows, %lld panes. %@%@" : { + "unreadable rex probe response" : { "localizations" : { - "en" : { - "stringUnit" : { - "state" : "new", - "value" : "%1$lld windows, %2$lld panes. %3$@%4$@" - } - }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "%lldウインドウ、%lldペイン。%@%@" + "value" : "rexの応答を読み取れません" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "%lld 個視窗,%lld 個窗格。%@%@" + "value" : "無法讀取的 rex 探測回應" } } } }, - "+ New Session" : { + "window %lld" : { "localizations" : { "ja" : { "stringUnit" : { "state" : "translated", - "value" : "+ 新規セッション" + "value" : "ウインドウ%lld" } }, "zh-Hant" : { "stringUnit" : { "state" : "translated", - "value" : "+ 新增工作階段" + "value" : "視窗 %lld" } } } @@ -2738,6 +3128,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" : { @@ -4568,6 +4990,22 @@ } } }, + "Couldn't close the pane. %@" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ペインを閉じられませんでした。%@" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "無法關閉窗格。%@" + } + } + } + }, "Couldn't connect to %@: %@" : { "localizations" : { "en" : { @@ -4714,6 +5152,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" : { @@ -4850,6 +5320,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" : { @@ -9450,6 +9936,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" : { @@ -10934,6 +11442,22 @@ } } }, + "Pane divider" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ペインの区切り線" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "窗格分隔線" + } + } + } + }, "PANE MENU" : { "localizations" : { "ja" : { @@ -13204,6 +13728,22 @@ } } }, + "Show all panes" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "すべてのペインを表示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "顯示所有窗格" + } + } + } + }, "Show connection stats" : { "localizations" : { "ja" : { @@ -13300,6 +13840,22 @@ } } }, + "Show Rex panes and terminals" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rexのペインとターミナルを表示" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "顯示 Rex 窗格與終端機" + } + } + } + }, "Show only changed files" : { "localizations" : { "ja" : { @@ -13887,6 +14443,22 @@ } } }, + "Split Down" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "下に分割" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "向下分割" + } + } + } + }, "Split Left / Right" : { "localizations" : { "ja" : { @@ -13903,6 +14475,22 @@ } } }, + "Split Right" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "右に分割" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "向右分割" + } + } + } + }, "Split Top / Bottom" : { "localizations" : { "ja" : { @@ -14365,6 +14953,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 +15087,22 @@ } } }, + "terminal" : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ターミナル" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "終端機" + } + } + } + }, "Tab" : { "localizations" : { "ja" : { @@ -15703,6 +16323,22 @@ } } }, + "The Rex server on this host is older than Multiplex can talk to. Update Rex there." : { + "localizations" : { + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "このホストのRexサーバーは古く、Multiplexから接続できません。ホスト側でRexをアップデートしてください。" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "這台主機上的 Rex 伺服器版本太舊,Multiplex 無法與它通訊。請在主機上更新 Rex。" + } + } + } + }, "The same block, right where you pressed — and it reaches links and paths at any mouse mode, when a tap belongs to the remote." : { "localizations" : { "ja" : { @@ -15751,6 +16387,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/Host.swift b/Multiplex/Models/Host.swift index a70df021..d173a07e 100644 --- a/Multiplex/Models/Host.swift +++ b/Multiplex/Models/Host.swift @@ -25,26 +25,86 @@ 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 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. - var reportsClientCount: Bool { self == .tmux } + /// 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) + + /// 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, + /// for that terminal (`TmuxSession.agent(inPane:)`). + 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. + /// 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 { - 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 +163,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 +203,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 +300,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 +435,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 +496,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..0e9ca3d7 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, 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: [] } } @@ -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.displayName + 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,26 @@ 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 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 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. + """) + /// 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/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 new file mode 100644 index 00000000..7ee871f2 --- /dev/null +++ b/Multiplex/Models/RexWire.swift @@ -0,0 +1,853 @@ +import Foundation + +/// 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 24 (Rex 0.1.0-preview.25, 2026-11-27). 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. The hello states the range of revisions the +/// client speaks and the server picks the newest both do (`apiRevision`, +/// `minimumAPIRevision`). +/// - `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" + /// The newest API revision this client speaks — the one its shapes + /// were last read against (`GET /llms.txt` of a preview.25 server). + static let apiRevision = 24 + /// The oldest revision this client can use. The server settles on the + /// newest revision both sides speak and translates to it, so an older + /// server is spoken to at ITS revision: everything a tab sends and + /// reads was compared at 14, 19 and 24 and has one shape in all three + /// (`backends-and-probe.md`). A server from before 14 closes the + /// connection with status 1008 and a reason that says to update it, + /// which is what the tab's ended line then reads. + static let minimumAPIRevision = 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, + "api_min_revision": minimumAPIRevision, + "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 { + /// `revision` is the API revision the server settled on for this + /// connection; a welcome that names none means 0, as the protocol + /// reads it. + case welcome(clientID: String?, revision: Int) + /// `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, + revision: object["api_revision"] as? Int ?? 0) + 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: - 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. + 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 + /// The client its size follows; nil for none. + var owner: String? + } + + /// 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, + owner: block["owner"] as? String + )) + } + } + } + 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: - 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 } + } + + /// A view's windows in tab order: what a later view is read against + /// when one of them has gone (`layer(replacing:among:inView:)`). + static func windowOrder(inView view: [String: Any]) -> [String] { + (view["windows"] as? [[String: Any]] ?? []).compactMap { $0["window_id"] as? String } + } + + /// Where a tab goes when what it drew is gone and the session still has + /// a terminal: the window Rex itself shows next. `order` is the tab + /// order from before, while `windowID` was still in it. + /// + /// Rex's rule for a closed window that was the active one: "the window + /// after it becomes active, or the one before it if it was last". The + /// same walk here, over the windows that still hold a terminal, so a + /// tab and a Rex app that were both on the window land on the same one. + /// A window that is still there and only lost the layer the tab drew (a + /// floating layer closed) keeps the tab. In a window, the layer its + /// focused block is in. + /// + /// nil only when no window of the session has a terminal left. + static func layer( + replacing windowID: String, among order: [String], inView view: [String: Any] + ) -> Layer? { + let layers = layers(inView: view, preferring: nil) + func layer(of window: String) -> Layer? { + let own = layers.filter { $0.windowID == window } + return own.first { $0.focusedBlockID != nil } ?? own.first + } + if let same = layer(of: windowID) { return same } + let place = order.firstIndex(of: windowID) ?? order.endIndex + let after = order[place...].dropFirst() + let before = order[.. [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 + /// .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 + /// (`chosenWindowLabel`) is `window N`, and a terminal whose label says + /// nothing more than its window is the window alone. `isActive` marks + /// 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] { + 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 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: count == 1 ? base : "\(base) \(String(count))") + } + } + + // 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? { + guard let bytes = Data(base64URLNoPad: ticket), 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)" + } + } + + // 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 +/// 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] { + // 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() + + 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 = carry.isEmpty ? [UInt8](chunk) : [UInt8](carry) + [UInt8](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. 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 >= 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 bytes[index + 1] == 0x5B, bytes[index + 2] == 0x3F 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..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 { @@ -125,13 +149,74 @@ struct ShortcutPanelContent: Equatable, Sendable { switchNoun: String(localized: "workspace") ) + /// Rex has no prefix-key client — Multiplex IS the client — so its panel + /// 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 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.", + 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 panes and terminals") + } + } +} 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/Models/TerminalRoute.swift b/Multiplex/Models/TerminalRoute.swift index ef3852f1..4d1efef4 100644 --- a/Multiplex/Models/TerminalRoute.swift +++ b/Multiplex/Models/TerminalRoute.swift @@ -17,6 +17,20 @@ struct TerminalRoute: Codable, Hashable, Identifiable { /// presses too. A real terminal like `.attach`: restores across /// launches, resumes per `SessionResumePolicy`. case herdrAttach(sessionName: String) + /// 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) — 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 + /// 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 +51,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, RexWire.bakeableSessionID(sessionID) else { return nil } + return .rexAttach(sessionName: sessionName, sessionID: sessionID) } } @@ -55,14 +79,36 @@ 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) + } + + /// 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 + else { return nil } + return .rexAttach( + sessionName: session.name, + sessionID: session.tmuxID, + block: RexBlockRef(id: pane.tmuxID, label: window.name) + ) } } @@ -82,7 +128,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 +155,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 +165,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 +183,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,6 +204,7 @@ struct TerminalRoute: Codable, Hashable, Identifiable { switch mode { case .attach, .create: .tmux case .herdrAttach: .herdr + case .rexAttach: .rex case .shell, .viewport, .fileViewer: nil } } @@ -217,7 +277,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 +335,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 app has + /// been `Rex.app` since preview.23): + /// - the server copy the app installs and runs, under Application + /// Support in `Versions/Current` — 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, under both names the app has had. + /// 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 +382,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 +393,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/TmuxModels.swift b/Multiplex/Models/TmuxModels.swift index 7c3569c3..c1f9fccb 100644 --- a/Multiplex/Models/TmuxModels.swift +++ b/Multiplex/Models/TmuxModels.swift @@ -188,6 +188,19 @@ 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 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 ?? [] } + .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`. @@ -200,6 +213,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 + /// 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/Models/WebSocketCodec.swift b/Multiplex/Models/WebSocketCodec.swift new file mode 100644 index 00000000..16a8d26d --- /dev/null +++ b/Multiplex/Models/WebSocketCodec.swift @@ -0,0 +1,297 @@ +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) + let count = payload.count + var frame = Data(capacity: count + 14) + frame.append(0x80 | opcode.rawValue) + 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) + // 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.. 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() + /// How much of `buffer` has already been handed out as frames. The + /// spent front is dropped once per `append`, not once per frame: a + /// chunk of a hundred small frames would otherwise be copied a + /// hundred times over on the terminal's hot path. + private var consumed = 0 + /// The data message being assembled across fragments. + private var partial: (opcode: Opcode, payload: Data)? + + mutating func append(_ bytes: Data) { + if consumed > 0 { + buffer.removeSubrange(buffer.startIndex..<(buffer.startIndex + consumed)) + consumed = 0 + } + 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 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") + } + 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 available >= offset + 2 else { return nil } + length = Int(buffer[base + 2]) << 8 | Int(buffer[base + 3]) + offset += 2 + } else if length == 127 { + guard available >= offset + 8 else { return nil } + var wide: UInt64 = 0 + 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)) + } + 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 available >= offset + 4 else { return nil } + key = [UInt8](buffer[(base + offset)..<(base + offset + 4)]) + offset += 4 + } + 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] }) + } + consumed += 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..c4d3b02c 100644 --- a/Multiplex/Services/ConnectionHub.swift +++ b/Multiplex/Services/ConnectionHub.swift @@ -226,6 +226,31 @@ 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) + } + } + } + + /// 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 @@ -327,6 +352,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 +446,12 @@ final class HostConnectionModel { let connection 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 } @@ -783,6 +818,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 + ) } } @@ -1055,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) @@ -1099,9 +1142,55 @@ 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: 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) @@ -1219,7 +1308,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 +1320,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 +1351,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. 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 + /// 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 sourceID = sourceSession + .flatMap { name in sessions(on: .rex).first { $0.name == name }?.tmuxID } + .flatMap { RexWire.bakeableSessionID($0) ? $0 : nil } + let command = RexProbe.mintCommand( + label: RexProbe.sessionLabel(base: base), + 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 +1584,10 @@ final class HostConnectionModel { running script: String? = nil, typing launch: String? ) async -> TerminalRoute.Mode? { + // 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 { @@ -1623,6 +1774,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 +1823,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..97cb0a9f 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(\.backend.opensWindowsInSession) 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") } @@ -440,18 +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 - 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).") - } - } - 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 9eff5ade..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,12 +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: + nil } } @@ -532,6 +537,8 @@ final class FileViewerController: AuxiliaryPaneController { HerdrProbe.parsePaneWorkingDirectory( output, atScreenCell: cell, screenSize: screenSize ) + case .rex: + 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/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/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/RexProbe.swift b/Multiplex/Services/RexProbe.swift new file mode 100644 index 00000000..78c86c99 --- /dev/null +++ b/Multiplex/Services/RexProbe.swift @@ -0,0 +1,870 @@ +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 and run +/// again, unchanged, against preview.25 / revision 24 on 2026-11-27 (a +/// throwaway server each time; fixtures from both 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 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 = 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. + /// + /// 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 = compactLua(""" + 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 + """) + + /// 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 { RexWire.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 + } + } + + /// 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.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 + ) + } + + 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'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 { + 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 + } + + /// 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)" + } + + // MARK: - Session actions + + /// 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 RexWire.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(RexWire.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(RexWire.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 = 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 + 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 } + """) + + /// 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, 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 = RexWire.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`; 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) { + let name = app.lowercased() + self.init(herdrAgent: name == "claude-code" ? "claude" : name) + } +} diff --git a/Multiplex/Services/RexSession.swift b/Multiplex/Services/RexSession.swift new file mode 100644 index 00000000..ad9182fc --- /dev/null +++ b/Multiplex/Services/RexSession.swift @@ -0,0 +1,1321 @@ +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 = OneShotGate(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.open() + } + 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() + } +} + +/// 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 byte pipes on +/// the tab's SSH connection (`SSHConnection.openPipe` running `rex +/// __internal dial-stdio`, the bridge Rex's own `ssh://` transport uses). +/// +/// - 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: +/// - **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 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 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 (`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 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 + + 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: 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 + private let sessionID: String + private let preferredBlockID: String? + private let clientVersion: String + + private var control: RexSocket? + private var controlReader: Task? + + private struct Reply: @unchecked Sendable { + var payload: [String: Any] + } + private var pending: [String: CheckedContinuation] = [:] + private var timeouts: [String: Task] = [:] + private var requestCount = 0 + + /// 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? + /// `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 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)? + /// The session's windows in tab order, as of the last view that still + /// had `shown` in it: where the tab goes when that window closes is + /// read off its place here. + private var windowOrder: [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, + 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: 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?, + 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 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) + 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 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.")) + } + 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) } + } + + // MARK: - The view + + /// 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) + } + // The window this tab drew has closed, or its last terminal + // has: the tab moves to the window Rex shows next, as its own + // app does when a tab is closed. With no terminal left in the + // session that is a clean end, like a shell exiting. + guard let layer = layer ?? shown.flatMap({ + RexWire.layer(replacing: $0.windowID, among: windowOrder, inView: view) + }) else { + finish(nil) + return + } + let failures = await show(layer, focusing: target, in: view) + for (id, failure) in failures { report(failure, inTerminal: id) } + } + } + + /// 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) + windowOrder = RexWire.windowOrder(inView: view) + 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: - The session's other terminals + + /// Every terminal of the session, as the REX panel's Switch Terminal + /// 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: focusedBlockID) + } + + /// 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 { + 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 { + 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 + /// 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 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 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(id, serial, replay: replay) + } + terminal.drawing = task + await task.value + } + + 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: id) + async let rendering = bootstrapScreen(blockID: id) + let (onAlternateScreen, screen) = await (alternate, rendering) + guard current(id, serial) != nil else { return } + // RIS first: a resumed tab still shows what the last run drew. + 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), from: terminal) } + // The size changed again while the rendering was on its way. + 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 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?, 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. + 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 + /// 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(_ id: String, _ serial: Int) async { + guard let terminal = current(id, serial), !terminal.isResyncing else { return } + terminal.isResyncing = true + defer { terminal.isResyncing = false } + repeat { + 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(_ 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(_ terminal: Terminal) async { + let started = ContinuousClock.now + while current(terminal.id, terminal.serial) != nil { + try? await Task.sleep(for: .milliseconds(60)) + let now = ContinuousClock.now + if now - terminal.lastOutput >= .milliseconds(120) + || now - started >= .milliseconds(800) { + break + } + } + } + + /// 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, 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 + /// 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(_ 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 + /// 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 terminalCall("modes", block: blockID) + return modes?["screen"] as? String == "alternate" + } + + /// 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) } + } + } + + /// 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 terminal: Terminal) async { + _ = try? await terminalCall( + "resize", block: terminal.id, + ["columns": terminal.size.cols, "rows": terminal.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 { + 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 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) + } + // 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 } + screen.append(contentsOf: piece.utf8) + if more["eof"] as? Bool == true { break } + } + 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 { + 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 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. + if offset > 0, !lines.isEmpty { lines.removeFirst() } + return Data(lines.joined(separator: "\r\n").utf8) + } + + // MARK: - PanedTerminalTransport + + /// Queues the input and returns; it does not wait for the server. + /// + /// 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") } + // 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: id, ["data": text]) + } catch { + Self.log.debug("write failed: \(String(describing: error), privacy: .public)") + } + } + } + + 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 pipes ride: a + /// tab that ended on its own (`finish`) still has that link to drop. + func close() async { + if phase != .closed { + phase = .closed + await teardown(failing: Failure("closed")) + } + await closeLink() + } + + // MARK: - Requests + + /// 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)" + 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: Self.replyTimeout) } 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) async throws { + guard !reached.contains(milestone) else { return } + let timer = Task { [weak self] in + 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."))) + } + 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, let revision)?: + // A server from before revisions were negotiated answers + // at its own, whatever range the hello gave. + guard revision >= RexWire.minimumAPIRevision else { + fail(.welcome, Failure(String(localized: """ + The Rex server on this host is older than Multiplex can talk to. \ + Update Rex there. + """))) + return + } + 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]) { + 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. + guard let id = fields["block_id"] as? String else { return } + terminals[id]?.owner = fields["owner"] as? String + case "block_closed": + 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 connections + + 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, id, serial) + } + await self?.dataLinkEnded(nil, id, serial) + } catch { + await self?.dataLinkEnded( + Self.failure(from: error).message, failed: true, id, serial) + } + } + } + + /// 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, _ id: String, _ serial: Int) { + guard let terminal = current(id, serial), !terminal.hasEnded else { return } + switch message { + case .binary(let bytes): + guard terminal.stream != nil else { + switch RexWire.parseDataReply(bytes) { + case .welcome(let nonce)?: + terminal.stream = RexTerminalStream(nonce: nonce) + reach(.dataWelcome(serial)) + case .reject(let reason)?: + fail(.dataWelcome(serial), Failure(String(localized: """ + The Rex server refused the terminal stream: \ + \(RexWire.rejectDescription(reason)). + """))) + case nil: + 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 = terminal.stream?.consume(bytes) ?? [] + if terminal.stream?.isLive == true { reach(.live(serial)) } + for event in events { + switch event { + case .output(let output): + if terminal.held == nil { + deliver(output, from: terminal) + } else { + terminal.held?.append(output) + terminal.lastOutput = .now + } + case .resize(let cols, let rows, let 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. + 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. 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 { + 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 + } + } + + // 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 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) } + 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 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 ? events?.close : nil + phase = .closed + 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 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 connections go first, with status + // 1000, which ends each stream; a control connection closed with a + // close frame ends its client at once. + for socket in sockets { await socket.close() } + await control?.close() + controlReader?.cancel() + controlReader = nil + for terminal in streams { + terminal.reader?.cancel() + terminal.reader = 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..7056da8c 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,9 +920,84 @@ 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 { +/// (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? @@ -849,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/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..? + /// 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 @@ -124,13 +137,60 @@ final class TerminalSessionController { keyboardObstruction = height } - /// 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. Released with the controller on close. + /// The view of the screen the keyboard is on — the tab's only one, or + /// the active pane's. The screen owns it (`TerminalScreen`); this is the + /// observed mirror everything above the terminal reads, so chrome + /// follows the tab's focus from pane to pane without knowing there are + /// panes. private(set) var terminalView: TerminalView? - /// The byte pipe under this tab — SSH PTY or mosh session. + /// The emulators this tab draws: one, or — on a paned tab — one per + /// pane in layout order, none until the attach has said what they are. + @ObservationIgnored private(set) var screens: [TerminalScreen] = [] + @ObservationIgnored private var activeScreen: TerminalScreen? + /// Whether this tab's backend hands its panes out separately, for the + /// tab to draw (`PanedTerminalTransport`). Rex is the one that does. + var drawsPanes: Bool { route.rexTarget != nil } + /// How a paned tab's panes are arranged, as its transport last said (and + /// as a divider drag here has since moved it). nil on every other tab, + /// and until an attach has answered. + private(set) var paneLayout: PaneLayout? + /// The pane the tab's keyboard is on. + private(set) var activePaneID: PaneID? + /// The pane a paned tab draws ALONE, over the room of all the others; + /// nil while it draws them all. The tab's own: no backend is asked, and + /// the layout — every hidden pane's size included — stays as it is, so + /// leaving the zoom is instant. It ends when the keyboard goes to + /// another pane, as tmux's and Rex's own zooms do. + private(set) var zoomedPaneID: PaneID? + /// The surface's side of `paneLayout`: it must have every pane laid out + /// — and so measured — by the time it returns. A new pane's terminal is + /// opened at the grid this pass gives it. + @ObservationIgnored private var onPaneLayoutChanged: (() -> Void)? + /// Whose `onPaneLayoutChanged` that is. A tab moved to another window + /// has two surfaces for a moment, and only the newer may make emulator + /// views: the older one adopting them back would pull them out of the + /// window the tab just arrived in. + @ObservationIgnored private weak var paneLayoutObserver: AnyObject? + /// The byte pipe under this tab — SSH PTY or mosh session. nil on a + /// paned tab, whose link is `panedTransport`. private var transport: (any TerminalTransport)? + /// A paned tab's link: one stream per pane and the layout they sit in. + private var panedTransport: (any PanedTerminalTransport)? + /// The paned transport as the Rex client it is on a Rex tab. + private var rexSession: RexSession? { panedTransport as? RexSession } + /// Routes each pane's output to its screen from the transport's own + /// isolation; one per paned run. + @ObservationIgnored private var paneOutput: PaneOutputRouter? + @ObservationIgnored private var paneCommands: AsyncStream.Continuation? + @ObservationIgnored private var paneCommandTask: Task? + /// The terminal a Rex tab's keyboard is on: learned when the attach + /// settles on one, moved by a touch on another pane and by the 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? @@ -140,17 +200,10 @@ final class TerminalSessionController { /// threshold. Input still queues and the link self-heals; the chrome /// just shows it truthfully. Always false on SSH tabs. private(set) var contactLost = false - 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. - private var outputCoalescer: TerminalOutputCoalescer? /// SSH handoff tabs only: watches early PTY output for the oh-my-zsh /// update prompt, whose stdin drain swallows the injected attach line. /// nil once resolved (prompt handled, attach seen, or window elapsed). private var handoffWatch: ShellHandoff.UpdatePromptWatch? - private var lastCols = 80 - private var lastRows = 24 private var started = false private var transportGeneration = 0 /// Session-volume counters drained by the stats pump. Written on the @@ -167,14 +220,6 @@ final class TerminalSessionController { private var statsLiveRuns = 0 private var statsTask: Task? private var runTask: Task? - private var inputTask: Task? - private var inputContinuation: AsyncStream.Continuation? - private struct TerminalSize: Sendable { - var cols: Int - var rows: Int - } - private var resizeTask: Task? - private var resizeContinuation: AsyncStream.Continuation? /// Background cadence for a plain PTY. The focused TerminalWindow may /// request a faster refresh, coalesced by the same in-flight/staleness /// gates; tmux tabs continue to use ConnectionHub's fleet probe. @@ -224,7 +269,9 @@ final class TerminalSessionController { /// The grid this tab reports to the remote — the attached client's /// screen as the backend lays it out, which herdr's content-relative /// pane rects need to land on screen cells. - var screenSize: (cols: Int, rows: Int) { (cols: lastCols, rows: lastRows) } + var screenSize: (cols: Int, rows: Int) { + (cols: activeScreen?.cols ?? 80, rows: activeScreen?.rows ?? 24) + } #if !os(visionOS) /// The terminal's app-owned dictation controls, from the pane's side: @@ -253,6 +300,11 @@ final class TerminalSessionController { self.route = route self.host = host self.attention = attention + if route.rexTarget == nil { + let screen = TerminalScreen() + screens = [screen] + activeScreen = screen + } #if !os(visionOS) dictationDriver.onStateChange = { [weak self] in guard let self else { return } @@ -273,9 +325,27 @@ final class TerminalSessionController { "\(route.displayName) — \(host.name)" } - func bind(_ view: TerminalView) { - terminalView = view - applyTouchInteractionModes() + /// The one screen of a tab that draws no panes. + var soleScreen: TerminalScreen? { drawsPanes ? nil : screens.first } + + /// Replace, never stack: the surface that lays this tab's panes out is + /// the last one installed. + func observePaneLayout(as observer: AnyObject, _ changed: @escaping () -> Void) { + paneLayoutObserver = observer + onPaneLayoutChanged = changed + } + + func isPaneLayoutObserver(_ candidate: AnyObject) -> Bool { + paneLayoutObserver === candidate + } + + func screen(for pane: PaneID) -> TerminalScreen? { + screens.first { $0.paneID == pane } + } + + /// A surface made (or adopted) the view for one of this tab's screens. + func bind(_ view: TerminalView, to screen: TerminalScreen) { + applyTouchInteractionModes(to: view) // Touch never hovers, so SwiftTerm's pointer-gated activation can // never fire here; this pane decides instead. The view owns the // closure and this controller owns the view — capture weakly. @@ -311,10 +381,8 @@ final class TerminalSessionController { // hands the drag to herdr instead. view.longPressDragSelectsRemotely = true } - if !pendingOutput.isEmpty { - view.feed(byteArray: pendingOutput[...]) - pendingOutput.removeAll() - } + screen.attach(view) + if screen === activeScreen { terminalView = view } } /// Route keyboard input to this window's terminal. @@ -416,34 +484,47 @@ final class TerminalSessionController { private func beginTransportRun() { transportGeneration &+= 1 let generation = transportGeneration - let output = TerminalOutputCoalescer { [weak self] bytes in - guard let self, self.transportGeneration == generation else { return } - self.feed(bytes) + for screen in screens { + // A new run attaches at this tab's own size. + screen.setGridPin(nil) + screen.outputCoalescer = makeOutputCoalescer(for: screen, generation: generation) } - outputCoalescer = output runTask?.cancel() runTask = Task { [weak self] in guard let self else { return } - await self.run(generation: generation, output: output) + await self.run(generation: generation) if self.transportGeneration == generation { self.runTask = nil } } } - private func run( - generation: Int, - output: TerminalOutputCoalescer - ) async { - if host.useMosh { - await runMosh(generation: generation, output: output) - } else { - await runSSH(generation: generation, output: output) + private func makeOutputCoalescer( + for screen: TerminalScreen, generation: Int + ) -> TerminalOutputCoalescer { + TerminalOutputCoalescer { [weak self, weak screen] bytes in + guard let self, let screen, self.transportGeneration == generation else { return } + self.feed(bytes, to: screen) } } + private func run(generation: Int) async { + if let rex = route.rexTarget { + await runRex(rex, generation: generation) + } else if let screen = screens.first, let output = screen.outputCoalescer { + if ridesMosh { + await runMosh(generation: generation, screen: screen, output: output) + } else { + await runSSH(generation: generation, screen: screen, output: output) + } + } + } + + /// The tab's own SSH connection, carrying a PTY that runs the route's + /// remote command. The connection stays this tab's exec surface. private func runSSH( generation: Int, + screen: TerminalScreen, output: TerminalOutputCoalescer ) async { let secrets = await HostSecrets.loadOffMain(for: host) @@ -454,7 +535,7 @@ final class TerminalSessionController { return } self.connection = connection - transport = connection + self.transport = connection do { try await connection.connect() try Task.checkCancellation() @@ -464,30 +545,24 @@ final class TerminalSessionController { 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). + let openedSize = screen.openingSize + // 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, + 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 - ) + self?.handleClose(reason: reason, generation: generation) } - } - ) + }) try Task.checkCancellation() guard transportGeneration == generation, self.connection === connection @@ -495,7 +570,7 @@ final class TerminalSessionController { await connection.close() return } - startTransportPumps(for: connection, openedAt: openedSize) + startTransportPumps(for: connection, screen: screen, openedAt: openedSize) markLive() startDirectShellMonitoring() } catch { @@ -508,19 +583,123 @@ final class TerminalSessionController { ?? String(localized: "Couldn't reach \(host.name). \(error.localizedDescription)") status = .ended(message) self.connection = nil - transport = nil - outputCoalescer = nil + self.transport = nil + screen.outputCoalescer = nil handoffWatch = nil considerAutomaticResume() } } + /// A Rex tab: the tab's own SSH connection carries no PTY at all, only + /// byte pipes to the Rex server — one for control and one per pane — + /// with `RexSession` speaking its protocol over them. The connection + /// stays this tab's exec surface, and closing the session closes it. + private func runRex( + _ target: (sessionID: String, blockID: String?), generation: Int + ) 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 rex = RexSession( + connection: connection, + sessionID: target.sessionID, + blockID: rexBlockID ?? target.blockID, + clientVersion: Bundle.main.object( + forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + ) + self.connection = connection + await runPanes(over: rex, generation: generation) { events in + try await connection.connect() + try Task.checkCancellation() + try await rex.open(events: events) + } + } + + /// One run of a paned transport, whichever backend's: hand it the tab's + /// side of `PaneEvents`, let `open` bring it up, and go live. Nothing in + /// here is Rex's — a second paned backend makes its transport and calls + /// this. + private func runPanes( + over transport: any PanedTerminalTransport, generation: Int, + open: (PaneEvents) async throws -> Void + ) async { + let router = PaneOutputRouter() + panedTransport = transport + paneOutput = router + startPaneCommandPump(for: transport) + do { + try await open(PaneEvents( + arrange: { [weak self] arrangement in + await MainActor.run { [weak self] in + self?.applyArrangement(arrangement, generation: generation) ?? [:] + } + }, + output: { pane, data in + router.append(data, to: pane) + }, + grid: { [weak self] pane, grid in + await MainActor.run { [weak self] in + guard let self, self.transportGeneration == generation, + let screen = self.screen(for: pane) + else { return } + // What was written for the old grid is parsed at + // the old grid. + screen.outputCoalescer?.flush() + screen.setGridPin(grid) + } + }, + close: { [weak self] reason in + Task { @MainActor [weak self] in + self?.handleClose(reason: reason, generation: generation) + } + })) + try Task.checkCancellation() + guard transportGeneration == generation, panedTransport === transport else { + await transport.close() + return + } + markLive() + #if DEBUG + debugAutoSwitchRexTerminal() + debugAutoPaneShortcuts() + #endif + } catch { + await transport.close() + guard transportGeneration == generation, panedTransport === transport + 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) + connection = nil + endPanedRun() + considerAutomaticResume() + } + } + + /// Runs this tab over a paned transport a test made, with no SSH + /// connection under it: everything from the arrangement down — screens, + /// focus, the pumps, the commands — is the real thing. + func runPanesForTesting( + over transport: any PanedTerminalTransport, + open: (PaneEvents) async throws -> Void + ) async { + transportGeneration &+= 1 + await runPanes(over: transport, generation: transportGeneration, open: open) + } + /// mosh: a transient SSH connection launches mosh-server, then the /// session itself rides UDP — resilient to roaming and sleep. The /// deck's probe (and file drops) stay SSH; this tab simply has no /// exec surface. private func runMosh( generation: Int, + screen: TerminalScreen, output: TerminalOutputCoalescer ) async { contactLost = false @@ -535,7 +714,7 @@ final class TerminalSessionController { ) try Task.checkCancellation() guard transportGeneration == generation else { return } - let openedSize = TerminalSize(cols: lastCols, rows: lastRows) + let openedSize = TerminalGrid(cols: screen.cols, rows: screen.rows) let session = try MoshSession( target: target, cols: openedSize.cols, @@ -549,11 +728,7 @@ final class TerminalSessionController { }, onClose: { [weak self] reason in Task { @MainActor [weak self] in - self?.handleClose( - reason: reason, - generation: generation, - output: output - ) + self?.handleClose(reason: reason, generation: generation) } }, onContact: { [weak self] lost in @@ -570,7 +745,7 @@ final class TerminalSessionController { await session.close() return } - startTransportPumps(for: session, openedAt: openedSize) + startTransportPumps(for: session, screen: screen, openedAt: openedSize) markLive() startDirectShellMonitoring() } catch { @@ -592,25 +767,16 @@ final class TerminalSessionController { status = .ended(message) moshSession = nil transport = nil - outputCoalescer = nil + screen.outputCoalescer = nil considerAutomaticResume() } } - /// 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)? - - private func feed(_ bytes: [UInt8]) { + private func feed(_ bytes: [UInt8], to screen: TerminalScreen) { statsBytesIn += bytes.count - scanForSwallowedHandoff(bytes) - guard let terminalView else { - pendingOutput.append(contentsOf: bytes) - return - } - terminalView.feed(byteArray: bytes[...]) - onOutputFlushed?() + // Only a PTY has a handoff line to lose. + if screen.paneID == nil { scanForSwallowedHandoff(bytes) } + screen.feed(bytes) } /// Modern oh-my-zsh drains all buffered stdin before blocking on its @@ -634,9 +800,7 @@ final class TerminalSessionController { // keystrokes; before the pump exists (output can arrive while // runSSH is still between openShell and startTransportPumps), // write straight to the transport — the user can't type yet. - if let inputContinuation { - inputContinuation.yield(payload) - } else if let transport { + if screens.first?.send(payload) != true, let transport { Task { try? await transport.write(payload) } } } @@ -646,7 +810,11 @@ final class TerminalSessionController { /// shells. SSH shells use the foreground process probe as authority, but /// retaining Claude/Codex's explicit title here prevents a very fast turn /// from erasing the identifying idle title before the next poll. - func terminalTitleChanged(_ title: String) { + func terminalTitleChanged(_ title: String, from screen: TerminalScreen? = nil) { + let screen = screen ?? activeScreen + screen?.title = title + // The tab's title is the pane's the keyboard is on. + guard screen === activeScreen else { return } remoteTitle = title guard route.sessionName == nil else { return } guard title != lastTerminalTitleProcessedForAgentHint else { return } @@ -663,18 +831,15 @@ final class TerminalSessionController { } } - private func handleClose( - reason: String?, - generation: Int, - output: TerminalOutputCoalescer - ) { + private func handleClose(reason: String?, generation: Int) { // Network callbacks enqueue bytes synchronously before their close // callback. Flush that final tail before ending the run, then ignore a - // late close from any superseded transport generation. - output.flush() + // late close from any superseded transport generation — or a second + // one from a run that has already been ended. guard transportGeneration == generation, - outputCoalescer === output + transport != nil || panedTransport != nil else { return } + for screen in screens { screen.outputCoalescer?.flush() } stopTransportPumps() stopDirectShellMonitoring() endStatsRun(reason: reason) @@ -685,11 +850,16 @@ final class TerminalSessionController { status = .ended(reason) contactLost = false let endedTransport = transport + let endedPanes = panedTransport transport = nil connection = nil moshSession = nil - outputCoalescer = nil - Task { await endedTransport?.close() } + endPanedRun() + for screen in screens { screen.outputCoalescer = nil } + Task { + await endedTransport?.close() + await endedPanes?.close() + } considerAutomaticResume() } @@ -807,12 +977,7 @@ final class TerminalSessionController { } private func terminalScreenSnapshot() -> (lines: [String], isAlternate: Bool) { - guard let terminalView else { return ([], false) } - // Copied reads: the terminal lives behind SwiftTerm's lock, and its - // parse runs on the feed thread. - let rows = max(0, terminalView.terminalDimensions.rows) - let lines = terminalView.visibleRowsText(0.. [PaneID: TerminalGrid] { + guard transportGeneration == generation, + let panedTransport, let paneOutput + else { return [:] } + var arranged: [TerminalScreen] = [] + for pane in arrangement.layout.panes { + let screen = screen(for: pane) ?? TerminalScreen(paneID: pane) + if screen.outputCoalescer == nil { + screen.outputCoalescer = makeOutputCoalescer(for: screen, generation: generation) } + paneOutput.set(screen.outputCoalescer, for: pane) + if !screen.hasPumps { + // From the arrangement on, not from the attach: a pane's + // size has to reach the transport while its terminal is + // still being opened. + screen.startPumps( + write: { try await panedTransport.write($0, to: pane) }, + resize: { + try await panedTransport.resize(pane: pane, cols: $0.cols, rows: $0.rows) + }, + openedAt: screen.openingSize) + } + arranged.append(screen) + } + let retired = screens.filter { screen in !arranged.contains { $0 === screen } } + screens = arranged + paneLayout = arrangement.layout + let focused = arrangement.focus.flatMap { screen(for: $0) } + if let focused { + activate(focused) + } else if activeScreen.map({ active in !arranged.contains { $0 === active } }) ?? true { + activate(arranged.first) + } + // A zoom needs its pane, and others for it to cover. + if let zoomed = zoomedPaneID, + arranged.count < 2 || !arranged.contains(where: { $0.paneID == zoomed }) { + zoomedPaneID = nil + } + for screen in retired { + screen.stopPumps() + screen.outputCoalescer = nil + if let pane = screen.paneID { paneOutput.set(nil, for: pane) } + if let view = screen.terminalView { Self.closeTerminalUI(view) } + } + // The surface lays the panes out NOW, so the grids below are the + // ones the panes really have. + onPaneLayoutChanged?() + return Dictionary(uniqueKeysWithValues: arranged.compactMap { screen in + screen.paneID.map { ($0, screen.openingSize) } + }) + } + + /// Moves the tab's focus to another of its screens. Everything that + /// reads `terminalView` follows; the keyboard itself is the surface's + /// to move (it knows whether this tab is the one on screen). + private func activate(_ screen: TerminalScreen?) { + guard screen !== activeScreen else { return } + // A selection in progress belongs to the pane being left — and so + // does a zoom: the pane the keyboard goes to has to be on screen. + setSelectTextModeUIActive(false) + if zoomedPaneID != nil, zoomedPaneID != screen?.paneID { zoomedPaneID = nil } + activeScreen = screen + terminalView = screen?.terminalView + activePaneID = screen?.paneID + remoteTitle = screen?.title ?? "" + guard let pane = screen?.paneID else { return } + if route.rexTarget != nil { rexBlockID = pane.rawValue } + paneCommands?.yield(.focus(pane)) + } + + /// The person put the keyboard on one of the tab's panes. + func focusPane(_ pane: PaneID) { + guard let screen = screen(for: pane) else { return } + let wasZoomed = zoomedPaneID + activate(screen) + if zoomedPaneID != wasZoomed { onPaneLayoutChanged?() } + } + + /// One row of a paned tab's shortcut panel, on the pane the keyboard is + /// on. + func performPaneShortcut(_ shortcut: PaneShortcut) { + guard status == .live, let pane = activePaneID else { return } + guard let command = shortcut.command(on: pane) else { + togglePaneZoom() + return } + paneCommands?.yield(command) } - private func stopResizePump() { - resizeContinuation?.finish() - resizeContinuation = nil - resizeTask?.cancel() - resizeTask = nil + /// Draws the pane the keyboard is on alone, or all of them again. A + /// tab with one pane has nothing to zoom; leaving a zoom always works, + /// whatever state the link is in. + func togglePaneZoom() { + if zoomedPaneID != nil { + zoomedPaneID = nil + } else { + guard let pane = activePaneID, screens.count > 1 else { return } + zoomedPaneID = pane + } + onPaneLayoutChanged?() } - private func startTransportPumps( - for transport: any TerminalTransport, - openedAt size: TerminalSize - ) { - startInputPump(for: transport) - 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 { - resizeContinuation?.yield(TerminalSize(cols: lastCols, rows: lastRows)) + /// A divider was dragged. The tab's own layout moves at once — the drag + /// has to follow the finger — and the transport is asked to make it so; + /// what it answers arrives as an arrangement like any other. + func setPaneRatio(_ ratio: Double, ofSplit splitID: String) { + guard status == .live, let layout = paneLayout, + layout.split(withID: splitID) != nil + else { return } + let moved = layout.settingRatio(ratio, ofSplit: splitID) + guard moved != layout else { return } + paneLayout = moved + onPaneLayoutChanged?() + paneCommands?.yield(.setRatio(ratio, splitID: splitID)) + } + + /// Commands go to the transport in the order they were made — a drag + /// makes dozens, and the last one has to be the one that stands. + private func startPaneCommandPump(for transport: any PanedTerminalTransport) { + stopPaneCommandPump() + let (commands, continuation) = AsyncStream.makeStream(of: PaneCommand.self) + paneCommands = continuation + paneCommandTask = Task { [weak self] in + for await command in commands { + do { + try await transport.perform(command) + } catch { + self?.paneCommandFailed(command, error) + } + } } } - private func stopTransportPumps() { - stopInputPump() - stopResizePump() + private func stopPaneCommandPump() { + paneCommands?.finish() + paneCommands = nil + paneCommandTask?.cancel() + paneCommandTask = nil + } + + /// A split or a close the backend refused is said on the pane; a focus + /// or a ratio it would not take needs no words — the next arrangement + /// shows what stands. + private func paneCommandFailed(_ command: PaneCommand, _ error: Error) { + let reason = (error as? RexSession.Failure)?.message ?? error.localizedDescription + switch command { + case .split: + showHistoryNotice(String(localized: "Couldn't split the pane. \(reason)")) + case .close: + showHistoryNotice(String(localized: "Couldn't close the pane. \(reason)")) + case .newWindow: + // "Tab" is the one paned backend's word for it (Rex). + showHistoryNotice(String(localized: "Couldn't open a new tab. \(reason)")) + case .setRatio, .focus: + break + } + } + + /// What a paned run leaves behind when it ends, however it ends. The + /// screens stay: a reconnect draws the same panes again, each over what + /// it last showed. + private func endPanedRun() { + panedTransport = nil + paneOutput?.removeAll() + paneOutput = nil + stopPaneCommandPump() + stopTransportPumps() } // MARK: Terminal view events - func sendInput(_ data: Data) { + /// 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, from screen: TerminalScreen? = nil) { + guard route.rexTarget == nil else { return } + sendInput(data, from: screen) + } + + /// `screen` is the emulator the input came out of; nil is the one the + /// keyboard is on, which is what every caller that is not an emulator + /// means. + func sendInput(_ data: Data, from screen: TerminalScreen? = nil) { guard status == .live else { return } // While the jump search pages the remote transcript, a keystroke // would interleave with the automated PgUp stream — the FINDING veil @@ -918,7 +1237,7 @@ final class TerminalSessionController { if !tmuxCopyModeUIActive { return } } statsBytesOut += data.count - inputContinuation?.yield(data) + (screen ?? activeScreen)?.send(data) // Both the app-owned DONE action and a hardware/software Escape key // travel through this same delegate path. Restore normal tmux mouse // reporting only after the cancel byte has joined the ordered pump. @@ -934,6 +1253,7 @@ final class TerminalSessionController { switch item.payload { case .tmux(let shortcut): performTmuxShortcut(shortcut) case .herdr(let shortcut): performHerdrShortcut(shortcut) + case .pane(let shortcut): performPaneShortcut(shortcut) } } @@ -1008,10 +1328,16 @@ final class TerminalSessionController { else { return } selectTextClampGeneration &+= 1 let generation = selectTextClampGeneration - let command = switch backend { + // nil where there is no pane-rect query to make: each pane of a Rex + // tab is its own emulator, so a selection cannot cross into a + // sibling and has nothing 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: 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. @@ -1038,6 +1364,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 +1396,8 @@ final class TerminalSessionController { await executeControlCommand(HerdrProbe.focusPaneDirectionCommand( sessionName: sessionName, direction: direction )) + case .rex: + return } } } @@ -1149,6 +1478,7 @@ final class TerminalSessionController { switch route.sessionBackend { case .tmux: await loadTmuxWindowList() case .herdr: await loadHerdrWorkspaceList() + case .rex: await loadRexTerminalList() case nil: nil } } @@ -1157,10 +1487,96 @@ 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]) + } + } + + private static var debugPaneActionsFired = false + + /// `MULTIPLEX_AUTO_PANE_ACTIONS=splitRight,splitDown,ratio:0.3,focus:1,closePane` + /// — the headless stand-in for the pane rows of the REX panel, a + /// divider drag and a touch on a pane (simctl has neither tap nor + /// drag). Each step goes through the entry point its control uses, four + /// seconds apart, starting six seconds after the first Rex tab goes + /// live, once per process. `ratio:` moves the first split of the + /// layout; `focus:` puts the keyboard on the nth pane in reading order. + private func debugAutoPaneShortcuts() { + guard !Self.debugPaneActionsFired, + let raw = ProcessInfo.processInfo.environment["MULTIPLEX_AUTO_PANE_ACTIONS"], + !raw.isEmpty + else { return } + Self.debugPaneActionsFired = true + let steps = raw.split(separator: ",").map(String.init) + Task { [weak self] in + try? await Task.sleep(for: .seconds(6)) + for step in steps { + guard let self, self.status == .live else { return } + if let shortcut = PaneShortcut(rawValue: step) { + self.performPaneShortcut(shortcut) + } else if step.hasPrefix("ratio:"), let ratio = Double(step.dropFirst(6)), + case .split(let split)? = self.paneLayout { + self.setPaneRatio(ratio, ofSplit: split.id) + } else if step.hasPrefix("focus:"), let position = Int(step.dropFirst(6)), + let panes = self.paneLayout?.panes, + panes.indices.contains(position - 1) { + self.focusPane(panes[position - 1]) + self.focusTerminal() + } + try? await Task.sleep(for: .seconds(4)) + } + } + } + #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 rexSession else { return nil } + return await rexSession.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.showTerminal`): a + /// terminal among the panes on show takes the keyboard, one in another + /// window brings that window's panes in. Where the tab lands comes back + /// as an arrangement's focus (`activate`), and 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 rexSession else { return } + Task { await rexSession.showTerminal(choice.tmuxID) } + } + + /// The directory the pane the keyboard is on is working in. + private func rexWorkingDirectory() async -> String? { + guard let rexSession, let pane = activePaneID else { return nil } + return await rexSession.workingDirectory(of: pane) + } + /// 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. @@ -1301,11 +1717,16 @@ final class TerminalSessionController { /// answers them); select-text has no remote listener, so its pans are /// suppressed outright — unless copy mode is active too and wins. private func applyTouchInteractionModes() { - guard let terminalView else { return } - terminalView.allowMouseReporting = + for screen in screens { + if let view = screen.terminalView { applyTouchInteractionModes(to: view) } + } + } + + private func applyTouchInteractionModes(to view: TerminalView) { + view.allowMouseReporting = !(tmuxCopyModeUIActive || selectTextModeUIActive) - terminalView.forceRemoteCursorScroll = tmuxCopyModeUIActive - terminalView.suppressRemotePanScroll = + view.forceRemoteCursorScroll = tmuxCopyModeUIActive + view.suppressRemotePanScroll = selectTextModeUIActive && !tmuxCopyModeUIActive } @@ -1708,12 +2129,11 @@ final class TerminalSessionController { } #endif - func terminalResized(cols: Int, rows: Int) { - guard cols != lastCols || rows != lastRows else { return } - lastCols = cols - lastRows = rows - guard status == .live else { return } - resizeContinuation?.yield(TerminalSize(cols: cols, rows: rows)) + func terminalResized(cols: Int, rows: Int, of screen: TerminalScreen? = nil) { + guard let screen = screen ?? activeScreen, + screen.resized(cols: cols, rows: rows), + status == .live + else { return } // 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). @@ -1739,7 +2159,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 = @@ -1911,6 +2331,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 rexWorkingDirectory() + 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 +2668,10 @@ final class TerminalSessionController { return HerdrProbe.parsePaneWorkingDirectory( output, atScreenCell: cell, screenSize: screenSize ) + case .rex: + // A press lands in one pane's own emulator and moves the + // keyboard there first, so the pressed cell is always its. + return await rexWorkingDirectory() case nil: return nil } @@ -2259,11 +2693,11 @@ final class TerminalSessionController { dropTask = nil dropClearTask?.cancel() dropState = nil - outputCoalescer?.flush() + for screen in screens { screen.outputCoalescer?.flush() } transportGeneration &+= 1 runTask?.cancel() runTask = nil - outputCoalescer = nil + for screen in screens { screen.outputCoalescer = nil } stopTransportPumps() stopDirectShellMonitoring() endStatsRun(reason: nil) @@ -2274,15 +2708,20 @@ final class TerminalSessionController { keyPassphraseChallenge = nil contactLost = false let transport = self.transport + let panes = panedTransport self.transport = nil self.connection = nil self.moshSession = nil - Task { await transport?.close() } + endPanedRun() + Task { + await transport?.close() + await panes?.close() + } // Closing is final — this path never runs on a tab move — so release - // the view's frame driver and renderer: SwiftTerm 2 leaves both to + // each view's frame driver and renderer: SwiftTerm 2 leaves both to // an explicit owner call. - if let terminalView { - Self.closeTerminalUI(terminalView) + for screen in screens { + if let view = screen.terminalView { Self.closeTerminalUI(view) } } } @@ -2506,7 +2945,7 @@ final class TerminalSessionController { /// one compact byte array to SwiftTerm per short display interval. A terminal /// still parses every byte in order; only cross-thread hops and array copies /// are coalesced. -private final class TerminalOutputCoalescer: @unchecked Sendable { +final class TerminalOutputCoalescer: @unchecked Sendable { private struct State { var chunks: [Data] = [] var byteCount = 0 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/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..4a3e8bcb 100644 --- a/Multiplex/Views/Deck/FleetWall.swift +++ b/Multiplex/Views/Deck/FleetWall.swift @@ -678,10 +678,14 @@ 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) - )) + self?.open( + TerminalRoute.Mode.attach(host: host, session: session), + of: session, on: host) + }, + openSessionPane: { [weak self] session, window, pane in + 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 @@ -744,16 +748,21 @@ 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). + + 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 +902,33 @@ final class FleetWallViewController: UIViewController { ) { return } - open(TerminalRoute(hostID: host.id, mode: .attach(host: host, session: session))) + 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 + } + 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) { @@ -957,18 +992,7 @@ final class FleetWallViewController: UIViewController { private func presentCreateSessionFailure( 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).") - } - } + let message = model.sessionCreateFailureMessage(hostName: host.name) let alert = UIAlertController( title: String(localized: "Couldn't Create Session"), message: message, @@ -1090,7 +1114,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 +1587,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 +1966,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 +2020,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 +3019,10 @@ struct FleetSessionTileConfiguration { let copyHandoffCommand: () -> Void let delete: () -> Void let droppedSession: (String) -> Void + /// Opens a tab on ONE terminal of the session (its window, the + /// keyboard on that terminal) — 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 +3148,24 @@ final class FleetSessionTileView: FleetPressView, configuration.attachNewWindow() }, ] + // A press opens the window the session is fronting. Its other + // terminals — in that window or another — 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 +3175,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 +4103,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 +4119,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/ShortcutPanel.swift b/Multiplex/Views/Terminal/ShortcutPanel.swift index a7ef7a58..50c9e75b 100644 --- a/Multiplex/Views/Terminal/ShortcutPanel.swift +++ b/Multiplex/Views/Terminal/ShortcutPanel.swift @@ -662,11 +662,15 @@ private final class ShortcutItemButton: ShortcutPressControl { commandLabel.setText( armed ? String(localized: "press again to close") : item.command ) + let binding = armed ? "AGAIN" : item.bindingLabel bindingLabel.configure( - armed ? "AGAIN" : item.bindingLabel, + binding, font: UIKitChassis.monoFont(9, weight: .semibold), color: UIKitChassis.signal2 ) + // A row with no key behind it (a native-pane tab's rows are not + // bindings) shows no empty keycap. + bindingBorder.isHidden = binding.isEmpty layer.borderWidth = armed ? 1 : 0 refreshBorder() accessibilityLabel = Self.accessibilityLabel(for: item, isArmed: armed) @@ -695,7 +699,9 @@ private final class ShortcutItemButton: ShortcutPressControl { if item.requiresDoubleActivation { return String(localized: "\(item.title), \(item.command), press twice to confirm") } - return "\(item.title), \(item.command), \(item.bindingLabel)" + return [item.title, item.command, item.bindingLabel] + .filter { !$0.isEmpty } + .joined(separator: ", ") } private func refreshBorder() { diff --git a/Multiplex/Views/Terminal/SwiftTermView.swift b/Multiplex/Views/Terminal/SwiftTermView.swift index 10c58cf6..bf274b3e 100644 --- a/Multiplex/Views/Terminal/SwiftTermView.swift +++ b/Multiplex/Views/Terminal/SwiftTermView.swift @@ -25,12 +25,15 @@ 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 } private static let focusTapName = "multiplex.focus-tap" + private static let focusTouchName = "multiplex.focus-touch" // Keep a compact gutter around the terminal grid, but let tmux's status // line meet the helper/key rail directly—any bottom inset reads as an // accidental black seam between the two surfaces. @@ -42,8 +45,17 @@ final class TerminalSurfaceView: UIView { ) let controller: TerminalSessionController + /// The surface's own: keyboard avoidance, the grid's outer edges, and — + /// on a tab with one emulator — that emulator's delegate. On a paned + /// tab every pane has a coordinator of its own (`PaneCellView`) and this + /// one only follows the pane the keyboard is on. private let coordinator: Coordinator private var configuration: Configuration + /// A paned tab's emulators; nil on a tab that draws one. + private(set) var paneSplitView: PaneSplitView? + #if !os(visionOS) + private weak var keyBar: TerminalKeyBar? + #endif init( controller: TerminalSessionController, @@ -51,7 +63,7 @@ final class TerminalSurfaceView: UIView { ) { self.controller = controller self.configuration = configuration - coordinator = Coordinator(controller: controller) + coordinator = Coordinator(controller: controller, screen: controller.soleScreen) super.init(frame: .zero) // PROTOTYPE(GLASS): THIS wrapper carries the glass pane (theme // background at `screenAlpha`) — it spans the whole silhouette, so @@ -68,9 +80,9 @@ final class TerminalSurfaceView: UIView { registerForTraitChanges( [GlassAppearanceTrait.self] ) { (surface: TerminalSurfaceView, _: UITraitCollection) in - guard let view = surface.coordinator.terminalView, - view.isDescendant(of: surface) else { return } - surface.apply(surface.configuration.theme, to: view) + for emulator in surface.emulators { + surface.apply(surface.configuration.theme, to: emulator.view, emulator.coordinator) + } } } @@ -79,9 +91,28 @@ final class TerminalSurfaceView: UIView { fatalError("init(coder:) has not been implemented") } - private func installTerminal() { + /// Every emulator this surface still holds, with the coordinator that + /// is its delegate. A moved tab's views may already belong to another + /// window while this (about to be torn down) surface gets one last + /// update; those are left out. + private var emulators: [(view: TerminalView, coordinator: Coordinator)] { + let all: [(view: TerminalView, coordinator: Coordinator)] + if let paneSplitView { + all = paneSplitView.cells.map { ($0.terminalView, $0.coordinator) } + } else { + all = coordinator.terminalView.map { [($0, coordinator)] } ?? [] + } + return all.filter { $0.view.isDescendant(of: self) } + } + + /// The emulator view for one of the tab's screens, ready to be placed: + /// made — or adopted from the window the tab just left — themed, sized, + /// and wired to `coordinator`. + private func prepareTerminalView( + for screen: TerminalScreen, coordinator: Coordinator + ) -> TerminalView { let view: TerminalView - if let existing = controller.terminalView { + if let existing = screen.terminalView { // This tab moved here from another window (merge/split): adopt // the live view so buffer, scrollback, and connection survive. // removeFromSuperview also drops constraints tied to the old @@ -118,8 +149,11 @@ final class TerminalSurfaceView: UIView { } TerminalFocusArbiter.installScribbleGate(on: view) view.renderUpdatesEnabled = configuration.isActive - apply(configuration.theme, to: view) - if view.font.pointSize != configuration.fontSize { + apply(configuration.theme, to: view, coordinator) + 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 screen.gridPin == nil, view.font.pointSize != configuration.fontSize { view.font = .monospacedSystemFont( ofSize: configuration.fontSize, weight: .regular @@ -139,10 +173,11 @@ final class TerminalSurfaceView: UIView { // Tapping the terminal claims app-wide keyboard focus (and re-summons // a dismissed keyboard) — without cancelling SwiftTerm's own - // selection/scroll gestures. An adopted view still carries the tap - // wired to its previous window's coordinator — replace, don't stack. + // selection/scroll gestures. An adopted view still carries the + // recognizers wired to its previous window's coordinator — replace, + // don't stack. view.gestureRecognizers? - .filter { $0.name == Self.focusTapName } + .filter { $0.name == Self.focusTapName || $0.name == Self.focusTouchName } .forEach(view.removeGestureRecognizer) let tap = UITapGestureRecognizer( target: coordinator, @@ -152,6 +187,108 @@ final class TerminalSurfaceView: UIView { tap.cancelsTouchesInView = false tap.delegate = coordinator view.addGestureRecognizer(tap) + if screen.paneID != nil { + // Among several panes the keyboard has to follow the finger + // before a gesture resolves: a long press raises the selection + // menu of whichever pane is the tab's active one. + let touch = TouchDownGestureRecognizer( + target: coordinator, + action: #selector(Coordinator.paneTouched(_:)) + ) + touch.name = Self.focusTouchName + touch.cancelsTouchesInView = false + touch.delaysTouchesBegan = false + touch.delaysTouchesEnded = false + touch.delegate = coordinator + view.addGestureRecognizer(touch) + } + return view + } + + #if os(visionOS) + /// 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 adopted view + /// rather than stacking another. + private func installLinkHoverOverlay( + on view: TerminalView, screen: TerminalScreen, coordinator: Coordinator + ) { + let overlay = view.subviews.compactMap { $0 as? TerminalLinkHoverOverlay }.first + ?? { + let created = TerminalLinkHoverOverlay(terminalView: view) + view.addSubview(created) + return created + }() + overlay.activate = { [weak controller] target in + _ = controller?.activateLink(target) + } + coordinator.linkHoverOverlay = overlay + screen.onOutputFlushed = { [weak overlay] in + overlay?.scheduleRefresh() + } + overlay.scheduleRefresh() + } + #endif + + /// Experimental Metal renderer (visionOS scale + glass fixes live in + /// the fork): a Settings toggle, default off, with MULTIPLEX_METAL=1 + /// as the harness/scheme override. Applied at install so a changed + /// setting reaches new terminal windows and re-hosted (merge/split) + /// tabs; setUseMetal early-returns when the state already matches. + private func applyRendererSetting(to view: TerminalView) { + let wantsMetal = MetalRendererSetting.isEnabled + guard wantsMetal != view.isUsingMetalRenderer else { return } + let log = Logger( + subsystem: "app.multiplexterm.multiplex", + category: "render" + ) + do { + try view.setUseMetal(wantsMetal) + log.info("Metal renderer \(wantsMetal ? "enabled" : "disabled")") + } catch { + log.error("setUseMetal(\(wantsMetal)) failed: \(error)") + } + } + + /// One pane of a paned tab: its emulator, with a coordinator of its own. + private func makePaneCell(for screen: TerminalScreen) -> PaneCellView { + let paneCoordinator = Coordinator(controller: controller, screen: screen) + let view = prepareTerminalView(for: screen, coordinator: paneCoordinator) + let cell = PaneCellView( + screen: screen, coordinator: paneCoordinator, terminalView: view) + #if os(visionOS) + installLinkHoverOverlay(on: view, screen: screen, coordinator: paneCoordinator) + #endif + applyRendererSetting(to: view) + controller.bind(view, to: screen) + // Replace, never stack: a moved tab's hook still names the pane + // cell it left. + screen.onGridPinChanged = { [weak paneCoordinator] in + paneCoordinator?.applyGridPin(synchronously: true) + } + return cell + } + + private func installTerminal() { + // What sits in the grid's place: the one emulator, or the split of + // a paned tab's. Everything below — the gutter, the rail, keyboard + // avoidance — holds `content` and does not care which. + let content: UIView + let soleView: TerminalView? + if controller.drawsPanes { + let split = PaneSplitView(controller: controller) { [unowned self] screen in + makePaneCell(for: screen) + } + paneSplitView = split + content = split + soleView = nil + } else if let screen = controller.soleScreen { + let view = prepareTerminalView(for: screen, coordinator: coordinator) + content = view + soleView = view + } else { + return + } // On iPad, the app-owned rail is a normal sibling below the terminal. // Moving its bottom constraint above a genuinely docked keyboard @@ -159,47 +296,35 @@ final class TerminalSurfaceView: UIView { // never enter TextInputUI's custom-accessory path. On visionOS the // keyboard floats in its own panel and never overlaps the window. #if os(visionOS) - addSubview(view) - view.translatesAutoresizingMaskIntoConstraints = false + addSubview(content) + content.translatesAutoresizingMaskIntoConstraints = false + let terminalTrailing = content.trailingAnchor.constraint( + equalTo: trailingAnchor, + constant: -Self.terminalInsets.right + ) + let terminalBottom = content.bottomAnchor.constraint( + equalTo: bottomAnchor, + constant: -Self.terminalInsets.bottom + ) NSLayoutConstraint.activate([ - view.topAnchor.constraint( + content.topAnchor.constraint( equalTo: topAnchor, constant: Self.terminalInsets.top ), - view.leadingAnchor.constraint( + content.leadingAnchor.constraint( 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, ]) - // 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 - // adopted view rather than stacking another. - let overlay = view.subviews.compactMap { $0 as? TerminalLinkHoverOverlay }.first - ?? { - let created = TerminalLinkHoverOverlay(terminalView: view) - view.addSubview(created) - return created - }() - overlay.activate = { [weak controller] target in - _ = controller?.activateLink(target) - } - coordinator.linkHoverOverlay = overlay - controller.onOutputFlushed = { [weak overlay] in - overlay?.scheduleRefresh() + coordinator.installGridEdges(trailing: terminalTrailing, bottom: terminalBottom) + if let soleView, let screen = controller.soleScreen { + installLinkHoverOverlay(on: soleView, screen: screen, coordinator: coordinator) } - overlay.scheduleRefresh() #else let keyBar = TerminalKeyBar( - terminal: view, + terminal: soleView, controller: controller, performShortcut: { [weak controller] item in controller?.performPanelShortcut(item) @@ -213,17 +338,19 @@ 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) + self.keyBar = keyBar + addSubview(content) addSubview(keyBar) - view.translatesAutoresizingMaskIntoConstraints = false + content.translatesAutoresizingMaskIntoConstraints = false keyBar.translatesAutoresizingMaskIntoConstraints = false - let terminalTop = view.topAnchor.constraint( + let terminalTop = content.topAnchor.constraint( equalTo: topAnchor, constant: Self.terminalInsets.top ) let keyBarBottom = keyBar.bottomAnchor.constraint(equalTo: bottomAnchor) - let terminalBottom = view.bottomAnchor.constraint( + let terminalBottom = content.bottomAnchor.constraint( equalTo: keyBar.topAnchor, constant: -( Self.terminalInsets.bottom + configuration.bottomChromeHeight @@ -232,11 +359,11 @@ final class TerminalSurfaceView: UIView { // The container spans whatever side safe areas the shell handed it, // and the pane's screen paints across them. The grid does not: it // rides these constants back inside the readable region. - let terminalLeading = view.leadingAnchor.constraint( + let terminalLeading = content.leadingAnchor.constraint( equalTo: leadingAnchor, constant: Self.terminalInsets.left + configuration.contentSafeArea.left ) - let terminalTrailing = view.trailingAnchor.constraint( + let terminalTrailing = content.trailingAnchor.constraint( equalTo: trailingAnchor, constant: -(Self.terminalInsets.right + configuration.contentSafeArea.right) ) @@ -280,36 +407,88 @@ 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) #endif - // Experimental Metal renderer (visionOS scale + glass fixes live in - // the fork): a Settings toggle, default off, with MULTIPLEX_METAL=1 - // as the harness/scheme override. Applied at install so a changed - // setting reaches new terminal windows and re-hosted (merge/split) - // tabs; setUseMetal early-returns when the state already matches. - let wantsMetal = MetalRendererSetting.isEnabled - if wantsMetal != view.isUsingMetalRenderer { - let log = Logger( - subsystem: "app.multiplexterm.multiplex", - category: "render" - ) - do { - try view.setUseMetal(wantsMetal) - log.info("Metal renderer \(wantsMetal ? "enabled" : "disabled")") - } catch { - log.error("setUseMetal(\(wantsMetal)) failed: \(error)") + if let soleView, let screen = controller.soleScreen { + applyRendererSetting(to: soleView) + controller.bind(soleView, to: screen) + // Replace, never stack: a moved tab's hook still names the pane + // it left. + screen.onGridPinChanged = { [weak coordinator] in + coordinator?.applyGridPin(synchronously: true) } + if configuration.isActive { + DispatchQueue.main.async { + TerminalFocusArbiter.claim(soleView) + } + } + } else { + // Replace, never stack — as above. The controller calls this + // the moment its transport says how the panes are arranged, and + // reads each pane's grid as soon as it returns. + controller.observePaneLayout(as: self) { [weak self] in + self?.syncPanes(synchronously: true) + } + syncPanes(synchronously: false) } + } - controller.bind(view) - if configuration.isActive { - DispatchQueue.main.async { - TerminalFocusArbiter.claim(view) + /// Brings a paned tab's cells in line with its controller: the panes + /// there are, where they sit, and which has the keyboard — the rail and + /// keyboard avoidance follow that one. + /// + /// `synchronously` is for the controller's call: a new pane's terminal + /// is opened at the grid its emulator measures, so the layout has to + /// have happened when this returns. + private func syncPanes(synchronously: Bool) { + // A moved tab's surface in the window it left gets one last update; + // the emulators are the new window's by then. + guard let paneSplitView, controller.isPaneLayoutObserver(self) else { return } + // Read before the cells change: the pane being left may be one + // that is about to go. + let previous = coordinator.terminalView + let hadKeyboard = previous != nil && TerminalFocusArbiter.current === previous + var active: TerminalView? + paneSplitView.apply( + layout: controller.paneLayout, screens: controller.screens, + activePane: controller.activePaneID, zoomedPane: controller.zoomedPaneID, + theme: configuration.theme + ) { [self] in + active = paneSplitView.cell(for: controller.activePaneID)?.terminalView + // Before the claim: keyboard avoidance acts only on the + // terminal the coordinator names, so the hide a resigning pane + // reports is not acted on and the show its successor's is. + coordinator.terminalView = active + // The keyboard follows the tab's focus when the tab had it — a + // split just made, a pane closed under the cursor, the tab + // moved to another window's panes — and it moves HERE, while + // the pane it is leaving is still in the window. Left until a + // pane that was going had gone, the keyboard went with it and + // came back a turn later, and the layout below measured the + // panes without it: a new pane's terminal was opened 22 rows + // too tall and its screen drawn into an emulator that had + // shrunk back by then (measured: the top of the screen + // scrolled away). A tab that did not have the keyboard does + // not take it because its layout changed. + if hadKeyboard, configuration.isActive, let active, active !== previous { + TerminalFocusArbiter.claim(active) } } + #if !os(visionOS) + keyBar?.retarget(to: active) + #endif + if synchronously { layoutIfNeeded() } + // The first pane an attach brings takes the keyboard a turn later, + // as a single emulator does when its surface is installed. + guard previous == nil, configuration.isActive, let active else { return } + DispatchQueue.main.async { [weak controller] in + guard controller?.terminalView === active else { return } + TerminalFocusArbiter.claim(active) + } } func update(configuration: Configuration) { @@ -317,10 +496,37 @@ final class TerminalSurfaceView: UIView { backgroundColor = GlassPrototype.terminalGround( themeBackground: UIColor(configuration.theme.background) ) + let emulators = emulators // A moved tab's view may already belong to another window while this // (about to be torn down) surface gets one last update. - guard let view = coordinator.terminalView, - view.isDescendant(of: self) else { return } + guard paneSplitView != nil || !emulators.isEmpty else { return } + // Every emulator is updated; `contains` on a lazy map would stop at + // the first whose font changed. + let fontChanged = emulators + .map { update($0.view, $0.coordinator, to: configuration) } + .contains(true) + #if !os(visionOS) + coordinator.updateBottomChromeHeight( + Self.terminalInsets.bottom + configuration.bottomChromeHeight + ) + coordinator.updateContentSafeArea(configuration.contentSafeArea) + coordinator.keyBar?.contentSafeArea = configuration.keyRailSafeArea + coordinator.setRailOwnsBottomSafeArea(configuration.railOwnsBottomSafeArea) + coordinator.setKeyRailHidden(configuration.keyRailHidden) + coordinator.keyBar?.bareChrome = configuration.bareChrome + coordinator.keyBar?.keyCommandPlan = configuration.keyCommandPlan + coordinator.keyBar?.shortcutHasChoices = configuration.shortcutHasChoices + if fontChanged { + coordinator.terminalMetricsDidChange() + } + #endif + syncPanes(synchronously: false) + } + + /// One emulator's share of an update. Returns whether its font changed. + private func update( + _ view: TerminalView, _ coordinator: Coordinator, to configuration: Configuration + ) -> Bool { if view.renderUpdatesEnabled != configuration.isActive { view.renderUpdatesEnabled = configuration.isActive } @@ -337,34 +543,30 @@ 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 isPinned = coordinator.screen?.gridPin != nil + let fontChanged = coordinator.preferredFontSize != configuration.fontSize + || (!isPinned && view.font.pointSize != configuration.fontSize) + coordinator.preferredFontSize = configuration.fontSize if fontChanged { - view.font = .monospacedSystemFont( - ofSize: configuration.fontSize, - weight: .regular - ) + if !isPinned { + view.font = .monospacedSystemFont( + ofSize: configuration.fontSize, + weight: .regular + ) + } else { + coordinator.applyGridPin(synchronously: false) + } } if coordinator.appliedTheme != configuration.theme { - apply(configuration.theme, to: view) + apply(configuration.theme, to: view, coordinator) } else if coordinator.appliedCaretVisible != (controller.status == .live) { // The pane re-runs this update on every observed status change, // which is where a connecting tab earns its caret back. - applyCaretColor(theme: configuration.theme, to: view) - } - #if !os(visionOS) - coordinator.updateBottomChromeHeight( - Self.terminalInsets.bottom + configuration.bottomChromeHeight - ) - coordinator.updateContentSafeArea(configuration.contentSafeArea) - coordinator.keyBar?.contentSafeArea = configuration.keyRailSafeArea - coordinator.setRailOwnsBottomSafeArea(configuration.railOwnsBottomSafeArea) - coordinator.setKeyRailHidden(configuration.keyRailHidden) - coordinator.keyBar?.bareChrome = configuration.bareChrome - coordinator.keyBar?.keyCommandPlan = configuration.keyCommandPlan - if fontChanged { - coordinator.terminalMetricsDidChange() + applyCaretColor(theme: configuration.theme, to: view, coordinator) } - #endif + return fontChanged } override func layoutSubviews() { @@ -372,11 +574,16 @@ final class TerminalSurfaceView: UIView { #if !os(visionOS) coordinator.containerDidLayout() #endif + // The pane changed size under a grid that is not its own: fit again. + // (A paned tab's cells each do this for themselves.) + if paneSplitView == nil { coordinator.applyGridPin(synchronously: false) } } /// Colors change live — SwiftTerm's setters queue a full redraw, so an /// open session re-skins in place when the user switches themes. - private func apply(_ theme: TerminalTheme, to view: TerminalView) { + private func apply( + _ theme: TerminalTheme, to view: TerminalView, _ coordinator: Coordinator + ) { // PROTOTYPE(GLASS): keep the fork's own non-opaque invariant — cells // stay transparent (`nativeBackgroundColor = .clear` is exactly what // its setupOptions chose) and the pane ground lives on the view's @@ -385,7 +592,7 @@ final class TerminalSurfaceView: UIView { themeBackground: UIColor(theme.background) ) view.nativeForegroundColor = UIColor(theme.foreground) - applyCaretColor(theme: theme, to: view) + applyCaretColor(theme: theme, to: view, coordinator) view.selectedTextBackgroundColor = UIColor(theme.cursor).withAlphaComponent(0.3) // SwiftTerm 1.15 adds an explicit selected-text foreground whose // upstream default is black. Preserve the theme's former text color, @@ -418,7 +625,9 @@ final class TerminalSurfaceView: UIView { /// still empty. Over the CONNECTING panel that lone red glyph reads as a /// rendering fault, so the caret stays invisible until the tab's transport /// is actually live. - private func applyCaretColor(theme: TerminalTheme, to view: TerminalView) { + private func applyCaretColor( + theme: TerminalTheme, to view: TerminalView, _ coordinator: Coordinator + ) { let visible = controller.status == .live view.caretColor = visible ? UIColor(theme.cursor) : .clear coordinator.appliedCaretVisible = visible @@ -427,8 +636,15 @@ final class TerminalSurfaceView: UIView { /// Forwards SwiftTerm delegate events to the session controller. /// SwiftTerm calls these on the main thread; `assumeIsolated` bridges /// into the controller's MainActor isolation. + /// + /// One per emulator: `screen` is the emulator's, and every event is + /// forwarded with it, so the controller knows which pane spoke. The + /// surface's own coordinator on a paned tab has no screen — it is + /// nobody's delegate there, and only carries keyboard avoidance for the + /// pane the keyboard is on (`terminalView`). final class Coordinator: NSObject, TerminalViewDelegate, UIGestureRecognizerDelegate { let controller: TerminalSessionController + let screen: TerminalScreen? weak var terminalView: TerminalView? #if os(visionOS) /// Gaze link regions — owned by the terminal view it floats over, @@ -440,8 +656,131 @@ final class TerminalSurfaceView: UIView { /// or clear. `nil` until the first application. var appliedCaretVisible: Bool? - init(controller: TerminalSessionController) { + init(controller: TerminalSessionController, screen: TerminalScreen?) { self.controller = controller + self.screen = screen + } + + // 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 (`TerminalScreen.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 = screen?.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) @@ -554,10 +893,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() } @@ -566,17 +905,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() } @@ -783,9 +1123,30 @@ final class TerminalSurfaceView: UIView { @objc func reclaimFocus(_ gesture: UITapGestureRecognizer) { guard let view = gesture.view as? TerminalView else { return } + if let pane = screen?.paneID { + MainActor.assumeIsolated { controller.focusPane(pane) } + } TerminalFocusArbiter.summon(view) } + /// A finger came down on one pane of several. The tab's focus goes + /// there at once; the keyboard goes with it only if the tab had it + /// — a scroll through a pane does not summon a dismissed keyboard, + /// the tap that `reclaimFocus` hears does. + @objc func paneTouched(_ gesture: TouchDownGestureRecognizer) { + guard gesture.state == .recognized, + let view = gesture.view as? TerminalView, + let pane = screen?.paneID + else { return } + MainActor.assumeIsolated { + guard controller.activePaneID != pane else { return } + let previous = controller.terminalView + let hadKeyboard = previous != nil && TerminalFocusArbiter.current === previous + controller.focusPane(pane) + if hadKeyboard { TerminalFocusArbiter.claim(view) } + } + } + func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer @@ -796,19 +1157,29 @@ final class TerminalSurfaceView: UIView { func send(source: TerminalView, data: ArraySlice) { let bytes = Data(data) MainActor.assumeIsolated { - controller.sendInput(bytes) + controller.sendInput(bytes, from: screen) + } + } + + /// 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, from: screen) } } func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) { MainActor.assumeIsolated { - controller.terminalResized(cols: newCols, rows: newRows) + controller.terminalResized(cols: newCols, rows: newRows, of: screen) } } func setTerminalTitle(source: TerminalView, title: String) { MainActor.assumeIsolated { - controller.terminalTitleChanged(title) + controller.terminalTitleChanged(title, from: screen) } } diff --git a/Multiplex/Views/Terminal/TerminalKeyBar.swift b/Multiplex/Views/Terminal/TerminalKeyBar.swift index 9fffd6d7..441f1208 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 @@ -1223,8 +1246,11 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface } } + /// `terminal` is nil for a paned tab that has not attached yet: its + /// emulators come with the layout, and `retarget` hands the rail the + /// one the keyboard is on. init( - terminal: TerminalView, + terminal: TerminalView?, controller: TerminalSessionController?, performShortcut: @escaping (ShortcutPanelItem) -> Void, finishTmuxCopyMode: @escaping () -> Void, @@ -1238,7 +1264,7 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface self.shortcutBackend = shortcutBackend self.orderStore = orderStore showsReturnKey = UIDevice.current.userInterfaceIdiom == .pad - ctrlLatched = terminal.controlModifier + ctrlLatched = terminal?.controlModifier ?? false super.init(frame: .zero) backgroundColor = UIKitChassis.bezel @@ -1249,12 +1275,7 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface dropCoordinator.installDropTarget(on: self) HardwareKeyboardMonitor.shared.startIfNeeded() - NotificationCenter.default.addObserver( - self, - selector: #selector(controlModifierDidReset), - name: .terminalViewControlModifierReset, - object: terminal - ) + observeControlModifierReset(of: terminal) observationGeneration &+= 1 observeAndRender(generation: observationGeneration) #if DEBUG @@ -1356,6 +1377,34 @@ final class TerminalKeyBar: UIView, UIInputViewAudioFeedback, KeyBarDropSurface hideCtrlCombos() } + private func observeControlModifierReset(of terminal: TerminalView?) { + guard let terminal else { return } + NotificationCenter.default.addObserver( + self, + selector: #selector(controlModifierDidReset), + name: .terminalViewControlModifierReset, + object: terminal + ) + } + + /// Points the rail at another emulator of the same tab: the pane the + /// keyboard moved to. A CTRL latch does not travel — it was armed for a + /// key about to be typed into the pane being left. + func retarget(to terminal: TerminalView?) { + guard terminal !== self.terminal else { return } + if let previous = self.terminal { + if ctrlLatched { previous.controlModifier = false } + NotificationCenter.default.removeObserver( + self, name: .terminalViewControlModifierReset, object: previous) + } + self.terminal = terminal + observeControlModifierReset(of: terminal) + let latched = terminal?.controlModifier ?? false + ctrlLatched = latched + ctrlKeyControl?.isLatched = latched + if !latched { hideCtrlCombos() } + } + private var currentObservedState: TerminalKeyBarObservedState { TerminalKeyBarObservedState( hardwareKeyboardConnected: HardwareKeyboardMonitor.shared.isConnected, @@ -1507,13 +1556,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" )) } @@ -1548,7 +1595,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 } } @@ -2145,11 +2194,17 @@ enum TmuxShortcutDebugHook { } -/// The rail beside the focused terminal — every headless hook's target. +/// The rail beside the focused terminal — every headless hook's target. A +/// single emulator is the rail's sibling; a pane of a paned tab sits two +/// levels further in (its cell, the split), so the search climbs. @MainActor private func focusedBar() -> TerminalKeyBar? { - guard let view = TerminalFocusArbiter.current else { return nil } - return view.superview?.subviews.compactMap { $0 as? TerminalKeyBar }.first + var ancestor = TerminalFocusArbiter.current?.superview + while let view = ancestor { + if let bar = view.subviews.compactMap({ $0 as? TerminalKeyBar }).first { return bar } + ancestor = view.superview + } + return nil } @MainActor diff --git a/Multiplex/Views/Terminal/TerminalPaneSplitView.swift b/Multiplex/Views/Terminal/TerminalPaneSplitView.swift new file mode 100644 index 00000000..31251504 --- /dev/null +++ b/Multiplex/Views/Terminal/TerminalPaneSplitView.swift @@ -0,0 +1,337 @@ +import SwiftTerm +import UIKit + +/// The panes of a tab whose backend hands them out separately, drawn the +/// way that backend arranged them (`PaneLayout`): one emulator per pane, a +/// hairline between the two sides of every split, and a frame around the +/// pane the keyboard is on. +/// +/// It sits exactly where a single-stream tab's one `TerminalView` sits in +/// `TerminalSurfaceView`, so the surface's keyboard avoidance, bottom +/// chrome and safe-area edges move it the same way and each pane's emulator +/// simply measures a new grid from its new frame. +/// +/// - **Dragging a line resizes** the split it divides. The tab's own layout +/// follows the finger at once (`TerminalSessionController.setPaneRatio`); +/// the backend is asked in order behind it. +/// - **A touch puts the keyboard on a pane** — at touch DOWN, not on the +/// tap's release, so a long press already has the pane's own selection +/// menu under it (`TerminalSurfaceView.Coordinator`). +/// - A tab with ONE pane draws no line and no frame: it is the single +/// emulator it always was. +/// +/// Colors come from the terminal theme, never the chassis: this is inside +/// the screen, and a light theme under dark chrome has to stay legible. +@MainActor +final class PaneSplitView: UIView { + /// The room between two panes: a hairline with clear ground either + /// side, so text never touches it. + static let gap: CGFloat = 9 + /// The frame around the focused pane lies ON the lines beside it: this + /// far outside the pane's own rectangle, which is the gap's centre. + private static let frameOutset: CGFloat = 5 + /// What several panes give up of the surface's top and bottom edges so + /// the frame around an outermost pane has somewhere to be drawn. + private static let framedInsets = UIEdgeInsets(top: 2, left: 0, bottom: 6, right: 0) + + private weak var controller: TerminalSessionController? + /// Makes one pane's cell around the emulator view the surface prepared + /// for it (themed, sized, and adopted from another window if the tab + /// just moved). + private let makeCell: (TerminalScreen) -> PaneCellView + + private(set) var cells: [PaneCellView] = [] + private var dividerViews: [PaneDividerView] = [] + private let focusFrame = UIView() + private var layout: PaneLayout? + private var activePane: PaneID? + private var zoomedPane: PaneID? + private var ink = UIColor.label + + init( + controller: TerminalSessionController, + makeCell: @escaping (TerminalScreen) -> PaneCellView + ) { + self.controller = controller + self.makeCell = makeCell + super.init(frame: .zero) + focusFrame.isUserInteractionEnabled = false + focusFrame.isAccessibilityElement = false + focusFrame.layer.borderWidth = 1 + focusFrame.isHidden = true + focusFrame.accessibilityIdentifier = "terminalPane.focusFrame" + addSubview(focusFrame) + accessibilityIdentifier = "terminalPane.split" + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("unused") } + + /// The cell showing `pane`, for the surface's per-emulator updates. + func cell(for pane: PaneID?) -> PaneCellView? { + guard let pane else { return nil } + return cells.first { $0.screen.paneID == pane } + } + + /// The pane under a point of this view — where a file was dropped. A + /// pane hidden behind a zoomed one is under nothing. + func pane(at point: CGPoint) -> PaneID? { + cells.first { !$0.isHidden && $0.frame.contains(point) }?.screen.paneID + } + + /// Brings the cells in line with the tab's screens and layout. Cells + /// are kept by screen — a pane that stays keeps its emulator view, its + /// scrollback and its selection — and only what changed is made or + /// dropped. + /// + /// `beforeDropping` runs once the new cells are in and before the ones + /// that are going leave: the one moment both the pane the keyboard is + /// on and the pane it is going to are in the window. + func apply( + layout: PaneLayout?, screens: [TerminalScreen], activePane: PaneID?, + zoomedPane: PaneID?, theme: TerminalTheme, + beforeDropping: () -> Void + ) { + var arranged: [PaneCellView] = [] + for screen in screens { + if let cell = cells.first(where: { $0.screen === screen }) { + arranged.append(cell) + } else { + let cell = makeCell(screen) + insertSubview(cell, belowSubview: focusFrame) + arranged.append(cell) + } + } + let leaving = cells.filter { cell in !arranged.contains { $0 === cell } } + cells = arranged + self.layout = layout + self.activePane = activePane + self.zoomedPane = zoomedPane + ink = UIColor(theme.foreground) + // Everything a layout pass reads is in place by now: a keyboard + // changing hands in there can ask for one. + beforeDropping() + for cell in leaving { cell.removeFromSuperview() } + setNeedsLayout() + } + + override func layoutSubviews() { + super.layoutSubviews() + // A surface not yet given a size has nothing to measure; laying an + // emulator out at zero would have it report a grid of nothing. + guard bounds.width >= 1, bounds.height >= 1, let layout else { + syncDividers([]) + focusFrame.isHidden = true + return + } + let isSplit = cells.count > 1 + let area = isSplit ? bounds.inset(by: Self.framedInsets) : bounds + let frames = layout.frames( + in: area, dividerThickness: Self.gap, + displayScale: traitCollection.displayScale) + // A zoomed pane takes the whole view. The others are hidden but + // still laid out where the split has them: their terminals keep the + // size they will be shown at again, so leaving the zoom redraws + // nothing and resizes only the pane that was zoomed. + let zoomed = isSplit ? cell(for: zoomedPane) : nil + for cell in cells { + guard let pane = cell.screen.paneID, let frame = frames.panes[pane] else { continue } + let placed = cell === zoomed ? bounds : frame + if cell.frame != placed { cell.frame = placed } + let hidden = zoomed != nil && cell !== zoomed + if cell.isHidden != hidden { cell.isHidden = hidden } + } + guard zoomed == nil else { + syncDividers([]) + focusFrame.isHidden = true + return + } + syncDividers(frames.dividers) + if isSplit, let active = cell(for: activePane) { + focusFrame.frame = active.frame.insetBy(dx: -Self.frameOutset, dy: -Self.frameOutset) + focusFrame.layer.borderColor = ink.withAlphaComponent(0.6).cgColor + focusFrame.isHidden = false + bringSubviewToFront(focusFrame) + } else { + focusFrame.isHidden = true + } + } + + /// A line's view is kept by the split it divides, so one being dragged + /// stays under the finger while the layout around it changes. + private func syncDividers(_ dividers: [PaneLayoutFrames.Divider]) { + var kept: [PaneDividerView] = [] + for divider in dividers { + let view = dividerViews.first { $0.splitID == divider.splitID } ?? { + let view = PaneDividerView() + view.moved = { [weak self] divider, position in + self?.moveDivider(divider, to: position) + } + view.nudged = { [weak self] divider, step in + self?.nudgeDivider(divider, by: step) + } + addSubview(view) + return view + }() + view.show(divider, ink: ink) + // Over the panes: a line's strip reaches onto the edge of both. + bringSubviewToFront(view) + kept.append(view) + } + for view in dividerViews where !kept.contains(where: { $0 === view }) { + view.removeFromSuperview() + } + dividerViews = kept + } + + /// A drag moved a line to `position` along its split's axis, in this + /// view's coordinates. + private func moveDivider(_ divider: PaneLayoutFrames.Divider, to position: CGFloat) { + let ratio = PaneLayout.ratio( + forDividerAt: position, in: divider.extent, axis: divider.axis, + dividerThickness: Self.gap) + controller?.setPaneRatio(ratio, ofSplit: divider.splitID) + } + + /// VoiceOver's adjust: a twentieth of the split either way. + private func nudgeDivider(_ divider: PaneLayoutFrames.Divider, by step: Double) { + guard let split = layout?.split(withID: divider.splitID) else { return } + controller?.setPaneRatio(split.ratio + step, ofSplit: divider.splitID) + } +} + +/// One pane: its emulator view, held at the pane's frame — or, while the +/// far side dictates the grid, at exactly the frame that grid measures +/// (`TerminalSurfaceView.Coordinator.applyGridPin`), top-leading in the +/// pane. +@MainActor +final class PaneCellView: UIView { + let screen: TerminalScreen + let coordinator: TerminalSurfaceView.Coordinator + let terminalView: TerminalView + + init( + screen: TerminalScreen, coordinator: TerminalSurfaceView.Coordinator, + terminalView: TerminalView + ) { + self.screen = screen + self.coordinator = coordinator + self.terminalView = terminalView + super.init(frame: .zero) + accessibilityIdentifier = "terminalPane.cell" + addSubview(terminalView) + terminalView.translatesAutoresizingMaskIntoConstraints = false + let trailing = terminalView.trailingAnchor.constraint(equalTo: trailingAnchor) + let bottom = terminalView.bottomAnchor.constraint(equalTo: bottomAnchor) + NSLayoutConstraint.activate([ + terminalView.topAnchor.constraint(equalTo: topAnchor), + terminalView.leadingAnchor.constraint(equalTo: leadingAnchor), + trailing, + bottom, + ]) + coordinator.installGridEdges(trailing: trailing, bottom: bottom) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("unused") } + + override func layoutSubviews() { + super.layoutSubviews() + // The pane changed size under a grid that is not its own: fit again. + coordinator.applyGridPin(synchronously: false) + } +} + +/// The line between a split's two sides, and the strip either side of it a +/// finger can take hold of. +@MainActor +final class PaneDividerView: UIView { + /// How far past the gap, each side, a drag may start. The strip lies + /// over the edge of both panes, where a terminal's own gestures would + /// otherwise take the touch. + private static let reach: CGFloat = 8 + + var moved: ((PaneLayoutFrames.Divider, CGFloat) -> Void)? + var nudged: ((PaneLayoutFrames.Divider, Double) -> Void)? + + private let line = UIView() + private var divider: PaneLayoutFrames.Divider? + var splitID: String? { divider?.splitID } + /// Where on the strip the finger came down, so the line keeps its place + /// under the finger instead of jumping to its centre. + private var grabOffset: CGFloat = 0 + private var grabPosition: CGFloat = 0 + private var isDragging = false + + init() { + super.init(frame: .zero) + line.isUserInteractionEnabled = false + addSubview(line) + // A press with no delay, not a pan. A pan recognizer begins only + // once the finger has travelled some way, and reports the travel + // from THERE: with a real touch a 180 pt drag moved the line 158, + // by position and by `translation` alike. The strip is the line's + // alone — nothing else wants its touches — so the drag can start + // where the finger lands. + let press = UILongPressGestureRecognizer(target: self, action: #selector(dragged(_:))) + press.minimumPressDuration = 0 + press.allowableMovement = .greatestFiniteMagnitude + addGestureRecognizer(press) + isAccessibilityElement = true + accessibilityTraits = .adjustable + accessibilityLabel = String(localized: "Pane divider") + accessibilityIdentifier = "terminalPane.divider" + #if os(visionOS) + hoverStyle = UIHoverStyle(effect: .highlight, shape: .rect(cornerRadius: 2)) + #else + addInteraction(UIPointerInteraction(delegate: nil)) + #endif + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("unused") } + + func show(_ divider: PaneLayoutFrames.Divider, ink: UIColor) { + self.divider = divider + let sideways = divider.axis == .sideBySide + let strip = divider.frame.insetBy( + dx: sideways ? -Self.reach : 0, dy: sideways ? 0 : -Self.reach) + if frame != strip { frame = strip } + // One point, in the middle of the gap. + line.frame = sideways + ? CGRect(x: bounds.midX - 0.5, y: 0, width: 1, height: bounds.height) + : CGRect(x: 0, y: bounds.midY - 0.5, width: bounds.width, height: 1) + line.backgroundColor = ink.withAlphaComponent(0.2) + accessibilityValue = sideways + ? String(localized: "Between left and right panes") + : String(localized: "Between top and bottom panes") + } + + @objc private func dragged(_ gesture: UILongPressGestureRecognizer) { + guard let divider, let container = superview else { return } + let point = gesture.location(in: container) + let position = divider.axis == .sideBySide ? point.x : point.y + switch gesture.state { + case .began: + let centre = divider.axis == .sideBySide ? divider.frame.midX : divider.frame.midY + grabOffset = position - centre + grabPosition = position + isDragging = false + case .changed, .ended: + // A touch that never moved is not a drag: a tap on the line + // must not re-state the ratio it already has, rounded. + if abs(position - grabPosition) >= 1 { isDragging = true } + if isDragging { moved?(divider, position - grabOffset) } + default: + break + } + } + + override func accessibilityIncrement() { + if let divider { nudged?(divider, 0.05) } + } + + override func accessibilityDecrement() { + if let divider { nudged?(divider, -0.05) } + } +} diff --git a/Multiplex/Views/Terminal/TerminalPaneUIKit.swift b/Multiplex/Views/Terminal/TerminalPaneUIKit.swift index 63f31fa4..1d12eab4 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 } @@ -42,9 +45,18 @@ struct TerminalPaneObservedState: Equatable { var isDictating: Bool #endif var keyboardLocked: Bool + /// A paned tab's arrangement and the pane its keyboard is on: the + /// surface redraws the split, and the overlays that hang on "the + /// terminal" move to the emulator that now is it. + var paneLayout: PaneLayout? + var activePaneID: PaneID? + var zoomedPaneID: PaneID? @MainActor init(controller: TerminalSessionController) { + paneLayout = controller.paneLayout + activePaneID = controller.activePaneID + zoomedPaneID = controller.zoomedPaneID status = controller.status isResuming = controller.isResuming tmuxCopyModeUIActive = controller.tmuxCopyModeUIActive @@ -76,6 +88,10 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg private(set) var missingHostView: UIView? private var selectionActionsOverlay: TerminalSelectionActionsOverlay? private var selectionMenuOverlay: TerminalSelectionMenuOverlay? + /// The emulator the two overlays above were installed on. On a paned + /// tab the controller's `terminalView` moves with the keyboard, and + /// overlays left on the pane it came from would answer its presses. + private weak var overlayTerminal: TerminalView? private let topCenterStack = UIStackView() private let topTrailingStack = UIStackView() @@ -209,6 +225,13 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg guard canAcceptFileDrop(session), let controller = configuration.controller else { return } + // Among several panes a file lands in the one it was dropped on: + // the upload goes to that pane's directory and its path is typed + // there, so the tab's focus moves to it first. + if let split = terminalSurface?.paneSplitView, + let pane = split.pane(at: session.location(in: split)) { + controller.focusPane(pane) + } let providers = session.items.map(\.itemProvider) Task { @MainActor [weak controller] in controller?.deliverDrop(await TerminalDropLoader.load(providers)) @@ -240,6 +263,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 ) } @@ -330,6 +354,13 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg _ state: TerminalPaneObservedState, controller: TerminalSessionController ) { + if overlayTerminal !== controller.terminalView { + selectionActionsOverlay?.detach() + selectionActionsOverlay = nil + selectionMenuOverlay?.detach() + selectionMenuOverlay = nil + overlayTerminal = controller.terminalView + } let wantsOverlay = state.selectTextModeUIActive && configuration.isActive && state.status == .live @@ -458,6 +489,15 @@ final class TerminalPaneViewController: UIViewController, UIDropInteractionDeleg ) { removeArrangedSubviews(from: topCenterStack) guard configuration.isActive else { return } + if state.zoomedPaneID != nil { + // One pane is drawn over the others: say so, and carry the way + // back — the panes it covers cannot be seen to be missed. + let bar = TerminalContextBarView.zoomed { [weak controller] in + controller?.togglePaneZoom() + } + bar.accessibilityIdentifier = "terminalPane.context.zoomed" + topCenterStack.addArrangedSubview(bar) + } if state.tmuxCopyModeUIActive { let bar = TerminalContextBarView.copyMode { [weak controller] in controller?.finishTmuxCopyMode() @@ -816,6 +856,20 @@ final class TerminalContextBarView: UIKitTallyBorderedView { ]) } + /// A paned tab drawing one pane over the rest: the lamp, and the chip + /// that brings the others back. + static func zoomed(showAll: @escaping () -> Void) -> TerminalContextBarView { + TerminalContextBarView(items: [ + UIKitTallyLamp(caption: "ZOOMED", color: TallyPalette.caution), + UIKitChassisChip( + "ALL PANES", + prominent: true, + accessibilityLabel: String(localized: "Show all panes"), + action: showAll + ), + ]) + } + /// Arrange Keys: the lamp, RESET off the shipped order, DONE — the /// copy-mode bar's anatomy. No hint text: the wiggling row is the /// instruction, and the bar must fit a 375 pt phone. diff --git a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift index 2f06ef40..2d6abff5 100644 --- a/Multiplex/Views/Terminal/TerminalWindowUIKit.swift +++ b/Multiplex/Views/Terminal/TerminalWindowUIKit.swift @@ -984,28 +984,45 @@ 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 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 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's strip is the terminal its keyboard is on — one pane + // of the window it draws, and not necessarily the one the session + // is fronting (Open Terminal, Switch Terminal, a touch on another + // pane, or the Rex app showing another window): `TmuxSession + // .agent(inPane:)`. + if let rex = activeTab.rexTarget { + 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 model.sessions(on: backend) - .first { $0.name == sessionName }? - .activeAgent + return session?.activeAgent } private var resolvedTerminalTheme: TerminalTheme { // Prefer the pinned choice over the live traits: the observation @@ -1049,6 +1066,9 @@ final class TerminalWindowViewController: UIViewController, _ = activeController?.pendingLink _ = activeController?.pendingPath _ = activeController?.talkbackOpen + // A paned tab's keyboard moved to another pane: the agent strip + // and the key cluster are that pane's now. + _ = activeController?.activePaneID #if os(visionOS) _ = activeController?.keyBarArranging #endif @@ -1476,8 +1496,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 +1527,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) @@ -1850,6 +1865,12 @@ final class TerminalWindowViewController: UIViewController, if agentChanged { renderNow() } await model.refreshAndWait(ifStaleFor: 4) + // 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 // authority. Between ticks, the one terminal that owns keyboard @@ -2602,6 +2623,7 @@ extension TerminalWindowViewController { isActive: isActive, focusAllowed: terminalFocusAllowed, keyCommandPlan: keyCommandPlan, + shortcutHasChoices: probedSession(for: tab)?.hasSwitchChoices == true, close: { [weak self] in self?.closeTab(tab.id) } ) } @@ -2935,6 +2957,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/TouchDownGestureRecognizer.swift b/Multiplex/Views/Terminal/TouchDownGestureRecognizer.swift new file mode 100644 index 00000000..2f72fffe --- /dev/null +++ b/Multiplex/Views/Terminal/TouchDownGestureRecognizer.swift @@ -0,0 +1,20 @@ +import UIKit.UIGestureRecognizerSubclass + +/// Recognizes the moment a touch lands and never holds it: nothing is +/// cancelled or delayed, so every other gesture on the view carries on as +/// if this were not there. A tap would be too late for its one use — a +/// pane has to take the tab's focus before a long press on it resolves. +final class TouchDownGestureRecognizer: UIGestureRecognizer { + override func touchesBegan(_ touches: Set, with event: UIEvent) { + super.touchesBegan(touches, with: event) + if state == .possible { state = .recognized } + } + + override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool { + false + } + + override func canBePrevented(by preventingGestureRecognizer: UIGestureRecognizer) -> Bool { + false + } +} diff --git a/Multiplex/Views/Terminal/UMDBarUIKit.swift b/Multiplex/Views/Terminal/UMDBarUIKit.swift index 1b8e80fb..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 } @@ -483,12 +493,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") + prominent: configuration.shortcutHasChoices, + accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) chip.accessibilityIdentifier = "umd.tmux" chip.isEnabled = state.status == .live @@ -497,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,12 +869,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") + prominent: configuration.shortcutHasChoices, + accessibilityLabel: backend.shortcutKeyAccessibilityLabel ) button.accessibilityIdentifier = "umd.tmux" button.isEnabled = currentObservedState.status == .live @@ -874,12 +881,13 @@ final class UMDBarViewController: UIViewController, self.showShortcutPanel(from: button) }, for: .touchUpInside) shortcutButtonView = button + shortcutChip = button return button } 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") @@ -1886,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/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/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-probe-preview25.txt b/MultiplexTests/Fixtures/rex-probe-preview25.txt new file mode 100644 index 00000000..b21e831b --- /dev/null +++ b/MultiplexTests/Fixtures/rex-probe-preview25.txt @@ -0,0 +1,86 @@ +MULTIPLEX_REX_PROBE +{ + "ok": true, + "sessions": [ + { + "active": "window:01a21b89-598f-7f2e-aca3-f6683eb1186a", + "clients": 0, + "id": "session:01a21b89-5982-70bb-aa31-e0ead58431fe", + "label": "work", + "tail": "editing README", + "windows": [ + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a21b89-5982-7167-861a-b5750eb6cc35", + "label": "shell", + "name": "sleep", + "pid": 56341, + "title": "vim README.md" + }, + { + "argv0": "sleep", + "id": "block:01a21b89-59ac-795a-803c-cfd62f577d3a", + "label": "logs", + "name": "sleep", + "pid": 56344, + "title": "" + } + ], + "focus": "block:01a21b89-5982-7167-861a-b5750eb6cc35", + "id": "window:01a21b89-598f-7f2e-aca3-f6683eb1186a", + "label": "editor" + }, + { + "blocks": [ + { + "argv0": "sleep", + "id": "block:01a21b89-59d0-7937-a023-c99895e249c1", + "label": "shell", + "name": "sleep", + "pid": 56347, + "status": [ + { + "app": "claude-code", + "kind": "permission", + "state": "blocked" + } + ], + "title": "✳ Claude Code" + } + ], + "focus": "block:01a21b89-59d0-7937-a023-c99895e249c1", + "id": "window:01a21b89-59db-7b10-8ef1-29f73a065c6a", + "label": "Window 3a065c6a" + } + ] + }, + { + "active": "window:01a21b89-59fe-7e44-a3f5-2fe891882add", + "clients": 0, + "clipped": true, + "id": "session:01a21b89-59f4-7163-8e86-f77b9b49239c", + "label": "drifting-bluff", + "tail": "本語の出力\n行 174 日本語の出力\n行 175 日本語の出力\n行 176 日本語の出力\n行 177 日本語の出力\n行 178 日本語の出力\n行 179 日本語の出力\n行 180 日本語の出力\n行 181 日本語の出力\n行 182 日本語の出力\n行 183 日本語の出力\n行 184 日本語の出力\n行 185 日本語の出力\n行 186 日本語の出力\n行 187 日本語の出力\n行 188 日本語の出力\n行 189 日本語の出力\n行 190 日本語の出力\n行 191 日本語の出力\n行 192 日本語の出力\n行 193 日本語の出力\n行 194 日本語の出力\n行 195 日本語の出力\n行 196 日本語の出力\n行 197 日本語の出力\n行 198 日本語の出力\n行 199 日本語の出力\n行 200 日本語の出力\n行 201 日本語の出力\n行 202 日本語の出力\n行 203 日本語の出力\n行 204 日本語の出力\n行 205 日本語の出力\n行 206 日本語の出力\n行 207 日本語の出力\n行 208 日本語の出力\n行 209 日本語の出力\n行 210 日本語の出力\n行 211 日本語の出力\n行 212 日本語の出力\n行 213 日本語の出力\n行 214 日本語の出力\n行 215 日本語の出力\n行 216 日本語の出力\n行 217 日本語の出力\n行 218 日本語の出力\n行 219 日本語の出力\n行 220 日本語の出力\n行 221 日本語の出力\n行 222 日本語の出力\n行 223 日本語の出力\n行 224 日本語の出力\n行 225 日本語の出力\n行 226 日本語の出力\n行 227 日本語の出力\n行 228 日本語の出力\n行 229 日本語の出力\n行 230 日本語の出力\n行 231 日本語の出力\n行 232 日本語の出力\n行 233 日本語の出力\n行 234 日本語の出力\n行 235 日本語の出力\n行 236 日本語の出力\n行 237 日本語の出力\n行 238 日本語の出力\n行 239 日本語の出力\n行 240 日本語の出力\n行 241 日本語の出力\n行 242 日本語の出力\n行 243 日本語の出力\n行 244 日本語の出力\n行 245 日本語の出力\n行 246 日本語の出力\n行 247 日本語の出力\n行 248 日本語の出力\n行 249 日本語の出力\n行 250 日本語の出力\n行 251 日本語の出力\n行 252 日本語の出力\n行 253 日本語の出力\n行 254 日本語の出力\n行 255 日本語の出力\n行 256 日本語の出力\n行 257 日本語の出力\n行 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:01a21b89-59f4-71ec-8006-afb537c09ecc", + "label": "shell", + "name": "sleep", + "pid": 56352, + "title": "" + } + ], + "focus": "block:01a21b89-59f4-71ec-8006-afb537c09ecc", + "id": "window:01a21b89-59fe-7e44-a3f5-2fe891882add", + "label": "Window 91882add" + } + ] + } + ] +} +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 00000000..ec9222a7 Binary files /dev/null and b/MultiplexTests/Fixtures/rex-terminal-stream-preview19.bin differ diff --git a/MultiplexTests/Fixtures/rex-terminal-stream-preview25.bin b/MultiplexTests/Fixtures/rex-terminal-stream-preview25.bin new file mode 100644 index 00000000..111adc93 Binary files /dev/null and b/MultiplexTests/Fixtures/rex-terminal-stream-preview25.bin differ 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/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/PaneLayoutTests.swift b/MultiplexTests/PaneLayoutTests.swift new file mode 100644 index 00000000..e3507a3a --- /dev/null +++ b/MultiplexTests/PaneLayoutTests.swift @@ -0,0 +1,169 @@ +import XCTest +@testable import Multiplex + +/// The pane tree a paned tab draws from, and its geometry. Pure: no view is +/// involved in deciding where a pane sits or what ratio a drag means. +final class PaneLayoutTests: XCTestCase { + private let a = PaneID("a"), b = PaneID("b"), c = PaneID("c") + + /// `a | (b / c)`: `a` on the left, `b` above `c` on the right. + private var nested: PaneLayout { + .split(PaneLayout.Split( + id: "outer", axis: .sideBySide, ratio: 0.5, + before: .pane(a), + after: .split(PaneLayout.Split( + id: "inner", axis: .stacked, ratio: 0.25, + before: .pane(b), after: .pane(c))))) + } + + func testPanesAreListedInReadingOrder() { + XCTAssertEqual(nested.panes, [a, b, c]) + XCTAssertEqual(nested.firstPane, a) + XCTAssertTrue(nested.contains(c)) + XCTAssertFalse(nested.contains(PaneID("d"))) + XCTAssertEqual(PaneLayout.pane(a).panes, [a]) + } + + func testASplitIsFoundByItsIDAtAnyDepth() { + XCTAssertEqual(nested.split(withID: "inner")?.axis, .stacked) + XCTAssertEqual(nested.split(withID: "outer")?.ratio, 0.5) + XCTAssertNil(nested.split(withID: "gone")) + XCTAssertNil(PaneLayout.pane(a).split(withID: "outer")) + } + + func testARatioIsSetOnOneSplitAndKeptOffTheEnds() { + let moved = nested.settingRatio(0.7, ofSplit: "inner") + XCTAssertEqual(moved.split(withID: "inner")?.ratio, 0.7) + XCTAssertEqual(moved.split(withID: "outer")?.ratio, 0.5) + // A pane of no width could not be dragged back open. + XCTAssertEqual(nested.settingRatio(0, ofSplit: "outer").split(withID: "outer")?.ratio, 0.05) + XCTAssertEqual(nested.settingRatio(3, ofSplit: "outer").split(withID: "outer")?.ratio, 0.95) + // No such split: nothing changes. + XCTAssertEqual(nested.settingRatio(0.9, ofSplit: "gone"), nested) + } + + func testAClosingPanesFocusGoesToItsNearestNeighbour() { + // The sibling takes a closed pane's room, and its focus. + XCTAssertEqual(nested.neighbor(ofClosing: b), c) + XCTAssertEqual(nested.neighbor(ofClosing: c), b) + // `a`'s sibling is a split: the pane of it that reads first. + XCTAssertEqual(nested.neighbor(ofClosing: a), b) + XCTAssertNil(PaneLayout.pane(a).neighbor(ofClosing: a)) + XCTAssertNil(nested.neighbor(ofClosing: PaneID("d"))) + // A split's LAST pane is the one beside what follows it. + let row = PaneLayout.split(PaneLayout.Split( + id: "row", axis: .sideBySide, ratio: 0.5, + before: nested.split(withID: "inner").map(PaneLayout.split) ?? .pane(b), + after: .pane(a))) + XCTAssertEqual(row.neighbor(ofClosing: a), c) + } + + // MARK: - Geometry + + func testASinglePaneFillsTheBoundsWithNoLine() { + let bounds = CGRect(x: 10, y: 20, width: 300, height: 200) + let frames = PaneLayout.pane(a).frames(in: bounds, dividerThickness: 9, displayScale: 2) + XCTAssertEqual(frames.panes, [a: bounds]) + XCTAssertTrue(frames.dividers.isEmpty) + } + + func testSplitsDivideWhatIsLeftAfterTheLineBetweenThem() { + let frames = nested.frames( + in: CGRect(x: 0, y: 0, width: 409, height: 209), + dividerThickness: 9, displayScale: 2) + // 400 usable points across: 200 each side of a 9-point line. + XCTAssertEqual(frames.panes[a], CGRect(x: 0, y: 0, width: 200, height: 209)) + // 200 usable points down the right side: a quarter above the line. + XCTAssertEqual(frames.panes[b], CGRect(x: 209, y: 0, width: 200, height: 50)) + XCTAssertEqual(frames.panes[c], CGRect(x: 209, y: 59, width: 200, height: 150)) + XCTAssertEqual(frames.dividers.map(\.splitID), ["outer", "inner"]) + let outer = frames.dividers[0], inner = frames.dividers[1] + XCTAssertEqual(outer.frame, CGRect(x: 200, y: 0, width: 9, height: 209)) + XCTAssertEqual(outer.extent, CGRect(x: 0, y: 0, width: 409, height: 209)) + // The inner line spans only its own split. + XCTAssertEqual(inner.frame, CGRect(x: 209, y: 50, width: 200, height: 9)) + XCTAssertEqual(inner.extent, CGRect(x: 209, y: 0, width: 200, height: 209)) + } + + func testEdgesLandOnPhysicalPixels() { + let layout = PaneLayout.split(PaneLayout.Split( + id: "s", axis: .sideBySide, ratio: 1.0 / 3, before: .pane(a), after: .pane(b))) + let frames = layout.frames( + in: CGRect(x: 0, y: 0, width: 300, height: 100), + dividerThickness: 9, displayScale: 2) + // 291 / 3 = 97: already whole. At a third of 292 it would be 97.33, + // which lands on the half point a 2x display has. + XCTAssertEqual(frames.panes[a]?.width, 97) + let odd = layout.frames( + in: CGRect(x: 0, y: 0, width: 301, height: 100), + dividerThickness: 9, displayScale: 2) + XCTAssertEqual(odd.panes[a]?.width, 97.5) + // Nothing is lost or doubled: the three widths are the bounds'. + XCTAssertEqual((odd.panes[a]?.width ?? 0) + 9 + (odd.panes[b]?.width ?? 0), 301) + } + + func testADragBecomesTheRatioThatPutsTheLineUnderIt() { + let extent = CGRect(x: 100, y: 0, width: 409, height: 200) + // The line's centre at the extent's middle: an even split. + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 304.5, in: extent, axis: .sideBySide, dividerThickness: 9), + 0.5, accuracy: 0.0001) + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 204.5, in: extent, axis: .sideBySide, dividerThickness: 9), + 0.25, accuracy: 0.0001) + // Laying the result out puts the line back where the drag was. + let layout = PaneLayout.split(PaneLayout.Split( + id: "s", axis: .sideBySide, ratio: 0.25, before: .pane(a), after: .pane(b))) + let line = layout.frames(in: extent, dividerThickness: 9, displayScale: 2).dividers[0] + XCTAssertEqual(line.frame.midX, 204.5) + // The other axis reads the other coordinate. + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 100, in: CGRect(x: 0, y: 0, width: 50, height: 409), + axis: .stacked, dividerThickness: 9), + (100 - 4.5) / 400, accuracy: 0.0001) + } + + func testADragCannotCrushEitherPane() { + let extent = CGRect(x: 0, y: 0, width: 409, height: 200) + // Past either end the pane keeps its minimum length. + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: -500, in: extent, axis: .sideBySide, dividerThickness: 9), + Double(PaneLayout.minimumPaneLength / 400), accuracy: 0.0001) + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 5000, in: extent, axis: .sideBySide, dividerThickness: 9), + Double(1 - PaneLayout.minimumPaneLength / 400), accuracy: 0.0001) + // A split too small to give both that still keeps a ratio off the + // ends, and one with no room at all is left even. + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 0, in: CGRect(x: 0, y: 0, width: 100, height: 50), + axis: .sideBySide, dividerThickness: 9), + 0.05) + XCTAssertEqual( + PaneLayout.ratio( + forDividerAt: 3, in: CGRect(x: 0, y: 0, width: 9, height: 50), + axis: .sideBySide, dividerThickness: 9), + 0.5) + } + + // MARK: - Shortcut rows + + func testThePanelRowsBecomeCommandsOnThePaneWithTheKeyboard() { + XCTAssertEqual(PaneShortcut.splitRight.command(on: a), .split(a, .sideBySide)) + XCTAssertEqual(PaneShortcut.splitDown.command(on: a), .split(a, .stacked)) + XCTAssertEqual(PaneShortcut.closePane.command(on: b), .close(b)) + XCTAssertEqual(PaneShortcut.newWindow.command(on: b), .newWindow(from: b)) + // The zoom is the tab's own drawing: no backend is asked. + XCTAssertNil(PaneShortcut.zoomPane.command(on: a)) + // Only the close ends a program, so only it asks twice. + XCTAssertEqual( + PaneShortcut.allCases.filter(\.requiresDoubleActivation), [.closePane]) + XCTAssertEqual(PaneShortcut.closePane.bindingLabel, "2×") + XCTAssertEqual(PaneShortcut.splitRight.bindingLabel, "") + } +} diff --git a/MultiplexTests/RexProbeTests.swift b/MultiplexTests/RexProbeTests.swift new file mode 100644 index 00000000..f4aca599 --- /dev/null +++ b/MultiplexTests/RexProbeTests.swift @@ -0,0 +1,877 @@ +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; a second capture off preview.25 +/// has its own test) 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(_ name: String = "rex-probe-preview19") throws -> String { + let url = try XCTUnwrap( + Bundle(for: RexFixtureAnchor.self).url(forResource: name, 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) + // 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") + 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) + } + + /// The same probe command against Rex 0.1.0-preview.25 (API revision + /// 24, captured 2026-11-27): `work` — window `editor` split in two, and + /// an unnamed window whose block reports `blocked` / `permission` for + /// `claude-code` — and an unnamed session with 400 multibyte lines. + func testTheNewestServersProbeReadsTheSameWay() throws { + let probe = RexProbe.parseProbe(try fixture("rex-probe-preview25")) + let sessions = try sessions(probe) + XCTAssertEqual(sessions.map(\.name), ["work", "drifting-bluff"]) + XCTAssertEqual( + sessions[0].tmuxID, "session:01a21b89-5982-70bb-aa31-e0ead58431fe") + + let work = sessions[0] + // The second window's generated `Window 3a065c6a` gives way to its + // focused block's label. + XCTAssertEqual(work.windows.map(\.name), ["editor", "shell"]) + XCTAssertEqual(work.windows.map(\.isActive), [true, false]) + XCTAssertEqual(work.windows.map(\.paneCount), [2, 1]) + XCTAssertEqual(work.windows[0].paneTitle, "vim README.md") + XCTAssertEqual(work.windows[0].panes?.map(\.command), ["sleep", "sleep"]) + XCTAssertEqual(work.windows[1].activeAgent, .claudeCode) + + XCTAssertEqual( + probe.signals["work"]?.reported, + [RexProbe.ProgramStatus(state: .blocked, kind: .permission)]) + XCTAssertEqual(probe.tails["work"], ["editing README"]) + let tail = try XCTUnwrap(probe.tails["drifting-bluff"]) + XCTAssertTrue(tail.allSatisfy { $0.hasPrefix("行 ") }) + XCTAssertEqual(tail.last, "行 400 日本語の出力") + XCTAssertEqual(tail.count, 30) + } + + 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.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(RexWire.bakeableSessionID("work")) + XCTAssertFalse(RexWire.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.sessionBackend, .rex) + XCTAssertEqual(Host.SessionBackend.rex.shortcutKeyCaption, "REX") + XCTAssertEqual(Host.SessionBackend.tmux.shortcutKeyCaption, "TMUX") + XCTAssertEqual(Host.SessionBackend.herdr.shortcutKeyCaption, "HRDR") + // The panel lists no bindings (Rex has no prefix-key client): its + // rows act on the tab's own panes, and the list below them reaches + // the session's other terminals. + let panel = ShortcutPanelContent.content(for: route.sessionBackend) + XCTAssertEqual(panel, .rex) + XCTAssertEqual( + panel?.sections.flatMap(\.items).map(\.payload), + [ + .pane(.splitRight), .pane(.splitDown), .pane(.zoomPane), .pane(.closePane), + .pane(.newWindow), + ]) + // Closing ends a program: asked twice, like every backend's close. + XCTAssertEqual( + panel?.sections.flatMap(\.items).map(\.requiresDoubleActivation), + [false, false, false, true, false]) + // Rex's own app calls a window a tab, and so does its row. + XCTAssertEqual(panel?.sections.map(\.title), ["Panes", "Tabs"]) + XCTAssertEqual(panel?.sections.last?.items.map(\.title), ["New Tab"]) + XCTAssertEqual(panel?.sections.last?.items.map(\.command), ["session.new_window"]) + 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 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) + 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( + 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") + // 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..8d50c266 --- /dev/null +++ b/MultiplexTests/RexSessionTests.swift @@ -0,0 +1,1639 @@ +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 — and what happens to +/// a tab's panes as the server's layout changes under it. +final class RexSessionTests: XCTestCase { + private let sessionID = "session:0000-aaaaaa" + private let front = PaneID("block:front") + private let side = PaneID("block:side") + private let other = PaneID("block:other") + + private func makeSession( + _ server: FakeRexServer, blockID: String? = nil + ) -> RexSession { + RexSession( + openPipe: { try server.makePipe() }, + closeLink: { server.note("link closed") }, + sessionID: sessionID, blockID: blockID, clientVersion: "test" + ) + } + + /// Collects what the session hands the tab: each pane's output, the + /// grids its emulator is given, the arrangements, and the end. + private final class Sink: @unchecked Sendable { + private let lock = NSLock() + private var chunks: [PaneID: [Data]] = [:] + private var arranged: [PaneArrangement] = [] + private var closes: [String?] = [] + /// What the tab "measures" for a pane; every other pane is 100x30. + var sizes: [PaneID: TerminalGrid] = [:] + + func data(_ pane: PaneID, _ chunk: Data) { + lock.withLock { chunks[pane, default: []].append(chunk) } + } + /// The emulator's grid changing hands, in line with what is drawn. + func grid(_ pane: PaneID, _ grid: TerminalGrid?) { + let text = grid.map { "GRID \($0.cols)x\($0.rows)" } ?? "GRID own" + lock.withLock { chunks[pane, default: []].append(Data(text.utf8)) } + } + func arrange(_ arrangement: PaneArrangement) -> [PaneID: TerminalGrid] { + lock.withLock { arranged.append(arrangement) } + return Dictionary(uniqueKeysWithValues: arrangement.layout.panes.map { + ($0, sizes[$0] ?? TerminalGrid(cols: 100, rows: 30)) + }) + } + func closed(_ reason: String?) { lock.withLock { closes.append(reason) } } + func text(_ pane: PaneID) -> [String] { + lock.withLock { + (chunks[pane] ?? []).map { String(decoding: $0, as: UTF8.self) } + } + } + var arrangements: [PaneArrangement] { lock.withLock { arranged } } + var closeReasons: [String?] { lock.withLock { closes } } + } + + private func open(_ session: RexSession, sink: Sink) async throws { + try await session.open(events: PaneEvents( + arrange: { sink.arrange($0) }, + output: { sink.data($0, $1) }, + grid: { sink.grid($0, $1) }, + close: { sink.closed($0) } + )) + } + + /// 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 { + for _ in 0..<300 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } + XCTAssertTrue(condition(), "condition never held", file: file, line: line) + } + + /// `block:side | block:front` in the fronted window, `front` focused. + private func splitServer() -> FakeRexServer { + let server = FakeRexServer() + server.setWindow("window:2", tree: .split( + id: "split:1", direction: "horizontal", ratio: 0.6, + before: .block("block:side"), after: .block("block:front"))) + return server + } + + // MARK: - Attach + + func testAttachClaimsAndSizesBeforeItAsksForTheScreenOrTheStream() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + 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", + ]) + 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 — and + // the tab was told so before anything was opened. + XCTAssertEqual(server.claims, [["block:front"]]) + XCTAssertEqual( + sink.arrangements, [PaneArrangement(layout: .pane(front), focus: 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(front), ["\u{1B}cSCREEN", "early\r\n"]) + + server.sendOutput("later\r\n") + await eventually { sink.text(self.front).count == 3 } + XCTAssertEqual(sink.text(front).last, "later\r\n") + await session.close() + } + + func testANamedBlockIsAttachedWhileItExists() async throws { + let server = FakeRexServer() + let session = makeSession(server, blockID: "block:other") + let sink = Sink() + try await open(session, sink: sink) + XCTAssertEqual(server.claims, [["block:other"]]) + XCTAssertEqual(sink.arrangements.last?.layout, .pane(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.claims, [["block:front"]]) + await second.close() + } + + // MARK: - A window's panes + + func testAWindowsPanesAreArrangedMeasuredClaimedTogetherAndEachDrawnInItsOwn() async throws { + let server = splitServer() + server.screens = ["block:side": "SIDE", "block:front": "FRONT"] + let session = makeSession(server) + let sink = Sink() + sink.sizes = [side: TerminalGrid(cols: 59, rows: 30), front: TerminalGrid(cols: 40, rows: 30)] + try await open(session, sink: sink) + + // The whole split, as the app's own tree, with the keyboard on the + // block the window is focused on. + XCTAssertEqual(sink.arrangements, [PaneArrangement( + layout: .split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.6, + before: .pane(side), after: .pane(front))), + focus: front)]) + // ONE claim for both, then each terminal at the grid its own pane + // measured, and only then the streams. + XCTAssertEqual(server.claims, [["block:side", "block:front"]]) + XCTAssertEqual(Array(server.calls.prefix(4)), [ + "session.attach", + "session.own_block", + "com.superlogical.terminal.resize 59x30", + "com.superlogical.terminal.resize 40x30", + ]) + XCTAssertEqual(server.resizes.map(\.block), ["block:side", "block:front"]) + XCTAssertEqual(server.calls.filter { $0 == "data.connect" }.count, 2) + // Each pane got its own terminal's screen, and gets its own output. + XCTAssertEqual(sink.text(side), ["\u{1B}cSIDE"]) + XCTAssertEqual(sink.text(front), ["\u{1B}cFRONT"]) + server.sendOutput("for side", to: "block:side") + await eventually { sink.text(self.side).last == "for side" } + XCTAssertEqual(sink.text(front), ["\u{1B}cFRONT"]) + + // Typing goes to the pane it was typed into, and a pane's new size + // to its own terminal. + try await session.write(Data("a".utf8), to: side) + await eventually { server.written == ["a"] } + XCTAssertEqual(server.lastWriteBlock, "block:side") + try await session.resize(pane: front, cols: 44, rows: 28) + XCTAssertEqual(server.resizes.last?.block, "block:front") + XCTAssertEqual(server.calls.last, "com.superlogical.terminal.resize 44x28") + await session.close() + } + + func testAPaneThatCannotBeOpenedSaysSoInItsPaneAndTheTabStays() async throws { + let server = splitServer() + server.rejectReasons = ["block:side": 0x04] + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + XCTAssertEqual(sink.text(front), ["\u{1B}cSCREEN"]) + XCTAssertEqual(sink.text(side).count, 1) + XCTAssertEqual(sink.text(side).first?.hasPrefix("\u{1B}cCouldn't open this terminal."), true) + XCTAssertEqual( + sink.text(side).first?.contains("the server is at its connection limit"), true) + // The pane that works still does. + server.sendOutput("still here") + await eventually { sink.text(self.front).last == "still here" } + XCTAssertTrue(sink.closeReasons.isEmpty) + await session.close() + } + + func testAPaneAnotherClientAddsIsDrawnAtItsOwnersSizeAndNotClaimed() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let claimsBefore = server.claims + + // The Rex app splits the window. The new terminal is its own, at + // the size of ITS pane. + server.openingSizes["block:added"] = (50, 20, "client:rex-app") + server.screens["block:added"] = "ADDED" + server.addBlock("block:added", beside: "block:front", owner: "client:rex-app") + let added = PaneID("block:added") + await eventually { sink.text(added).last == "\u{1B}cADDED" } + + // The tab follows: the pane appears, drawn at its owner's grid, and + // the keyboard stays where it was. + XCTAssertEqual(sink.arrangements.last, PaneArrangement( + layout: .split(PaneLayout.Split( + id: "split:added", axis: .sideBySide, ratio: 0.5, + before: .pane(front), after: .pane(added))), + focus: nil)) + XCTAssertEqual(sink.text(added), ["GRID 50x20", "\u{1B}cADDED"]) + // Nothing was taken from the client that made it. + XCTAssertEqual(server.claims, claimsBefore) + XCTAssertFalse(server.resizes.contains { $0.block == "block:added" }) + + // Typing here is what claims — every terminal the tab draws that it + // does not own, the one typed into first. + try await session.write(Data("x".utf8), to: front) + await eventually { server.written == ["x"] } + XCTAssertEqual(server.claims.count, claimsBefore.count) + try await session.write(Data("y".utf8), to: added) + await eventually { server.written == ["x", "y"] } + XCTAssertEqual(server.claims.last, ["block:added"]) + XCTAssertEqual(server.resizes.last?.block, "block:added") + await session.close() + } + + // MARK: - Changing the layout + + func testASplitIsAskedOfTheServerAndTheNewPaneArrivesWithTheKeyboard() async throws { + let server = FakeRexServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + try await session.perform(.split(front, .stacked)) + let made = PaneID("block:new1") + await eventually { sink.text(made) == ["\u{1B}cSCREEN"] } + + // Below the pane it was split from, starting where that pane's + // program is, and NOT focused on the server: that would also make + // this window the one the Rex app shows. + let asked = try XCTUnwrap(server.splitRequests.first) + XCTAssertEqual(asked["anchor_id"] as? String, "block:front") + XCTAssertEqual(asked["direction"] as? String, "vertical") + XCTAssertEqual(asked["side"] as? String, "after") + XCTAssertEqual(asked["focus"] as? Bool, false) + let block = (asked["layout"] as? [String: Any])?["block"] as? [String: Any] + XCTAssertEqual(block?["flavor"] as? String, "com.superlogical.terminal.shell") + XCTAssertEqual((block?["options"] as? [String: Any])?["cwd"] as? String, "/work/block:front") + + // The tab hears of it as an arrangement, the new pane focused. + XCTAssertEqual(sink.arrangements.last?.layout, .split(PaneLayout.Split( + id: "split:new1", axis: .stacked, ratio: 0.5, + before: .pane(front), after: .pane(made)))) + XCTAssertTrue(sink.arrangements.contains { $0.focus == made }) + // It is this tab's own pane: claimed and sized like the attach's. + XCTAssertEqual(server.claims.last, ["block:new1"]) + XCTAssertEqual(server.resizes.last?.block, "block:new1") + let listed = await session.terminalChoices() + XCTAssertEqual(listed?.first(where: \.isActive)?.tmuxID, "block:new1") + await session.close() + } + + func testClosingAPaneRemovesItAndTheKeyboardGoesToItsNeighbour() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + try await session.perform(.close(front)) + await eventually { sink.arrangements.last?.layout == .pane(self.side) } + XCTAssertEqual(server.calls.filter { $0.hasPrefix("block.close") }, ["block.close block:front"]) + XCTAssertEqual(sink.arrangements.last?.focus, side) + // A pane closing is not the tab ending, and a block that no longer + // exists is not disowned (one unknown id fails that whole call). + XCTAssertTrue(sink.closeReasons.isEmpty) + XCTAssertFalse(server.calls.contains { $0.hasPrefix("session.disown_block") }) + // The pane that is left still works. + try await session.write(Data("z".utf8), to: side) + await eventually { server.written == ["z"] } + // Nothing reaches the one that went. + try await session.write(Data("lost".utf8), to: front) + try await Task.sleep(for: .milliseconds(100)) + XCTAssertEqual(server.written, ["z"]) + + // Closing the last pane closes the window, and the tab goes to the + // window Rex shows next — the one before it, this one being last. + try await session.perform(.close(side)) + await eventually { sink.arrangements.last?.layout == .pane(self.other) } + XCTAssertEqual(sink.arrangements.last?.focus, other) + XCTAssertTrue(sink.closeReasons.isEmpty) + await session.close() + } + + func testADraggedLineSendsOnlyTheNewestRatioAndIsNotDraggedBackByOlderAnswers() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let arrangedBefore = sink.arrangements.count + + // A slow link: the first ask is still out while the drag goes on. + server.hold("session.resize_pane") + try await session.perform(.setRatio(0.3, splitID: "split:1")) + await eventually { server.ratioRequests.count == 1 } + try await session.perform(.setRatio(0.4, splitID: "split:1")) + try await session.perform(.setRatio(0.7, splitID: "split:1")) + XCTAssertEqual(server.ratioRequests.map { $0["ratio"] as? Double }, [0.3]) + + server.release() + await eventually { server.ratioRequests.count == 2 } + // 0.4 was never sent: only where the line is NOW matters. + XCTAssertEqual(server.ratioRequests.map { $0["ratio"] as? Double }, [0.3, 0.7]) + // The server names the split by a block on each side of it. + XCTAssertEqual(server.ratioRequests.last?["direction"] as? String, "horizontal") + XCTAssertEqual(server.ratioRequests.last?["before_block_id"] as? String, "block:side") + XCTAssertEqual(server.ratioRequests.last?["after_block_id"] as? String, "block:front") + // The view the server sent for 0.3 arrived while 0.7 was the tab's + // word; the tab — which moved its own line already — was told + // nothing, least of all to go back. + await eventually { server.calls.filter { $0 == "session.view" }.count >= 2 } + try await Task.sleep(for: .milliseconds(150)) + XCTAssertEqual(sink.arrangements.count, arrangedBefore) + + // A ratio somebody ELSE sets does arrive. + server.setRatio(0.25, ofSplit: "split:1") + await eventually { sink.arrangements.count == arrangedBefore + 1 } + XCTAssertEqual(sink.arrangements.last, PaneArrangement( + layout: .split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.25, + before: .pane(side), after: .pane(front))), + focus: nil)) + await session.close() + } + + func testANewTabIsMadeUnfocusedOnTheServerAndTheTabMovesToIt() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + try await session.perform(.newWindow(from: front)) + let made = PaneID("block:tab1") + await eventually { sink.text(made) == ["\u{1B}cSCREEN"] } + + // One shell, starting where the pane it was asked from is — and NOT + // the session's active window: that is the tab the Rex app shows. + let asked = try XCTUnwrap(server.windowRequests.first) + XCTAssertEqual(asked["focus"] as? Bool, false) + let block = (asked["layout"] as? [String: Any])?["block"] as? [String: Any] + XCTAssertEqual(block?["flavor"] as? String, "com.superlogical.terminal.shell") + XCTAssertEqual((block?["options"] as? [String: Any])?["cwd"] as? String, "/work/block:front") + + // The tab draws the new window now, the keyboard in its shell. + XCTAssertEqual( + sink.arrangements.last, PaneArrangement(layout: .pane(made), focus: made)) + XCTAssertEqual(server.claims.last, ["block:tab1"]) + // The window it left is let go like one left through Switch + // Terminal: its streams closed, its blocks given back. + XCTAssertEqual(server.closeFramesReceived, [RexWire.dataPath, RexWire.dataPath]) + XCTAssertTrue(server.calls.contains("session.disown_block block:front,block:side")) + // And is not the tab ending. + XCTAssertTrue(sink.closeReasons.isEmpty) + + // The way back is the switch list, which now has four terminals. + let listed = await session.terminalChoices() + XCTAssertEqual( + listed?.map(\.tmuxID), ["block:other", "block:side", "block:front", "block:tab1"]) + XCTAssertEqual(listed?.map(\.isActive), [false, false, false, true]) + await session.showTerminal("block:front") + await eventually { sink.arrangements.last?.focus == self.front } + XCTAssertEqual(sink.arrangements.last?.layout.panes, [side, front]) + await session.close() + } + + func testAServerThatRefusesASplitFailsTheCommandWithItsReason() async throws { + let server = FakeRexServer() + server.errors["session.new_split"] = [ + "code": "conflict", "message": "too many blocks in this window", "status": 409, + ] + let session = makeSession(server) + try await open(session, sink: Sink()) + do { + try await session.perform(.split(front, .sideBySide)) + XCTFail("the split should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, + "The Rex server refused: too many blocks in this window") + } + await session.close() + } + + // MARK: - The session's other terminals + + func testTheSwitchListNamesEveryTerminalAndMarksTheOneWithTheKeyboard() async throws { + let server = splitServer() + 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]) + // Two panes of one window with the same label are told apart. + XCTAssertEqual(choices.map(\.name), ["one — shell", "two — shell", "two — shell 2"]) + + // The keyboard moving to another pane moves the mark: the tab's + // focus is its own, and is not written to the server. + let callsBefore = server.calls.count + try await session.perform(.focus(side)) + XCTAssertEqual(server.calls.count, callsBefore) + let moved = await session.terminalChoices() + XCTAssertEqual(moved?.map(\.isActive), [false, true, false]) + await session.close() + } + + func testATerminalAmongThePanesOnShowOnlyTakesTheKeyboard() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let callsBefore = server.calls.count + + await session.showTerminal("block:side") + await eventually { sink.arrangements.last?.focus == self.side } + // The same panes, nothing opened or let go: one view read. + XCTAssertEqual(sink.arrangements.last?.layout, sink.arrangements.first?.layout) + XCTAssertEqual(Array(server.calls.dropFirst(callsBefore)), ["session.view"]) + await session.close() + } + + func testATerminalInAnotherWindowBringsThatWindowsPanesInWithoutEndingTheTab() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let attachCalls = server.calls.count + + server.screens["block:other"] = "OTHER" + await session.showTerminal("block:other") + await eventually { sink.text(self.other) == ["\u{1B}cOTHER"] } + + // The old streams were closed properly, the old blocks 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, RexWire.dataPath]) + let switchCalls = Array(server.calls.dropFirst(attachCalls)) + XCTAssertEqual(Array(switchCalls.prefix(5)), [ + "session.view", + "session.disown_block block:front,block:side", + "session.own_block", + "com.superlogical.terminal.resize 100x30", + "data.connect", + ]) + XCTAssertEqual(switchCalls.dropFirst(5).sorted(), Self.screenReads) + XCTAssertEqual(server.claims.last, ["block:other"]) + XCTAssertEqual( + sink.arrangements.last, PaneArrangement(layout: .pane(other), focus: other)) + // The retired streams 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", to: "block:other") + await eventually { sink.text(self.other).last == "from other\r\n" } + try await session.write(Data("x".utf8), to: other) + await eventually { + server.written == ["x"] + && server.calls.last == "com.superlogical.terminal.write" + } + XCTAssertEqual(server.lastWriteBlock, "block:other") + let listed = await session.terminalChoices() + XCTAssertEqual(listed?.map(\.isActive), [true, false, false]) + await session.close() + } + + func testTheWorkingDirectoryIsThePanesOwn() async throws { + let server = splitServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + let inFront = await session.workingDirectory(of: front) + XCTAssertEqual(inFront, "/work/block:front") + let inSide = await session.workingDirectory(of: side) + XCTAssertEqual(inSide, "/work/block:side") + // A pane the tab does not draw has no answer. + let elsewhere = await session.workingDirectory(of: other) + XCTAssertNil(elsewhere) + await session.close() + // Nor has a closed tab — the $HOME fallback. + let closed = await session.workingDirectory(of: front) + 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), to: front) + // A character split across two writes is sent whole. + let wide = Data("測".utf8) + try await session.write(wide.prefix(2), to: front) + try await session.write(wide.suffix(1), to: front) + try await session.write(Data([0x1B, 0x5B, 0x41]), to: front) + // 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(pane: front, 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.hold("com.superlogical.terminal.write") + try await session.write(Data("a".utf8), to: front) + await eventually { server.written == ["a"] } + // None of these waits for "a" to be answered... + try await session.write(Data("b".utf8), to: front) + try await session.write(Data("c".utf8), to: front) + try await session.write(Data("d".utf8), to: front) + XCTAssertEqual(server.written, ["a"]) + + // ...and once it is, they go as one call, not three round trips. + server.release() + await eventually { server.written == ["a", "bcd"] } + 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), to: front) + 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 + // re-sizes it — the last client to type owns the size. + server.announceOwner("client:rex-app", of: "block:front") + await eventually { server.eventsDelivered == 1 } + try await Task.sleep(for: .milliseconds(150)) + try await session.write(Data("b".utf8), to: front) + 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", + "com.superlogical.terminal.resize 100x30", + "com.superlogical.terminal.write", + ]) + await session.close() + } + + func testTypingInOnePaneClaimsEveryPaneAnotherClientHolds() async throws { + let server = splitServer() + let session = makeSession(server) + try await open(session, sink: Sink()) + + // The Rex app took both; a key in ONE pane here takes both back. + // The tab draws them as one window, and half of it at another + // client's size is a layout nobody chose. + server.announceOwner("client:rex-app", of: "block:front") + server.announceOwner("client:rex-app", of: "block:side") + await eventually { server.eventsDelivered == 2 } + try await Task.sleep(for: .milliseconds(150)) + try await session.write(Data("k".utf8), to: side) + await eventually { server.written == ["k"] } + XCTAssertEqual(server.claims.last, ["block:side", "block:front"]) + XCTAssertEqual(server.resizes.suffix(2).map(\.block), ["block:side", "block:front"]) + 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(front), ["\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(self.front).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(front), ["\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(self.front).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(self.front).last == "\u{1B}cOWN" } + XCTAssertEqual(Array(sink.text(front).suffix(2)), ["GRID own", "\u{1B}cOWN"]) + await session.close() + } + + func testOnePaneFollowingAnotherClientsSizeLeavesItsSiblingAlone() async throws { + let server = splitServer() + server.screens = ["block:side": "SIDE", "block:front": "FRONT"] + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + server.screens["block:side"] = "SIDE WIDE" + server.sendResize(cols: 170, rows: 50, owner: "client:rex-app", to: "block:side") + await eventually { sink.text(self.side).last == "\u{1B}cSIDE WIDE" } + XCTAssertEqual(sink.text(side), ["\u{1B}cSIDE", "GRID 170x50", "\u{1B}cSIDE WIDE"]) + XCTAssertEqual(sink.text(front), ["\u{1B}cFRONT"]) + 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(pane: front, 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(self.front).last == "after" } + try await Task.sleep(for: .milliseconds(400)) + + XCTAssertEqual(sink.text(front), ["\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(self.front).count == 2 } + try await Task.sleep(for: .milliseconds(300)) + + XCTAssertEqual(sink.text(front), ["\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.openingSizes["block:front"] = (170, 50, "client:rex-app") + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + XCTAssertEqual(sink.text(front), ["GRID 170x50", "\u{1B}cSCREEN"]) + 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(front), ["\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(self.front).last == "\u{1B}cHISTORY" } + // The exit burst passed through, then ONE redraw replaced it. + XCTAssertEqual( + sink.text(front), ["\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 testAClosedWindowsTabMovesToTheNextWindowAndTheLastOneEndsItCleanly() async throws { + let server = FakeRexServer() + server.screens["block:other"] = "OTHER" + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + let attachCalls = server.calls.count + + // The shell exits: its stream closes (4000), the block goes, and + // with it the window. The session has another, so the tab is not + // over: it draws that one, as Rex's own app shows the next tab + // when one is closed. + server.closeBlock("block:front") + await eventually { sink.text(self.other) == ["\u{1B}cOTHER"] } + XCTAssertEqual( + sink.arrangements.last, PaneArrangement(layout: .pane(other), focus: other)) + XCTAssertTrue(sink.closeReasons.isEmpty) + // Nobody's terminal is claimed and sized like one of an attach; a + // block that closed is not given up (one unknown id fails the call). + XCTAssertEqual(server.claims.last, ["block:other"]) + XCTAssertFalse(server.calls.dropFirst(attachCalls).contains { + $0.hasPrefix("session.disown_block") + }) + // The tab is live there. + try await session.write(Data("x".utf8), to: other) + await eventually { server.written == ["x"] } + XCTAssertEqual(server.lastWriteBlock, "block:other") + + // The last terminal of the session goes: nowhere is left. + server.closeBlock("block:other") + await eventually { !sink.closeReasons.isEmpty } + // 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 testAProgramExitingInOnePaneTakesOnlyThatPane() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + server.closeBlock("block:side") + await eventually { sink.arrangements.last?.layout == .pane(self.front) } + // The keyboard was on the other pane and stays there. + XCTAssertNil(sink.arrangements.last?.focus) + XCTAssertTrue(sink.closeReasons.isEmpty) + server.sendOutput("alive") + await eventually { sink.text(self.front).last == "alive" } + await session.close() + } + + func testClosingTheTabClosesEveryStreamBeforeTheControlConnection() async throws { + let server = splitServer() + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + await session.close() + + // Data first, with status 1000 (which ends each stream), then + // control. + XCTAssertEqual( + server.closeFramesReceived, + [RexWire.dataPath, 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 = splitServer() + 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), to: front) + XCTFail("a dead tab accepted input") + } catch {} + await session.close() + } + + // MARK: - Failing to attach + + func testASessionThatIsGoneFailsTheOpenWithAReadableReason() async { + let server = FakeRexServer() + server.errors["session.attach"] = [ + "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(front).isEmpty) + await session.close() + } + + func testASessionWithNoTerminalAndARefusedStreamBothFailTheOpen() async { + let empty = FakeRexServer() + empty.removeAllWindows() + 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.") + } + + // With no pane opened there is no tab to say it in: the open fails + // with the terminal's own reason. + let refusing = FakeRexServer() + refusing.rejectReasons = ["block:front": 0x02] + let sink = Sink() + 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) + } + XCTAssertTrue(sink.text(front).isEmpty) + } + + // MARK: - API revision + + func testTheServerSettlesOnTheNewestRevisionBothSidesSpeak() async throws { + let newest = FakeRexServer() + let current = makeSession(newest) + try await open(current, sink: Sink()) + XCTAssertEqual(newest.agreedRevision, RexWire.apiRevision) + await current.close() + + // An older server is spoken to at its own revision: nothing a tab + // sends or reads differs between the oldest it accepts and the + // newest it knows. + let older = FakeRexServer() + older.apiRevision = 19 + let session = makeSession(older) + let sink = Sink() + try await open(session, sink: sink) + XCTAssertEqual(older.agreedRevision, 19) + XCTAssertEqual(sink.text(front), ["\u{1B}cSCREEN"]) + await session.close() + } + + func testAServerTooOldToTalkToFailsTheOpenAndSaysToUpdateIt() async { + // One that negotiates closes the connection instead of welcoming, + // and its reason is the tab's. + let old = FakeRexServer() + old.apiRevision = RexWire.minimumAPIRevision - 1 + do { + try await open(makeSession(old), sink: Sink()) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, + "no common API revision: server speaks 0 to 13, client needs 14 to 24; " + + "update the server") + } + XCTAssertFalse(old.calls.contains("session.attach")) + + // One from before revisions were negotiated welcomes anyway, at a + // revision this client cannot read. + let ancient = FakeRexServer() + ancient.apiRevision = nil + do { + try await open(makeSession(ancient), sink: Sink()) + XCTFail("the open should have thrown") + } catch { + XCTAssertEqual( + (error as? RexSession.Failure)?.message, + "The Rex server on this host is older than Multiplex can talk to. " + + "Update Rex there.") + } + XCTAssertFalse(ancient.calls.contains("session.attach")) + } + + 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") + } + } + + func testAConnectionWithNoRoomForOnePanesPipeLeavesTheOtherPanesUp() async throws { + // sshd's MaxSessions: the control pipe and the first stream open, + // the third channel is refused. + let server = splitServer() + server.pipeLimit = 2 + let session = makeSession(server) + let sink = Sink() + try await open(session, sink: sink) + + let texts = [sink.text(side), sink.text(front)] + XCTAssertEqual(texts.filter { $0 == ["\u{1B}cSCREEN"] }.count, 1) + XCTAssertEqual( + texts.filter { + $0.first?.contains("Couldn't open this terminal. Couldn't reach the Rex server.") + == true + }.count, 1) + XCTAssertTrue(sink.closeReasons.isEmpty) + await session.close() + } +} + +// MARK: - The in-process server + +/// A Rex server small enough to read: it answers the upgrade, the hello, +/// and the methods a tab makes, keeps a real layout tree per window, and +/// streams what a test tells it to. One instance serves every pipe of a +/// session. +private final class FakeRexServer: @unchecked Sendable { + indirect enum Node { + case block(String) + case split(id: String, direction: String, ratio: Double, before: Node, after: Node) + + var blocks: [String] { + switch self { + case .block(let id): [id] + case .split(_, _, _, let before, let after): before.blocks + after.blocks + } + } + + func removing(_ block: String) -> Node? { + switch self { + case .block(let id): + return id == block ? nil : self + case .split(let id, let direction, let ratio, let before, let after): + guard let first = before.removing(block) else { return after.removing(block) } + guard let second = after.removing(block) else { return first } + return .split( + id: id, direction: direction, ratio: ratio, before: first, after: second) + } + } + + func splitting(_ anchor: String, direction: String, splitID: String, adding new: String) -> Node { + switch self { + case .block(let id): + guard id == anchor else { return self } + return .split( + id: splitID, direction: direction, ratio: 0.5, + before: self, after: .block(new)) + case .split(let id, let own, let ratio, let before, let after): + return .split( + id: id, direction: own, ratio: ratio, + before: before.splitting( + anchor, direction: direction, splitID: splitID, adding: new), + after: after.splitting( + anchor, direction: direction, splitID: splitID, adding: new)) + } + } + + func settingRatio(_ ratio: Double, where matches: (Node, Node, String, String) -> Bool) -> Node { + guard case .split(let id, let direction, let own, let before, let after) = self + else { return self } + if matches(before, after, direction, id) { + return .split(id: id, direction: direction, ratio: ratio, before: before, after: after) + } + return .split( + id: id, direction: direction, ratio: own, + before: before.settingRatio(ratio, where: matches), + after: after.settingRatio(ratio, where: matches)) + } + + func json(in rect: [Double]) -> [String: Any] { + switch self { + case .block(let id): + return ["rect": rect, "block_id": id] + case .split(let id, let direction, let ratio, let before, let after): + return ["rect": rect, "split": [ + "split_id": id, "direction": direction, "ratio": ratio, + "before": before.json(in: rect), "after": after.json(in: rect), + ] as [String: Any]] + } + } + } + + private struct Window { + var id: String + var label: String + var focused: String? + var tree: Node? + } + + private let lock = NSLock() + private var windows = [ + Window(id: "window:1", label: "one", focused: "block:other", tree: .block("block:other")), + Window(id: "window:2", label: "two", focused: "block:front", tree: .block("block:front")), + ] + private var revision = 1 + private var recordedCalls: [String] = [] + private var recordedWrites: [String] = [] + private var recordedNotes: [String] = [] + private var recordedCloses: [String] = [] + private var recordedClaims: [[String]] = [] + private var recordedResizes: [(block: String, cols: Int, rows: Int)] = [] + private var recordedSplits: [[String: Any]] = [] + private var recordedWindows: [[String: Any]] = [] + private var recordedRatios: [[String: Any]] = [] + private var kind: String? + private var writeBlock: String? + private var events = 0 + private var pipes = 0 + private var created = 0 + private var owners: [String: String] = [:] + private var tickets: [String] = [] + private var controlFeed: AsyncThrowingStream.Continuation? + private var dataFeeds: [String: AsyncThrowingStream.Continuation] = [:] + /// The method whose answers a test is sitting on, and the answers. + private var heldMethod: String? + private var heldReplies: [() -> Void] = [] + + // What a test configures before the attach. + var errors: [String: [String: Any]] = [:] + var rejectReasons: [String: UInt8] = [:] + var earlyOutput = "" + var screen = "SCREEN" + var screens: [String: String] = [:] + var screenKind = "primary" + /// The size a block's stream opens by stating, and whose it is. + var openingSizes: [String: (cols: Int, rows: Int, owner: String)] = [:] + /// How many pipes may open; the next one is refused, as sshd refuses a + /// channel past `MaxSessions`. + var pipeLimit = Int.max + /// The newest API revision this server speaks. nil is a server from + /// before revisions were negotiated: its welcome names none. + var apiRevision: Int? = RexWire.apiRevision + private var agreed: Int? + 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 claims: [[String]] { lock.withLock { recordedClaims } } + var resizes: [(block: String, cols: Int, rows: Int)] { lock.withLock { recordedResizes } } + var splitRequests: [[String: Any]] { lock.withLock { recordedSplits } } + var windowRequests: [[String: Any]] { lock.withLock { recordedWindows } } + var ratioRequests: [[String: Any]] { lock.withLock { recordedRatios } } + var helloKind: String? { lock.withLock { kind } } + /// The revision the welcome settled on. + var agreedRevision: Int? { lock.withLock { agreed } } + var lastWriteBlock: String? { lock.withLock { writeBlock } } + var eventsDelivered: Int { lock.withLock { events } } + + func note(_ text: String) { lock.withLock { recordedNotes.append(text) } } + + func setWindow(_ id: String, tree: Node) { + lock.withLock { + guard let index = windows.firstIndex(where: { $0.id == id }) else { return } + windows[index].tree = tree + } + } + + func removeAllWindows() { + lock.withLock { windows = [] } + } + + func makePipe() throws -> RemotePipe { + let refused = lock.withLock { + pipes += 1 + return pipes > pipeLimit + } + if refused { + throw SSHConnectionError.connectFailed("channel open failed: administratively prohibited") + } + 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 a stream from a test + + func sendOutput(_ text: String, to block: String = "block:front") { + lock.withLock { dataFeeds[block] }?.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, to block: String = "block:front") { + lock.withLock { dataFeeds[block] }?.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, of block: String = "block:front") { + let feed = lock.withLock { dataFeeds[block] } + feed?.yield(Self.closeFrame(code: code, reason: reason)) + feed?.finish() + } + + /// Every pipe fails at once, as when the SSH connection under them dies. + func dropLinks(_ error: Error) { + let feeds = lock.withLock { [controlFeed] + Array(dataFeeds.values) } + feeds.forEach { $0?.finish(throwing: error) } + } + + /// Calls to `method` are recorded as they arrive but go unanswered + /// until `release` — a link slow enough to act ahead of. + func hold(_ method: String) { + lock.withLock { heldMethod = method } + } + + func release() { + let held = lock.withLock { + defer { + heldMethod = nil + heldReplies = [] + } + return heldReplies + } + held.forEach { $0() } + } + + // MARK: Changing the session from a test, as another client would + + func announceOwner(_ owner: String, of block: String) { + lock.withLock { owners[block] = owner } + sendEvent("block_owner_changed", ["block_id": block, "owner": owner]) + lock.withLock { events += 1 } + } + + /// A program exits: its stream closes, its block goes, and — if it was + /// the last — its window with it. + func closeBlock(_ block: String) { + let revision = lock.withLock { () -> Int in + for index in windows.indices { + windows[index].tree = windows[index].tree?.removing(block) + if windows[index].focused == block { + windows[index].focused = windows[index].tree?.blocks.first + } + } + windows.removeAll { $0.tree == nil } + self.revision += 1 + return self.revision + } + closeData(code: 4000, reason: "block closed", of: block) + sendEvent("block_closed", ["block_id": block]) + sendEvent("session_view_changed", ["revision": revision]) + } + + /// Another client splits `anchor`, side by side. + func addBlock(_ block: String, beside anchor: String, owner: String) { + let revision = lock.withLock { () -> Int in + for index in windows.indices { + windows[index].tree = windows[index].tree?.splitting( + anchor, direction: "horizontal", splitID: "split:added", adding: block) + } + owners[block] = owner + self.revision += 1 + return self.revision + } + sendEvent("block_created", ["block_id": block]) + sendEvent("block_owner_changed", ["block_id": block, "owner": owner]) + sendEvent("session_view_changed", ["revision": revision]) + } + + func setRatio(_ ratio: Double, ofSplit splitID: String) { + let revision = lock.withLock { () -> Int in + for index in windows.indices { + windows[index].tree = windows[index].tree?.settingRatio(ratio) { _, _, _, id in + id == splitID + } + } + self.revision += 1 + return self.revision + } + sendEvent("session_view_changed", ["revision": revision]) + } + + private func sendEvent(_ type: String, _ payload: [String: Any]) { + let event: [String: Any] = [ + "type": "event", "seq": 9, + "payload": [ + "type": "session_event", + "payload": [ + "session_id": "session:0000-aaaaaa", + "event": ["type": type, "payload": payload], + ], + ], + ] + lock.withLock { controlFeed }?.yield(Self.frame(0x1, Self.json(event))) + } + + // 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 + } + + /// A server's close: the status, then why. + static func closeFrame(code: UInt16, reason: String) -> Data { + frame(0x8, Data([UInt8(code >> 8), UInt8(code & 0xFF)]) + Data(reason.utf8)) + } + + 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 } + } + 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 } + var welcome: [String: Any] = [ + "type": "welcome", "protocol": RexWire.controlSubprotocol, + "client": ["id": server.clientID], + ] + // A real server's rule: the newest revision both sides + // speak, or no welcome at all. + if let newest = server.apiRevision { + let asked = message["api_revision"] as? Int ?? 0 + let oldest = message["api_min_revision"] as? Int ?? 0 + guard newest >= oldest else { + let reason = "no common API revision: server speaks 0 to \(newest), " + + "client needs \(oldest) to \(asked); update the server" + feed.yield(FakeRexServer.closeFrame(code: 1008, reason: reason)) + feed.finish() + return + } + let agreed = min(asked, newest) + server.lock.withLock { server.agreed = agreed } + welcome["api_revision"] = agreed + welcome["api_server_revision"] = newest + } + send(welcome) + 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] ?? [:] + let block = payload["block_id"] as? String ?? "" + var record = method + var result: [String: Any] = [:] + var error = server.errors[method] + var after: (() -> Void)? + switch method { + case "session.attach": + result = ["client_id": server.clientID, "view": view()] + case "session.own_block": + let ids = payload["block_ids"] as? [String] ?? [] + server.lock.withLock { + server.recordedClaims.append(ids) + for id in ids { server.owners[id] = server.clientID } + } + result = ["blocks": ids.map { ["block_id": $0, "owner": server.clientID] }] + case "session.disown_block": + let ids = payload["block_ids"] as? [String] ?? [] + record += " " + ids.sorted().joined(separator: ",") + result = ["blocks": ids.map { ["block_id": $0] }] + case "session.view": + result = view() + case "session.new_split" where error == nil: + server.lock.withLock { server.recordedSplits.append(payload) } + let (new, split, revision) = server.lock.withLock { () -> (String, String, Int) in + server.created += 1 + let new = "block:new\(server.created)" + let split = "split:new\(server.created)" + let anchor = payload["anchor_id"] as? String ?? "" + for index in server.windows.indices { + server.windows[index].tree = server.windows[index].tree?.splitting( + anchor, direction: payload["direction"] as? String ?? "", + splitID: split, adding: new) + } + // A block's maker owns it from the start. + server.owners[new] = server.clientID + server.revision += 1 + return (new, split, server.revision) + } + result = [ + "anchor_id": payload["anchor_id"] ?? "", "block_ids": [new], + "split_ids": [split], "revision": revision, + ] + after = { [server] in + server.sendEvent("block_created", ["block_id": new]) + server.sendEvent("session_view_changed", ["revision": revision]) + } + case "session.new_window" where error == nil: + let (window, new, revision) = server.lock.withLock { () -> (String, String, Int) in + server.recordedWindows.append(payload) + server.created += 1 + let window = "window:new\(server.created)" + let new = "block:tab\(server.created)" + server.windows.append(Window( + id: window, label: "three", focused: new, tree: .block(new))) + server.owners[new] = server.clientID + server.revision += 1 + return (window, new, server.revision) + } + result = ["window_id": window, "block_ids": [new], "revision": revision] + after = { [server] in + server.sendEvent("window_created", ["window_id": window, "label": "three"]) + server.sendEvent("session_view_changed", ["revision": revision]) + } + case "session.resize_pane": + server.lock.withLock { server.recordedRatios.append(payload) } + let before = payload["before_block_id"] as? String ?? "" + let behind = payload["after_block_id"] as? String ?? "" + let direction = payload["direction"] as? String ?? "" + let ratio = (payload["ratio"] as? NSNumber)?.doubleValue ?? 0.5 + let revision = server.lock.withLock { () -> Int in + for index in server.windows.indices { + server.windows[index].tree = server.windows[index].tree? + .settingRatio(ratio) { first, second, own, _ in + own == direction && first.blocks.contains(before) + && second.blocks.contains(behind) + } + } + server.revision += 1 + return server.revision + } + result = ["revision": revision] + after = { [server] in + server.sendEvent("session_view_changed", ["revision": revision]) + } + case "block.close": + record += " " + block + result = [ + "block_id": block, + "revision": server.lock.withLock { server.revision + 1 }, + ] + after = { [server] in server.closeBlock(block) } + case "com.superlogical.terminal.process": + result = ["foreground": ["cwd": "/work/\(block)"], "child": ["cwd": "/home"]] + case "com.superlogical.terminal.resize": + let cols = args["columns"] as? Int ?? 0, rows = args["rows"] as? Int ?? 0 + record += " \(cols)x\(rows)" + server.lock.withLock { server.recordedResizes.append((block, cols, rows)) } + case "data.connect": + let ticket = server.lock.withLock { () -> String in + server.tickets.append(block) + var bytes = [UInt8](repeating: 0, count: 16) + bytes[15] = UInt8(server.tickets.count) + return Data(bytes).base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + result = ["ticket": ticket, "expires_in_ms": 60_000] + case "com.superlogical.terminal.modes": + result = ["screen": server.screenKind] + case "com.superlogical.terminal.format": + result = ["content": server.screens[block] ?? server.screen] + case "com.superlogical.terminal.write": + let text = args["data"] as? String ?? "" + server.lock.withLock { + server.recordedWrites.append(text) + server.writeBlock = block + } + result = ["bytes_written": text.utf8.count] + default: + if error == nil { + 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 } + let reply = response + let answer = { [self] in + send(reply) + after?() + } + let isHeld = server.lock.withLock { + guard server.heldMethod == method else { return false } + server.heldReplies.append(answer) + return true + } + if !isHeld { answer() } + } + + private func view() -> [String: Any] { + server.lock.withLock { + func block(_ id: String) -> [String: Any] { + var block: [String: Any] = [ + "block_id": id, "label": "shell", + "creator_name": RexWire.terminalCreator, + ] + if let owner = server.owners[id] { block["owner"] = owner } + return block + } + return [ + "revision": server.revision, + "active_window_id": "window:2", + "windows": server.windows.map { window -> [String: Any] in + [ + "window_id": window.id, "label": window.label, + "focused_block_id": window.focused ?? "", + "layers": [[ + "layer_id": "layer:" + window.id, "kind": "tiled", + "layout": window.tree?.json(in: [0, 0, 1, 1]) ?? NSNull(), + "blocks": (window.tree?.blocks ?? []).map(block), + ] as [String: Any]], + ] + }, + ] + } + } + + private func dataHello(_ bytes: Data) { + guard bytes.first == 0x01, bytes.count == 17 else { return } + let index = Int(bytes[bytes.startIndex + 16]) + let block = server.lock.withLock { + server.tickets.indices.contains(index - 1) ? server.tickets[index - 1] : "" + } + if let reason = server.rejectReasons[block] { + feed.yield(FakeRexServer.frame(0x2, Data([0x82, reason]))) + feed.yield(FakeRexServer.closeFrame( + code: 1008, reason: "data handshake rejected")) + feed.finish() + return + } + server.lock.withLock { server.dataFeeds[block] = feed } + 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 opening = server.openingSizes[block] ?? (100, 30, server.clientID) + feed.yield(FakeRexServer.frame( + 0x2, + Data("GHOSTSNP\u{1}\u{0}binary snapshot".utf8) + + Data(FakeRexServer.resizeMessage( + nonce: server.nonce, cols: opening.cols, rows: opening.rows, + owner: opening.owner).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..9495208e --- /dev/null +++ b/MultiplexTests/RexWireTests.swift @@ -0,0 +1,787 @@ +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. A second recording, +/// off preview.25, has its own test. +final class RexWireTests: XCTestCase { + private let nonce: UInt64 = 4_078_407_816_757_279_798 + + private func streamFixture(_ name: String = "rex-terminal-stream-preview19") throws -> Data { + let url = try XCTUnwrap( + Bundle(for: RexWireFixtureAnchor.self).url(forResource: name, 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 testTheHelloStatesItsRevisionRangeAndStaysSmall() 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") + // The newest revision this client was read against, and the oldest + // whose shapes are the same: the server picks between them. + XCTAssertEqual(object["api_revision"] as? Int, 24) + XCTAssertEqual(object["api_min_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, let revision)? = decode(""" + {"type":"welcome","protocol":"rex.control.v1","limits":{"max_message_bytes":1048576},\ + "client":{"id":"client:01a1e1d4-754f","reconnect_token":"CARtI14i"},\ + "api_revision":24,"api_server_revision":24} + """) + else { return XCTFail("welcome") } + XCTAssertEqual(clientID, "client:01a1e1d4-754f") + XCTAssertEqual(revision, 24) + // A welcome that names no revision speaks revision 0. + guard case .welcome(_, let unnamed)? = decode( + #"{"type":"welcome","protocol":"rex.control.v1"}"#) + else { return XCTFail("welcome without a revision") } + XCTAssertEqual(unnamed, 0) + // 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]) + } + + // MARK: - The panes a tab draws + + /// A window as measured on preview.23 (revision 14 shapes): `a | (b / c)` + /// in its tiled layer with a non-terminal block beside `c`, and a + /// floating layer holding one more terminal. + private func layeredView() throws -> [String: Any] { + let json = """ + {"revision": 7, "active_window_id": "window:1", "windows": [ + {"window_id": "window:1", "label": "editor", "focused_block_id": "block:b", + "layers": [ + {"layer_id": "layer:tiled", "kind": "tiled", "bounds": [0, 0, 1, 1], + "layout": {"rect": [0, 0, 1, 1], "split": { + "split_id": "split:outer", "direction": "horizontal", "ratio": 0.3, + "before": {"rect": [0, 0, 0.3, 1], "block_id": "block:a"}, + "after": {"rect": [0.3, 0, 0.7, 1], "split": { + "split_id": "split:inner", "direction": "vertical", "ratio": 0.7, + "before": {"rect": [0.3, 0, 0.7, 0.7], "block_id": "block:b"}, + "after": {"rect": [0.3, 0.7, 0.7, 0.3], "split": { + "split_id": "split:mixed", "direction": "sideways", "ratio": 0.5, + "before": {"rect": [0.3, 0.7, 0.35, 0.3], "block_id": "block:c"}, + "after": {"rect": [0.65, 0.7, 0.35, 0.3], "block_id": "block:tunnel"}}}}}}}, + "blocks": [ + {"block_id": "block:a", "label": "shell", + "creator_name": "com.superlogical.terminal", "owner": "client:me"}, + {"block_id": "block:b", "label": "logs", + "creator_name": "com.superlogical.terminal", "owner": "client:app"}, + {"block_id": "block:c", "label": "repl", + "creator_name": "com.superlogical.terminal"}, + {"block_id": "block:tunnel", "creator_name": "com.example.tunnel"}]}, + {"layer_id": "layer:float", "kind": "floating", "bounds": [0.2, 0.2, 0.6, 0.6], + "layout": {"rect": [0.2, 0.2, 0.6, 0.6], "block_id": "block:f"}, + "blocks": [{"block_id": "block:f", "label": "scratch", + "creator_name": "com.superlogical.terminal"}]}]}, + {"window_id": "window:2", "label": "old", + "layers": [{"layer_id": "layer:bare", + "blocks": [{"block_id": "block:x", + "creator_name": "com.superlogical.terminal"}, + {"block_id": "block:y", + "creator_name": "com.superlogical.terminal"}]}]}]} + """ + return try XCTUnwrap( + JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any]) + } + + func testALayerBecomesThePaneTreeOfItsTerminals() throws { + let layer = try XCTUnwrap(RexWire.layer(holding: "block:c", inView: try layeredView())) + XCTAssertEqual(layer.windowID, "window:1") + XCTAssertEqual(layer.layerID, "layer:tiled") + // `horizontal` is side by side, `vertical` stacked. The block that + // is not a terminal is cut out and `c` has its split's room — which + // takes the split with the direction nobody knows away with it. + XCTAssertEqual(layer.layout, .split(PaneLayout.Split( + id: "split:outer", axis: .sideBySide, ratio: 0.3, + before: .pane(PaneID("block:a")), + after: .split(PaneLayout.Split( + id: "split:inner", axis: .stacked, ratio: 0.7, + before: .pane(PaneID("block:b")), after: .pane(PaneID("block:c"))))))) + XCTAssertEqual(layer.focusedBlockID, "block:b") + // Each block says whose size it follows. + XCTAssertEqual( + RexWire.terminalBlocks(inView: try layeredView()).prefix(3).map(\.owner), + ["client:me", "client:app", nil]) + } + + func testAFloatingLayerIsALayerOfItsOwnAndTheWindowsFocusIsNotItsOwn() throws { + let view = try layeredView() + let floating = try XCTUnwrap(RexWire.layer(holding: "block:f", inView: view)) + XCTAssertEqual(floating.layerID, "layer:float") + XCTAssertEqual(floating.layout, .pane(PaneID("block:f"))) + // The window is focused on a block of its other layer. + XCTAssertNil(floating.focusedBlockID) + // A tab keeps drawing the layer it was on, by window and layer. + XCTAssertEqual( + RexWire.layer( + windowID: "window:1", layerID: "layer:float", preferring: nil, inView: view), + floating) + XCTAssertNil(RexWire.layer( + windowID: "window:1", layerID: "layer:gone", preferring: nil, inView: view)) + // A block nobody shows as a terminal names no layer. + XCTAssertNil(RexWire.layer(holding: "block:tunnel", inView: view)) + XCTAssertNil(RexWire.layer(holding: "block:gone", inView: view)) + } + + // MARK: - Where a tab goes when its window closes + + /// Windows in tab order, each one shell — or, named in `bare`, a block + /// that is not a terminal. + private func windows(_ ids: [String], bare: Set = []) -> [String: Any] { + ["windows": ids.map { id -> [String: Any] in + let block = "block:" + id + return [ + "window_id": "window:" + id, "focused_block_id": block, + "layers": [[ + "layer_id": "layer:" + id, + "layout": ["block_id": block], + "blocks": [[ + "block_id": block, + "creator_name": bare.contains(id) + ? "com.superlogical.tunnel" : RexWire.terminalCreator, + ]], + ]], + ] + }] + } + + func testAClosedWindowsTabGoesToTheWindowAfterItOrTheOneBeforeIfItWasLast() { + let order = ["window:a", "window:b", "window:c", "window:d"] + XCTAssertEqual(RexWire.windowOrder(inView: windows(["a", "b", "c", "d"])), order) + func next(after closed: String, _ left: [String], bare: Set = []) -> String? { + RexWire.layer( + replacing: "window:" + closed, among: order, + inView: windows(left, bare: bare))?.windowID + } + // Rex's own rule for a closed window: the one after it, or the one + // before it if it was last. + XCTAssertEqual(next(after: "b", ["a", "c", "d"]), "window:c") + XCTAssertEqual(next(after: "d", ["a", "b", "c"]), "window:c") + XCTAssertEqual(next(after: "a", ["b", "c", "d"]), "window:b") + // A window with no terminal is not somewhere a tab can go: the walk + // passes it, forward first and then back, nearest first. + XCTAssertEqual(next(after: "b", ["a", "c", "d"], bare: ["c"]), "window:d") + XCTAssertEqual(next(after: "c", ["a", "b", "d"], bare: ["d"]), "window:b") + // One made since the order was read is in neither walk, and still + // beats ending a tab whose session has a terminal. + XCTAssertEqual(next(after: "a", ["new"]), "window:new") + XCTAssertEqual(next(after: "never-seen", ["a", "b"]), "window:b") + // Nothing left to draw is the one case with no answer. + XCTAssertNil(next(after: "a", [])) + XCTAssertNil(next(after: "a", ["b"], bare: ["b"])) + } + + func testAWindowThatOnlyLostTheLayerATabDrewKeepsTheTab() throws { + // The floating layer a tab drew has closed; its window is still + // there, and the tab stays in it — on the layer the window's + // focused block is in. + var view = try layeredView() + var all = try XCTUnwrap(view["windows"] as? [[String: Any]]) + var layers = try XCTUnwrap(all[0]["layers"] as? [[String: Any]]) + layers.removeLast() + all[0]["layers"] = layers + view["windows"] = all + let kept = try XCTUnwrap(RexWire.layer( + replacing: "window:1", among: ["window:1", "window:2"], inView: view)) + XCTAssertEqual(kept.windowID, "window:1") + XCTAssertEqual(kept.layerID, "layer:tiled") + XCTAssertEqual(kept.focusedBlockID, "block:b") + } + + func testALayerThatStatesNoLayoutIsOneOfItsTerminalsAlone() throws { + let view = try layeredView() + // The one asked for, not an arrangement invented here. + XCTAssertEqual( + RexWire.layer(holding: "block:y", inView: view)?.layout, .pane(PaneID("block:y"))) + XCTAssertEqual( + RexWire.layer( + windowID: "window:2", layerID: "layer:bare", preferring: nil, inView: view + )?.layout, + .pane(PaneID("block:x"))) + } + + func testLayoutRequestsNameWhatTheServerNeeds() throws { + let split = RexWire.newSplitPayload( + sessionID: "session:1", anchorID: "block:a", axis: .stacked, cwd: "/work") + XCTAssertEqual(split["anchor_id"] as? String, "block:a") + XCTAssertEqual(split["direction"] as? String, "vertical") + XCTAssertEqual(split["side"] as? String, "after") + // Never focused on the server: that would also front the window. + XCTAssertEqual(split["focus"] as? Bool, false) + let block = (split["layout"] as? [String: Any])?["block"] as? [String: Any] + XCTAssertEqual(block?["flavor"] as? String, "com.superlogical.terminal.shell") + XCTAssertEqual((block?["options"] as? [String: Any])?["cwd"] as? String, "/work") + // No directory known: none is sent, and the server starts in $HOME. + let bare = RexWire.newSplitPayload( + sessionID: "session:1", anchorID: "block:a", axis: .sideBySide, cwd: nil) + XCTAssertEqual(bare["direction"] as? String, "horizontal") + XCTAssertNil(((bare["layout"] as? [String: Any])?["block"] as? [String: Any])?["options"]) + + // A new tab is a window with one shell — and never the active one. + let window = RexWire.newWindowPayload(sessionID: "session:1", cwd: "/work") + XCTAssertEqual(window["focus"] as? Bool, false) + let shell = (window["layout"] as? [String: Any])?["block"] as? [String: Any] + XCTAssertEqual(shell?["flavor"] as? String, "com.superlogical.terminal.shell") + XCTAssertEqual((shell?["options"] as? [String: Any])?["cwd"] as? String, "/work") + XCTAssertNil(window["window_label"]) + + // A split is named by a block on each side of it: the first of each. + let layer = try XCTUnwrap(RexWire.layer(holding: "block:a", inView: try layeredView())) + let outer = try XCTUnwrap(layer.layout.split(withID: "split:outer")) + let resize = RexWire.resizePanePayload(sessionID: "session:1", split: outer, ratio: 0.4) + XCTAssertEqual(resize["direction"] as? String, "horizontal") + XCTAssertEqual(resize["before_block_id"] as? String, "block:a") + XCTAssertEqual(resize["after_block_id"] as? String, "block:b") + XCTAssertEqual(resize["ratio"] as? Double, 0.4) + } + + 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]) + + // A window split three ways is three shells called `shell`. The tab + // draws all three, so the rows are counted in the order the panes + // are in — and a same-named terminal of ANOTHER window is its own. + func shell(_ id: String, window: String, at position: Int) -> RexWire.Block { + RexWire.Block( + id: id, label: "Shell", windowID: "window:" + window, windowLabel: window, + windowPosition: position, isFocused: false, isFronted: false) + } + let split = RexWire.terminalChoices( + in: [ + shell("block:1", window: "api", at: 1), shell("block:2", window: "api", at: 1), + shell("block:3", window: "web", at: 2), shell("block:4", window: "API", at: 1), + ], + showing: "block:2") + XCTAssertEqual( + split.map(\.name), + ["api — Shell", "api — Shell 2", "web — Shell", "API — Shell 3"]) + XCTAssertEqual(split.map(\.isActive), [false, true, 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: - 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] { + [ + .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) + } + + /// 1558 bytes off a Rex 0.1.0-preview.25 data connection (API revision + /// 24, 2026-11-27): the stream still opens with a Ghostty snapshot + /// whose length nothing states, and the first `resize` still ends it. + func testTheNewestServersStreamOpensTheSameWay() throws { + let fixture = try streamFixture("rex-terminal-stream-preview25") + XCTAssertEqual(String(decoding: fixture.prefix(8), as: UTF8.self), "GHOSTSNP") + let owner = "client:01a21b89-9478-7a29-995c-6da52ce05171" + var stream = RexTerminalStream(nonce: 12_387_399_168_064_344_086) + // A `resize` now states the cell size in pixels too; a field this + // client has no use for is skipped. + XCTAssertEqual(stream.consume(fixture), [ + .resize(cols: 80, rows: 24, owner: owner), + .output(Data("tick 8\r\ntick 9\r\n".utf8)), + .resize(cols: 100, rows: 30, owner: owner), + .output(Data("tick 10\r\ntick 11\r\n".utf8)), + ]) + 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.. 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/MultiplexTests/TerminalKeyBarUIKitTests.swift b/MultiplexTests/TerminalKeyBarUIKitTests.swift index 4dccb3ea..68d5fe2d 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/TerminalPaneSplitUIKitTests.swift b/MultiplexTests/TerminalPaneSplitUIKitTests.swift new file mode 100644 index 00000000..3fa7dbf7 --- /dev/null +++ b/MultiplexTests/TerminalPaneSplitUIKitTests.swift @@ -0,0 +1,586 @@ +import SwiftTerm +import UIKit +import XCTest +@testable import Multiplex + +/// A paned tab from the transport's events up: the real controller, the +/// real surface and split view, over a transport that only records. What a +/// backend says about its panes has to become emulators on screen, and what +/// a person does to them has to reach the right pane, in order. +@MainActor +final class TerminalPaneSplitUIKitTests: XCTestCase { + private let left = PaneID("block:left") + private let right = PaneID("block:right") + private let below = PaneID("block:below") + + private var sideBySide: PaneLayout { + .split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.5, + before: .pane(left), after: .pane(right))) + } + + /// A paned transport that records what it is asked. + private actor Transport: PanedTerminalTransport { + private(set) var written: [String] = [] + private(set) var resized: [PaneID: TerminalGrid] = [:] + private(set) var commands: [PaneCommand] = [] + private(set) var isClosed = false + var failure: Error? + + func fail(with error: Error?) { failure = error } + + func write(_ data: Data, to pane: PaneID) async throws { + written.append("\(pane.rawValue):\(String(decoding: data, as: UTF8.self))") + } + + func resize(pane: PaneID, cols: Int, rows: Int) async throws { + resized[pane] = TerminalGrid(cols: cols, rows: rows) + } + + func perform(_ command: PaneCommand) async throws { + commands.append(command) + if let failure { throw failure } + } + + func close() async { isClosed = true } + } + + /// One live paned tab in a window: the pieces a test pokes at. + private struct Tab { + var controller: TerminalSessionController + var pane: TerminalPaneViewController + var transport: Transport + var events: PaneEvents + var window: UIWindow + /// The grids the tab answered the first arrangement with. + var measured: [PaneID: TerminalGrid] + + @MainActor var split: PaneSplitView { + get throws { try XCTUnwrap(pane.terminalSurface?.paneSplitView) } + } + } + + private func eventually( + _ condition: () async -> Bool, file: StaticString = #filePath, line: UInt = #line + ) async { + for _ in 0..<200 { + if await condition() { return } + try? await Task.sleep(for: .milliseconds(10)) + } + XCTFail("condition never held", file: file, line: line) + } + + private func makeTab(_ arrangement: PaneArrangement) async throws -> Tab { + TerminalFocusArbiter.inputSuppressed = false + let host = Host(name: "devbox", hostname: "127.0.0.1", username: "tester") + let controller = TerminalSessionController( + route: TerminalRoute( + hostID: host.id, + mode: .rexAttach(sessionName: "work", sessionID: "session:0000-aaaa")), + host: host) + let (pane, window) = mount(controller) + + let transport = Transport() + var handed: PaneEvents? + var measured: [PaneID: TerminalGrid] = [:] + await controller.runPanesForTesting(over: transport) { events in + handed = events + measured = await events.arrange(arrangement) + } + return Tab( + controller: controller, pane: pane, transport: transport, + events: try XCTUnwrap(handed), window: window, measured: measured) + } + + private func configuration(_ controller: TerminalSessionController) -> TerminalPaneConfiguration { + TerminalPaneConfiguration( + controller: controller, hostExists: true, fontSize: 14, theme: .tally, + bottomChromeHeight: 0, contentSafeArea: .zero, keyRailSafeArea: .zero, + railOwnsBottomSafeArea: false, isActive: true, focusAllowed: true, + close: {}) + } + + /// The tab's pane in a window of its own, laid out. + private func mount( + _ controller: TerminalSessionController + ) -> (TerminalPaneViewController, UIWindow) { + let pane = TerminalPaneViewController(configuration: configuration(controller)) + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 900, height: 600)) + window.rootViewController = pane + window.isHidden = false + pane.view.layoutIfNeeded() + return (pane, window) + } + + // MARK: - Arrangement + + func testAPanedTabStartsWithNoEmulatorAndGetsOnePerPaneFromItsTransport() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + + XCTAssertTrue(tab.controller.drawsPanes) + XCTAssertNil(tab.controller.soleScreen) + XCTAssertEqual(tab.controller.status, .live) + XCTAssertEqual(tab.controller.screens.map(\.paneID), [left, right]) + XCTAssertEqual(split.cells.map(\.screen.paneID), [left, right]) + + // Side by side, the gap's width apart, and laid out BEFORE the + // transport got its answer: each pane's grid is the one its own + // emulator measured, which is what its terminal is opened at. + let first = split.cells[0].frame, second = split.cells[1].frame + XCTAssertEqual(first.minX, 0) + XCTAssertEqual(second.minX - first.maxX, PaneSplitView.gap) + XCTAssertEqual(second.maxX, split.bounds.maxX) + XCTAssertEqual(first.width, second.width, accuracy: 1) + let leftGrid = try XCTUnwrap(tab.measured[left]) + let rightGrid = try XCTUnwrap(tab.measured[right]) + XCTAssertGreaterThan(leftGrid.cols, 20) + XCTAssertEqual(leftGrid.cols, rightGrid.cols, accuracy: 1) + XCTAssertEqual(leftGrid.cols, split.cells[0].terminalView.terminalDimensions.cols) + XCTAssertEqual(leftGrid.rows, split.cells[0].terminalView.terminalDimensions.rows) + + // The keyboard is where the transport said, and "the terminal" of + // the tab is that pane's emulator. + XCTAssertEqual(tab.controller.activePaneID, right) + XCTAssertTrue(tab.controller.terminalView === split.cells[1].terminalView) + XCTAssertEqual(tab.controller.rexBlockID, "block:right") + // A line between the two, and a frame around the focused one. + XCTAssertEqual(views(ofType: PaneDividerView.self, in: split).count, 1) + tab.window.isHidden = true + } + + func testASinglePaneDrawsNoLineAndFillsTheSurface() async throws { + let tab = try await makeTab(PaneArrangement(layout: .pane(left), focus: left)) + let split = try tab.split + XCTAssertEqual(split.cells.count, 1) + XCTAssertEqual(split.cells[0].frame, split.bounds) + XCTAssertTrue(views(ofType: PaneDividerView.self, in: split).isEmpty) + tab.window.isHidden = true + } + + func testOutputAndInputEachReachTheirOwnPane() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + + tab.events.output(right, Data("for the right pane".utf8)) + await eventually { + split.cells[1].screen.snapshot().lines.first?.contains("for the right pane") == true + } + XCTAssertFalse( + split.cells[0].screen.snapshot().lines.contains { $0.contains("for the right pane") }) + + // What an emulator sends is its own pane's; what the chrome sends + // goes to the pane the keyboard is on. + split.cells[1].terminalView.send(txt: "r") + tab.controller.sendInput(Data("k".utf8)) + await eventually { + await Set(tab.transport.written) == ["block:right:r", "block:left:k"] + } + tab.window.isHidden = true + } + + // MARK: - Focus + + func testFocusMovesTheTabsTerminalAndTellsTheTransport() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + XCTAssertTrue(tab.controller.terminalView === split.cells[0].terminalView) + + tab.controller.focusPane(right) + XCTAssertEqual(tab.controller.activePaneID, right) + XCTAssertTrue(tab.controller.terminalView === split.cells[1].terminalView) + XCTAssertEqual(tab.controller.rexBlockID, "block:right") + await eventually { await tab.transport.commands.last == .focus(self.right) } + // The chrome's input follows. + tab.controller.sendInput(Data("k".utf8)) + await eventually { await tab.transport.written == ["block:right:k"] } + + // The transport moving the focus (a terminal chosen from the panel) + // does the same; saying nothing leaves it where the person put it. + _ = await tab.events.arrange(PaneArrangement(layout: sideBySide, focus: left)) + XCTAssertEqual(tab.controller.activePaneID, left) + _ = await tab.events.arrange(PaneArrangement(layout: sideBySide, focus: nil)) + XCTAssertEqual(tab.controller.activePaneID, left) + tab.window.isHidden = true + } + + // MARK: - Changing the layout + + func testADraggedLineMovesThePanesAtOnceAndAsksTheTransportInOrder() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + let before = split.cells[0].frame.width + + tab.controller.setPaneRatio(0.4, ofSplit: "split:1") + tab.controller.setPaneRatio(0.3, ofSplit: "split:1") + tab.controller.setPaneRatio(0.25, ofSplit: "split:1") + // The layout followed synchronously — the drag has to stay under + // the finger — and each emulator measured its new grid. + XCTAssertEqual(tab.controller.paneLayout?.split(withID: "split:1")?.ratio, 0.25) + XCTAssertEqual(split.cells[0].frame.width, before / 2, accuracy: 1) + XCTAssertLessThan( + split.cells[0].terminalView.terminalDimensions.cols, + split.cells[1].terminalView.terminalDimensions.cols) + // The transport hears every step in the order it was made. + await eventually { + await tab.transport.commands.filter { $0 != .focus(self.left) } == [ + .setRatio(0.4, splitID: "split:1"), + .setRatio(0.3, splitID: "split:1"), + .setRatio(0.25, splitID: "split:1"), + ] + } + // And each pane's new size, as its own. + await eventually { + let resized = await tab.transport.resized + return resized[self.left].map { $0.cols } ?? 0 < resized[self.right].map { $0.cols } ?? 0 + } + + // VoiceOver's adjust moves the same line a twentieth at a time. + let divider = try XCTUnwrap(views(ofType: PaneDividerView.self, in: split).first) + divider.accessibilityIncrement() + XCTAssertEqual( + tab.controller.paneLayout?.split(withID: "split:1")?.ratio ?? 0, 0.3, accuracy: 0.0001) + tab.window.isHidden = true + } + + func testThePanelsRowsActOnThePaneWithTheKeyboard() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let panel = try XCTUnwrap(ShortcutPanelContent.content(for: .rex)) + for item in panel.sections.flatMap(\.items) { + tab.controller.performPanelShortcut(item) + } + await eventually { + await tab.transport.commands.filter { $0 != .focus(self.right) } == [ + .split(self.right, .sideBySide), + .split(self.right, .stacked), + .close(self.right), + .newWindow(from: self.right), + ] + } + // The zoom row asked the transport nothing: it is the tab's own. + XCTAssertEqual(tab.controller.zoomedPaneID, right) + tab.window.isHidden = true + } + + // MARK: - Zoom + + func testAZoomedPaneIsDrawnAloneAndTheOthersKeepTheirPlaceAndSize() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + let leftFrame = split.cells[0].frame + let leftGrid = split.cells[0].terminalView.terminalDimensions + let rightColumns = split.cells[1].terminalView.terminalDimensions.cols + + tab.controller.performPaneShortcut(.zoomPane) + XCTAssertEqual(tab.controller.zoomedPaneID, right) + // The pane the keyboard is on has the whole view: no line, no + // frame, and its emulator measured the larger grid. + XCTAssertEqual(split.cells[1].frame, split.bounds) + XCTAssertFalse(split.cells[1].isHidden) + XCTAssertTrue(views(ofType: PaneDividerView.self, in: split).isEmpty) + XCTAssertGreaterThan(split.cells[1].terminalView.terminalDimensions.cols, rightColumns) + // The other is hidden, not gone — still where the split has it and + // at the size it will be shown at again, so nothing is resized or + // redrawn for it on the way in or out. + XCTAssertTrue(split.cells[0].isHidden) + XCTAssertEqual(split.cells[0].frame, leftFrame) + XCTAssertEqual(split.cells[0].terminalView.terminalDimensions.cols, leftGrid.cols) + // What is under a point is what is on screen there. + XCTAssertEqual(split.pane(at: CGPoint(x: 20, y: 40)), right) + // It still gets its output while hidden. + tab.events.output(left, Data("behind the zoom".utf8)) + await eventually { + split.cells[0].screen.snapshot().lines.contains { $0.contains("behind the zoom") } + } + // The tab says it is zoomed and carries the way back. + await eventually { + self.views(ofType: TerminalContextBarView.self, in: tab.pane.view) + .contains { $0.accessibilityIdentifier == "terminalPane.context.zoomed" } + } + let asked = await tab.transport.commands + XCTAssertFalse(asked.contains { $0 != .focus(self.right) }) + + // ALL PANES on that bar is the way back. + let showAll = try XCTUnwrap( + views(ofType: UIKitChassisChip.self, in: tab.pane.view) + .first { $0.accessibilityLabel == "Show all panes" }) + XCTAssertTrue(showAll.accessibilityActivate()) + XCTAssertNil(tab.controller.zoomedPaneID) + XCTAssertFalse(split.cells[0].isHidden) + XCTAssertEqual(split.cells[0].frame, leftFrame) + XCTAssertEqual(split.cells[1].terminalView.terminalDimensions.cols, rightColumns) + XCTAssertEqual(views(ofType: PaneDividerView.self, in: split).count, 1) + tab.window.isHidden = true + } + + func testAZoomEndsWhenTheKeyboardLeavesItsPaneOrThePaneGoes() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + + // The keyboard going to another pane ends it: that pane has to be + // on screen. + tab.controller.togglePaneZoom() + tab.controller.focusPane(left) + XCTAssertNil(tab.controller.zoomedPaneID) + XCTAssertFalse(split.cells[1].isHidden) + + // So does a pane the transport brings the focus to — a split made + // while zoomed. + tab.controller.togglePaneZoom() + XCTAssertEqual(tab.controller.zoomedPaneID, left) + let grown = PaneLayout.split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.5, + before: .split(PaneLayout.Split( + id: "split:2", axis: .stacked, ratio: 0.5, + before: .pane(left), after: .pane(below))), + after: .pane(right))) + _ = await tab.events.arrange(PaneArrangement(layout: grown, focus: below)) + XCTAssertNil(tab.controller.zoomedPaneID) + XCTAssertTrue(split.cells.allSatisfy { !$0.isHidden }) + + // A layout change that leaves the focus alone leaves the zoom too… + tab.controller.togglePaneZoom() + _ = await tab.events.arrange(PaneArrangement(layout: sideBySide, focus: nil)) + XCTAssertNil(tab.controller.zoomedPaneID, "the zoomed pane itself closed") + tab.controller.focusPane(right) + tab.controller.togglePaneZoom() + _ = await tab.events.arrange(PaneArrangement( + layout: sideBySide.settingRatio(0.3, ofSplit: "split:1"), focus: nil)) + XCTAssertEqual(tab.controller.zoomedPaneID, right) + // …and one pane alone has nothing to cover. + _ = await tab.events.arrange(PaneArrangement(layout: .pane(right), focus: nil)) + XCTAssertNil(tab.controller.zoomedPaneID) + tab.controller.togglePaneZoom() + XCTAssertNil(tab.controller.zoomedPaneID) + tab.window.isHidden = true + } + + func testARefusedSplitIsSaidOnThePane() async throws { + let tab = try await makeTab(PaneArrangement(layout: .pane(left), focus: left)) + await tab.transport.fail(with: RexSession.Failure("The Rex server refused: too many blocks")) + tab.controller.performPaneShortcut(.splitRight) + await eventually { + tab.controller.historyNotice + == "Couldn't split the pane. The Rex server refused: too many blocks" + } + tab.window.isHidden = true + } + + func testPanesComeAndGoWithTheArrangementAndKeepTheirEmulators() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + let leftView = split.cells[0].terminalView + + // A pane is split below the right one: it arrives with the focus. + let grown = PaneLayout.split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.5, + before: .pane(left), + after: .split(PaneLayout.Split( + id: "split:2", axis: .stacked, ratio: 0.5, + before: .pane(right), after: .pane(below))))) + let sizes = await tab.events.arrange(PaneArrangement(layout: grown, focus: below)) + XCTAssertEqual(split.cells.map(\.screen.paneID), [left, right, below]) + // The pane that stayed kept its emulator — buffer, scrollback, all. + XCTAssertTrue(split.cells[0].terminalView === leftView) + XCTAssertEqual(tab.controller.activePaneID, below) + // The new pane was measured before the transport was answered: it + // is half the height of the pane beside the split. + let tall = try XCTUnwrap(sizes[left]), short = try XCTUnwrap(sizes[below]) + XCTAssertLessThan(short.rows, tall.rows) + XCTAssertEqual(views(ofType: PaneDividerView.self, in: split).count, 2) + + // The focused pane closes: its neighbour is named, and the tab + // follows; the pane and its emulator are gone. + _ = await tab.events.arrange(PaneArrangement(layout: sideBySide, focus: right)) + XCTAssertEqual(split.cells.map(\.screen.paneID), [left, right]) + XCTAssertEqual(tab.controller.screens.map(\.paneID), [left, right]) + XCTAssertEqual(tab.controller.activePaneID, right) + XCTAssertEqual(views(ofType: PaneDividerView.self, in: split).count, 1) + + // A pane that leaves without the transport naming a focus still + // cannot leave the keyboard on nothing. + _ = await tab.events.arrange(PaneArrangement(layout: .pane(left), focus: nil)) + XCTAssertEqual(tab.controller.activePaneID, left) + XCTAssertTrue(tab.controller.terminalView === leftView) + // Output for a pane that is gone goes nowhere, harmlessly. + tab.events.output(right, Data("late".utf8)) + tab.window.isHidden = true + } + + // MARK: - The keyboard, when its pane goes + + func testCellsThatLeaveAreStillInTheWindowWhileTheNewOnesAreAlreadyIn() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + let staying = split.cells[0], going = split.cells[1] + let arriving = TerminalScreen(paneID: below) + + var handedOver = false + split.apply( + layout: PaneLayout.split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.5, + before: .pane(left), after: .pane(below))), + screens: [staying.screen, arriving], activePane: below, zoomedPane: nil, + theme: .tally + ) { + handedOver = true + // The one moment a first responder can pass from the pane that + // is going to the pane that came, with no turn in which neither + // is in the window — which is when the keyboard would leave. + XCTAssertNotNil(going.window) + XCTAssertNotNil(split.cell(for: self.below)?.terminalView.window) + } + XCTAssertTrue(handedOver) + XCTAssertNil(going.superview) + XCTAssertEqual(split.cells.map(\.screen.paneID), [left, below]) + tab.window.isHidden = true + } + + func testTheKeyboardGoesWithTheFocusBeforeTheTransportIsAnswered() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let split = try tab.split + let goingView = split.cells[1].terminalView + await eventually { TerminalFocusArbiter.current === goingView } + + // The tab moves to another window of its session — New Tab, or a + // terminal chosen from the panel: every pane it drew goes, one new + // pane comes, and the keyboard is on it when the transport is + // answered with its grid. + let sizes = await tab.events.arrange(PaneArrangement(layout: .pane(below), focus: below)) + let arrived = try XCTUnwrap(split.cells.first?.terminalView) + XCTAssertEqual(split.cells.map(\.screen.paneID), [below]) + XCTAssertTrue(TerminalFocusArbiter.current === arrived) + XCTAssertNil(goingView.window) + XCTAssertNotNil(sizes[below]) + + // A pane that arrives beside one that stays takes it the same way. + _ = await tab.events.arrange(PaneArrangement( + layout: PaneLayout.split(PaneLayout.Split( + id: "split:9", axis: .sideBySide, ratio: 0.5, + before: .pane(below), after: .pane(right))), + focus: right)) + let arrivedBeside = try XCTUnwrap(split.cell(for: right)?.terminalView) + XCTAssertTrue(TerminalFocusArbiter.current === arrivedBeside) + + // A tab that did not have the keyboard does not take it because + // its panes changed. + TerminalFocusArbiter.release(arrivedBeside) + _ = await tab.events.arrange(PaneArrangement(layout: .pane(left), focus: left)) + XCTAssertNil(TerminalFocusArbiter.current) + tab.window.isHidden = true + } + + // MARK: - Moving to another window + + func testAMovedTabsNewWindowAdoptsTheEmulatorsAndTheOldSurfaceCannotTakeThemBack() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: right)) + let old = try tab.split + let views = old.cells.map(\.terminalView) + + // Merge / split: another window mounts the same controller. Its + // cells take the live views — buffers, scrollback, connection. + let (moved, window) = mount(tab.controller) + let new = try XCTUnwrap(moved.terminalSurface?.paneSplitView) + XCTAssertEqual(new.cells.map(\.terminalView), views) + XCTAssertTrue(views.allSatisfy { $0.isDescendant(of: moved.view) }) + XCTAssertTrue(tab.controller.terminalView === views[1]) + + // The window the tab left gets one last update. It must not make + // cells of its own: adopting the views would pull them back out. + tab.pane.update(configuration: configuration(tab.controller)) + tab.pane.view.layoutIfNeeded() + XCTAssertTrue(views.allSatisfy { $0.isDescendant(of: moved.view) }) + + // From here on the layout is the new window's to draw. + let grown = PaneLayout.split(PaneLayout.Split( + id: "split:1", axis: .sideBySide, ratio: 0.5, + before: .pane(left), + after: .split(PaneLayout.Split( + id: "split:2", axis: .stacked, ratio: 0.5, + before: .pane(right), after: .pane(below))))) + let sizes = await tab.events.arrange(PaneArrangement(layout: grown, focus: below)) + XCTAssertEqual(new.cells.map(\.screen.paneID), [left, right, below]) + XCTAssertEqual(old.cells.count, 2) + XCTAssertTrue(new.cells[2].terminalView.isDescendant(of: moved.view)) + // And measured there: the new pane's grid is its cell's in the new + // window. + XCTAssertEqual( + sizes[below]?.rows, new.cells[2].terminalView.terminalDimensions.rows) + window.isHidden = true + tab.window.isHidden = true + } + + func testAFileDroppedOnAPaneIsThatPanes() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + XCTAssertEqual(split.pane(at: CGPoint(x: 20, y: 40)), left) + XCTAssertEqual(split.pane(at: CGPoint(x: split.bounds.maxX - 20, y: 40)), right) + // On the line between them: nobody's, and the focus stays put. + XCTAssertNil(split.pane(at: CGPoint(x: split.cells[0].frame.maxX + 4, y: 40))) + tab.window.isHidden = true + } + + // MARK: - A grid the backend dictates + + func testOnePaneIsHeldToAnotherClientsGridWhileItsSiblingKeepsItsOwn() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + let own = split.cells[1].terminalView.terminalDimensions + + await tab.events.grid(left, TerminalGrid(cols: 30, rows: 8)) + XCTAssertEqual(split.cells[0].screen.gridPin, TerminalGrid(cols: 30, rows: 8)) + XCTAssertEqual(split.cells[0].terminalView.terminalDimensions.cols, 30) + XCTAssertEqual(split.cells[0].terminalView.terminalDimensions.rows, 8) + // The other pane is untouched, and the pinned grid — somebody + // else's — is never sent back as this tab's ask. + XCTAssertEqual(split.cells[1].terminalView.terminalDimensions.cols, own.cols) + let asked = await tab.transport.resized[left] + XCTAssertNotEqual(asked, TerminalGrid(cols: 30, rows: 8)) + + // Its own grid again: the pane measures and reports it. + await tab.events.grid(left, nil) + XCTAssertNil(split.cells[0].screen.gridPin) + XCTAssertEqual(split.cells[0].terminalView.terminalDimensions.cols, own.cols, accuracy: 1) + tab.window.isHidden = true + } + + // MARK: - Ending + + func testTheTransportEndingEndsTheTabAndAReconnectKeepsThePanes() async throws { + let tab = try await makeTab(PaneArrangement(layout: sideBySide, focus: left)) + let split = try tab.split + let views = split.cells.map(\.terminalView) + + tab.events.close("The connection to the Rex server was lost.") + await eventually { + tab.controller.status == .ended("The connection to the Rex server was lost.") + } + await eventually { await tab.transport.isClosed } + // Nothing typed reaches a tab that ended. + tab.controller.sendInput(Data("x".utf8)) + try await Task.sleep(for: .milliseconds(50)) + let written = await tab.transport.written + XCTAssertTrue(written.isEmpty) + // The panes stay on screen under the ended panel, as a single + // emulator does. + XCTAssertEqual(split.cells.map(\.terminalView), views) + + // The next run draws the same panes into the same emulators. + let again = Transport() + await tab.controller.runPanesForTesting(over: again) { events in + _ = await events.arrange(PaneArrangement(layout: self.sideBySide, focus: self.left)) + } + XCTAssertEqual(tab.controller.status, .live) + XCTAssertEqual(split.cells.map(\.terminalView), views) + tab.controller.sendInput(Data("y".utf8)) + await eventually { await again.written == ["block:left:y"] } + tab.controller.detach() + tab.window.isHidden = true + } + + private func views(ofType type: T.Type, in root: UIView) -> [T] { + root.subviews.flatMap { child -> [T] in + (child as? T).map { [$0] } ?? views(ofType: type, in: child) + } + } +} 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/MultiplexTests/TerminalWindowUIKitTests.swift b/MultiplexTests/TerminalWindowUIKitTests.swift index 0da5de83..341ff8af 100644 --- a/MultiplexTests/TerminalWindowUIKitTests.swift +++ b/MultiplexTests/TerminalWindowUIKitTests.swift @@ -8,7 +8,7 @@ import SwiftUI @MainActor final class TerminalWindowUIKitTests: XCTestCase { - func testSurfaceAppearanceRestoresOnlyTheExistingAppWideFocusOwner() { + func testSurfaceAppearanceRestoresOnlyTheExistingAppWideFocusOwner() throws { TerminalFocusArbiter.inputSuppressed = false let host = Host( name: "devbox", @@ -31,8 +31,8 @@ final class TerminalWindowUIKitTests: XCTestCase { frame: .zero, font: .monospacedSystemFont(ofSize: 14, weight: .regular) ) - first.bind(owner) - second.bind(contender) + first.bind(owner, to: try XCTUnwrap(first.soleScreen)) + second.bind(contender, to: try XCTUnwrap(second.soleScreen)) TerminalFocusArbiter.claim(owner) TerminalWindowViewController.restoreFocusAfterSurfaceAppearance( 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/MultiplexUITests/RexPanesUITests.swift b/MultiplexUITests/RexPanesUITests.swift new file mode 100644 index 00000000..dde7b209 --- /dev/null +++ b/MultiplexUITests/RexPanesUITests.swift @@ -0,0 +1,86 @@ +import XCTest + +/// Real touches on a paned (Rex) tab: a tap moves the tab's focus to the +/// pane under it, and a finger on the line between two panes drags it. No +/// headless tap or drag exists on Xcode 27 simulators, so this is the one +/// road that drives the two gesture recognizers a paned tab adds. +/// +/// Needs a host whose `rex` reaches a Rex server with a session to attach — +/// `docs/agents/backends-and-probe.md` has the throwaway-server recipe. Run +/// with, in xcodebuild's environment: +/// - `TEST_RUNNER_MULTIPLEX_SEED_HOST=` +/// - `TEST_RUNNER_MULTIPLEX_REX_SESSION=` +/// Skipped without them. Deliberately outside the unit scheme and CI. What +/// each pane received is read host-side afterwards (`rex capture`): the test +/// types a different line into each. +final class RexPanesUITests: XCTestCase { + override func setUpWithError() throws { + continueAfterFailure = false + } + + func testATapFocusesAPaneAndAFingerDragsTheLineBetweenTwo() throws { + let environment = ProcessInfo.processInfo.environment + guard let seed = environment["MULTIPLEX_SEED_HOST"], + let session = environment["MULTIPLEX_REX_SESSION"] + else { throw XCTSkip("needs MULTIPLEX_SEED_HOST and MULTIPLEX_REX_SESSION") } + + let app = XCUIApplication() + app.launchEnvironment["MULTIPLEX_SEED_HOST"] = seed + app.launchEnvironment["MULTIPLEX_METAL"] = "0" + app.launchEnvironment["MULTIPLEX_AUTO_ACTION_URL"] = + "multiplex://open?host=devbox&action=shell&session=\(session)&backend=rex" + // One pane becomes two, side by side, through the panel's own row. + app.launchEnvironment["MULTIPLEX_AUTO_PANE_ACTIONS"] = "splitRight" + app.launch() + + let divider = app.descendants(matching: .any) + .matching(identifier: "terminalPane.divider").firstMatch + XCTAssertTrue(divider.waitForExistence(timeout: 60), "No second pane appeared") + sleep(2) + let line = divider.frame + let split = app.descendants(matching: .any) + .matching(identifier: "terminalPane.split").firstMatch.frame + NSLog("RexPanesUITests line %@ split %@", "\(line)", "\(split)") + let window = app.windows.firstMatch + func point(_ x: CGFloat, _ y: CGFloat) -> XCUICoordinate { + window.coordinate(withNormalizedOffset: .zero) + .withOffset(CGVector(dx: x - window.frame.minX, dy: y - window.frame.minY)) + } + let row = line.minY + 160 + + // The split left the keyboard in the NEW pane, on the right. A tap + // on the left pane moves it there; what is typed next proves where. + point(line.minX - 120, row).tap() + sleep(1) + app.typeText("echo typed-in-left\n") + sleep(1) + point(line.maxX + 120, row).tap() + sleep(1) + app.typeText("echo typed-in-right\n") + sleep(1) + attach(app, "after-taps") + + // A finger on the line carries it: the line follows. + point(line.midX, row) + .press(forDuration: 0.3, thenDragTo: point(line.midX - 180, row)) + sleep(2) + let moved = divider.frame + NSLog("RexPanesUITests line after drag %@", "\(moved)") + attach(app, "after-drag") + XCTAssertEqual(moved.midX, line.midX - 180, accuracy: 6, "The line should stay under the finger") + + // The pane on the right grew; a tap on it is still its own. + point(moved.maxX + 120, row).tap() + sleep(1) + app.typeText("echo after-drag-right\n") + sleep(2) + } + + private func attach(_ app: XCUIApplication, _ name: String) { + let shot = XCTAttachment(screenshot: app.screenshot()) + shot.name = name + shot.lifetime = .keepAlways + add(shot) + } +} 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..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) @@ -2851,6 +2859,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 +3327,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 +8666,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 +8685,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/architecture.md b/docs/agents/architecture.md index e217a4fa..4c83f72f 100644 --- a/docs/agents/architecture.md +++ b/docs/agents/architecture.md @@ -41,6 +41,9 @@ UIKit scene runtime (MultiplexSceneDelegate + UIKitSceneRootViewController; DeckSnapshotStore last-known wall state per host (device-local) — cold launches paint instantly; attention is never cached TmuxProbe tmux list/capture/ps command builders + parsers (pure) + RexProbe Rex on the deck: one `rex do` Lua exec → one JSON + document of sessions, statuses, fronted screen; and + the Rex mint, one exec of the same shape (pure) AgentSignature classifies a pane's CLI agent; helper command sets (pure) AppLockStore optional biometric app lock (device-local, free): locks at launch + didEnterBackground (never resign-active); @@ -83,7 +86,13 @@ UIKit scene runtime (MultiplexSceneDelegate + UIKitSceneRootViewController; SidePanelViewController one active-window mount around an existing ▤/⌗ pane: 30 pt header + iPad seam or visionOS trailing slab; presentation only, never controller lifetime - TerminalSessionController one per tab; input pump + TerminalView + TerminalSessionController one per tab: the transport run and everything + above the emulator. "The terminal" of a tab is its + active screen's view + TerminalScreen one emulator endpoint: the SwiftTerm view, its + output coalescer, ordered input + resize pumps, its + grid pin. A tab has one — or one per PANE on a + paned transport (docs/agents/panes.md) TalkbackDraft the tab's chat-style message box (text + attachments; pure) beside its observed talkbackOpen — sendTalkback = one paste + CR through the pump, @@ -98,13 +107,24 @@ UIKit scene runtime (MultiplexSceneDelegate + UIKitSceneRootViewController; analyzer or SFSpeechRecognizer behind AudioDenoiser (RNNoise, Vendor/rnnoise) when the model is on; RNNoiseModelStore downloads + SHA-256-pins it - TerminalTransport the tab's byte pipe; picked by host.useMosh - (exec + SFTP stay SSH-only capabilities) + TerminalTransport the tab's byte pipe (SSH PTY or mosh), picked by + host.useMosh (exec + SFTP stay SSH-only + capabilities) + PanedTerminalTransport the other kind of link: one stream per pane + plus the layout they sit in (PaneLayout / + PaneCommand, pure), drawn by the app + (PaneSplitView). Picked by the route — a Rex tab SessionResumePolicy pure: suspension damage vs user-ended session SSHConnection (actor) Citadel → SwiftNIO SSH; exec channel (probe, mosh bootstrap, drops) + PTY shell ⇄ SwiftTerm MoshSession (actor) UDP socket + MoshTransportEngine; bootstrapped over a throwaway SSHConnection + RexSession (actor) a Rex window, the first paned transport: Rex has + no client to run in a PTY, so the tab speaks its + WebSocket API over SSHConnection.openPipe byte pipes + (one control, one data per terminal block) + WebSocketCodec / RexWire RFC 6455 client codec and the Rex control, + data-handshake and terminal-stream formats (pure) Mosh/* clean-room mosh stack, pure + unit-tested against RFC 7253 / real mosh-server TerminalFocusArbiter app-wide single owner of keyboard focus diff --git a/docs/agents/backends-and-probe.md b/docs/agents/backends-and-probe.md index 678719df..b8d2e56b 100644 --- a/docs/agents/backends-and-probe.md +++ b/docs/agents/backends-and-probe.md @@ -1,7 +1,7 @@ -# Backends & the probe (tmux facts, mixed hosts, herdr, session creation, drops) +# Backends & the probe (tmux facts, mixed hosts, herdr, Rex, session creation, drops) Load-bearing decisions split from AGENTS.md — read before touching TmuxProbe, -HerdrProbe, session creation/targeting, or file attach/drop. +HerdrProbe, RexProbe, session creation/targeting, or file attach/drop. - **Every SSH exec rides `RemoteShellEnvelope`: `printf '' | `.** sshd runs exec requests through the account's login shell, and fish (exit @@ -271,6 +271,684 @@ 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; written + against Rex 0.1.0-preview.25 / API revision 24, measured 2026-11-27 + against a throwaway server), + adapted as session→tile, window (a tab)→window, terminal block→pane. + - **Opt-in per host, like herdr as a second backend — and nothing else + gates it.** A host shows Rex once `secondaryBackends` lists it: the + rail's `+ REX` offer, or the box in Host Settings ▸ Backends. (A + per-device Settings ▸ Experimental switch hid it for a few days in + 2026-11; a record that listed `rex` while it was off is monitored.) + - **The hello states a RANGE of API revisions and the server picks** + (`RexWire.apiRevision` 24, `minimumAPIRevision` 14; the welcome's + `api_revision` is the newest both sides speak, and a server translates + to and from it). A preview server gains a revision every few days — 14 + on 2026-11-16, 18 a week later, 24 by 2026-11-27 — so what matters is + which shapes this client READS, and those have not moved: every call + and event a tab makes or handles was sent at 14 and at 24 to one + preview.25 server, and at 19 to a preview.23 one, and the answers + differ only in ids (`session.attach`'s view and its layout tree, + `own_block`, `data.connect`, the stream's handshake and its `resize`, + `modes`, `format`, `blob_read`, `process`, `new_split`, `resize_pane`, + `block.close`, `new_window`, `disown_block`, and the three events). + The probe and mint scripts, `ls -q`, `kill`, exit status 4 and + `__internal dial-stdio` were run unchanged with the preview.25 CLI, + which also probes a preview.23 server. Fixtures from both ends are in + the tests (`rex-probe-preview19` / `-preview25`, and the two stream + recordings). + - **To move the range up**: fetch the new server's `/llms.txt`, diff it + against the last one read, and send the tab's calls at the old and + the new revision to one server (a script that prints each answer with + ids replaced, run twice, then `diff`). Raise `apiRevision` only after + that; raise `minimumAPIRevision` only when a shape this client reads + differs below it. + - A server with no revision in common closes with status 1008 and a + reason that names the side to update (`no common API revision: + server speaks 0 to 13, client needs 14 to 24; update the server`, + measured by asking for 25–30); it becomes the tab's ended line as it + is. A welcome that names a revision below the minimum — a server + from before revisions were negotiated names none, which reads as 0 — + fails the attach here with "older than Multiplex can talk to". NOT + measured: a real server older than preview.23; none is installed any + more. + - **What revisions 20–24 added, and what this client does with it**: + - `block.close` / `session.close_window` / `session.destroy` take + `undoable`, and `client.undo_close` reopens the caller's newest + close for about a minute. Not sent: a close that can be undone + only by the client that made it needs an undo row to be worth its + minute, and the reopened block "becomes its window's focused + block, its window becomes the active window" — the Rex app on the + host would flip to it, which every other call here avoids + (`focus: false`). What it changes for a tab without sending it: + ANOTHER client's undoable close takes the block out of every + window at once and sends `block_closed` only when it is freed, and + an undo brings it back with the same ids. The tab already reads + both from the view — the pane goes, and comes back as a new pane + would, at its owner's size until someone types here (measured on + the iPad simulator: a stand-in client closed one of three panes + with `undoable`, the tab drew two; six seconds later it called + `client.undo_close` and the pane was back with its screen). + - `session.transfer_window` moves a window to another session. To + the session it leaves that is a window closing (`window_closed`, a + `block_closed` each, the streams end), so a tab drawing it goes + where a closed window's tab goes (measured with no other window + left in the session: ENDED, with RECONNECT, and the client gone + from the server at once). + - A window has TWO zooms now (`tiled_zoomed_block_id` beside + `zoomed_block_id`) and a split no longer ends one (measured: a + block zoomed by `window_id`, then `new_split` with `focus: false`, + and the view still named it zoomed). So a pane this tab splits off + while the Rex app has its neighbour zoomed is hidden behind that + zoom ON THE HOST until the zoom ends. Both fields stay ignored + here (the zoom bullet below). + - `com.superlogical.fs` blocks (`rex cp`) and + `com.superlogical.terminal.program_resume_records` are not used. + Only `com.superlogical.terminal` blocks are drawn or listed, so a + block of another creator in a view is cut out as before. + - **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`. + - ⚠ The CLI found there and the server it reaches can be two releases. + Seen 2026-11-27: the app had updated to preview.25 (its helper, and a + new `Versions/2147/` named for the build) while `Versions/Current/` + and the server still running out of it were preview.23. Either pair + works — the preview.23 CLI ran the probe against a preview.25 server + and the preview.25 CLI against a preview.23 one — because the CLI + negotiates its revision like any client and `dial-stdio` only moves + bytes. What becomes of `Current` when the server restarts was not + seen. + - **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 draws ONE layer of one Rex window, natively** — every terminal + block of it as a pane of its own, in the server's split tree + (`RexWire.Layer` → the app's `PaneLayout`; the machinery above the + transport is in `panes.md`). A tile press attaches the window of the + block the session is fronting (active window, focused block — + `RexWire.attachTarget`, decided at attach time) with the keyboard on + that block; 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 layout is the SERVER's. `session.view` carries it as a tree + (`split_id`, `direction`, `ratio`, `before`, `after`, leaves by + `block_id`); `session_view_changed` carries only a revision, so every + change is one `session.view` read (`refreshView`, one reader at a + time). ⚠ A change of OWNER is a view change too — most reads find the + layout unchanged, and those say nothing to the tab. + - `horizontal` is side by side, `vertical` stacked. A block that is not + a terminal has no stream this client can draw: its leaf is cut out + and its sibling takes the room. A FLOATING layer is a layer of its + own — a tab pointed at a terminal in one draws that layer alone, + filling the tab (`bounds` is where it sits over a Rex window). + `zoomed_block_id` is ignored: the tab draws the layout it was given, + and its own zoom is its own (below). + - **The tab changes the layout by asking** (`RexSession.perform`): + `session.new_split` (anchor = the focused pane, `side: after`, one + `com.superlogical.terminal.shell` block whose `cwd` is the source + pane's `foreground.cwd`), `block.close`, `session.resize_pane` (the + split is named by a block on each side of it — the first pane of + each — and a direction; any such pair names exactly that split). + The result is never applied locally: it comes back in the view like + another client's change. All measured. + - ⚠ **`new_split` is sent `focus: false`, and the tab's own focus is + never `session.focus_block`.** Focusing also makes the block's window + the session's ACTIVE one — the tab the Rex app on the host is + showing — so a tap on a pane here would flip a Mac's window. Which + pane has the keyboard is this tab's own (`focusedBlockID`), told to + the transport only so it can keep drawing the right layer and name + the neighbour when that pane closes. Measured: after two splits and a + focus change here, the window's `focused_block_id` was still the + block it started on. + - **A drag asks for only the newest ratio.** One `resize_pane` is in + flight at a time, and until the last ask is answered the tab's ratio + stands in for the view's (`pendingRatios`): `resize_pane` "always + raises revision and sends `session_view_changed`", so the answer to + an EARLIER ask arrives mid-drag and pulled the divider back under the + finger. `floorRevision` drops a view read before this tab's own last + change was answered, for the same reason. + - **A window that closes under a tab moves the tab to the window Rex + shows next** (`RexWire.layer(replacing:among:inView:)`, asked in + `refreshView`) — its last terminal exited, its last pane was closed + from the panel, another client closed or transferred it. Rex's own + rule for a closed active window is "the window after it becomes + active, or the one before it if it was last"; the tab walks the same + way from the closed window's place in the tab order it last read, + passing windows with no terminal, so a tab and a Rex app that were + both on the window land on the same one (measured: `exit` in the + first of three windows put the tab AND `active_window_id` on the + second; New Tab then Close Pane came back to the window the tab + had left). The first shape ended the tab there, with DETACHED and + RECONNECT, which read as the session being gone while its other + tabs were one press away. + - It is not an attach and not a choice: the arrangement names no + focus, so the window's own focused pane takes the keyboard, and + only terminals nobody owns are claimed. One another client holds + is drawn at that client's size until someone types here, like a + pane another client adds. + - A window that is still there and only lost the layer the tab drew + (a floating layer closed) keeps the tab, on the layer its focused + block is in. + - The tab ends cleanly only when no window of the session has a + terminal left (the ended panel and RECONNECT, which then has + nothing to attach either). One pane closing is not the tab ending. + - **The REX key's panel acts on the focused pane, then lists the + session's terminals** (`ShortcutPanelContent.rex`). Rex has no prefix + keys to list — Multiplex is the client — so its rows are + `PaneShortcut`s: Split Right, Split Down, Toggle Pane Zoom, Close + Pane (asked twice, like every backend's close), and — under Tabs — New + Tab. Below them + `RexWire.terminalChoices`, `window — terminal` in window order, the one + the keyboard is on marked ACTIVE, and rows that would read the same + counted (`shell`, `shell 2` — a window split three ways is three shells + with one label, in the order the panes are on screen): a terminal among + the panes on show + takes the keyboard; one in another Rex window brings THAT window's + panes into the tab, in place (`RexSession.showTerminal` — the control + connection and the tab stay; the streams of the window being left are + closed with status 1000 and its blocks `disown_block`ed, which hands + their sizes back to the Rex app instead of leaving them at this tab's). + A pane has its own serial (`Terminal.serial`), so a stream that ended + with the window it belonged to is never read as the tab ending. 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. + - **New Tab is `session.new_window`, sent `focus: false`, and the tab + moves to it** (`PaneCommand.newWindow` → `RexWire.newWindowPayload`): + one shell starting where the focused pane's program is. Rex's own app + calls a window a tab, so the row does; the server, the switch list and + the rest of this app say window. The new block's id comes back in the + answer and becomes the tab's target exactly as a Switch Terminal choice + does — the window being left is closed and disowned the same way. + - ⚠ `focus` defaults to TRUE, which makes the new window the session's + active one: the Rex app on the host would flip to a tab made from a + tablet. Measured with false: `active_window_id` stays where it was, + the window appears in the view (`window_created`, then + `session_view_changed`), and its block is its maker's. + - **Zoom is the tab's own, not `session.zoom_block`** + (`TerminalSessionController.togglePaneZoom`, `panes.md`). The server's + zoom cannot be aimed at the pane the tab's keyboard is on without + moving the session: with `block_id` it "first focuses the block and + makes its window active", and with `window_id` it zooms whatever block + the SERVER has focused in that window — the Rex app's choice, not this + tab's (measured: `zoom_block {window_id}` set `zoomed_block_id` and + left the active window alone). So the tab hides its other panes + itself, asks the server nothing, and what the Rex app has zoomed is + not followed either: each client's zoom is its own picture of one + layout. + - **A Rex tab has a working directory, the focused pane's**: + `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; a path pressed in a pane resolves against THAT pane, because + the press moves the keyboard there first. (Unit tested; not yet driven + end to end.) + - **The link is byte pipes on the tab's own SSH connection — one for + control and one per pane** (`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`.) + - ⚠ **Every pane is a channel, and sshd allows ten a connection** + (`MaxSessions`): the control pipe and nine panes, fewer while a drop + or the file viewer has a channel open. A pane past that is not + opened — it says why in its own emulator and the rest of the tab is + unaffected (`testAConnectionWithNoRoomForOnePanesPipe…`). A second + connection for the overflow was not built: a window of ten panes on + a tablet has not been seen. + - **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), the hello states the revision range + above, pings are answered in `RexSocket`, and requests are matched by + id with a 10 s timeout. + - **Attach order is load-bearing** (`RexSession.attach`, `show`): hello + → `session.attach` → **the tab lays the panes out and answers with + each one's grid** (`PaneEvents.arrange`) → ONE `own_block(take)` for + every pane, then a `resize` each, **first** → and then per pane, all at + once: `data.connect` → data HELLO/WELCOME → wait for the first server + message → `modes` + `format(vt)` (two reads, asked together) → RIS + + rendering → flush the held stream. A pane added later goes through the + same steps on its own. + - ⚠ **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 its PANE's size — which is why the layout + is asked for before anything is opened, not after. + - **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. + ⚠ `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 sizes** (tmux's latest-client + rule): the Rex app can claim a block back (`block_owner_changed`); the + next keystroke here claims EVERY terminal the tab draws that it does + not own — the one typed into first, one `own_block` for all — and + re-sizes each to its pane. All of them, because the tab draws them as + one window: half of it at another client's size is a layout nobody + chose. Until then a terminal has the other client's size, and its pane + draws it AT that size (next bullet). + - **What is claimed without a keystroke**: the panes of an attach, the + panes of a window Switch Terminal brings in, a terminal this tab + just made (the server hands a block to its maker; the view's `owner` + says so, which does not depend on which of the split's answer and + its event arrives first), and one that is nobody's. A pane ANOTHER + client just made beside the ones on show is not: it is opened + unclaimed and drawn at its owner's size + (`testAPaneAnotherClientAdds…`). + - ⚠ One id that is no longer a block fails the whole `own_block` with + `bad_request` and claims nothing — a pane closing as another is + typed into. The claim is then made one block at a time. The same + rule is why a block that CLOSED is never named in `disown_block`. + - ⚠ **An emulator's grid follows its terminal's, not its pane's** — per + pane: one of a tab's panes can be held to another client's grid while + its siblings keep their own. 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` — one coordinator per + pane, on its `PaneCellView`'s two edges — `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 + (`TerminalScreen.gridPin`, `isSettlingGridPin`); the + pane'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 + 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 + lost", its stream parked for a resume. Every data connection closes + first with status 1000 (ends its stream), then the control connection + (ends the client at once). A data close of 4000 (`block closed`) or + 1000 is that PANE's clean end, like a shell exiting — the view is read + again and the pane goes with its block; any other code after a stream + was up ends the tab with the reason, and RECONNECT is the way back. + 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's rows + are commands, not bindings), Copy Mode, HISTORY, the one-second helper-chip + 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). + - **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 + scrollback, no FILE and a MOSH badge. + - ⚠ **A Rex tab's agent bar is the pane's the keyboard is on, 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's focus is its own, and the + session's 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 + moved by a touch on another pane, a split, and 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: + - **Floating layers over the layout, moving and swapping panes, + closing or renaming a window.** A tab draws one layer as the server + arranged it. Each of those is a state the Rex app owns + (`session.float_block`, `move_block`, `swap_blocks`, + `close_window`, `set_window_label` exist and were not called); a tab + that changed them would be rearranging the Mac's window from a + tablet. (A window still closes when its last pane does.) + - **A second SSH connection past `MaxSessions`** (above). + - **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). + - **An EXTERNAL launch into an existing Rex session** + (`launchInSession`): a widget / Shortcut / URL `in=tab` launch mints + a fresh session instead. (A tab already attached makes a new Rex tab + itself — the REX panel's New Tab, above.) + - 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's Switch + Terminal list once the tab is live, and `MULTIPLEX_AUTO_PANE_ACTIONS= + splitRight,splitDown,ratio:0.3,focus:1,zoomPane,closePane,newWindow` + walks the panel's rows, a divider drag and a touch on a pane (proof host-side: `rex api call -s + session.view` shows the tree and every block's `owner`, and + `com.superlogical.terminal.size` each pane's own columns × rows); + `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..9d4cc12f 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,20 @@ 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_PANE_ACTIONS=splitRight,splitDown,ratio:0.3,focus:1,closePane` + — on a paned (Rex) tab, walks the steps four seconds apart from six + seconds after it goes live, each through the entry point its control + uses: the REX panel's rows (`PaneShortcut` raw values — `splitRight`, + `splitDown`, `zoomPane`, `closePane`, `newWindow`), a divider + drag on the layout's first split (`ratio:`), a touch on the nth pane in + reading order (`focus:`). Fires once per process. Proof host-side: `rex + api call -s session.view` (the tree, every block's `owner`) + and `com.superlogical.terminal.size` per block. - `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/agents/input-and-windows.md b/docs/agents/input-and-windows.md index 6b62ab36..f01d2d73 100644 --- a/docs/agents/input-and-windows.md +++ b/docs/agents/input-and-windows.md @@ -89,7 +89,20 @@ 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 its Switch Terminal list has a + row per terminal and a single split window already has a second. (A Rex + tab draws its panes itself; which pane the keyboard, the rail and the + rest of the chrome follow is in `panes.md`.) 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/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/docs/agents/panes.md b/docs/agents/panes.md new file mode 100644 index 00000000..f4b90752 --- /dev/null +++ b/docs/agents/panes.md @@ -0,0 +1,217 @@ +# Native panes (a tab that draws its backend's panes itself) + +Split from AGENTS.md. Read before touching `PaneLayout`, +`PanedTerminalTransport`, `TerminalScreen`, `PaneSplitView`, or the paned +half of `TerminalSessionController` / `TerminalSurfaceView`. The first (and +so far only) backend that uses it is Rex — its own facts are in +`backends-and-probe.md`. + +- **Two kinds of tab.** A tmux, herdr, shell or mosh tab carries ONE byte + stream: the multiplexer on the far side composes its panes into it, and + the tab is one emulator. A **paned** tab carries one stream PER PANE and + the layout they sit in, and the app draws them — one emulator each, lines + between, resize by dragging. Which kind a tab is, is the route's fact + (`TerminalSessionController.drawsPanes`), never a setting. +- **Four pieces, and what each may know.** + - `PaneLayout` (Models, pure): a binary tree of splits with a `PaneID` at + every leaf, its geometry (`frames`, `ratio(forDividerAt:)`), and what a + tab can ask for (`PaneCommand`). No backend's vocabulary: an axis is + `sideBySide` or `stacked` because Rex, tmux and herdr do not agree + which of those is "horizontal". + - `PanedTerminalTransport` (Services, protocol) + `PaneEvents`: what a + backend that hands its panes out separately looks like to a tab — + write / resize per pane, `perform(PaneCommand)`, and four events + (`arrange`, `output`, `grid`, `close`). `RexSession` conforms; nothing + above it names Rex except the three places that are Rex features + (Switch Terminal, a pane's working directory, the route). + - `TerminalScreen` (Services): ONE emulator endpoint — the SwiftTerm + view, its output coalescer, its ordered input and resize pumps, its grid + pin. A single-stream tab has exactly one (`soleScreen`); a paned tab + one per pane. It writes through two closures, so it does not know which + kind of transport it belongs to. + - `PaneSplitView` (Views): the cells, the lines, the focus frame. It sits + exactly where the one `TerminalView` sits in `TerminalSurfaceView`, so + keyboard avoidance, bottom chrome and the safe-area edges move it the + same way and need no second version. +- **"The terminal" of a tab is the pane the keyboard is on.** + `TerminalSessionController.terminalView` is an observed mirror of the + active screen's view, moved by `activate`. Everything above the emulator + already read it lazily — the key rail, the ornament cluster, Talkback, + dictation, file drops, links, the agent strip — so a paned tab needed no + second chrome. Three things cached the view and had to learn to follow: + the iPad rail (`TerminalKeyBar.retarget`; a CTRL latch does NOT travel), + the surface's own coordinator (keyboard avoidance asks "is MY terminal + the first responder"), and the pane's two selection overlays + (`overlayTerminal` — left behind, they answered the old pane's presses). + The window observes `activePaneID` so the agent strip and the visionOS + cluster re-read. +- **The tab's focus is the tab's own.** `PaneCommand.focus` tells the + transport where the person is; what a backend makes of that is its + business. Rex only remembers it (see `backends-and-probe.md` for why it + is never `session.focus_block`). The transport moves the tab's focus only + with a reason, by naming a pane in `PaneArrangement.focus`: the attach's + target, a pane the tab just made, the neighbour of one that closed + (`PaneLayout.neighbor(ofClosing:)`), a terminal chosen from the panel. + nil leaves it where the person put it. +- **The keyboard follows the focus only if the tab had it.** + `TerminalSurfaceView.syncPanes` claims the new pane's view when the pane + being left was the first responder, or when there was none (the attach — + what a single emulator does when its surface is installed). A tab that + did not have the keyboard never takes it because its layout changed + somewhere else. A touch moves focus at touch DOWN + (`TouchDownGestureRecognizer`, which neither cancels nor delays + anything): the tap's release is too late — a long press raises the + selection menu of whichever pane is active, and it has to be the one + under the finger. Touch-down moves the keyboard only if the tab had it; + the tap (`reclaimFocus`) is still what summons a dismissed keyboard. + - ⚠ **The keyboard moves INSIDE `PaneSplitView.apply`, while the pane it + is leaving is still in the window** (`beforeDropping`, the one claim in + `syncPanes` for a tab that had the keyboard; only an attach's first + claim waits a turn, as a single emulator's does). It used to move a + turn later for every case, which is too late for a pane that GOES — a + closed pane, and every pane of the window a tab leaves for another + (New Tab, a terminal chosen from the panel): the keyboard left with + the old pane, and the layout pass the transport is answered from + measured the panes WITHOUT it. Measured on an iPad: a new window's + pane was opened at 73 rows, its terminal sized and rendered at 73, and + the pane was back at 51 before that rendering was fed — the + rendering's blank rows scrolled the top of the screen away (a shell's + first line gone, about three times in five). + - The coordinator is pointed at the new pane BEFORE the claim: + keyboard avoidance acts only on the terminal it names, so the hide + the resigning pane reports is not acted on and the show its + successor's is. + - Not closed by that: UIKit still reports the keyboard hidden and + shown again about 270 ms later (the hide it started and took back), + and the panes are 73 rows for one layout pass — two more `resize`s + for the terminal, no damage to the screen (a rendering fed to a + TALLER emulator scrolls nothing). +- ⚠ **A pane is laid out BEFORE its terminal is opened, and the transport + waits for that.** `PaneEvents.arrange` is async and answers with the grid + each pane measured: the controller makes the screens, the surface's + `observePaneLayout` hook lays them out synchronously (`layoutIfNeeded` — + SwiftTerm measures its grid from its frame in that pass), and only then + does the transport claim, size and render. A screen fetched for one size + and drawn at another is the stray-character bug `backends-and-probe.md` + records; without a mounted surface (a tab opened in the background) the + answer is the emulator's default grid and the first real layout resizes + it, which is no worse than a single-stream tab opened unseen. + - Still open: nothing ties a rendering to the grid the emulator has at + the moment it is FED. The transport hears a pane's size through its + pump, a moment after the emulator has it, so a pane that shrinks + between the fetch and the feed gets a rendering made for more rows + than it has (the keyboard handover above was the one case seen). The + complete fix is a feed that is refused when the grids differ — a + fifth `PaneEvents` member, awaited like `grid` — and was not built. + - A pane's pumps start at the arrangement, not at `.live`: its size has + to reach the transport while its terminal is still being opened. The + transport keeps the newest size it was told per pane even before it + knows the pane (`RexSession.requestedSizes`) and prefers it over what + `arrange` returned — the pump's word is the later one. +- **Zoom is the tab's own picture, and no backend is asked.** + `zoomedPaneID` draws the pane the keyboard is on over the whole split + (`PaneSplitView`: that cell gets the view's bounds, the others are + HIDDEN). Hidden is not gone: the other cells stay laid out where the + split has them, so their terminals keep the size they will be shown at + again and keep taking their output — leaving the zoom redraws nothing + and resizes only the pane that was zoomed. It ends when the tab's focus + goes to another pane, however that happens (a split made while zoomed, a + terminal chosen from the panel, the zoomed pane closing): the pane the + keyboard goes to has to be on screen, which is tmux's and Rex's own + rule. A layout change that leaves the focus alone leaves the zoom. A + bar over the pane (`TerminalContextBarView.zoomed`: ZOOMED + ALL PANES) + says so and is the way back — the panes it covers cannot be seen to be + missed. Why not the backend's own zoom: for Rex it cannot be aimed at + the tab's focus (`backends-and-probe.md`); a backend whose zoom CAN be + would state it in the arrangement instead, which nothing here forbids. +- **A session can have more windows than the tab draws.** A tab draws + one; `PaneCommand.newWindow(from:)` asks for another holding one pane, + and the transport moves the tab there by sending that window's + arrangement — the same road a terminal chosen from the panel's switch + list takes. Which word the row wears is the backend's (`PaneShortcut + .newWindow` is "New Window"; Rex's row is titled New Tab). + - The same road is how a tab survives its window closing: the transport + sends another window's arrangement instead of `close`, and names no + focus (Rex: `backends-and-probe.md`). `close` is for a session with + nothing left to draw. A tab whose every pane just went therefore gets + a new set in one arrangement — the case the keyboard handover above + exists for. +- **A file dropped on a pane lands in that pane.** The drop moves the + tab's focus to the pane under it first (`PaneSplitView.pane(at:)`), so + the upload goes to that pane's directory and the path is typed there — + the same road a path pressed in a pane takes, because a press moves the + focus too. +- **A drag moves the tab first and asks the backend second.** + `setPaneRatio` updates `paneLayout`, relays out synchronously, and queues + `.setRatio`. Commands leave through ONE ordered pump + (`startPaneCommandPump`): a drag makes dozens, and a `Task` per event let + an older ratio land last. The transport then owes two things, both + measured against Rex: send only the newest ratio while one is in flight, + and do not let the backend's answer to an EARLIER ask drag the line back + (`pendingRatios`, `floorRevision`). + - ⚠ The line is dragged by a press with NO delay + (`UILongPressGestureRecognizer`, `minimumPressDuration` 0), not a pan. + A pan begins only once the finger has travelled some way and reports + the travel from there — by position and by `translation` alike: with a + real touch a 180 pt drag moved the line 158. The strip is the line's + alone, so the drag can start where the finger lands; a touch that never + moves sends nothing. + - The strip a finger can take hold of reaches 8 pt onto each pane beside + the line, and sits above the panes: without it the terminal's own + gestures took the touch. +- **One pane cannot be opened: say so in the pane, keep the tab.** The + attach fails only when no pane opened. A pane that could not — sshd's + `MaxSessions` (10 channels a connection: the control pipe and nine + panes), a refused stream — gets one line in its own emulator and is not + retried on every layout change. +- **A reconnect keeps the screens.** `endPanedRun` drops the transport and + the pumps, not the `TerminalScreen`s: the next arrangement finds the same + panes by id and redraws into the same emulators (RIS + rendering), so + scrollback and the views survive a link drop the way a single emulator's + do. +- ⚠ **A moved tab has two surfaces for a moment.** The window it left gets + one last `update`; if that surface made cells it would adopt the emulator + views back out of the window the tab arrived in. `observePaneLayout(as:)` + records whose hook is installed and `syncPanes` does nothing for anyone + else. (The single-emulator path has the same guard as `isDescendant(of:)`.) +- **Colors inside the split are the terminal theme's**, not the chassis's: + lines at 20 % of the theme foreground, the focus frame at 60 %. The frame + lies ON the lines beside the pane (`frameOutset` = half the gap), so the + focused pane reads as one rectangle; a tab with one pane draws neither + and is pixel-for-pixel the single emulator. +- **What a second backend has to do** — nothing above the transport: + 1. Conform to `PanedTerminalTransport`; map its ids to `PaneID` and its + layout to `PaneLayout` (an n-ary row nests: `a | (b | c)`, ratios from + cell counts). + 2. Call `arrange` at the attach and on every layout change, and open a + pane's stream only after it returns. + 3. Make `drawsPanes` true for its route and start it from + `TerminalSessionController.run` through `runPanes(over:generation: + open:)` — that function has no Rex in it. + - **tmux control mode (`tmux -CC`)**, if it is ever wanted: `%output + %` is `output`, `%layout-change` an arrangement, `send-keys -t + % -H` a write, `split-window` / `kill-pane` / `resize-pane` the + commands. The one real difference: tmux sizes panes itself from the + client's WHOLE size. That adapter sums the panes' measured grids into + one `refresh-client -C` and pins every pane to the grid tmux answers + with through `PaneEvents.grid` — the road a Rex terminal already takes + while another client owns its size. Not measured; nothing was built. + - **herdr** (a core that serves panes apart from its TUI): not measured, + nothing built. What `HerdrProbe` already reads from the snapshot API is + half of an adapter — pane ids, each pane's rectangle, which is focused, + and close verbs by id. The other half is the part that decides it: a + stream per pane, and input addressed to one. +- Not built, on purpose: moving or swapping panes, a pane title + strip, hardware-keyboard chords for pane focus (a paned tab has no prefix + key to hang them on), and a pool of SSH connections past `MaxSessions`. +- Tests: `PaneLayoutTests` (tree + geometry), `TerminalPaneSplitUIKitTests` + (the real controller and surface over a recording transport — + `runPanesForTesting`), `RexSessionTests` (the Rex adapter against an + in-process server with a real layout tree). Real touches — + the tap that moves focus, the finger on a line — are + `MultiplexUITests/RexPanesUITests`, outside the unit scheme and CI like + the Arrange Keys one: it needs a Rex server (`TEST_RUNNER_MULTIPLEX_SEED + _HOST` + `TEST_RUNNER_MULTIPLEX_REX_SESSION`), and each step waits out + XCUITest's 60 s idle timeout because a terminal never idles, so one run + is about twelve minutes. Headless, without touches: + `MULTIPLEX_AUTO_PANE_ACTIONS` (`e2e-headless.md`). diff --git a/docs/agents/swiftterm-fork.md b/docs/agents/swiftterm-fork.md index 1f738478..97854669 100644 --- a/docs/agents/swiftterm-fork.md +++ b/docs/agents/swiftterm-fork.md @@ -247,6 +247,37 @@ 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. + - **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/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 — diff --git a/docs/store-metadata.md b/docs/store-metadata.md index 62d03188..10bdd61b 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 opens the window the session is showing, with its panes: every terminal of that window as a pane of its own, in Rex's split layout, resized by dragging the line between two. The tile menu's **Open Terminal** opens another window of the session as its own tab. The tab's **REX** key splits the focused pane right or down, zooms it (in this tab only), closes it, opens a new Rex tab (a window of the session), or switches the tab to another terminal. When the Rex tab on show is closed (its last shell exits, or its last pane is closed), the Multiplex tab moves to the Rex tab next to it, and ends only when the session has no terminal left. 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 (written against 0.1.0-preview.25, API revision 24, and speaking any revision from 14 up — Rex is a preview, 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 terminals' sizes, so a Rex window showing the same panes resizes with the tab; until someone types in the tab, it shows a pane another client holds at that client's size. In a window of more than nine panes, nine open and each further one says why it could not (one SSH connection carries ten channels). 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 113088e5..18d4fe31 100644 --- a/fastlane/testflight-whats-new.txt +++ b/fastlane/testflight-whats-new.txt @@ -1,9 +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. +• Rex: a host that runs Rex (superlogical.com/rex) can show its Rex sessions as tiles, and a tile opens a Rex window as a tab with its panes laid out as in Rex. Tap a pane to type in it; drag the line between two panes to resize them. The REX key splits the focused pane right or down, zooms or closes it, opens a new Rex tab, or switches to another terminal of the session. A host with Rex sessions gets a + REX chip on its rail; press it, or check REX in Host Settings under Backends. New Session and + TAB can create a Rex session while a Rex server runs on the host. While the Rex app holds a pane at another size, the tab shows it at that size until you type. Checked against Rex 0.1.0-preview.25. +• Terminal: the TMUX, HRDR or REX key now lights up when the session has more than one window (for Rex, terminal). 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. +1. On iPhone Duo, 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: they 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 ink and no text typed. Unlock: the Pencil should type again. +3. On a host running Rex with a session open, press the + REX chip on the host's rail: the Rex sessions should appear as tinted tiles. +4. Press the tile of a Rex session with a split: the tab should show every pane where Rex has it, colors and earlier output included. Tap a pane and type: it should run in that pane. +5. Open vim in a Rex terminal, then attach it: 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 second window and choose Open Terminal: that window should open as its own tab. +7. Exit the shell in one pane: that pane should close and the others stay. Exit the last pane of a Rex tab while the session has another: the tab should show that other Rex tab. Exit the last of the session: the tab should end with RECONNECT, 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, press the REX key and choose Split Right, then Split Down: each should add a pane in the same directory with the keyboard in it. Drag a line between panes: both should resize. Toggle Pane Zoom: that pane should fill the tab until ALL PANES. Close Pane twice: it should go. Rex on the host should show the same panes. New Tab: the tab should show a new Rex tab, and Switch Terminal should lead back. +10. Press + NEW SESSION and choose REX under Runs on: a new Rex session should open as a tab and appear in Rex. With no Rex server running, it should say so. +11. Lock the device for a minute with a Rex tab open: on return it should reconnect by itself. +12. In Host Settings under Backends, uncheck REX: the Rex tiles should go away. Check it again: they should come back. +13. Run an agent in one pane and a shell in another: the Agent Bar should show its keys only while the agent's pane is the framed one. +14. Attach a tmux session with one window, then add a second from the TMUX panel: the TMUX key should brighten. +15. Open the same Rex window on the Mac and in a tab, then work on the Mac without touching the tab: the Mac's panes should keep their sizes and not flicker, and the tab should show them at the Mac's sizes, never garbled. Type in the tab: it should take the sizes back. Feedback: screenshot in TestFlight