diff --git a/cmux-tui/Cargo.lock b/cmux-tui/Cargo.lock index 58e1dca302b2..fd4efb879180 100644 --- a/cmux-tui/Cargo.lock +++ b/cmux-tui/Cargo.lock @@ -679,6 +679,7 @@ dependencies = [ "crossterm", "getrandom 0.3.4", "ghostty-vt", + "glob", "libc", "parking_lot", "ratatui", diff --git a/cmux-tui/Cargo.toml b/cmux-tui/Cargo.toml index da92327e088c..352a4be78b29 100644 --- a/cmux-tui/Cargo.toml +++ b/cmux-tui/Cargo.toml @@ -94,6 +94,7 @@ regex = "1" bindgen = "0.72" smallvec = "1" getrandom = "0.3" +glob = "0.3" bytes = "1" diffy = "0.4" fs4 = "1.1.0" diff --git a/cmux-tui/README.md b/cmux-tui/README.md index 7ffe3b24211a..b8fcbbc9afff 100644 --- a/cmux-tui/README.md +++ b/cmux-tui/README.md @@ -59,15 +59,16 @@ cmux session current events --jsonl Resource IDs are opaque typed strings. Selectors also accept `current` or an exact name. Duplicate names return `selector.ambiguous` with every candidate ID; use an ID to choose one. Prefix a reserved or ID-shaped name with `name:`. -Packaged builds can run as `npx cmux`. The optional machine rail lets that local client switch among the current session, other Unix sockets, and sessions reached through SSH. It is disabled by default and activates when `machine_sidebar.enabled` is true or `machines` contains a valid entry in `cmux-tui.json`. `npx cmux --cloud` composes those local targets with the Cloud catalog and enables temporary machine connections without sending local SSH details to Cloud. The client uses noninteractive SSH with strict host-key checking and the remote `cmux relay --session ` transport primitive, so the remote headless session, trusted host key, authentication key, and binary must already exist. See [Machines and remote sessions](docs/machines.md). +Packaged builds can run as `npx cmux`. The optional machine rail lets that local client switch among the current session, other Unix sockets, and sessions reached through SSH. It is disabled by default and activates when `machine_sidebar.enabled` is true or `machines` contains a valid entry in `cmux-tui.json`. `npx cmux --cloud` composes those local targets with the Cloud catalog and enables temporary machine connections without sending local SSH details to Cloud. The rail uses the same managed connection path as `cmux ssh`: it probes compatibility, packaged releases can install their pinned remote binary, and it starts the named remote session on demand. Source builds require the exact matching binary to be installed remotely. SSH remains noninteractive with strict host-key checking and disabled forwarding. See [Machines and remote sessions](docs/machines.md). ```bash npx cmux npx cmux machine-agent --session agents +npx cmux ssh dev@buildbox --session agents ssh -T dev@buildbox cmux relay --session agents ``` -The Unix-only `machine-agent` shares an existing local session through one outbound SSH registration with cmux.cloud. It prints a one-time pairing code and opens no listener. The final command carries raw JSON-lines protocol traffic and is normally started by the machine connector, not used as an interactive TUI. +The Unix-only `machine-agent` shares an existing local session through one outbound SSH registration with cmux.cloud. It prints a one-time pairing code and opens no listener. The final command is a low-level raw JSON-lines diagnostic; the machine rail and `cmux ssh` use the managed remote lifecycle instead. Use `--term ` to set `TERM` for child PTYs. Without it, children get `xterm-256color`; `CMUX_TUI_TERM` can override the terminal runtime default, with `CMUX_MUX_TERM` retained as a legacy fallback. diff --git a/cmux-tui/bindings/cpp/.cmux-sdk-manifest.json b/cmux-tui/bindings/cpp/.cmux-sdk-manifest.json index a6cdb79a1b33..651929b7e5eb 100644 --- a/cmux-tui/bindings/cpp/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/cpp/.cmux-sdk-manifest.json @@ -7,22 +7,22 @@ }, { "path": "include/cmux/raw/generated/events.hpp", - "sha256": "11f825023a6b0faa094c53a852007e660210329642b51480240c492523a866aa", - "size": 1986 + "sha256": "d14ebe18356460e0385b8580495da3f5c5a44fd702d0691253d75c0e81f02856", + "size": 2005 }, { "path": "include/cmux/raw/generated/models.hpp", - "sha256": "cbf029475b06d5bd083b42c3c9d7f2024fcb718b4372a6ffdddbc18a3a2e94a7", - "size": 115380 + "sha256": "386b3a3b82d86f28fe6ab87fcf82160746710003cad19e9941ffef6e3c75df4c", + "size": 115850 }, { "path": "src/raw/generated/protocol.cpp", - "sha256": "32b62828cafdd329d180905df279d440dfd71d95fc001098aa7ae8b436c9b928", - "size": 763149 + "sha256": "0dd2671aa5984a29276e54667b13c45df611cdc1c741360414bbc3bb4bd7b762", + "size": 767317 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "cpp", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/cpp/include/cmux/raw/generated/events.hpp b/cmux-tui/bindings/cpp/include/cmux/raw/generated/events.hpp index 0f5a14643c0e..bc2147269599 100644 --- a/cmux-tui/bindings/cpp/include/cmux/raw/generated/events.hpp +++ b/cmux-tui/bindings/cpp/include/cmux/raw/generated/events.hpp @@ -17,7 +17,7 @@ struct UnknownEvent { }; struct Event { - using Variant = std::variant; + using Variant = std::variant; Variant value; Json raw; [[nodiscard]] std::string_view name() const noexcept; diff --git a/cmux-tui/bindings/cpp/include/cmux/raw/generated/models.hpp b/cmux-tui/bindings/cpp/include/cmux/raw/generated/models.hpp index fd5cdc55d43f..f8b2aecbafe7 100644 --- a/cmux-tui/bindings/cpp/include/cmux/raw/generated/models.hpp +++ b/cmux-tui/bindings/cpp/include/cmux/raw/generated/models.hpp @@ -14,7 +14,7 @@ namespace cmux::raw { inline constexpr std::uint32_t kMuxProtocolVersion = 11U; -inline constexpr std::string_view kProtocolIrSha256 = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1"; +inline constexpr std::string_view kProtocolIrSha256 = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3"; struct AgentRecord; enum class AgentReportSource; @@ -211,6 +211,7 @@ struct UndoLayoutRequest; struct VtStateRequest; struct WaitForRequest; struct ZoomPaneRequest; +struct AgentChangedEvent; struct BellEvent; struct BrowserStateEvent; struct ClientAttachedEvent; @@ -301,6 +302,15 @@ struct Id { friend bool operator==(const Id&, const Id&) = default; }; +struct AgentChangedEvent { + std::optional session{}; + AgentSource source{}; + AgentState state{}; + Id surface{}; + std::uint64_t updated_at_ms{}; + friend bool operator==(const AgentChangedEvent&, const AgentChangedEvent&) = default; +}; + struct AgentRecord { std::optional session{}; AgentSource source{}; @@ -3565,6 +3575,12 @@ struct Codec { static Result decode(const Json& value); }; +template <> +struct Codec { + static Result encode(const AgentChangedEvent& value); + static Result decode(const Json& value); +}; + template <> struct Codec { static Result encode(const BellEvent& value); diff --git a/cmux-tui/bindings/cpp/src/raw/generated/protocol.cpp b/cmux-tui/bindings/cpp/src/raw/generated/protocol.cpp index 8ab9842ea2c4..97261dd53cd3 100644 --- a/cmux-tui/bindings/cpp/src/raw/generated/protocol.cpp +++ b/cmux-tui/bindings/cpp/src/raw/generated/protocol.cpp @@ -11825,6 +11825,97 @@ Result Codec::decode(const Json& value) { return result; } +Result Codec::encode(const AgentChangedEvent& value) { + (void)value; + Json::Object object; + object.emplace("event", Json(std::string("agent-changed"))); + if (value.session) { + auto encoded = encode_value(*value.session); + if (!encoded) return std::move(encoded).error(); + object.emplace("session", std::move(encoded).value()); + } else { + object.emplace("session", Json(nullptr)); + } + auto encoded_source = encode_value(value.source); + if (!encoded_source) return std::move(encoded_source).error(); + object.emplace("source", std::move(encoded_source).value()); + auto encoded_state = encode_value(value.state); + if (!encoded_state) return std::move(encoded_state).error(); + object.emplace("state", std::move(encoded_state).value()); + auto encoded_surface = encode_value(value.surface); + if (!encoded_surface) return std::move(encoded_surface).error(); + object.emplace("surface", std::move(encoded_surface).value()); + auto encoded_updated_at_ms = encode_value(value.updated_at_ms); + if (!encoded_updated_at_ms) return std::move(encoded_updated_at_ms).error(); + object.emplace("updated_at_ms", std::move(encoded_updated_at_ms).value()); + return Json(std::move(object)); +} + +Result Codec::decode(const Json& value) { + auto source = value.as_object(); + if (!source) return std::move(source).error(); + AgentChangedEvent result{}; + const Json* field_session = value.find("session"); + if (!field_session) { + return make_error(ErrorCode::decode, "missing required field 'session'"); + } + if (field_session) { + if (field_session->is_null()) { + result.session.reset(); + } else { + auto decoded = decode_value(*field_session); + if (!decoded) return std::move(decoded).error(); + result.session = std::move(decoded).value(); + } + } + const Json* field_source = value.find("source"); + if (!field_source) { + return make_error(ErrorCode::decode, "missing required field 'source'"); + } + if (field_source) { + auto decoded = decode_value(*field_source); + if (!decoded) return std::move(decoded).error(); + result.source = std::move(decoded).value(); + } + const Json* field_state = value.find("state"); + if (!field_state) { + return make_error(ErrorCode::decode, "missing required field 'state'"); + } + if (field_state) { + auto decoded = decode_value(*field_state); + if (!decoded) return std::move(decoded).error(); + result.state = std::move(decoded).value(); + } + const Json* field_surface = value.find("surface"); + if (!field_surface) { + return make_error(ErrorCode::decode, "missing required field 'surface'"); + } + if (field_surface) { + auto decoded = decode_value(*field_surface); + if (!decoded) return std::move(decoded).error(); + result.surface = std::move(decoded).value(); + } + const Json* field_updated_at_ms = value.find("updated_at_ms"); + if (!field_updated_at_ms) { + return make_error(ErrorCode::decode, "missing required field 'updated_at_ms'"); + } + if (field_updated_at_ms) { + auto decoded = decode_value(*field_updated_at_ms); + if (!decoded) return std::move(decoded).error(); + result.updated_at_ms = std::move(decoded).value(); + } + const Json* field_event = value.find("event"); + if (!field_event) { + return make_error(ErrorCode::decode, "missing required field 'event'"); + } + if (field_event) { + if (*field_event != Json(std::string("agent-changed"))) { + return make_error(ErrorCode::decode, "field 'event' has the wrong literal value"); + } + } + return result; +} + Result Codec::encode(const BellEvent& value) { (void)value; Json::Object object; @@ -15948,6 +16039,11 @@ Result Codec::encode(const Event& value) { Result Codec::decode(const Json& value) { auto name = require_string(value, "event"); if (!name) return std::move(name).error(); + if (name.value() == "agent-changed") { + auto decoded = decode_value(value); + if (!decoded) return std::move(decoded).error(); + return Event{Event::Variant(std::move(decoded).value()), value}; + } if (name.value() == "bell") { auto decoded = decode_value(value); if (!decoded) return std::move(decoded).error(); @@ -16337,7 +16433,8 @@ constexpr std::array kCommands{{ {"wait-for", "control", 6U, "", false, "", "", std::span{}}, {"zoom-pane", "control", 6U, "", false, "", "", std::span{}}, }}; -constexpr std::array kEvents{{ +constexpr std::array kEvents{{ + {"agent-changed", 11U, "", "subscribe", "emitted"}, {"bell", 5U, "", "subscribe", "emitted"}, {"browser-state", 6U, "", "attach-browser", "emitted"}, {"client-attached", 6U, "", "subscribe", "emitted"}, diff --git a/cmux-tui/bindings/cpp/tests/test_generated.cpp b/cmux-tui/bindings/cpp/tests/test_generated.cpp index 82166c3af474..2ddb66aaaaca 100644 --- a/cmux-tui/bindings/cpp/tests/test_generated.cpp +++ b/cmux-tui/bindings/cpp/tests/test_generated.cpp @@ -102,7 +102,7 @@ TEST("generated command and event metadata is exhaustive and unique") { const auto commands = cmux::raw::command_metadata(); const auto events = cmux::raw::event_metadata(); CHECK_EQ(commands.size(), kExpectedRawCommandCount); - CHECK_EQ(events.size(), 45U); + CHECK_EQ(events.size(), 46U); std::set command_names; bool checked_attach_fields = false; diff --git a/cmux-tui/bindings/go/raw/.cmux-sdk-manifest.json b/cmux-tui/bindings/go/raw/.cmux-sdk-manifest.json index 9b2ad41f1cff..ea5d7af52190 100644 --- a/cmux-tui/bindings/go/raw/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/go/raw/.cmux-sdk-manifest.json @@ -2,32 +2,32 @@ "files": [ { "path": "generated_commands.go", - "sha256": "83469141b0e989346b3e46699956f723eeb920811d40c1fe5793efca48634beb", + "sha256": "6abb809eac29e47915323446537dac6cb1e3b8c28c216633bb86ffabdb45a74b", "size": 341918 }, { "path": "generated_events.go", - "sha256": "33b571e822ff4d66b5cb7a78bdbcfb5a5734b9f21f3950ecce559ba0235fc058", - "size": 105515 + "sha256": "ca30202063847ccfe59b56a205ec643ac0fb8869f9818b62e03724e595c3baf6", + "size": 108363 }, { "path": "generated_metadata.go", - "sha256": "bd9cf8bcfa548bd11b21151687e3f1b159ae648a0be09917740d9be4dafd72a2", - "size": 45686 + "sha256": "078a807f2964c4f17812eac696f27ddb296375f911a572cc1e6b3165950e2abe", + "size": 45964 }, { "path": "generated_presence_test.go", - "sha256": "458eaf4ae57b5f66e5c060a38b988fb852c98acc59a50426dc0a710737239c1a", - "size": 946491 + "sha256": "36a5768a5ceb0f1c34df8a161391aff96c240f1d64e56bf6f7f6b9c1fd59e5cb", + "size": 951987 }, { "path": "generated_types.go", - "sha256": "55c34f9cd24c85679c30bf182affb79cb45866a4be6c0481ab48f13392bd60b5", + "sha256": "bbcfdb6d3d3fb43bcb778f3dec9d53e9f4e2d3c7008e8169b24a57dab47d7011", "size": 244810 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "go", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/go/raw/client_test.go b/cmux-tui/bindings/go/raw/client_test.go index 1474950edd0b..47ae30025f77 100644 --- a/cmux-tui/bindings/go/raw/client_test.go +++ b/cmux-tui/bindings/go/raw/client_test.go @@ -51,8 +51,8 @@ func TestGeneratedInventoryHasTypedMethodForEveryCommand(t *testing.T) { t.Errorf("generated command inventory is missing %s", name) } } - if events := AllEventMetadata(); len(events) != 45 { - t.Fatalf("generated events = %d, want 45", len(events)) + if events := AllEventMetadata(); len(events) != 46 { + t.Fatalf("generated events = %d, want 46", len(events)) } } diff --git a/cmux-tui/bindings/go/raw/generated_commands.go b/cmux-tui/bindings/go/raw/generated_commands.go index 29273a6cd6d7..ba80db1d7b13 100644 --- a/cmux-tui/bindings/go/raw/generated_commands.go +++ b/cmux-tui/bindings/go/raw/generated_commands.go @@ -1,5 +1,5 @@ // Code generated by cmux-tui SDK codegen. DO NOT EDIT. -// Mux protocol 11; IR SHA-256 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// Mux protocol 11; IR SHA-256 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. package raw diff --git a/cmux-tui/bindings/go/raw/generated_events.go b/cmux-tui/bindings/go/raw/generated_events.go index acc8f2e71069..afd40de01512 100644 --- a/cmux-tui/bindings/go/raw/generated_events.go +++ b/cmux-tui/bindings/go/raw/generated_events.go @@ -1,5 +1,5 @@ // Code generated by cmux-tui SDK codegen. DO NOT EDIT. -// Mux protocol 11; IR SHA-256 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// Mux protocol 11; IR SHA-256 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. package raw @@ -38,6 +38,85 @@ type BrowserAttachEvent interface { isBrowserAttachEvent() } +// AgentChangedEvent is emitted by protocol v11. +type AgentChangedEvent struct { + Session RequiredNullable[string] `json:"-"` + Source AgentSource `json:"source"` + State AgentState `json:"state"` + Surface ID `json:"surface"` + UpdatedAtMs uint64 `json:"updated_at_ms"` +} + +func (value AgentChangedEvent) MarshalJSON() ([]byte, error) { + type wire AgentChangedEvent + encoded, err := json.Marshal(wire(value)) + if err != nil { + return nil, err + } + var object map[string]json.RawMessage + if err := json.Unmarshal(encoded, &object); err != nil { + return nil, err + } + if !value.Session.IsSet() { + return nil, fmt.Errorf("encode AgentChangedEvent: required nullable field session is missing") + } + if value.Session.IsNull() { + object["session"] = json.RawMessage("null") + } else { + fieldValue, _ := value.Session.Get() + encodedField, err := json.Marshal(fieldValue) + if err != nil { + return nil, fmt.Errorf("encode AgentChangedEvent.Session: %w", err) + } + object["session"] = encodedField + } + return json.Marshal(object) +} + +func (value *AgentChangedEvent) UnmarshalJSON(data []byte) error { + if !isJSONObject(data) { + return fmt.Errorf("decode AgentChangedEvent: expected object") + } + var fields struct { + Session RequiredNullable[string] `json:"session"` + Source *AgentSource `json:"source"` + State *AgentState `json:"state"` + Surface *ID `json:"surface"` + UpdatedAtMs *uint64 `json:"updated_at_ms"` + } + if err := json.Unmarshal(data, &fields); err != nil { + return fmt.Errorf("decode AgentChangedEvent: %w", err) + } + type wire AgentChangedEvent + var decoded wire + if !fields.Session.IsSet() { + return fmt.Errorf("decode AgentChangedEvent: required field session is missing") + } + decoded.Session = fields.Session + if fields.Source == nil { + return fmt.Errorf("decode AgentChangedEvent: required field source is missing or null") + } + decoded.Source = *fields.Source + if fields.State == nil { + return fmt.Errorf("decode AgentChangedEvent: required field state is missing or null") + } + decoded.State = *fields.State + if fields.Surface == nil { + return fmt.Errorf("decode AgentChangedEvent: required field surface is missing or null") + } + decoded.Surface = *fields.Surface + if fields.UpdatedAtMs == nil { + return fmt.Errorf("decode AgentChangedEvent: required field updated_at_ms is missing or null") + } + decoded.UpdatedAtMs = *fields.UpdatedAtMs + *value = AgentChangedEvent(decoded) + return nil +} + +func (AgentChangedEvent) EventName() string { return "agent-changed" } +func (AgentChangedEvent) isDeltaEvent() {} +func (AgentChangedEvent) isSubscribeEvent() {} + // BellEvent is emitted by protocol v5. type BellEvent struct { Surface ID `json:"surface"` @@ -2859,6 +2938,11 @@ func (UnknownEvent) isBrowserAttachEvent() {} func parseEvent(raw map[string]any) Event { name, _ := raw["event"].(string) switch name { + case "agent-changed": + var event AgentChangedEvent + if decodeEvent(raw, &event) { + return event + } case "bell": var event BellEvent if decodeEvent(raw, &event) { diff --git a/cmux-tui/bindings/go/raw/generated_metadata.go b/cmux-tui/bindings/go/raw/generated_metadata.go index 836ab5bb2256..6ee5f68aeaab 100644 --- a/cmux-tui/bindings/go/raw/generated_metadata.go +++ b/cmux-tui/bindings/go/raw/generated_metadata.go @@ -1,12 +1,12 @@ // Code generated by cmux-tui SDK codegen. DO NOT EDIT. -// Mux protocol 11; IR SHA-256 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// Mux protocol 11; IR SHA-256 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. package raw const ( SDKSchemaVersion = 2 MuxProtocolVersion = 11 - SDKIRSHA256 = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1" + SDKIRSHA256 = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3" ) type Authority string @@ -162,6 +162,7 @@ var commandMetadata = map[string]CommandMetadata{ } var eventMetadata = map[string]EventMetadata{ + "agent-changed": {Name: "agent-changed", Since: 11, Capability: "", Streams: []string{"subscribe"}, Emission: "emitted"}, "bell": {Name: "bell", Since: 5, Capability: "", Streams: []string{"subscribe"}, Emission: "emitted"}, "browser-state": {Name: "browser-state", Since: 6, Capability: "", Streams: []string{"attach-browser"}, Emission: "emitted"}, "client-attached": {Name: "client-attached", Since: 6, Capability: "", Streams: []string{"subscribe"}, Emission: "emitted"}, @@ -354,8 +355,11 @@ func AllCommandMetadata() []CommandMetadata { } func AllEventMetadata() []EventMetadata { - result := make([]EventMetadata, 0, 45) + result := make([]EventMetadata, 0, 46) var metadata EventMetadata + metadata = eventMetadata["agent-changed"] + metadata.Streams = append([]string(nil), metadata.Streams...) + result = append(result, metadata) metadata = eventMetadata["bell"] metadata.Streams = append([]string(nil), metadata.Streams...) result = append(result, metadata) diff --git a/cmux-tui/bindings/go/raw/generated_presence_test.go b/cmux-tui/bindings/go/raw/generated_presence_test.go index d28a11a7c42e..6f9dc83e30eb 100644 --- a/cmux-tui/bindings/go/raw/generated_presence_test.go +++ b/cmux-tui/bindings/go/raw/generated_presence_test.go @@ -1,5 +1,5 @@ // Code generated by cmux-tui SDK codegen. DO NOT EDIT. -// Mux protocol 11; IR SHA-256 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// Mux protocol 11; IR SHA-256 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. package raw @@ -10641,6 +10641,28 @@ func TestGeneratedSchemaPresenceRoundTrips(t *testing.T) { } assertGeneratedFieldJSON(t, presentValue, "pane", true, "1") }) + t.Run("AgentChangedEvent.Session", func(t *testing.T) { + var missing AgentChangedEvent + if err := json.Unmarshal([]byte("{\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &missing); err == nil { + t.Fatal("missing required nullable field session decoded successfully") + } + var nullValue AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &nullValue); err != nil { + t.Fatal(err) + } + if !nullValue.Session.IsSet() || !nullValue.Session.IsNull() { + t.Fatal("Session did not preserve required null") + } + assertGeneratedFieldJSON(t, nullValue, "session", true, "null") + var presentValue AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":\"value\",\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &presentValue); err != nil { + t.Fatal(err) + } + if _, ok := presentValue.Session.Get(); !ok { + t.Fatal("Session did not preserve a required value") + } + assertGeneratedFieldJSON(t, presentValue, "session", true, "\"value\"") + }) t.Run("BrowserStateEvent.Error", func(t *testing.T) { var missing BrowserStateEvent if err := json.Unmarshal([]byte("{\"cols\":1,\"frames_stalled\":true,\"rows\":1,\"status\":\"starting\",\"surface\":1,\"title\":\"value\",\"url\":\"value\"}"), &missing); err == nil { @@ -14688,6 +14710,36 @@ func TestGeneratedRequiredFieldsRejectOmission(t *testing.T) { t.Fatal("missing required field timeout_ms decoded successfully") } }) + t.Run("AgentChangedEvent.Session", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("missing required field session decoded successfully") + } + }) + t.Run("AgentChangedEvent.Source", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("missing required field source decoded successfully") + } + }) + t.Run("AgentChangedEvent.State", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("missing required field state decoded successfully") + } + }) + t.Run("AgentChangedEvent.Surface", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("missing required field surface decoded successfully") + } + }) + t.Run("AgentChangedEvent.UpdatedAtMs", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":1}"), &decoded); err == nil { + t.Fatal("missing required field updated_at_ms decoded successfully") + } + }) t.Run("BellEvent.Surface", func(t *testing.T) { var decoded BellEvent if err := json.Unmarshal([]byte("{}"), &decoded); err == nil { @@ -18117,6 +18169,30 @@ func TestGeneratedRequiredNonnullableFieldsRejectNull(t *testing.T) { t.Fatal("required non-nullable field timeout_ms accepted null") } }) + t.Run("AgentChangedEvent.Source", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":null,\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("required non-nullable field source accepted null") + } + }) + t.Run("AgentChangedEvent.State", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":null,\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("required non-nullable field state accepted null") + } + }) + t.Run("AgentChangedEvent.Surface", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":null,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("required non-nullable field surface accepted null") + } + }) + t.Run("AgentChangedEvent.UpdatedAtMs", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":null}"), &decoded); err == nil { + t.Fatal("required non-nullable field updated_at_ms accepted null") + } + }) t.Run("BellEvent.Surface", func(t *testing.T) { var decoded BellEvent if err := json.Unmarshal([]byte("{\"surface\":null}"), &decoded); err == nil { @@ -19368,6 +19444,18 @@ func TestGeneratedConstrainedFieldsRejectUnknownValues(t *testing.T) { t.Fatal("invalid constrained field mode decoded successfully") } }) + t.Run("AgentChangedEvent.Source", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"__cmux_invalid__\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("invalid constrained field source decoded successfully") + } + }) + t.Run("AgentChangedEvent.State", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"__cmux_invalid__\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err == nil { + t.Fatal("invalid constrained field state decoded successfully") + } + }) t.Run("BrowserStateEvent.Status", func(t *testing.T) { var decoded BrowserStateEvent if err := json.Unmarshal([]byte("{\"cols\":1,\"error\":null,\"frames_stalled\":true,\"rows\":1,\"status\":\"__cmux_invalid__\",\"surface\":1,\"title\":\"value\",\"url\":\"value\"}"), &decoded); err == nil { @@ -20125,6 +20213,26 @@ func TestGeneratedConstrainedFieldsRejectUnknownValuesOnMarshal(t *testing.T) { t.Fatal("invalid constrained field mode encoded successfully") } }) + t.Run("AgentChangedEvent.Source", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err != nil { + t.Fatal(err) + } + decoded.Source = AgentSource("__cmux_invalid__") + if _, err := json.Marshal(decoded); err == nil { + t.Fatal("invalid constrained field source encoded successfully") + } + }) + t.Run("AgentChangedEvent.State", func(t *testing.T) { + var decoded AgentChangedEvent + if err := json.Unmarshal([]byte("{\"session\":null,\"source\":\"detected\",\"state\":\"working\",\"surface\":1,\"updated_at_ms\":1}"), &decoded); err != nil { + t.Fatal(err) + } + decoded.State = AgentState("__cmux_invalid__") + if _, err := json.Marshal(decoded); err == nil { + t.Fatal("invalid constrained field state encoded successfully") + } + }) t.Run("BrowserStateEvent.Status", func(t *testing.T) { var decoded BrowserStateEvent if err := json.Unmarshal([]byte("{\"cols\":1,\"error\":null,\"frames_stalled\":true,\"rows\":1,\"status\":\"starting\",\"surface\":1,\"title\":\"value\",\"url\":\"value\"}"), &decoded); err != nil { @@ -20199,12 +20307,12 @@ func TestGeneratedConstrainedFieldsRejectUnknownValuesOnMarshal(t *testing.T) { } const ( - generatedFieldShapeCount = 477 + generatedFieldShapeCount = 478 generatedOptionalNullableFieldCount = 321 - generatedRequiredNullableFieldCount = 69 + generatedRequiredNullableFieldCount = 70 generatedOptionalNonnullableFieldCount = 87 - generatedRequiredFieldCount = 627 - generatedRequiredNonnullableFieldCount = 558 - generatedConstrainedFieldCount = 78 - generatedEncodedConstrainedFieldCount = 78 + generatedRequiredFieldCount = 632 + generatedRequiredNonnullableFieldCount = 562 + generatedConstrainedFieldCount = 80 + generatedEncodedConstrainedFieldCount = 80 ) diff --git a/cmux-tui/bindings/go/raw/generated_types.go b/cmux-tui/bindings/go/raw/generated_types.go index 3adb2ca8eb18..76b41246d164 100644 --- a/cmux-tui/bindings/go/raw/generated_types.go +++ b/cmux-tui/bindings/go/raw/generated_types.go @@ -1,5 +1,5 @@ // Code generated by cmux-tui SDK codegen. DO NOT EDIT. -// Mux protocol 11; IR SHA-256 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// Mux protocol 11; IR SHA-256 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. package raw diff --git a/cmux-tui/bindings/java/src/com/cmux/raw/.cmux-sdk-manifest.json b/cmux-tui/bindings/java/src/com/cmux/raw/.cmux-sdk-manifest.json index 00ba61e68f31..fa2dba43e487 100644 --- a/cmux-tui/bindings/java/src/com/cmux/raw/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/java/src/com/cmux/raw/.cmux-sdk-manifest.json @@ -1,5 +1,10 @@ { "files": [ + { + "path": "AgentChangedEvent.java", + "sha256": "541d7a39ee461d670c8827a7dc33d61a67f35fc3c4a62194cd5f44db5b2ff837", + "size": 5113 + }, { "path": "AgentRecord.java", "sha256": "eef00432f4ddccf77ea227a7a744562bb05d4d529c03e789caaf21bb4a8969be", @@ -392,8 +397,8 @@ }, { "path": "Events.java", - "sha256": "ea4d3a5388d173e2a5a132e6e44deda398f091f867c4aec4481c8719cdde80af", - "size": 8859 + "sha256": "71c5c3389dd353275d2820e385d869a46006b00fdc41064cb6b6ddc4754b2e8e", + "size": 9039 }, { "path": "ExportLayoutRequest.java", @@ -762,8 +767,8 @@ }, { "path": "Protocol.java", - "sha256": "457298b3a6661f0eae6f288a02b8bebac4c559a7dca0b41637122efd2f021fcd", - "size": 3967 + "sha256": "523f051e137f3482edd8574c636cb24b5e81212b754d6ac1296a67e0d8894b8c", + "size": 4038 }, { "path": "ProtocolEvent.java", @@ -1382,7 +1387,7 @@ } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "java", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/java/src/com/cmux/raw/AgentChangedEvent.java b/cmux-tui/bindings/java/src/com/cmux/raw/AgentChangedEvent.java new file mode 100644 index 000000000000..2f1ea304057b --- /dev/null +++ b/cmux-tui/bindings/java/src/com/cmux/raw/AgentChangedEvent.java @@ -0,0 +1,123 @@ +// Generated from cmux-tui/spec/sdk-schema.json. DO NOT EDIT. +package com.cmux.raw; + + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + + +/** Immutable agent-changed event. Protocol v11; streams: subscribe. */ +public final class AgentChangedEvent implements WireValue, DeltaStreamEvent, ProtocolEvent, SubscribeEvent { + private final String session; + private final AgentSource source; + private final AgentState state; + private final UInt64 surface; + private final UInt64 updatedAtMs; + + private AgentChangedEvent(Builder builder) { + if (!builder.sessionSet) throw new IllegalArgumentException("session is required"); + this.session = builder.session; + if (!builder.sourceSet) throw new IllegalArgumentException("source is required"); + this.source = Wire.nonNull(builder.source, "source"); + if (!builder.stateSet) throw new IllegalArgumentException("state is required"); + this.state = Wire.nonNull(builder.state, "state"); + if (!builder.surfaceSet) throw new IllegalArgumentException("surface is required"); + this.surface = Wire.nonNull(builder.surface, "surface"); + if (!builder.updatedAtMsSet) throw new IllegalArgumentException("updated_at_ms is required"); + this.updatedAtMs = Wire.nonNull(builder.updatedAtMs, "updated_at_ms"); + } + + public static Builder builder() { return new Builder(); } + + public String session() { return session; } + public AgentSource source() { return source; } + public AgentState state() { return state; } + public UInt64 surface() { return surface; } + public UInt64 updatedAtMs() { return updatedAtMs; } + @Override public String event() { return "agent-changed"; } + + public static AgentChangedEvent fromWire(Object value) { + Map object = Wire.object(value, "AgentChangedEvent"); + Builder builder = builder(); + ProtocolSupport.literal(Wire.required(object, "event"), "agent-changed", "AgentChangedEvent.event"); + Object rawSession = Wire.required(object, "session"); + builder.session(rawSession == null ? null : Wire.string(rawSession, "AgentChangedEvent.session")); + Object rawSource = Wire.required(object, "source"); + builder.source(AgentSource.fromWire(rawSource)); + Object rawState = Wire.required(object, "state"); + builder.state(AgentState.fromWire(rawState)); + Object rawSurface = Wire.required(object, "surface"); + builder.surface(Wire.uint64(rawSurface, "AgentChangedEvent.surface")); + Object rawUpdatedAtMs = Wire.required(object, "updated_at_ms"); + builder.updatedAtMs(Wire.uint64(rawUpdatedAtMs, "AgentChangedEvent.updated_at_ms")); + return builder.build(); + } + + @Override + public Map toWire() { + LinkedHashMap object = new LinkedHashMap<>(); + object.put("event", "agent-changed"); + Wire.put(object, "session", session); + Wire.put(object, "source", source); + Wire.put(object, "state", state); + Wire.put(object, "surface", surface); + Wire.put(object, "updated_at_ms", updatedAtMs); + return Collections.unmodifiableMap(object); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof AgentChangedEvent that)) return false; + return Objects.equals(session, that.session) && Objects.equals(source, that.source) && Objects.equals(state, that.state) && Objects.equals(surface, that.surface) && Objects.equals(updatedAtMs, that.updatedAtMs); + } + + @Override + public int hashCode() { return Objects.hash(session, source, state, surface, updatedAtMs); } + + @Override + public String toString() { return "AgentChangedEvent" + toWire(); } + + public static final class Builder { + private String session; + private boolean sessionSet; + private AgentSource source; + private boolean sourceSet; + private AgentState state; + private boolean stateSet; + private UInt64 surface; + private boolean surfaceSet; + private UInt64 updatedAtMs; + private boolean updatedAtMsSet; + + public Builder session(String value) { + this.session = value; + this.sessionSet = true; + return this; + } + public Builder source(AgentSource value) { + this.source = value; + this.sourceSet = true; + return this; + } + public Builder state(AgentState value) { + this.state = value; + this.stateSet = true; + return this; + } + public Builder surface(UInt64 value) { + this.surface = value; + this.surfaceSet = true; + return this; + } + public Builder updatedAtMs(UInt64 value) { + this.updatedAtMs = value; + this.updatedAtMsSet = true; + return this; + } + public AgentChangedEvent build() { return new AgentChangedEvent(this); } + } +} diff --git a/cmux-tui/bindings/java/src/com/cmux/raw/Events.java b/cmux-tui/bindings/java/src/com/cmux/raw/Events.java index b6572df627d4..d8b4db08f3fb 100644 --- a/cmux-tui/bindings/java/src/com/cmux/raw/Events.java +++ b/cmux-tui/bindings/java/src/com/cmux/raw/Events.java @@ -11,6 +11,7 @@ public final class Events { private Events() {} + public static final EventMetadata AGENT_CHANGED = new EventMetadata("agent-changed", 11, null, List.of("subscribe"), true); public static final EventMetadata BELL = new EventMetadata("bell", 5, null, List.of("subscribe"), true); public static final EventMetadata BROWSER_STATE = new EventMetadata("browser-state", 6, null, List.of("attach-browser"), true); public static final EventMetadata CLIENT_ATTACHED = new EventMetadata("client-attached", 6, null, List.of("subscribe"), true); @@ -60,6 +61,7 @@ private Events() {} public static final Map ALL; static { LinkedHashMap values = new LinkedHashMap<>(); + values.put("agent-changed", AGENT_CHANGED); values.put("bell", BELL); values.put("browser-state", BROWSER_STATE); values.put("client-attached", CLIENT_ATTACHED); diff --git a/cmux-tui/bindings/java/src/com/cmux/raw/Protocol.java b/cmux-tui/bindings/java/src/com/cmux/raw/Protocol.java index 306665e5936b..b60eacf5635b 100644 --- a/cmux-tui/bindings/java/src/com/cmux/raw/Protocol.java +++ b/cmux-tui/bindings/java/src/com/cmux/raw/Protocol.java @@ -9,13 +9,14 @@ public final class Protocol { public static final String SDK_VERSION = "1.0.0"; public static final int VERSION = 11; public static final int SCHEMA_VERSION = 2; - public static final String IR_SHA256 = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1"; + public static final String IR_SHA256 = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3"; private Protocol() {} public static ProtocolEvent decodeEvent(Object value) { Map object = Wire.object(value, "event"); String event = Wire.string(Wire.required(object, "event"), "event.event"); return switch (event) { + case "agent-changed" -> AgentChangedEvent.fromWire(value); case "bell" -> BellEvent.fromWire(value); case "browser-state" -> BrowserStateEvent.fromWire(value); case "client-attached" -> ClientAttachedEvent.fromWire(value); diff --git a/cmux-tui/bindings/java/tests/com/cmux/raw/GeneratedCoverageTest.java b/cmux-tui/bindings/java/tests/com/cmux/raw/GeneratedCoverageTest.java index 1a634e129c44..90106e6aee0b 100644 --- a/cmux-tui/bindings/java/tests/com/cmux/raw/GeneratedCoverageTest.java +++ b/cmux-tui/bindings/java/tests/com/cmux/raw/GeneratedCoverageTest.java @@ -21,7 +21,7 @@ public static void main(String[] args) throws Exception { check(Protocol.VERSION == 11, "protocol version"); check("1.0.0".equals(Protocol.SDK_VERSION), "SDK release version"); check(Commands.ALL.size() == 97, "all 97 commands generated"); - check(Events.ALL.size() == 45, "all 45 events generated"); + check(Events.ALL.size() == 46, "all 46 events generated"); Map methods = Arrays.stream(GeneratedCmuxClient.class.getDeclaredMethods()) .filter(method -> Modifier.isPublic(method.getModifiers())) diff --git a/cmux-tui/bindings/python/cmux/raw/_generated/.cmux-sdk-manifest.json b/cmux-tui/bindings/python/cmux/raw/_generated/.cmux-sdk-manifest.json index ca1dc412ce75..ca113f91241e 100644 --- a/cmux-tui/bindings/python/cmux/raw/_generated/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/python/cmux/raw/_generated/.cmux-sdk-manifest.json @@ -7,8 +7,8 @@ }, { "path": "_schema.py", - "sha256": "63b0047a911e5a3943f5dd53210ad445dbdc1b5d083f2a01ed4257a3fddbde45", - "size": 145356 + "sha256": "f7065a37c1f6f2dc9500356be30f563ca315586d629e8c87a62068670b5e8473", + "size": 146090 }, { "path": "client.py", @@ -17,22 +17,22 @@ }, { "path": "codec.py", - "sha256": "dd5858e867654f7b9548124fa1db7be540c5f282f210ba4a304cf9ba0f4e43ca", - "size": 27051 + "sha256": "d83ccf98e5a6593dd89e3802fe3171a8b5d13acb760ccc96d74ce7fe7c8bad92", + "size": 27113 }, { "path": "metadata.py", - "sha256": "7da7f358ef8657df72fc8f510c2f1d2558dca73a4f4de91fbb969306866b1ebb", - "size": 43206 + "sha256": "8130a4679ca52c20631b424681e3b30ae252bcaab504d4e82c54db6c344e3d5e", + "size": 43296 }, { "path": "models.py", - "sha256": "a934a20edd5bd3e5651dffb5b7a09d4e079f345704a7950f277c319ca689273a", - "size": 79952 + "sha256": "e3fc0bd2dd35c05f7c6a9325cd5e2f1a427e05773d7f1e838c2859a8fc699aba", + "size": 80396 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "python", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/python/cmux/raw/_generated/_schema.py b/cmux-tui/bindings/python/cmux/raw/_generated/_schema.py index a4999d824473..4dd75d99c5f6 100644 --- a/cmux-tui/bindings/python/cmux/raw/_generated/_schema.py +++ b/cmux-tui/bindings/python/cmux/raw/_generated/_schema.py @@ -5,4 +5,4 @@ import json -SCHEMA = json.loads('{"$schema":"./sdk-schema.schema.json","commands":{"apply-layout":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["layout must contain at least one leaf or stack member.","cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ApplyLayoutResult"},"since":6,"stream":null},"attach-surface":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows must be supplied together.","Browser surfaces reject mode:render."],"fields":{"cols":{"capability":"attach-initial-size","default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"mode":{"default":"bytes","nullable":true,"presence":"optional","since":7,"type":{"kind":"enum","values":["bytes","render"]}},"rows":{"capability":"attach-initial-size","default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":{"event_names":["browser-state","colors-changed","detached","frame","notification","output","overflow","render-delta","render-state","resized","scroll-changed","vt-state"],"kind":"attach","mode_field":"mode","modes":{"browser":["browser-state","frame","notification","scroll-changed","overflow","detached"],"bytes":["vt-state","output","resized","colors-changed","scroll-changed","notification","overflow","detached"],"render":["render-state","render-delta","scroll-changed","overflow","detached"]},"ordering":"Initial state precedes the command response. Later surface events preserve order. A resized replay replaces the previous byte mirror; overflow ends that surface stream.","terminal_event":"detached"}},"browser-activate":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-back":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-forward":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-frame-presented":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Acknowledges the exact rendered browser frame for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-insert-text":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-key":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up"]}},"modifiers":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"windows_virtual_key_code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-key-press":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","One request preserves the atomic press sequence through the bounded input queue."],"request":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"modifiers":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"windows_virtual_key_code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-mouse":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; coordinates are CSS pixels.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"button":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"click_count":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"frame_seq":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up","move"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-mouse-guarded":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Browser surfaces only; coordinates are CSS pixels.","The frame sequence must be the exact presented token for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"button":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"click_count":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up","move"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-navigate":{"authority":"frontend","capability":null,"constraints":["Queue acknowledgement only; observe browser-state for outcome.","Navigation is latest-wins."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-reload":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-wheel":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; values are CSS pixels.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"delta_y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"frame_seq":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-wheel-guarded":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Browser surfaces only; values are CSS pixels.","The frame sequence must be the exact presented token for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"delta_y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"clear-history":{"authority":"control","capability":"clear-history-v1","constraints":["PTY surfaces only.","Failed responses classify error_delivery as known-not-delivered or ambiguous."],"request":{"additional_properties":false,"fields":{"fallback_key":{"capability":"clear-history-key-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"TerminalKeyInput"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"clear-window-title":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"close-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-provider-managed-workspace":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Call only after the external provider durably accepts the close."],"request":{"additional_properties":false,"constraints":["workspace and key must identify the same live provider-managed workspace."],"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProviderWorkspaceMutationResult"},"since":9,"stream":null},"close-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-surface":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-terminal":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"CloseTerminalResult"},"since":9,"stream":null},"close-workspace":{"authority":"control","capability":null,"constraints":["Provider-managed workspaces reject this ordinary mutation."],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"copy":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"mode":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["screen","selection","scrollback"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"CopyResult"},"since":6,"stream":null},"create-surface-with-receipt":{"authority":"control","capability":"creation-receipts-v1","constraints":["Repeating one origin and receipt with identical fields returns the original creation result."],"request":{"additional_properties":false,"constraints":["operation is one of new-tab, run-command, new-browser-tab, new-workspace, new-screen, new-pane, new-pane-right, split-right, or split-down.","Each operation admits only its documented selector and option fields.","cols and rows must be supplied together."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"operation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"receipt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"selector_fallbacks":{"default":[],"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"ResourceSelectors"},"kind":"array","max_items":7}},"selectors":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ResourceSelectors"}},"url":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"width":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"float32"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"JsonValue"},"since":10,"stream":null},"create-terminal":{"authority":"control","capability":"workspace-registry-v1","constraints":[],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; when both are supplied they must identify the same workspace.","argv and command are mutually exclusive and must be nonempty when supplied.","cols and rows must be supplied together.","origin and mutation_id are either both present or both absent.","terminal_id may be supplied only when origin and mutation_id are both present."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"command":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"key":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"terminal_id":{"constraints":[{"format":"32-character lowercase UUIDv4 hex without dashes","pattern":"^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$"}],"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"TerminalPlacement"},"since":7,"stream":null},"create-workspace":{"authority":"control","capability":"workspace-registry-v1","constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent.","At most 4096 live workspaces may exist; tombstoned keys cannot be reused."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"key":{"constraints":[{"format":"lowercase canonical UUID"}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":7,"stream":null},"detach-attached-view":{"authority":"frontend","capability":"view-attachment-detach-v1","constraints":["The command closes only the named view stream and releases its size contribution.","A retired lease returns outcome:superseded."],"request":{"additional_properties":false,"fields":{"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewOutcomeResult"},"since":10,"stream":null},"detach-client":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"export-layout":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"screen":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ExportLayoutResult"},"since":6,"stream":null},"focus-direction":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"FocusDirectionResult"},"since":6,"stream":null},"focus-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"get-cell-pixels":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"GetCellPixelsResult"},"since":6,"stream":null},"get-frontend-projection":{"authority":"control","capability":null,"constraints":["Each identifier is nonempty, contains no control character, and is at most 128 bytes."],"request":{"additional_properties":false,"fields":{"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"FrontendProjection"},"since":7,"stream":null},"identify":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"IdentifyResult"},"since":5,"stream":null},"ids":{"authority":"control","capability":null,"constraints":["Short ids are snapshot-local labels; command parameters accept numeric ids only."],"request":{"additional_properties":false,"fields":{"kind":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"enum","values":["workspace","screen","pane","surface"]}}},"kind":"object"},"result":{"kind":"ref","name":"IdsResult"},"since":6,"stream":null},"list-agents":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"state":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"AgentState"}},"surface":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ListAgentsResult"},"since":6,"stream":null},"list-clients":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"items":{"kind":"ref","name":"ClientInfo"},"kind":"array"},"since":6,"stream":null},"list-terminals":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"ListTerminalsResult"},"since":9,"stream":null},"list-workspaces":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"Tree"},"since":5,"stream":null},"mark-workspaces-provider-managed":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Authority must match the value provisioned before this mux generation accepted control clients."],"request":{"additional_properties":false,"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"mint-terminal-renderer":{"authority":"frontend","capability":null,"constraints":["Only terminal-host-backed PTYs can mint one-use renderer credentials."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"ttl_ms":{"constraints":[{"maximum":60000,"minimum":1}],"default":30000,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"MintTerminalRendererResult"},"since":9,"stream":null},"mint-terminal-renderer-by-terminal":{"authority":"frontend","capability":null,"constraints":["The terminal resource ID is resolved atomically to the live terminal-host-backed PTY before minting a one-use renderer credential."],"request":{"additional_properties":false,"fields":{"terminal":{"constraints":[{"pattern":"^term_[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"ttl_ms":{"constraints":[{"maximum":60000,"minimum":1}],"default":30000,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"MintTerminalRendererResult"},"since":11,"stream":null},"move-tab":{"authority":"control","capability":null,"constraints":["An out-of-range index clamps to the destination end."],"request":{"additional_properties":false,"fields":{"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"move-terminal":{"authority":"control","capability":null,"constraints":["A move to the current workspace still commits a terminal revision with changed:false."],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"MoveTerminalResult"},"since":9,"stream":null},"move-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"new-browser-tab":{"authority":"control","capability":null,"constraints":["Bootstrap and navigation failures are asynchronous browser-state outcomes."],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":9,"stream":null},"new-pane-right":{"authority":"control","capability":"viewport-splits-v1","constraints":[],"request":{"additional_properties":false,"constraints":["Omitted width defaults to two thirds.","cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"width":{"constraints":[{"maximum":1.0,"minimum":0.1}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":9,"stream":null},"new-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-tab":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"notify":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"body":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"level":{"default":"info","nullable":true,"presence":"optional","type":{"kind":"ref","name":"NotificationLevel"}},"surface":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"title":{"constraints":[{"min_length":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"NotifyResult"},"since":6,"stream":null},"pairing-response":{"authority":"local-admin","capability":null,"constraints":["The request id must identify a live, unexpired pairing challenge."],"request":{"additional_properties":false,"fields":{"approve":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":7,"stream":null},"pane-neighbor":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"PaneNeighborResult"},"since":6,"stream":null},"ping":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"PingResult"},"since":6,"stream":null},"process-info":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProcessInfoResult"},"since":6,"stream":null},"put-frontend-projection":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent.","Serialized projection must be at most 1048576 bytes."],"fields":{"expected_generation":{"default":null,"description":"Accepted by the current decoder but ignored for projection writes.","nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_projection_revision":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"description":"Accepted by the current decoder but ignored for projection writes.","nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"projection":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"schema_version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"FrontendProjection"},"since":7,"stream":null},"read-screen":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReadScreenResult"},"since":5,"stream":null},"read-scrollback":{"authority":"control","capability":null,"constraints":["PTY surfaces only; row indexes are snapshot-relative and not durable."],"request":{"additional_properties":false,"fields":{"count":{"constraints":[{"maximum":65535,"minimum":0}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"start":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReadScrollbackResult"},"since":7,"stream":null},"release-attached-view-size":{"authority":"frontend","capability":"view-attachment-lease-v1","constraints":["The attach stream remains live for cached rendering."],"request":{"additional_properties":false,"fields":{"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewOutcomeResult"},"since":10,"stream":null},"release-surface-size":{"authority":"control","capability":null,"constraints":["An absent lease is a successful no-op."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":7,"stream":null},"reload-config":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"additional_properties":false,"fields":{"path":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"reloaded":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}}},"kind":"object"},"since":6,"stream":null},"rename-pane":{"authority":"control","capability":null,"constraints":["An empty name clears the pane name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-provider-managed-workspace":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Call only after the external provider durably accepts the rename."],"request":{"additional_properties":false,"constraints":["workspace and key must identify the same live provider-managed workspace."],"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProviderWorkspaceMutationResult"},"since":9,"stream":null},"rename-screen":{"authority":"control","capability":null,"constraints":["An empty name clears the screen name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-surface":{"authority":"control","capability":null,"constraints":["An empty name clears the surface name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-workspace":{"authority":"control","capability":null,"constraints":["Provider-managed workspaces reject this ordinary mutation."],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"report-agent":{"authority":"control","capability":null,"constraints":["A stored hook report outranks later socket reports until another hook report or surface close."],"request":{"additional_properties":false,"fields":{"session":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentReportSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReportAgentResult"},"since":6,"stream":null},"resize-attached-view":{"authority":"frontend","capability":"view-attachment-lease-v1","constraints":["The lease must belong to this connection and surface.","A retired lease returns outcome:superseded without changing replacement views."],"request":{"additional_properties":false,"fields":{"cols":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"rows":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewResizeResult"},"since":10,"stream":null},"resize-surface":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"cols":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ResizeSurfaceResult"},"since":5,"stream":null},"resolve-terminal":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"terminal_id":{"constraints":[{"format":"UUIDv4 hex without dashes","pattern":"^[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"ResolveTerminalResult"},"since":9,"stream":null},"run":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["Exactly one of argv and command must be supplied.","pane and new_workspace:true are mutually exclusive.","key is valid only with new_workspace:true.","cols and rows affect sizing only when both are present."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"command":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"key":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"new_workspace":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"RunResult"},"since":6,"stream":null},"scroll-surface":{"authority":"control","capability":null,"constraints":["PTY surfaces only; negative values scroll up."],"request":{"additional_properties":false,"fields":{"delta":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-tab":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"send":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both are present, UTF-8 text bytes precede decoded bytes."],"fields":{"bytes":{"constraints":[{"encoding":"standard base64"}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Base64"}},"paste":{"default":false,"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"send-key":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"keys":{"constraints":[{"syntax":"lowercase modifier+key chords"}],"nullable":false,"presence":"required","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"set-cell-pixels":{"authority":"frontend","capability":null,"constraints":["Accepted browser resizes complete asynchronously."],"request":{"additional_properties":false,"fields":{"height_px":{"constraints":[{"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"width_px":{"constraints":[{"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SetCellPixelsResult"},"since":6,"stream":null},"set-client-info":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"capabilities":{"constraints":["Advertises additive client capabilities for this connection."],"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"kind":{"constraints":["Control characters become spaces; at most 64 Unicode characters are retained."],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"constraints":["Control characters become spaces; at most 64 Unicode characters are retained."],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"set-client-sizing":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["exclusive:true requires client and enabled:true.","Omitting client is valid only with enabled:true and restores all clients for the surface."],"fields":{"client":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"enabled":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"exclusive":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"set-default-colors":{"authority":"control","capability":null,"constraints":["Color strings are exactly #rrggbb.","With complete:true, absent optional values reset to built-in defaults."],"request":{"additional_properties":false,"fields":{"bg":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"complete":{"default":false,"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"cursor":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"CursorStyle"}},"fg":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"palette":{"constraints":["Decimal string keys are palette indexes 0 through 255."],"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"set-ratio":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"set-split-ratio":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"split":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"transaction":{"capability":"layout-undo-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":8,"stream":null},"set-viewport-pane-width":{"authority":"control","capability":"viewport-column-resize-v1","constraints":["width must be finite."],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"transaction":{"capability":"layout-undo-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"width":{"constraints":[{"maximum":1.0,"minimum":0.1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"set-window-title":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"title":{"constraints":["C0 controls are sanitized before OSC output."],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"shutdown-daemon":{"authority":"local-admin","capability":null,"constraints":["pid and generation must match the latest identify result.","force bypasses native-browser ownership only; the identity fence and trusted-local authority still apply.","Clients must require daemon-handoff-force-v1 before sending force:true.","The daemon exits only after the success response is queued."],"request":{"additional_properties":false,"fields":{"force":{"capability":"daemon-handoff-force-v1","default":false,"nullable":false,"presence":"optional","since":10,"type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"ShutdownDaemonResult"},"since":9,"stream":null},"sidebar-plugin":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"relaunch":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SidebarPluginResult"},"since":6,"stream":null},"split":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"subscribe":{"authority":"frontend","capability":null,"constraints":["subscribe sends no initial tree snapshot.","surface filtering occurs before the bounded mailbox."],"request":{"additional_properties":false,"fields":{"surface":{"capability":"surface-subscribe-filter","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"Id"}},"tree_events":{"default":"coarse","nullable":true,"presence":"optional","since":7,"type":{"kind":"enum","values":["coarse","deltas"]}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":{"event_names":["bell","client-attached","client-changed","client-detached","client-list-invalidated","config-reload-requested","empty","frontend-projection-changed","layout-changed","notification","overflow","pairing-requested","pairing-resolved","pane-added","pane-closed","screen-added","screen-closed","screen-renamed","scroll-changed","status","surface-exited","surface-output","surface-resize-failed","surface-resized","tab-added","tab-closed","tab-renamed","terminal-registry-changed","title-changed","tree-changed","window-title-requested","workspace-added","workspace-closed","workspace-moved","workspace-renamed"],"kind":"subscribe","mode_field":"tree_events","modes":{"coarse":["tree-changed"],"deltas":["workspace-added","workspace-closed","workspace-renamed","workspace-moved","screen-added","screen-closed","screen-renamed","pane-added","pane-closed","tab-added","tab-closed","tab-renamed","tree-changed"]},"ordering":"Response and event objects may interleave. Events preserve enqueue order per subscription. Delta workspace revisions are serialized in durable commit order; overflow ends the stream and requires resubscribe plus snapshot.","terminal_event":null}},"swap-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["Exactly one of dir and target must be supplied."],"fields":{"dir":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"target":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"terminal-events":{"authority":"control","capability":null,"constraints":["Consumers apply only contiguous revisions for one registry_id and generation."],"request":{"additional_properties":false,"fields":{"after_revision":{"default":0,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"TerminalEventsResult"},"since":9,"stream":null},"undo-layout":{"authority":"control","capability":"layout-undo-v1","constraints":["Clients must reject incomplete or contradictory result variants."],"request":{"additional_properties":false,"constraints":["confirm_close requires the exact preview revision."],"fields":{"confirm_close":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"revision":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"LayoutUndoResult"},"since":9,"stream":null},"vt-state":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"VtStateResult"},"since":5,"stream":null},"wait-for":{"authority":"control","capability":null,"constraints":["Blocks subsequent requests on this connection; SDKs should use a dedicated connection."],"request":{"additional_properties":false,"fields":{"pattern":{"constraints":[{"syntax":"Rust regex"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"timeout_ms":{"description":"Zero performs one immediate check.","nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"WaitForResult"},"since":6,"stream":null},"zoom-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"mode":{"default":"toggle","nullable":true,"presence":"optional","type":{"kind":"enum","values":["toggle","on","off"]}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ZoomPaneResult"},"since":6,"stream":null}},"events":{"bell":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"bell"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"browser-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"browser-state"}},"frame":{"description":"The initial browser-state includes the latest frame when one exists; later state updates omit it.","nullable":true,"presence":"optional","type":{"kind":"ref","name":"BrowserFrame"}},"frames_stalled":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"status":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["starting","live","failed"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["attach-browser"]},"client-attached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-attached"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"transport":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["unix","ws"]}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-changed"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-detached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-detached"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-list-invalidated":{"capability":null,"emission":"serialized-never-emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-list-invalidated"}}},"kind":"object"},"since":9,"streams":["subscribe"]},"colors-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"cursor":{"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"nullable":true,"presence":"optional","type":{"kind":"ref","name":"CursorStyle"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"colors-changed"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"palette":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"surface":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["attach-byte"]},"config-reload-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"config-reload-requested"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"detached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"detached"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte","attach-render","attach-browser"]},"empty":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"empty"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"frame":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"frame"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"since":6,"streams":["attach-browser"]},"frontend-projection-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"frontend-projection-changed"}},"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"projection_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"graphics-status":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["kitty-image-budget-worker-start-failed carries error.","kitty-image-budget-update-failed carries retry_exhausted and summary.","cell-pixel-update-retries-exhausted carries attempts, remaining, cell_width, and cell_height."],"fields":{"attempts":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cell_height":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cell_width":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"graphics-status"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["kitty-image-budget-worker-start-failed","kitty-image-budget-update-failed","cell-pixel-update-retries-exhausted"]}},"remaining":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"retry_exhausted":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"summary":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":10,"streams":["subscribe"]},"layout-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"layout-changed"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"notification":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"body":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"notification"}},"level":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"NotificationLevel"}},"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe","attach-byte","attach-browser"]},"output":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"colors":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"TerminalColors"}},"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"output"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte"]},"overflow":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["scope and surface are either both present for attach overflow or both absent for subscribe overflow."],"fields":{"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"overflow"}},"scope":{"nullable":false,"presence":"optional","type":{"kind":"literal","value":"surface"}},"surface":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe","attach-byte","attach-render","attach-browser"]},"pairing-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pairing-requested"}},"expires_in":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"peer":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"pairing-resolved":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pairing-resolved"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"pane-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Pane"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pane-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"pane-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Pane"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pane-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"render-delta":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["size is present if and only if the surface resized; every resize has full:true."],"fields":{"cursor":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderCursor"}},"default_bg":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"default_fg":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"render-delta"}},"full":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"graphics":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderGraphicsDelta"}},"history_epoch":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"scrollback_rows":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"size":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"Size"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["attach-render"]},"render-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cursor":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderCursor"}},"default_bg":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"default_fg":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"render-state"}},"graphics":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderGraphics"}},"history_epoch":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"scrollback_rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"size":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Size"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["attach-render"]},"resized":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["At least one of replay and data is present; replay is canonical from protocol 7."],"fields":{"colors":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"TerminalColors"}},"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"description":"Protocol 6 compatibility field.","nullable":false,"presence":"optional","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"resized"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"replay":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"Base64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["attach-byte"]},"screen-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"screen-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"screen-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-renamed"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"scroll-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"at_bottom":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"scroll-changed"}},"offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["subscribe","attach-byte","attach-render","attach-browser"]},"status":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"status"}},"message":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-exited":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-exited"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-output":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-output"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-resize-failed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-resize-failed"}},"reservation_id":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"retry_after_ms":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"surface-resized":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-resized"}},"reservation_id":{"nullable":true,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"tab-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"tab-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"tab-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-renamed"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"terminal-registry-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"terminal-registry-changed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"refetch":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"terminal-events-or-list-terminals"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":9,"streams":["subscribe"]},"title-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"title-changed"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"tree-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tree-changed"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"vt-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"colors":{"nullable":false,"presence":"optional","since":6,"type":{"kind":"ref","name":"TerminalColors"}},"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"vt-state"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte"]},"window-title-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"window-title-requested"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"workspace-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-added"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-closed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-moved":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-moved"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-renamed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]}},"ir_sha256":"5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1","profiles":{"control":{"description":"Base authenticated session-control commands available to ordinary SDK clients.","inherits":[]},"frontend":{"description":"Rendering, input, presentation, subscribe, and attach commands.","inherits":["control"]},"local-admin":{"description":"Trusted local administration commands.","inherits":["control"],"transport":"Unix-classified transport, including direct Unix and the current stdio relay"},"provider-authority":{"description":"Provider-owned workspace mutation commands.","inherits":["control"],"requires_authority":true}},"protocol":{"id_type":"uint64","javascript_id_policy":"All protocol identifiers are uint64 JSON numbers. JavaScript and TypeScript SDKs must decode them losslessly as bigint (or validated decimal strings at their public boundary), and must not expose IEEE-754 number ids. Pairing request ids, revisions, timestamps, frame sequences, and reservation ids follow the same rule.","name":"cmux-tui-mux","version":11},"schema_version":2,"types":{"AgentRecord":{"additional_properties":false,"fields":{"session":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"updated_at_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"AgentReportSource":{"kind":"enum","values":["socket","hook"]},"AgentSource":{"kind":"enum","values":["detected","socket","hook"]},"AgentState":{"kind":"enum","values":["working","blocked","idle","done","unknown"]},"AppliedPane":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ApplyLayoutResult":{"additional_properties":false,"fields":{"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"AppliedPane"},"kind":"array"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"AttachedViewOutcomeResult":{"additional_properties":false,"fields":{"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ViewAttachmentOutcome"}}},"kind":"object"},"AttachedViewResizeResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ViewAttachmentOutcome"}},"reservation_id":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"Base64":{"kind":"alias","target":{"kind":"scalar","name":"string"}},"BrowserFrame":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"CellPixelFailure":{"additional_properties":false,"fields":{"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"CellPixelResize":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"reservation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"CellPixelSurface":{"additional_properties":false,"fields":{"height_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"width_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"ClientInfo":{"additional_properties":false,"fields":{"attached":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}},"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"connected_seconds":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"self":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"sizes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"ClientSize"},"kind":"array"}},"transport":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ClientTransport"}}},"kind":"object"},"ClientSize":{"additional_properties":false,"fields":{"cols":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"size_participating":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ClientTransport":{"kind":"enum","values":["local","unix","ws"]},"CloseTerminalResult":{"additional_properties":false,"fields":{"already_closed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"closed":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ColorHex":{"kind":"alias","target":{"kind":"scalar","name":"string"}},"CopyResult":{"additional_properties":false,"fields":{"mode":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["screen","selection","scrollback"]}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"CursorStyle":{"kind":"enum","values":["block","underline","bar"]},"DeadPane":{"additional_properties":false,"fields":{"dead":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"DeclarativeLayout":{"kind":"tagged_union","tag":"type","variants":{"leaf":{"additional_properties":false,"fields":{"command":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"leaf"}}},"kind":"object"},"split":{"additional_properties":false,"fields":{"a":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"b":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"split"}}},"kind":"object"},"stack":{"additional_properties":false,"fields":{"expanded":{"constraints":["Must identify a member of panes."],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array","min_items":1}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"stack"}}},"kind":"object"}}},"EmptyResult":{"additional_properties":false,"fields":{},"kind":"object"},"ExportLayoutResult":{"additional_properties":false,"fields":{"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"ExportedPane"},"kind":"array"}}},"kind":"object"},"ExportedPane":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surfaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}}},"kind":"object"},"FocusDirectionResult":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"FrontendProjection":{"additional_properties":false,"fields":{"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"projection":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"projection_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"replayed":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"schema_version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"GetCellPixelsResult":{"additional_properties":false,"fields":{"height_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surfaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelSurface"},"kind":"array"}},"width_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"Id":{"kind":"alias","target":{"kind":"scalar","name":"uint64"}},"IdMapping":{"additional_properties":false,"fields":{"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["workspace","screen","pane","surface"]}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"IdentifyResult":{"additional_properties":false,"fields":{"app":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"cmux-tui"}},"build_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"capabilities":{"default":[],"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"daemon_handoff":{"nullable":false,"presence":"required","since":9,"type":{"kind":"literal","value":1}},"generation":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"string"}},"ghostty_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"protocol":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"registry_id":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"string"}},"session":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","since":9,"type":{"kind":"scalar","name":"uint64"}},"version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace_revision":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"IdsResult":{"additional_properties":false,"fields":{"ids":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"IdMapping"},"kind":"array"}}},"kind":"object"},"JsonValue":{"kind":"opaque_json","reason":"The wire field intentionally carries a frontend-authored or runtime-authored arbitrary JSON document."},"KittyGraphicsState":{"additional_properties":false,"fields":{"alternate_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"alternate_replay_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_bytes":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"inflight_bytes":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"placements":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"primary_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"primary_replay_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"replay_cursor_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"KittyImageAlias":{"additional_properties":false,"fields":{"image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_number":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"Layout":{"kind":"tagged_union","tag":"type","variants":{"leaf":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"leaf"}}},"kind":"object"},"split":{"additional_properties":false,"fields":{"a":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"b":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"ratio":{"constraints":[{"maximum":0.95,"minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"split":{"description":"Stable for the lifetime of this split node.","nullable":false,"presence":"optional","since":8,"type":{"kind":"ref","name":"Id"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"split"}}},"kind":"object"},"stack":{"additional_properties":false,"fields":{"expanded":{"constraints":["Must identify a member of panes."],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array","min_items":1}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"stack"}}},"kind":"object"}}},"LayoutUndoConfirmationRequired":{"additional_properties":false,"fields":{"closes_panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}},"confirmation_required":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"undone":{"nullable":false,"presence":"required","type":{"kind":"literal","value":false}}},"kind":"object"},"LayoutUndoResult":{"kind":"untagged_union","variants":[{"kind":"ref","name":"LayoutUndoUndone"},{"kind":"ref","name":"LayoutUndoConfirmationRequired"}]},"LayoutUndoUndone":{"additional_properties":false,"fields":{"confirmation_required":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"literal","value":false}},"revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"undone":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}}},"kind":"object"},"ListAgentsResult":{"additional_properties":false,"fields":{"agents":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"AgentRecord"},"kind":"array"}}},"kind":"object"},"ListTerminalsResult":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"terminals":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"TerminalRecord"},"kind":"array"}}},"kind":"object"},"LivePane":{"additional_properties":false,"fields":{"active_tab":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"focused_at":{"default":0,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"tabs":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Tab"},"kind":"array"}}},"kind":"object"},"MintTerminalRendererResult":{"additional_properties":false,"fields":{"endpoint":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"incarnation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"protocol_version":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"uint16"}},"rights":{"constraints":[{"current_value":7}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"token":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"ttl_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"MoveTerminalResult":{"additional_properties":false,"fields":{"changed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"NotificationLevel":{"kind":"enum","values":["info","warning","error"]},"NotificationMarker":{"additional_properties":false,"fields":{"level":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"NotificationLevel"}},"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"unread":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}}},"kind":"object"},"NotifyResult":{"additional_properties":false,"fields":{"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Pane":{"kind":"untagged_union","variants":[{"kind":"ref","name":"LivePane"},{"kind":"ref","name":"DeadPane"}]},"PaneDirection":{"kind":"enum","values":["left","right","up","down"]},"PaneNeighborResult":{"additional_properties":false,"fields":{"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"PingResult":{"additional_properties":false,"fields":{"build_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"ghostty_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"ok":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"protocol":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ProcessInfoResult":{"additional_properties":false,"fields":{"command":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"cwd":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"ProviderWorkspaceMutationResult":{"additional_properties":false,"fields":{"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ReadScreenResult":{"additional_properties":false,"fields":{"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ReadScrollbackResult":{"additional_properties":false,"fields":{"epoch":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"start":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"total":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"RenderCursor":{"additional_properties":false,"fields":{"blink":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"color":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"style":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"CursorStyle"}},"visible":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"x":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"y":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"RenderGraphicFormat":{"kind":"enum","values":["rgb","rgba"]},"RenderGraphicImage":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"format":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderGraphicFormat"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"RenderGraphicPlacement":{"additional_properties":false,"fields":{"anchor_col":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"anchor_row":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"columns":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"grid_cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"grid_rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"ordinal":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"pixel_height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"pixel_width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"placement_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_x":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_y":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"viewport_col":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"viewport_row":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"viewport_visible":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"x_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"y_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"z":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}}},"kind":"object"},"RenderGraphics":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicImage"},"kind":"array"}},"placements":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderGraphicPlacement"},"kind":"array"}},"removed_image_ids":{"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"uint32"},"kind":"array"}}},"kind":"object"},"RenderGraphicsDelta":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicImage"},"kind":"array"}},"placements":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicPlacement"},"kind":"array"}},"removed_image_ids":{"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"uint32"},"kind":"array"}}},"kind":"object"},"RenderRow":{"additional_properties":false,"fields":{"row":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"runs":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRun"},"kind":"array"}}},"kind":"object"},"RenderRun":{"additional_properties":false,"fields":{"attrs":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"underline":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderUnderline"}},"width_hint":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"RenderUnderline":{"kind":"enum","values":["single","double","curly","dotted","dashed"]},"ReportAgentResult":{"additional_properties":false,"fields":{"session":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentReportSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ResizeSurfaceResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"reservation_id":{"nullable":true,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ResolveTerminalResult":{"additional_properties":false,"fields":{"exit":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"TerminalExit"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"launch_spec":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ResourceSelectors":{"additional_properties":false,"fields":{"agent":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"browser":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"client":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"frontend_projection":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"machine":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"notification":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pairing_request":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"screen":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"session":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"sidebar_view":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"split":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"stream":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"tab":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"RunResult":{"additional_properties":false,"fields":{"already_exited":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"boolean"}},"exit":{"nullable":true,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalExit"}},"lifecycle":{"nullable":false,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Screen":{"additional_properties":false,"fields":{"active":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"active_pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Pane"},"kind":"array"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"zoomed_pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"SetCellPixelsResult":{"additional_properties":false,"fields":{"failures":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelFailure"},"kind":"array"}},"resizes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelResize"},"kind":"array"}}},"kind":"object"},"ShutdownDaemonResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"SidebarPluginResult":{"additional_properties":false,"fields":{"error":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"retry_after_ms":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Size":{"additional_properties":false,"fields":{"cols":{"constraints":[{"maximum":10000,"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"constraints":[{"maximum":10000,"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"SplitDirection":{"kind":"enum","values":["right","down"]},"SurfaceResult":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Tab":{"additional_properties":false,"fields":{"browser_error":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"browser_frames_stalled":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"boolean"}},"browser_source":{"nullable":true,"presence":"required","type":{"kind":"enum","values":["external","launched"]}},"browser_status":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"enum","values":["starting","live","failed"]}},"dead":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["pty","browser"]}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"notification":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"NotificationMarker"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"size":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Size"}},"supports_clear_history_key_fallback":{"capability":"clear-history-key-v1","nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_resource_id":{"constraints":[{"pattern":"^term_[0-9a-f]{32}$"}],"nullable":true,"presence":"optional","since":10,"type":{"kind":"scalar","name":"string"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalColors":{"additional_properties":false,"fields":{"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"cursor":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"CursorStyle"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"palette":{"constraints":["Decimal string keys are palette indexes 0 through 255."],"nullable":false,"presence":"optional","since":7,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}}},"kind":"object"},"TerminalEventsResult":{"additional_properties":false,"fields":{"events":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"TerminalRegistryEvent"},"kind":"array"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"TerminalExit":{"additional_properties":false,"fields":{"exited_at_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalExitOutcome"}}},"kind":"object"},"TerminalExitOutcome":{"kind":"tagged_union","tag":"kind","variants":{"exit":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"exit"}}},"kind":"object"},"signal":{"additional_properties":false,"fields":{"core_dumped":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"signal"}},"signal":{"constraints":[{"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}}},"kind":"object"},"unknown":{"additional_properties":false,"fields":{"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"unknown"}},"reason":{"constraints":[{"min_length":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"}}},"TerminalKey":{"kind":"enum","values":["unidentified","backquote","backslash","bracket-left","bracket-right","comma","digit0","digit1","digit2","digit3","digit4","digit5","digit6","digit7","digit8","digit9","equal","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","minus","period","quote","semicolon","slash","backspace","enter","space","tab","delete","end","home","insert","page-down","page-up","arrow-down","arrow-left","arrow-right","arrow-up","numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9","numpad-add","numpad-backspace","numpad-comma","numpad-decimal","numpad-divide","numpad-enter","numpad-equal","numpad-multiply","numpad-subtract","numpad-up","numpad-down","numpad-right","numpad-left","numpad-begin","numpad-home","numpad-end","numpad-insert","numpad-delete","numpad-page-up","numpad-page-down","escape","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","f13","f14","f15","f16","f17","f18","f19","f20"]},"TerminalKeyAction":{"kind":"enum","values":["press","release","repeat"]},"TerminalKeyInput":{"additional_properties":false,"constraints":["consumed_mods must be a subset of mods.","unshifted_codepoint, shifted_codepoint, and base_layout_codepoint contain exactly one Unicode scalar when present.","utf8 contains no control characters.","macos_option_as_alt may be false only when Alt is active and consumed."],"fields":{"action":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"TerminalKeyAction"}},"base_layout_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"composing":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"consumed_mods":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalModifiers"}},"key":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalKey"}},"macos_option_as_alt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"mods":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalModifiers"}},"shifted_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"unshifted_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"utf8":{"constraints":[{"max_length":4096}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalLifecycle":{"kind":"enum","values":["launching","adopting","running","exited","tombstoned"]},"TerminalModifiers":{"additional_properties":false,"fields":{"alt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"caps_lock":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"control":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"num_lock":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"shift":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"super":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}}},"kind":"object"},"TerminalPlacement":{"additional_properties":false,"fields":{"already_exited":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"boolean"}},"exit":{"nullable":true,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalExit"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"TerminalRecord":{"additional_properties":false,"fields":{"exit":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"TerminalExit"}},"launch_spec":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"terminal_id":{"constraints":[{"format":"UUIDv4 hex without dashes","pattern":"^[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalRegistryEvent":{"additional_properties":false,"fields":{"kind":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"result":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Tree":{"additional_properties":false,"fields":{"generation":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"pane_revision":{"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"registry_id":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"workspace_revision":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"workspaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Workspace"},"kind":"array"}}},"kind":"object"},"ViewAttachmentOutcome":{"kind":"enum","values":["applied","passive","superseded"]},"VtStateResult":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"constraints":[{"encoding":"standard base64"}],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"WaitForResult":{"additional_properties":false,"fields":{"elapsed_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"matched":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Workspace":{"additional_properties":false,"fields":{"active":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"key":{"capability":"workspace-registry-v1","constraints":[{"format":"lowercase canonical UUID"}],"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"screens":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Screen"},"kind":"array"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"WorkspaceMutationResult":{"additional_properties":false,"fields":{"changed":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ZoomPaneResult":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"zoomed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"zoomed_pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"}}}') +SCHEMA = json.loads('{"$schema":"./sdk-schema.schema.json","commands":{"apply-layout":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["layout must contain at least one leaf or stack member.","cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ApplyLayoutResult"},"since":6,"stream":null},"attach-surface":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows must be supplied together.","Browser surfaces reject mode:render."],"fields":{"cols":{"capability":"attach-initial-size","default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"mode":{"default":"bytes","nullable":true,"presence":"optional","since":7,"type":{"kind":"enum","values":["bytes","render"]}},"rows":{"capability":"attach-initial-size","default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":{"event_names":["browser-state","colors-changed","detached","frame","notification","output","overflow","render-delta","render-state","resized","scroll-changed","vt-state"],"kind":"attach","mode_field":"mode","modes":{"browser":["browser-state","frame","notification","scroll-changed","overflow","detached"],"bytes":["vt-state","output","resized","colors-changed","scroll-changed","notification","overflow","detached"],"render":["render-state","render-delta","scroll-changed","overflow","detached"]},"ordering":"Initial state precedes the command response. Later surface events preserve order. A resized replay replaces the previous byte mirror; overflow ends that surface stream.","terminal_event":"detached"}},"browser-activate":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-back":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-forward":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-frame-presented":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Acknowledges the exact rendered browser frame for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-insert-text":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-key":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up"]}},"modifiers":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"windows_virtual_key_code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-key-press":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only.","One request preserves the atomic press sequence through the bounded input queue."],"request":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"modifiers":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"windows_virtual_key_code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-mouse":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; coordinates are CSS pixels.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"button":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"click_count":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"frame_seq":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up","move"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-mouse-guarded":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Browser surfaces only; coordinates are CSS pixels.","The frame sequence must be the exact presented token for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"button":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"click_count":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["down","up","move"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"browser-navigate":{"authority":"frontend","capability":null,"constraints":["Queue acknowledgement only; observe browser-state for outcome.","Navigation is latest-wins."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-reload":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; queue acknowledgement is not page-load success."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-wheel":{"authority":"frontend","capability":null,"constraints":["Browser surfaces only; values are CSS pixels.","The bounded disposable input queue drops newest input when full."],"request":{"additional_properties":false,"fields":{"delta_y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"frame_seq":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"browser-wheel-guarded":{"authority":"frontend","capability":"browser-pointer-frame-guard-v1","constraints":["Browser surfaces only; values are CSS pixels.","The frame sequence must be the exact presented token for this connection.","Requires browser-pointer-frame-guard-v1."],"request":{"additional_properties":false,"fields":{"delta_y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"frame_seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"x_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}},"y_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"clear-history":{"authority":"control","capability":"clear-history-v1","constraints":["PTY surfaces only.","Failed responses classify error_delivery as known-not-delivered or ambiguous."],"request":{"additional_properties":false,"fields":{"fallback_key":{"capability":"clear-history-key-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"TerminalKeyInput"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"clear-window-title":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"close-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-provider-managed-workspace":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Call only after the external provider durably accepts the close."],"request":{"additional_properties":false,"constraints":["workspace and key must identify the same live provider-managed workspace."],"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProviderWorkspaceMutationResult"},"since":9,"stream":null},"close-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-surface":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"close-terminal":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"CloseTerminalResult"},"since":9,"stream":null},"close-workspace":{"authority":"control","capability":null,"constraints":["Provider-managed workspaces reject this ordinary mutation."],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"copy":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"mode":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["screen","selection","scrollback"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"CopyResult"},"since":6,"stream":null},"create-surface-with-receipt":{"authority":"control","capability":"creation-receipts-v1","constraints":["Repeating one origin and receipt with identical fields returns the original creation result."],"request":{"additional_properties":false,"constraints":["operation is one of new-tab, run-command, new-browser-tab, new-workspace, new-screen, new-pane, new-pane-right, split-right, or split-down.","Each operation admits only its documented selector and option fields.","cols and rows must be supplied together."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"operation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"receipt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"selector_fallbacks":{"default":[],"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"ResourceSelectors"},"kind":"array","max_items":7}},"selectors":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ResourceSelectors"}},"url":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"width":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"float32"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"JsonValue"},"since":10,"stream":null},"create-terminal":{"authority":"control","capability":"workspace-registry-v1","constraints":[],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; when both are supplied they must identify the same workspace.","argv and command are mutually exclusive and must be nonempty when supplied.","cols and rows must be supplied together.","origin and mutation_id are either both present or both absent.","terminal_id may be supplied only when origin and mutation_id are both present."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"command":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"key":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"terminal_id":{"constraints":[{"format":"32-character lowercase UUIDv4 hex without dashes","pattern":"^[0-9a-f]{12}4[0-9a-f]{3}[89ab][0-9a-f]{15}$"}],"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"TerminalPlacement"},"since":7,"stream":null},"create-workspace":{"authority":"control","capability":"workspace-registry-v1","constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent.","At most 4096 live workspaces may exist; tombstoned keys cannot be reused."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"key":{"constraints":[{"format":"lowercase canonical UUID"}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":7,"stream":null},"detach-attached-view":{"authority":"frontend","capability":"view-attachment-detach-v1","constraints":["The command closes only the named view stream and releases its size contribution.","A retired lease returns outcome:superseded."],"request":{"additional_properties":false,"fields":{"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewOutcomeResult"},"since":10,"stream":null},"detach-client":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"export-layout":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"screen":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ExportLayoutResult"},"since":6,"stream":null},"focus-direction":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"FocusDirectionResult"},"since":6,"stream":null},"focus-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"get-cell-pixels":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"GetCellPixelsResult"},"since":6,"stream":null},"get-frontend-projection":{"authority":"control","capability":null,"constraints":["Each identifier is nonempty, contains no control character, and is at most 128 bytes."],"request":{"additional_properties":false,"fields":{"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"FrontendProjection"},"since":7,"stream":null},"identify":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"IdentifyResult"},"since":5,"stream":null},"ids":{"authority":"control","capability":null,"constraints":["Short ids are snapshot-local labels; command parameters accept numeric ids only."],"request":{"additional_properties":false,"fields":{"kind":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"enum","values":["workspace","screen","pane","surface"]}}},"kind":"object"},"result":{"kind":"ref","name":"IdsResult"},"since":6,"stream":null},"list-agents":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"state":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"AgentState"}},"surface":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ListAgentsResult"},"since":6,"stream":null},"list-clients":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"items":{"kind":"ref","name":"ClientInfo"},"kind":"array"},"since":6,"stream":null},"list-terminals":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"ListTerminalsResult"},"since":9,"stream":null},"list-workspaces":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"Tree"},"since":5,"stream":null},"mark-workspaces-provider-managed":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Authority must match the value provisioned before this mux generation accepted control clients."],"request":{"additional_properties":false,"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"mint-terminal-renderer":{"authority":"frontend","capability":null,"constraints":["Only terminal-host-backed PTYs can mint one-use renderer credentials."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"ttl_ms":{"constraints":[{"maximum":60000,"minimum":1}],"default":30000,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"MintTerminalRendererResult"},"since":9,"stream":null},"mint-terminal-renderer-by-terminal":{"authority":"frontend","capability":null,"constraints":["The terminal resource ID is resolved atomically to the live terminal-host-backed PTY before minting a one-use renderer credential."],"request":{"additional_properties":false,"fields":{"terminal":{"constraints":[{"pattern":"^term_[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"ttl_ms":{"constraints":[{"maximum":60000,"minimum":1}],"default":30000,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"MintTerminalRendererResult"},"since":11,"stream":null},"move-tab":{"authority":"control","capability":null,"constraints":["An out-of-range index clamps to the destination end."],"request":{"additional_properties":false,"fields":{"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"move-terminal":{"authority":"control","capability":null,"constraints":["A move to the current workspace still commits a terminal revision with changed:false."],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"MoveTerminalResult"},"since":9,"stream":null},"move-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"new-browser-tab":{"authority":"control","capability":null,"constraints":["Bootstrap and navigation failures are asynchronous browser-state outcomes."],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":9,"stream":null},"new-pane-right":{"authority":"control","capability":"viewport-splits-v1","constraints":[],"request":{"additional_properties":false,"constraints":["Omitted width defaults to two thirds.","cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"width":{"constraints":[{"maximum":1.0,"minimum":0.1}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":9,"stream":null},"new-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-tab":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"new-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"notify":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"body":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"level":{"default":"info","nullable":true,"presence":"optional","type":{"kind":"ref","name":"NotificationLevel"}},"surface":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"title":{"constraints":[{"min_length":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"NotifyResult"},"since":6,"stream":null},"pairing-response":{"authority":"local-admin","capability":null,"constraints":["The request id must identify a live, unexpired pairing challenge."],"request":{"additional_properties":false,"fields":{"approve":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":7,"stream":null},"pane-neighbor":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"PaneNeighborResult"},"since":6,"stream":null},"ping":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"kind":"ref","name":"PingResult"},"since":6,"stream":null},"process-info":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProcessInfoResult"},"since":6,"stream":null},"put-frontend-projection":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent.","Serialized projection must be at most 1048576 bytes."],"fields":{"expected_generation":{"default":null,"description":"Accepted by the current decoder but ignored for projection writes.","nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"expected_projection_revision":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"description":"Accepted by the current decoder but ignored for projection writes.","nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"projection":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"schema_version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"FrontendProjection"},"since":7,"stream":null},"read-screen":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReadScreenResult"},"since":5,"stream":null},"read-scrollback":{"authority":"control","capability":null,"constraints":["PTY surfaces only; row indexes are snapshot-relative and not durable."],"request":{"additional_properties":false,"fields":{"count":{"constraints":[{"maximum":65535,"minimum":0}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"start":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReadScrollbackResult"},"since":7,"stream":null},"release-attached-view-size":{"authority":"frontend","capability":"view-attachment-lease-v1","constraints":["The attach stream remains live for cached rendering."],"request":{"additional_properties":false,"fields":{"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewOutcomeResult"},"since":10,"stream":null},"release-surface-size":{"authority":"control","capability":null,"constraints":["An absent lease is a successful no-op."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":7,"stream":null},"reload-config":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{},"kind":"object"},"result":{"additional_properties":false,"fields":{"path":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"reloaded":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}}},"kind":"object"},"since":6,"stream":null},"rename-pane":{"authority":"control","capability":null,"constraints":["An empty name clears the pane name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-provider-managed-workspace":{"authority":"provider-authority","capability":"provider-managed-workspace-authority-v2","constraints":["Call only after the external provider durably accepts the rename."],"request":{"additional_properties":false,"constraints":["workspace and key must identify the same live provider-managed workspace."],"fields":{"authority":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ProviderWorkspaceMutationResult"},"since":9,"stream":null},"rename-screen":{"authority":"control","capability":null,"constraints":["An empty name clears the screen name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-surface":{"authority":"control","capability":null,"constraints":["An empty name clears the surface name."],"request":{"additional_properties":false,"fields":{"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"rename-workspace":{"authority":"control","capability":null,"constraints":["Provider-managed workspaces reject this ordinary mutation."],"request":{"additional_properties":false,"constraints":["At least one of workspace and key must be supplied; both must identify the same workspace when supplied.","origin and mutation_id are either both present or both absent."],"fields":{"expected_generation":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"expected_revision":{"aliases":["expected_terminal_revision"],"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"key":{"capability":"workspace-registry-v1","default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"mutation_id":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"name":{"constraints":[{"max_utf8_bytes":1024}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"default":null,"nullable":true,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"WorkspaceMutationResult"},"since":5,"stream":null},"report-agent":{"authority":"control","capability":null,"constraints":["A stored hook report outranks later socket reports until another hook report or surface close."],"request":{"additional_properties":false,"fields":{"session":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentReportSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ReportAgentResult"},"since":6,"stream":null},"resize-attached-view":{"authority":"frontend","capability":"view-attachment-lease-v1","constraints":["The lease must belong to this connection and surface.","A retired lease returns outcome:superseded without changing replacement views."],"request":{"additional_properties":false,"fields":{"cols":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"lease":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"rows":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"AttachedViewResizeResult"},"since":10,"stream":null},"resize-surface":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"cols":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"constraints":[{"clamped_maximum":10000,"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ResizeSurfaceResult"},"since":5,"stream":null},"resolve-terminal":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"terminal_id":{"constraints":[{"format":"UUIDv4 hex without dashes","pattern":"^[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"ResolveTerminalResult"},"since":9,"stream":null},"run":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["Exactly one of argv and command must be supplied.","pane and new_workspace:true are mutually exclusive.","key is valid only with new_workspace:true.","cols and rows affect sizing only when both are present."],"fields":{"argv":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"command":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"key":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"name":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"new_workspace":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"RunResult"},"since":6,"stream":null},"scroll-surface":{"authority":"control","capability":null,"constraints":["PTY surfaces only; negative values scroll up."],"request":{"additional_properties":false,"fields":{"delta":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-screen":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-tab":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"select-workspace":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both index and delta are supplied, index wins."],"fields":{"delta":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"int64"}},"index":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"send":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["When both are present, UTF-8 text bytes precede decoded bytes."],"fields":{"bytes":{"constraints":[{"encoding":"standard base64"}],"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Base64"}},"paste":{"default":false,"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"text":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"send-key":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"keys":{"constraints":[{"syntax":"lowercase modifier+key chords"}],"nullable":false,"presence":"required","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"set-cell-pixels":{"authority":"frontend","capability":null,"constraints":["Accepted browser resizes complete asynchronously."],"request":{"additional_properties":false,"fields":{"height_px":{"constraints":[{"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"width_px":{"constraints":[{"clamped_minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SetCellPixelsResult"},"since":6,"stream":null},"set-client-info":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"capabilities":{"constraints":["Advertises additive client capabilities for this connection."],"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"kind":{"constraints":["Control characters become spaces; at most 64 Unicode characters are retained."],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"name":{"constraints":["Control characters become spaces; at most 64 Unicode characters are retained."],"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"set-client-sizing":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["exclusive:true requires client and enabled:true.","Omitting client is valid only with enabled:true and restores all clients for the surface."],"fields":{"client":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"enabled":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"exclusive":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":10,"stream":null},"set-default-colors":{"authority":"control","capability":null,"constraints":["Color strings are exactly #rrggbb.","With complete:true, absent optional values reset to built-in defaults."],"request":{"additional_properties":false,"fields":{"bg":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"complete":{"default":false,"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"cursor":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"CursorStyle"}},"fg":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"palette":{"constraints":["Decimal string keys are palette indexes 0 through 255."],"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"ColorHex"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"set-ratio":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":null},"set-split-ratio":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"split":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"transaction":{"capability":"layout-undo-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":8,"stream":null},"set-viewport-pane-width":{"authority":"control","capability":"viewport-column-resize-v1","constraints":["width must be finite."],"request":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"transaction":{"capability":"layout-undo-v1","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"width":{"constraints":[{"maximum":1.0,"minimum":0.1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":9,"stream":null},"set-window-title":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"title":{"constraints":["C0 controls are sanitized before OSC output."],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"shutdown-daemon":{"authority":"local-admin","capability":null,"constraints":["pid and generation must match the latest identify result.","force bypasses native-browser ownership only; the identity fence and trusted-local authority still apply.","Clients must require daemon-handoff-force-v1 before sending force:true.","The daemon exits only after the success response is queued."],"request":{"additional_properties":false,"fields":{"force":{"capability":"daemon-handoff-force-v1","default":false,"nullable":false,"presence":"optional","since":10,"type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"result":{"kind":"ref","name":"ShutdownDaemonResult"},"since":9,"stream":null},"sidebar-plugin":{"authority":"frontend","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"relaunch":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SidebarPluginResult"},"since":6,"stream":null},"split":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["cols and rows affect sizing only when both are present."],"fields":{"cols":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"rows":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"result":{"kind":"ref","name":"SurfaceResult"},"since":5,"stream":null},"subscribe":{"authority":"frontend","capability":null,"constraints":["subscribe sends no initial tree snapshot.","surface filtering occurs before the bounded mailbox."],"request":{"additional_properties":false,"fields":{"surface":{"capability":"surface-subscribe-filter","default":null,"nullable":true,"presence":"optional","since":9,"type":{"kind":"ref","name":"Id"}},"tree_events":{"default":"coarse","nullable":true,"presence":"optional","since":7,"type":{"kind":"enum","values":["coarse","deltas"]}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":5,"stream":{"event_names":["agent-changed","bell","client-attached","client-changed","client-detached","client-list-invalidated","config-reload-requested","empty","frontend-projection-changed","layout-changed","notification","overflow","pairing-requested","pairing-resolved","pane-added","pane-closed","screen-added","screen-closed","screen-renamed","scroll-changed","status","surface-exited","surface-output","surface-resize-failed","surface-resized","tab-added","tab-closed","tab-renamed","terminal-registry-changed","title-changed","tree-changed","window-title-requested","workspace-added","workspace-closed","workspace-moved","workspace-renamed"],"kind":"subscribe","mode_field":"tree_events","modes":{"coarse":["tree-changed"],"deltas":["workspace-added","workspace-closed","workspace-renamed","workspace-moved","screen-added","screen-closed","screen-renamed","pane-added","pane-closed","tab-added","tab-closed","tab-renamed","tree-changed"]},"ordering":"Response and event objects may interleave. Events preserve enqueue order per subscription. Delta workspace revisions are serialized in durable commit order; overflow ends the stream and requires resubscribe plus snapshot.","terminal_event":null}},"swap-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"constraints":["Exactly one of dir and target must be supplied."],"fields":{"dir":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"PaneDirection"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"target":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"EmptyResult"},"since":6,"stream":null},"terminal-events":{"authority":"control","capability":null,"constraints":["Consumers apply only contiguous revisions for one registry_id and generation."],"request":{"additional_properties":false,"fields":{"after_revision":{"default":0,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"TerminalEventsResult"},"since":9,"stream":null},"undo-layout":{"authority":"control","capability":"layout-undo-v1","constraints":["Clients must reject incomplete or contradictory result variants."],"request":{"additional_properties":false,"constraints":["confirm_close requires the exact preview revision."],"fields":{"confirm_close":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"revision":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"LayoutUndoResult"},"since":9,"stream":null},"vt-state":{"authority":"control","capability":null,"constraints":["PTY surfaces only."],"request":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"VtStateResult"},"since":5,"stream":null},"wait-for":{"authority":"control","capability":null,"constraints":["Blocks subsequent requests on this connection; SDKs should use a dedicated connection."],"request":{"additional_properties":false,"fields":{"pattern":{"constraints":[{"syntax":"Rust regex"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"timeout_ms":{"description":"Zero performs one immediate check.","nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"result":{"kind":"ref","name":"WaitForResult"},"since":6,"stream":null},"zoom-pane":{"authority":"control","capability":null,"constraints":[],"request":{"additional_properties":false,"fields":{"mode":{"default":"toggle","nullable":true,"presence":"optional","type":{"kind":"enum","values":["toggle","on","off"]}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"result":{"kind":"ref","name":"ZoomPaneResult"},"since":6,"stream":null}},"events":{"agent-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"agent-changed"}},"session":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"updated_at_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":11,"streams":["subscribe"]},"bell":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"bell"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"browser-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"browser-state"}},"frame":{"description":"The initial browser-state includes the latest frame when one exists; later state updates omit it.","nullable":true,"presence":"optional","type":{"kind":"ref","name":"BrowserFrame"}},"frames_stalled":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"status":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["starting","live","failed"]}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"url":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["attach-browser"]},"client-attached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-attached"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"transport":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["unix","ws"]}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-changed"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-detached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-detached"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"client-list-invalidated":{"capability":null,"emission":"serialized-never-emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"client-list-invalidated"}}},"kind":"object"},"since":9,"streams":["subscribe"]},"colors-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"cursor":{"nullable":true,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"nullable":true,"presence":"optional","type":{"kind":"ref","name":"CursorStyle"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"colors-changed"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"palette":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"surface":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["attach-byte"]},"config-reload-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"config-reload-requested"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"detached":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"detached"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte","attach-render","attach-browser"]},"empty":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"empty"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"frame":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"frame"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"since":6,"streams":["attach-browser"]},"frontend-projection-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"frontend-projection-changed"}},"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"projection_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"graphics-status":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["kitty-image-budget-worker-start-failed carries error.","kitty-image-budget-update-failed carries retry_exhausted and summary.","cell-pixel-update-retries-exhausted carries attempts, remaining, cell_width, and cell_height."],"fields":{"attempts":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cell_height":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"cell_width":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"graphics-status"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["kitty-image-budget-worker-start-failed","kitty-image-budget-update-failed","cell-pixel-update-retries-exhausted"]}},"remaining":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"retry_exhausted":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"summary":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":10,"streams":["subscribe"]},"layout-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"layout-changed"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"notification":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"body":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"notification"}},"level":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"NotificationLevel"}},"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe","attach-byte","attach-browser"]},"output":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"colors":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"TerminalColors"}},"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"output"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte"]},"overflow":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["scope and surface are either both present for attach overflow or both absent for subscribe overflow."],"fields":{"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"overflow"}},"scope":{"nullable":false,"presence":"optional","type":{"kind":"literal","value":"surface"}},"surface":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe","attach-byte","attach-render","attach-browser"]},"pairing-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pairing-requested"}},"expires_in":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"peer":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"pairing-resolved":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pairing-resolved"}},"request":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"pane-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Pane"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pane-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"pane-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Pane"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"pane-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"render-delta":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["size is present if and only if the surface resized; every resize has full:true."],"fields":{"cursor":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderCursor"}},"default_bg":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"default_fg":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"ColorHex"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"render-delta"}},"full":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"graphics":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderGraphicsDelta"}},"history_epoch":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"scrollback_rows":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"size":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"Size"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["attach-render"]},"render-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cursor":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderCursor"}},"default_bg":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"default_fg":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"render-state"}},"graphics":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderGraphics"}},"history_epoch":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"scrollback_rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"size":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Size"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["attach-render"]},"resized":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["At least one of replay and data is present; replay is canonical from protocol 7."],"fields":{"colors":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"TerminalColors"}},"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"description":"Protocol 6 compatibility field.","nullable":false,"presence":"optional","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"resized"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"replay":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"ref","name":"Base64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["attach-byte"]},"screen-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"screen-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"screen-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Screen"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"screen-renamed"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"scroll-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"at_bottom":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"scroll-changed"}},"offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":6,"streams":["subscribe","attach-byte","attach-render","attach-browser"]},"status":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"status"}},"message":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-exited":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-exited"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-output":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-output"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"surface-resize-failed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-resize-failed"}},"reservation_id":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"retry_after_ms":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe"]},"surface-resized":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"surface-resized"}},"reservation_id":{"nullable":true,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"tab-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-added"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"tab-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-closed"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"tab-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Tab"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tab-renamed"}},"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"terminal-registry-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"terminal-registry-changed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"refetch":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"terminal-events-or-list-terminals"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":9,"streams":["subscribe"]},"title-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"title-changed"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"title":{"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"tree-changed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"tree-changed"}}},"kind":"object"},"since":5,"streams":["subscribe"]},"vt-state":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"colors":{"nullable":false,"presence":"optional","since":6,"type":{"kind":"ref","name":"TerminalColors"}},"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"vt-state"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"since":5,"streams":["attach-byte"]},"window-title-requested":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"fields":{"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"window-title-requested"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"since":6,"streams":["subscribe"]},"workspace-added":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-added"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-closed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-closed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-moved":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-moved"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]},"workspace-renamed":{"capability":null,"emission":"emitted","payload":{"additional_properties":false,"constraints":["origin and mutation_id are either both present or both absent."],"fields":{"entity":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Workspace"}},"event":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"workspace-renamed"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"since":7,"streams":["subscribe-deltas"]}},"ir_sha256":"6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3","profiles":{"control":{"description":"Base authenticated session-control commands available to ordinary SDK clients.","inherits":[]},"frontend":{"description":"Rendering, input, presentation, subscribe, and attach commands.","inherits":["control"]},"local-admin":{"description":"Trusted local administration commands.","inherits":["control"],"transport":"Unix-classified transport, including direct Unix and the current stdio relay"},"provider-authority":{"description":"Provider-owned workspace mutation commands.","inherits":["control"],"requires_authority":true}},"protocol":{"id_type":"uint64","javascript_id_policy":"All protocol identifiers are uint64 JSON numbers. JavaScript and TypeScript SDKs must decode them losslessly as bigint (or validated decimal strings at their public boundary), and must not expose IEEE-754 number ids. Pairing request ids, revisions, timestamps, frame sequences, and reservation ids follow the same rule.","name":"cmux-tui-mux","version":11},"schema_version":2,"types":{"AgentRecord":{"additional_properties":false,"fields":{"session":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"updated_at_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"AgentReportSource":{"kind":"enum","values":["socket","hook"]},"AgentSource":{"kind":"enum","values":["detected","socket","hook"]},"AgentState":{"kind":"enum","values":["working","blocked","idle","done","unknown"]},"AppliedPane":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ApplyLayoutResult":{"additional_properties":false,"fields":{"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"AppliedPane"},"kind":"array"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"AttachedViewOutcomeResult":{"additional_properties":false,"fields":{"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ViewAttachmentOutcome"}}},"kind":"object"},"AttachedViewResizeResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ViewAttachmentOutcome"}},"reservation_id":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"Base64":{"kind":"alias","target":{"kind":"scalar","name":"string"}},"BrowserFrame":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"seq":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"CellPixelFailure":{"additional_properties":false,"fields":{"error":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"CellPixelResize":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"reservation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"CellPixelSurface":{"additional_properties":false,"fields":{"height_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"width_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"ClientInfo":{"additional_properties":false,"fields":{"attached":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}},"client":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"connected_seconds":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"kind":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"self":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"sizes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"ClientSize"},"kind":"array"}},"transport":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"ClientTransport"}}},"kind":"object"},"ClientSize":{"additional_properties":false,"fields":{"cols":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"size_participating":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ClientTransport":{"kind":"enum","values":["local","unix","ws"]},"CloseTerminalResult":{"additional_properties":false,"fields":{"already_closed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"closed":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ColorHex":{"kind":"alias","target":{"kind":"scalar","name":"string"}},"CopyResult":{"additional_properties":false,"fields":{"mode":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["screen","selection","scrollback"]}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"CursorStyle":{"kind":"enum","values":["block","underline","bar"]},"DeadPane":{"additional_properties":false,"fields":{"dead":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"DeclarativeLayout":{"kind":"tagged_union","tag":"type","variants":{"leaf":{"additional_properties":false,"fields":{"command":{"default":null,"nullable":true,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array","min_items":1}},"cwd":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"leaf"}}},"kind":"object"},"split":{"additional_properties":false,"fields":{"a":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"b":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"DeclarativeLayout"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"ratio":{"constraints":[{"clamped_maximum":0.95,"clamped_minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"split"}}},"kind":"object"},"stack":{"additional_properties":false,"fields":{"expanded":{"constraints":["Must identify a member of panes."],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array","min_items":1}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"stack"}}},"kind":"object"}}},"EmptyResult":{"additional_properties":false,"fields":{},"kind":"object"},"ExportLayoutResult":{"additional_properties":false,"fields":{"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"ExportedPane"},"kind":"array"}}},"kind":"object"},"ExportedPane":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"surfaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}}},"kind":"object"},"FocusDirectionResult":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"FrontendProjection":{"additional_properties":false,"fields":{"frontend":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"projection":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"projection_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"replayed":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"schema_version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"scope":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"subject_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"GetCellPixelsResult":{"additional_properties":false,"fields":{"height_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"surfaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelSurface"},"kind":"array"}},"width_px":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"Id":{"kind":"alias","target":{"kind":"scalar","name":"uint64"}},"IdMapping":{"additional_properties":false,"fields":{"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["workspace","screen","pane","surface"]}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"IdentifyResult":{"additional_properties":false,"fields":{"app":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"cmux-tui"}},"build_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"capabilities":{"default":[],"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"string"},"kind":"array"}},"daemon_handoff":{"nullable":false,"presence":"required","since":9,"type":{"kind":"literal","value":1}},"generation":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"string"}},"ghostty_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"protocol":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"registry_id":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"string"}},"session":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","since":9,"type":{"kind":"scalar","name":"uint64"}},"version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace_revision":{"nullable":false,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"IdsResult":{"additional_properties":false,"fields":{"ids":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"IdMapping"},"kind":"array"}}},"kind":"object"},"JsonValue":{"kind":"opaque_json","reason":"The wire field intentionally carries a frontend-authored or runtime-authored arbitrary JSON document."},"KittyGraphicsState":{"additional_properties":false,"fields":{"alternate_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"alternate_replay_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_bytes":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"inflight_bytes":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"placements":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"primary_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"primary_replay_next_image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"replay_cursor_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"KittyImageAlias":{"additional_properties":false,"fields":{"image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_number":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"Layout":{"kind":"tagged_union","tag":"type","variants":{"leaf":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"leaf"}}},"kind":"object"},"split":{"additional_properties":false,"fields":{"a":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"b":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"dir":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"SplitDirection"}},"ratio":{"constraints":[{"maximum":0.95,"minimum":0.05}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"float32"}},"split":{"description":"Stable for the lifetime of this split node.","nullable":false,"presence":"optional","since":8,"type":{"kind":"ref","name":"Id"}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"split"}}},"kind":"object"},"stack":{"additional_properties":false,"fields":{"expanded":{"constraints":["Must identify a member of panes."],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array","min_items":1}},"type":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"stack"}}},"kind":"object"}}},"LayoutUndoConfirmationRequired":{"additional_properties":false,"fields":{"closes_panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Id"},"kind":"array"}},"confirmation_required":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"undone":{"nullable":false,"presence":"required","type":{"kind":"literal","value":false}}},"kind":"object"},"LayoutUndoResult":{"kind":"untagged_union","variants":[{"kind":"ref","name":"LayoutUndoUndone"},{"kind":"ref","name":"LayoutUndoConfirmationRequired"}]},"LayoutUndoUndone":{"additional_properties":false,"fields":{"confirmation_required":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"literal","value":false}},"revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"screen":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"undone":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}}},"kind":"object"},"ListAgentsResult":{"additional_properties":false,"fields":{"agents":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"AgentRecord"},"kind":"array"}}},"kind":"object"},"ListTerminalsResult":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"terminals":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"TerminalRecord"},"kind":"array"}}},"kind":"object"},"LivePane":{"additional_properties":false,"fields":{"active_tab":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"focused_at":{"default":0,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint64"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"tabs":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Tab"},"kind":"array"}}},"kind":"object"},"MintTerminalRendererResult":{"additional_properties":false,"fields":{"endpoint":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"incarnation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"protocol_version":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"uint16"}},"rights":{"constraints":[{"current_value":7}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"token":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"ttl_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"MoveTerminalResult":{"additional_properties":false,"fields":{"changed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"NotificationLevel":{"kind":"enum","values":["info","warning","error"]},"NotificationMarker":{"additional_properties":false,"fields":{"level":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"NotificationLevel"}},"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"unread":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}}},"kind":"object"},"NotifyResult":{"additional_properties":false,"fields":{"notification":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Pane":{"kind":"untagged_union","variants":[{"kind":"ref","name":"LivePane"},{"kind":"ref","name":"DeadPane"}]},"PaneDirection":{"kind":"enum","values":["left","right","up","down"]},"PaneNeighborResult":{"additional_properties":false,"fields":{"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"PingResult":{"additional_properties":false,"fields":{"build_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"ghostty_commit":{"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"ok":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"protocol":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"version":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ProcessInfoResult":{"additional_properties":false,"fields":{"command":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"cwd":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"ProviderWorkspaceMutationResult":{"additional_properties":false,"fields":{"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ReadScreenResult":{"additional_properties":false,"fields":{"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ReadScrollbackResult":{"additional_properties":false,"fields":{"epoch":{"nullable":false,"presence":"required","since":10,"type":{"kind":"scalar","name":"uint64"}},"rows":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRow"},"kind":"array"}},"start":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"total":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"RenderCursor":{"additional_properties":false,"fields":{"blink":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"color":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"style":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"CursorStyle"}},"visible":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"x":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"y":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"RenderGraphicFormat":{"kind":"enum","values":["rgb","rgba"]},"RenderGraphicImage":{"additional_properties":false,"fields":{"data":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"format":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"RenderGraphicFormat"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"RenderGraphicPlacement":{"additional_properties":false,"fields":{"anchor_col":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}},"anchor_row":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint32"}},"columns":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"grid_cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"grid_rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"image_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"ordinal":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"pixel_height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"pixel_width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"placement_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_height":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_width":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_x":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"source_y":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"viewport_col":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"viewport_row":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"viewport_visible":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"x_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"y_offset":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"z":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}}},"kind":"object"},"RenderGraphics":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicImage"},"kind":"array"}},"placements":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderGraphicPlacement"},"kind":"array"}},"removed_image_ids":{"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"uint32"},"kind":"array"}}},"kind":"object"},"RenderGraphicsDelta":{"additional_properties":false,"fields":{"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"images":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicImage"},"kind":"array"}},"placements":{"nullable":false,"presence":"optional","type":{"items":{"kind":"ref","name":"RenderGraphicPlacement"},"kind":"array"}},"removed_image_ids":{"nullable":false,"presence":"optional","type":{"items":{"kind":"scalar","name":"uint32"},"kind":"array"}}},"kind":"object"},"RenderRow":{"additional_properties":false,"fields":{"row":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"runs":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"RenderRun"},"kind":"array"}}},"kind":"object"},"RenderRun":{"additional_properties":false,"fields":{"attrs":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}},"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"underline":{"nullable":false,"presence":"optional","type":{"kind":"ref","name":"RenderUnderline"}},"width_hint":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"RenderUnderline":{"kind":"enum","values":["single","double","curly","dotted","dashed"]},"ReportAgentResult":{"additional_properties":false,"fields":{"session":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"source":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentReportSource"}},"state":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"AgentState"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"ResizeSurfaceResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"reservation_id":{"nullable":true,"presence":"required","since":7,"type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ResolveTerminalResult":{"additional_properties":false,"fields":{"exit":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"TerminalExit"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"launch_spec":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"ResourceSelectors":{"additional_properties":false,"fields":{"agent":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"browser":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"client":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"frontend_projection":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"machine":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"notification":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pairing_request":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"pane":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"screen":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"session":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"sidebar_view":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"split":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"stream":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"tab":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"terminal":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"workspace":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"RunResult":{"additional_properties":false,"fields":{"already_exited":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"boolean"}},"exit":{"nullable":true,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalExit"}},"lifecycle":{"nullable":false,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Screen":{"additional_properties":false,"fields":{"active":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"active_pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"layout":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Layout"}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"panes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Pane"},"kind":"array"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"zoomed_pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"SetCellPixelsResult":{"additional_properties":false,"fields":{"failures":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelFailure"},"kind":"array"}},"resizes":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"CellPixelResize"},"kind":"array"}}},"kind":"object"},"ShutdownDaemonResult":{"additional_properties":false,"fields":{"accepted":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"pid":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint32"}}},"kind":"object"},"SidebarPluginResult":{"additional_properties":false,"fields":{"error":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"retry_after_ms":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"Size":{"additional_properties":false,"fields":{"cols":{"constraints":[{"maximum":10000,"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"rows":{"constraints":[{"maximum":10000,"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"SplitDirection":{"kind":"enum","values":["right","down"]},"SurfaceResult":{"additional_properties":false,"fields":{"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Tab":{"additional_properties":false,"fields":{"browser_error":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"browser_frames_stalled":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"boolean"}},"browser_source":{"nullable":true,"presence":"required","type":{"kind":"enum","values":["external","launched"]}},"browser_status":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"enum","values":["starting","live","failed"]}},"dead":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"enum","values":["pty","browser"]}},"name":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"notification":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"NotificationMarker"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}},"size":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Size"}},"supports_clear_history_key_fallback":{"capability":"clear-history-key-v1","nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"boolean"}},"surface":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"optional","since":9,"type":{"kind":"scalar","name":"string"}},"terminal_resource_id":{"constraints":[{"pattern":"^term_[0-9a-f]{32}$"}],"nullable":true,"presence":"optional","since":10,"type":{"kind":"scalar","name":"string"}},"title":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalColors":{"additional_properties":false,"fields":{"bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"cursor":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"ColorHex"}},"cursor_blink":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"scalar","name":"boolean"}},"cursor_style":{"nullable":true,"presence":"optional","since":6,"type":{"kind":"ref","name":"CursorStyle"}},"fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"palette":{"constraints":["Decimal string keys are palette indexes 0 through 255."],"nullable":false,"presence":"optional","since":7,"type":{"kind":"map","values":{"kind":"ref","name":"ColorHex"}}},"selection_bg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}},"selection_fg":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"ColorHex"}}},"kind":"object"},"TerminalEventsResult":{"additional_properties":false,"fields":{"events":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"TerminalRegistryEvent"},"kind":"array"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"TerminalExit":{"additional_properties":false,"fields":{"exited_at_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"outcome":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalExitOutcome"}}},"kind":"object"},"TerminalExitOutcome":{"kind":"tagged_union","tag":"kind","variants":{"exit":{"additional_properties":false,"fields":{"code":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"exit"}}},"kind":"object"},"signal":{"additional_properties":false,"fields":{"core_dumped":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"signal"}},"signal":{"constraints":[{"minimum":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"int32"}}},"kind":"object"},"unknown":{"additional_properties":false,"fields":{"kind":{"nullable":false,"presence":"required","type":{"kind":"literal","value":"unknown"}},"reason":{"constraints":[{"min_length":1}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"}}},"TerminalKey":{"kind":"enum","values":["unidentified","backquote","backslash","bracket-left","bracket-right","comma","digit0","digit1","digit2","digit3","digit4","digit5","digit6","digit7","digit8","digit9","equal","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","minus","period","quote","semicolon","slash","backspace","enter","space","tab","delete","end","home","insert","page-down","page-up","arrow-down","arrow-left","arrow-right","arrow-up","numpad0","numpad1","numpad2","numpad3","numpad4","numpad5","numpad6","numpad7","numpad8","numpad9","numpad-add","numpad-backspace","numpad-comma","numpad-decimal","numpad-divide","numpad-enter","numpad-equal","numpad-multiply","numpad-subtract","numpad-up","numpad-down","numpad-right","numpad-left","numpad-begin","numpad-home","numpad-end","numpad-insert","numpad-delete","numpad-page-up","numpad-page-down","escape","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","f11","f12","f13","f14","f15","f16","f17","f18","f19","f20"]},"TerminalKeyAction":{"kind":"enum","values":["press","release","repeat"]},"TerminalKeyInput":{"additional_properties":false,"constraints":["consumed_mods must be a subset of mods.","unshifted_codepoint, shifted_codepoint, and base_layout_codepoint contain exactly one Unicode scalar when present.","utf8 contains no control characters.","macos_option_as_alt may be false only when Alt is active and consumed."],"fields":{"action":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"ref","name":"TerminalKeyAction"}},"base_layout_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"composing":{"default":false,"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"consumed_mods":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalModifiers"}},"key":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalKey"}},"macos_option_as_alt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"mods":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalModifiers"}},"shifted_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"unshifted_codepoint":{"default":null,"nullable":true,"presence":"optional","type":{"kind":"scalar","name":"string"}},"utf8":{"constraints":[{"max_length":4096}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalLifecycle":{"kind":"enum","values":["launching","adopting","running","exited","tombstoned"]},"TerminalModifiers":{"additional_properties":false,"fields":{"alt":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"caps_lock":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"control":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"num_lock":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"shift":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"super":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}}},"kind":"object"},"TerminalPlacement":{"additional_properties":false,"fields":{"already_exited":{"nullable":false,"presence":"required","since":11,"type":{"kind":"scalar","name":"boolean"}},"exit":{"nullable":true,"presence":"required","since":11,"type":{"kind":"ref","name":"TerminalExit"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"screen":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"surface":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"},"TerminalRecord":{"additional_properties":false,"fields":{"exit":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"TerminalExit"}},"launch_spec":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"lifecycle":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"TerminalLifecycle"}},"terminal_id":{"constraints":[{"format":"UUIDv4 hex without dashes","pattern":"^[0-9a-f]{32}$"}],"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_incarnation":{"nullable":true,"presence":"required","type":{"kind":"scalar","name":"string"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"TerminalRegistryEvent":{"additional_properties":false,"fields":{"kind":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"mutation_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"origin":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"result":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"JsonValue"}},"terminal_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"workspace_key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Tree":{"additional_properties":false,"fields":{"generation":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"pane_revision":{"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"registry_id":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"terminal_revision":{"nullable":false,"presence":"optional","since":9,"type":{"kind":"scalar","name":"uint64"}},"workspace_revision":{"capability":"workspace-registry-v1","nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"uint64"}},"workspaces":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Workspace"},"kind":"array"}}},"kind":"object"},"ViewAttachmentOutcome":{"kind":"enum","values":["applied","passive","superseded"]},"VtStateResult":{"additional_properties":false,"fields":{"cols":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}},"data":{"constraints":[{"encoding":"standard base64"}],"nullable":false,"presence":"required","type":{"kind":"ref","name":"Base64"}},"kitty_graphics_state":{"nullable":false,"presence":"optional","since":10,"type":{"kind":"ref","name":"KittyGraphicsState"}},"kitty_image_aliases":{"nullable":false,"presence":"optional","since":9,"type":{"items":{"kind":"ref","name":"KittyImageAlias"},"kind":"array"}},"rows":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint16"}}},"kind":"object"},"WaitForResult":{"additional_properties":false,"fields":{"elapsed_ms":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"matched":{"nullable":false,"presence":"required","type":{"kind":"literal","value":true}},"text":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}}},"kind":"object"},"Workspace":{"additional_properties":false,"fields":{"active":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"id":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"key":{"capability":"workspace-registry-v1","constraints":[{"format":"lowercase canonical UUID"}],"nullable":false,"presence":"optional","since":7,"type":{"kind":"scalar","name":"string"}},"name":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"screens":{"nullable":false,"presence":"required","type":{"items":{"kind":"ref","name":"Screen"},"kind":"array"}},"short_id":{"constraints":[{"pattern":"^[a-z0-9]{6}$"}],"nullable":false,"presence":"optional","since":6,"type":{"kind":"scalar","name":"string"}}},"kind":"object"},"WorkspaceMutationResult":{"additional_properties":false,"fields":{"changed":{"nullable":false,"presence":"optional","type":{"kind":"scalar","name":"boolean"}},"generation":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"index":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}},"key":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"registry_id":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"string"}},"replayed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"workspace":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"workspace_revision":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"uint64"}}},"kind":"object"},"ZoomPaneResult":{"additional_properties":false,"fields":{"pane":{"nullable":false,"presence":"required","type":{"kind":"ref","name":"Id"}},"zoomed":{"nullable":false,"presence":"required","type":{"kind":"scalar","name":"boolean"}},"zoomed_pane":{"nullable":true,"presence":"required","type":{"kind":"ref","name":"Id"}}},"kind":"object"}}}') diff --git a/cmux-tui/bindings/python/cmux/raw/_generated/codec.py b/cmux-tui/bindings/python/cmux/raw/_generated/codec.py index d119cba883ca..0be9ce011ad7 100644 --- a/cmux-tui/bindings/python/cmux/raw/_generated/codec.py +++ b/cmux-tui/bindings/python/cmux/raw/_generated/codec.py @@ -195,6 +195,7 @@ class ProtocolDecodeError(ValueError): 'commands/vt-state/request': models.VtStateRequest, 'commands/wait-for/request': models.WaitForRequest, 'commands/zoom-pane/request': models.ZoomPaneRequest, + 'events/agent-changed/payload': models.AgentChangedEvent, 'events/bell/payload': models.BellEvent, 'events/browser-state/payload': models.BrowserStateEvent, 'events/client-attached/payload': models.ClientAttachedEvent, diff --git a/cmux-tui/bindings/python/cmux/raw/_generated/metadata.py b/cmux-tui/bindings/python/cmux/raw/_generated/metadata.py index 47e487bcc310..c1cd332cc2c8 100644 --- a/cmux-tui/bindings/python/cmux/raw/_generated/metadata.py +++ b/cmux-tui/bindings/python/cmux/raw/_generated/metadata.py @@ -8,7 +8,7 @@ SCHEMA_VERSION = 2 MUX_PROTOCOL = 11 -IR_SHA256 = '5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1' +IR_SHA256 = '6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3' @dataclass(frozen=True) @@ -1309,6 +1309,7 @@ class EventMetadata: } EVENTS = { + 'agent-changed': EventMetadata('agent-changed', 11, None, ('subscribe',), 'emitted'), 'bell': EventMetadata('bell', 5, None, ('subscribe',), 'emitted'), 'browser-state': EventMetadata('browser-state', 6, None, ('attach-browser',), 'emitted'), 'client-attached': EventMetadata('client-attached', 6, None, ('subscribe',), 'emitted'), diff --git a/cmux-tui/bindings/python/cmux/raw/_generated/models.py b/cmux-tui/bindings/python/cmux/raw/_generated/models.py index 340b4e2f738a..5e88ad915cbf 100644 --- a/cmux-tui/bindings/python/cmux/raw/_generated/models.py +++ b/cmux-tui/bindings/python/cmux/raw/_generated/models.py @@ -1830,6 +1830,18 @@ class ZoomPaneRequest: mode: Union[Literal['toggle', 'on', 'off'], None, MissingType] = field(default=MISSING) +@dataclass(frozen=True) +class AgentChangedEvent(EventBase): + __cmux_schema_path__: ClassVar[str] = 'events/agent-changed/payload' + surface: Id + event: Literal['agent-changed'] + session: Union[str, None] + source: AgentSource + state: AgentState + updated_at_ms: int + raw: Mapping[str, Any] = field(default_factory=dict, repr=False, compare=False, metadata={'cmux_skip': True}) + + @dataclass(frozen=True) class BellEvent(EventBase): __cmux_schema_path__: ClassVar[str] = 'events/bell/payload' @@ -2346,7 +2358,7 @@ class WorkspaceRenamedEvent(EventBase): Pane = Union[LivePane, DeadPane] TerminalExitOutcome = Union[TerminalExitOutcomeExit, TerminalExitOutcomeSignal, TerminalExitOutcomeUnknown] -KnownEvent = Union[BellEvent, BrowserStateEvent, ClientAttachedEvent, ClientChangedEvent, ClientDetachedEvent, ClientListInvalidatedEvent, ColorsChangedEvent, ConfigReloadRequestedEvent, DetachedEvent, EmptyEvent, FrameEvent, FrontendProjectionChangedEvent, GraphicsStatusEvent, LayoutChangedEvent, NotificationEvent, OutputEvent, OverflowEvent, PairingRequestedEvent, PairingResolvedEvent, PaneAddedEvent, PaneClosedEvent, RenderDeltaEvent, RenderStateEvent, ResizedEvent, ScreenAddedEvent, ScreenClosedEvent, ScreenRenamedEvent, ScrollChangedEvent, StatusEvent, SurfaceExitedEvent, SurfaceOutputEvent, SurfaceResizeFailedEvent, SurfaceResizedEvent, TabAddedEvent, TabClosedEvent, TabRenamedEvent, TerminalRegistryChangedEvent, TitleChangedEvent, TreeChangedEvent, VtStateEvent, WindowTitleRequestedEvent, WorkspaceAddedEvent, WorkspaceClosedEvent, WorkspaceMovedEvent, WorkspaceRenamedEvent] +KnownEvent = Union[AgentChangedEvent, BellEvent, BrowserStateEvent, ClientAttachedEvent, ClientChangedEvent, ClientDetachedEvent, ClientListInvalidatedEvent, ColorsChangedEvent, ConfigReloadRequestedEvent, DetachedEvent, EmptyEvent, FrameEvent, FrontendProjectionChangedEvent, GraphicsStatusEvent, LayoutChangedEvent, NotificationEvent, OutputEvent, OverflowEvent, PairingRequestedEvent, PairingResolvedEvent, PaneAddedEvent, PaneClosedEvent, RenderDeltaEvent, RenderStateEvent, ResizedEvent, ScreenAddedEvent, ScreenClosedEvent, ScreenRenamedEvent, ScrollChangedEvent, StatusEvent, SurfaceExitedEvent, SurfaceOutputEvent, SurfaceResizeFailedEvent, SurfaceResizedEvent, TabAddedEvent, TabClosedEvent, TabRenamedEvent, TerminalRegistryChangedEvent, TitleChangedEvent, TreeChangedEvent, VtStateEvent, WindowTitleRequestedEvent, WorkspaceAddedEvent, WorkspaceClosedEvent, WorkspaceMovedEvent, WorkspaceRenamedEvent] AnyEvent = Union[KnownEvent, UnknownEvent] __all__ = [ @@ -2550,6 +2562,7 @@ class WorkspaceRenamedEvent(EventBase): 'VtStateRequest', 'WaitForRequest', 'ZoomPaneRequest', + 'AgentChangedEvent', 'BellEvent', 'BrowserStateEvent', 'ClientAttachedEvent', diff --git a/cmux-tui/bindings/rust/src/generated/.cmux-sdk-manifest.json b/cmux-tui/bindings/rust/src/generated/.cmux-sdk-manifest.json index 21964825cde1..acefaf1bcc7b 100644 --- a/cmux-tui/bindings/rust/src/generated/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/rust/src/generated/.cmux-sdk-manifest.json @@ -2,32 +2,32 @@ "files": [ { "path": "commands.rs", - "sha256": "6a5db40f35ec4813694de84793021cff7d0e557bec8a89e0ff2232a9efaa920f", + "sha256": "143af1d5ef750dbc20421bf4e947de8c365de1a1ba3252773141c4fe5fab762a", "size": 60007 }, { "path": "events.rs", - "sha256": "2b00edd92788c9c1b77acbe899f089ac63b70c6d681a13a16eaae0cb772babf6", - "size": 40682 + "sha256": "afac6666286d25c37a19355283caad020e3bfbd6ac497b3c007742fd79724bbd", + "size": 41444 }, { "path": "metadata.rs", - "sha256": "3152a1c401152a1714afe57e4d9ac79738b1f0e1b29d820e62291131102c5491", - "size": 35676 + "sha256": "6f842ef111514bd024f727f996bb428975723e5e5d3ba88db23ad6f29635630f", + "size": 35917 }, { "path": "mod.rs", - "sha256": "02570d20406540e4fc365b33f1bcfb199add2aa2fed9d155ca2406a71c7b189d", + "sha256": "0d50e1d7b535bd60e65668569ad7fcdd8aaf893be8b3b029e2e0e14cd7852b6e", "size": 365 }, { "path": "types.rs", - "sha256": "f2f68b96c0e41327d33ecdc464a807b5cc4f4a336b391e6b394e69190f04b027", + "sha256": "ac422e88ad2b7c9650f9708c70cb65d544a7fb2d8bb234e208173aef75993fbc", "size": 37555 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "rust", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/rust/src/generated/commands.rs b/cmux-tui/bindings/rust/src/generated/commands.rs index 2a6e56477368..1d2ff8720fad 100644 --- a/cmux-tui/bindings/rust/src/generated/commands.rs +++ b/cmux-tui/bindings/rust/src/generated/commands.rs @@ -1,5 +1,5 @@ // This file is generated. Do not edit by hand. -// cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. // The emitter owns this layout so generation is independent of the installed rustfmt. use super::metadata::*; diff --git a/cmux-tui/bindings/rust/src/generated/events.rs b/cmux-tui/bindings/rust/src/generated/events.rs index e515d5b2bb77..def07a32afe9 100644 --- a/cmux-tui/bindings/rust/src/generated/events.rs +++ b/cmux-tui/bindings/rust/src/generated/events.rs @@ -1,5 +1,5 @@ // This file is generated. Do not edit by hand. -// cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. // The emitter owns this layout so generation is independent of the installed rustfmt. use super::metadata::*; @@ -9,6 +9,16 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use std::collections::BTreeMap; +#[rustfmt::skip] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AgentChangedEvent { + pub session: Nullable, + pub source: T::AgentSource, + pub state: T::AgentState, + pub surface: T::Id, + pub updated_at_ms: u64, +} + #[rustfmt::skip] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct BellEvent { @@ -509,6 +519,7 @@ pub struct UnknownEvent { #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum Event { + AgentChanged(AgentChangedEvent), Bell(BellEvent), BrowserState(BrowserStateEvent), ClientAttached(ClientAttachedEvent), @@ -561,6 +572,7 @@ pub enum Event { impl Event { pub fn wire_name(&self) -> Option<&str> { match self { + Self::AgentChanged(_) => Some("agent-changed"), Self::Bell(_) => Some("bell"), Self::BrowserState(_) => Some("browser-state"), Self::ClientAttached(_) => Some("client-attached"), @@ -612,6 +624,7 @@ impl Event { pub fn metadata(&self) -> Option<&'static EventMetadata> { match self { + Self::AgentChanged(_) => Some(&AGENT_CHANGED_EVENT_METADATA), Self::Bell(_) => Some(&BELL_EVENT_METADATA), Self::BrowserState(_) => Some(&BROWSER_STATE_EVENT_METADATA), Self::ClientAttached(_) => Some(&CLIENT_ATTACHED_EVENT_METADATA), @@ -666,6 +679,14 @@ impl Event { pub fn decode_event(raw: Value) -> Event { let name = raw.get("event").and_then(Value::as_str).map(str::to_owned); match name.as_deref() { + Some("agent-changed") => match serde_json::from_value::(raw.clone()) { + Ok(event) => Event::AgentChanged(event), + Err(error) => Event::Unknown(UnknownEvent { + name, + raw, + decode_error: Some(error.to_string()), + }), + }, Some("bell") => match serde_json::from_value::(raw.clone()) { Ok(event) => Event::Bell(event), Err(error) => Event::Unknown(UnknownEvent { diff --git a/cmux-tui/bindings/rust/src/generated/metadata.rs b/cmux-tui/bindings/rust/src/generated/metadata.rs index e4afbc12a5b7..02df77cd090b 100644 --- a/cmux-tui/bindings/rust/src/generated/metadata.rs +++ b/cmux-tui/bindings/rust/src/generated/metadata.rs @@ -1,12 +1,12 @@ // This file is generated. Do not edit by hand. -// cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. // The emitter owns this layout so generation is independent of the installed rustfmt. use crate::{CommandMetadata, EventMetadata, ProfileMetadata, StreamMetadata}; pub const SDK_SCHEMA_VERSION: u32 = 2; pub const MUX_PROTOCOL_VERSION: u32 = 11; -pub const SDK_IR_SHA256: &str = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1"; +pub const SDK_IR_SHA256: &str = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3"; #[rustfmt::skip] pub const CONTROL_PROFILE: ProfileMetadata = ProfileMetadata { @@ -917,6 +917,15 @@ pub const ZOOM_PANE_METADATA: CommandMetadata = CommandMetadata { stream: None, }; +#[rustfmt::skip] +pub const AGENT_CHANGED_EVENT_METADATA: EventMetadata = EventMetadata { + name: "agent-changed", + since: 11, + capability: None, + streams: &["subscribe"], + emission: "emitted", +}; + #[rustfmt::skip] pub const BELL_EVENT_METADATA: EventMetadata = EventMetadata { name: "bell", @@ -1327,4 +1336,4 @@ pub static PROFILES: &[ProfileMetadata] = &[CONTROL_PROFILE, FRONTEND_PROFILE, L #[rustfmt::skip] pub static COMMANDS: &[CommandMetadata] = &[APPLY_LAYOUT_METADATA, ATTACH_SURFACE_METADATA, BROWSER_ACTIVATE_METADATA, BROWSER_BACK_METADATA, BROWSER_FORWARD_METADATA, BROWSER_FRAME_PRESENTED_METADATA, BROWSER_INSERT_TEXT_METADATA, BROWSER_KEY_METADATA, BROWSER_KEY_PRESS_METADATA, BROWSER_MOUSE_METADATA, BROWSER_MOUSE_GUARDED_METADATA, BROWSER_NAVIGATE_METADATA, BROWSER_RELOAD_METADATA, BROWSER_WHEEL_METADATA, BROWSER_WHEEL_GUARDED_METADATA, CLEAR_HISTORY_METADATA, CLEAR_WINDOW_TITLE_METADATA, CLOSE_PANE_METADATA, CLOSE_PROVIDER_MANAGED_WORKSPACE_METADATA, CLOSE_SCREEN_METADATA, CLOSE_SURFACE_METADATA, CLOSE_TERMINAL_METADATA, CLOSE_WORKSPACE_METADATA, COPY_METADATA, CREATE_SURFACE_WITH_RECEIPT_METADATA, CREATE_TERMINAL_METADATA, CREATE_WORKSPACE_METADATA, DETACH_ATTACHED_VIEW_METADATA, DETACH_CLIENT_METADATA, EXPORT_LAYOUT_METADATA, FOCUS_DIRECTION_METADATA, FOCUS_PANE_METADATA, GET_CELL_PIXELS_METADATA, GET_FRONTEND_PROJECTION_METADATA, IDENTIFY_METADATA, IDS_METADATA, LIST_AGENTS_METADATA, LIST_CLIENTS_METADATA, LIST_TERMINALS_METADATA, LIST_WORKSPACES_METADATA, MARK_WORKSPACES_PROVIDER_MANAGED_METADATA, MINT_TERMINAL_RENDERER_METADATA, MINT_TERMINAL_RENDERER_BY_TERMINAL_METADATA, MOVE_TAB_METADATA, MOVE_TERMINAL_METADATA, MOVE_WORKSPACE_METADATA, NEW_BROWSER_TAB_METADATA, NEW_PANE_METADATA, NEW_PANE_RIGHT_METADATA, NEW_SCREEN_METADATA, NEW_TAB_METADATA, NEW_WORKSPACE_METADATA, NOTIFY_METADATA, PAIRING_RESPONSE_METADATA, PANE_NEIGHBOR_METADATA, PING_METADATA, PROCESS_INFO_METADATA, PUT_FRONTEND_PROJECTION_METADATA, READ_SCREEN_METADATA, READ_SCROLLBACK_METADATA, RELEASE_ATTACHED_VIEW_SIZE_METADATA, RELEASE_SURFACE_SIZE_METADATA, RELOAD_CONFIG_METADATA, RENAME_PANE_METADATA, RENAME_PROVIDER_MANAGED_WORKSPACE_METADATA, RENAME_SCREEN_METADATA, RENAME_SURFACE_METADATA, RENAME_WORKSPACE_METADATA, REPORT_AGENT_METADATA, RESIZE_ATTACHED_VIEW_METADATA, RESIZE_SURFACE_METADATA, RESOLVE_TERMINAL_METADATA, RUN_METADATA, SCROLL_SURFACE_METADATA, SELECT_SCREEN_METADATA, SELECT_TAB_METADATA, SELECT_WORKSPACE_METADATA, SEND_METADATA, SEND_KEY_METADATA, SET_CELL_PIXELS_METADATA, SET_CLIENT_INFO_METADATA, SET_CLIENT_SIZING_METADATA, SET_DEFAULT_COLORS_METADATA, SET_RATIO_METADATA, SET_SPLIT_RATIO_METADATA, SET_VIEWPORT_PANE_WIDTH_METADATA, SET_WINDOW_TITLE_METADATA, SHUTDOWN_DAEMON_METADATA, SIDEBAR_PLUGIN_METADATA, SPLIT_METADATA, SUBSCRIBE_METADATA, SWAP_PANE_METADATA, TERMINAL_EVENTS_METADATA, UNDO_LAYOUT_METADATA, VT_STATE_METADATA, WAIT_FOR_METADATA, ZOOM_PANE_METADATA]; #[rustfmt::skip] -pub static EVENTS: &[EventMetadata] = &[BELL_EVENT_METADATA, BROWSER_STATE_EVENT_METADATA, CLIENT_ATTACHED_EVENT_METADATA, CLIENT_CHANGED_EVENT_METADATA, CLIENT_DETACHED_EVENT_METADATA, CLIENT_LIST_INVALIDATED_EVENT_METADATA, COLORS_CHANGED_EVENT_METADATA, CONFIG_RELOAD_REQUESTED_EVENT_METADATA, DETACHED_EVENT_METADATA, EMPTY_EVENT_METADATA, FRAME_EVENT_METADATA, FRONTEND_PROJECTION_CHANGED_EVENT_METADATA, GRAPHICS_STATUS_EVENT_METADATA, LAYOUT_CHANGED_EVENT_METADATA, NOTIFICATION_EVENT_METADATA, OUTPUT_EVENT_METADATA, OVERFLOW_EVENT_METADATA, PAIRING_REQUESTED_EVENT_METADATA, PAIRING_RESOLVED_EVENT_METADATA, PANE_ADDED_EVENT_METADATA, PANE_CLOSED_EVENT_METADATA, RENDER_DELTA_EVENT_METADATA, RENDER_STATE_EVENT_METADATA, RESIZED_EVENT_METADATA, SCREEN_ADDED_EVENT_METADATA, SCREEN_CLOSED_EVENT_METADATA, SCREEN_RENAMED_EVENT_METADATA, SCROLL_CHANGED_EVENT_METADATA, STATUS_EVENT_METADATA, SURFACE_EXITED_EVENT_METADATA, SURFACE_OUTPUT_EVENT_METADATA, SURFACE_RESIZE_FAILED_EVENT_METADATA, SURFACE_RESIZED_EVENT_METADATA, TAB_ADDED_EVENT_METADATA, TAB_CLOSED_EVENT_METADATA, TAB_RENAMED_EVENT_METADATA, TERMINAL_REGISTRY_CHANGED_EVENT_METADATA, TITLE_CHANGED_EVENT_METADATA, TREE_CHANGED_EVENT_METADATA, VT_STATE_EVENT_METADATA, WINDOW_TITLE_REQUESTED_EVENT_METADATA, WORKSPACE_ADDED_EVENT_METADATA, WORKSPACE_CLOSED_EVENT_METADATA, WORKSPACE_MOVED_EVENT_METADATA, WORKSPACE_RENAMED_EVENT_METADATA]; +pub static EVENTS: &[EventMetadata] = &[AGENT_CHANGED_EVENT_METADATA, BELL_EVENT_METADATA, BROWSER_STATE_EVENT_METADATA, CLIENT_ATTACHED_EVENT_METADATA, CLIENT_CHANGED_EVENT_METADATA, CLIENT_DETACHED_EVENT_METADATA, CLIENT_LIST_INVALIDATED_EVENT_METADATA, COLORS_CHANGED_EVENT_METADATA, CONFIG_RELOAD_REQUESTED_EVENT_METADATA, DETACHED_EVENT_METADATA, EMPTY_EVENT_METADATA, FRAME_EVENT_METADATA, FRONTEND_PROJECTION_CHANGED_EVENT_METADATA, GRAPHICS_STATUS_EVENT_METADATA, LAYOUT_CHANGED_EVENT_METADATA, NOTIFICATION_EVENT_METADATA, OUTPUT_EVENT_METADATA, OVERFLOW_EVENT_METADATA, PAIRING_REQUESTED_EVENT_METADATA, PAIRING_RESOLVED_EVENT_METADATA, PANE_ADDED_EVENT_METADATA, PANE_CLOSED_EVENT_METADATA, RENDER_DELTA_EVENT_METADATA, RENDER_STATE_EVENT_METADATA, RESIZED_EVENT_METADATA, SCREEN_ADDED_EVENT_METADATA, SCREEN_CLOSED_EVENT_METADATA, SCREEN_RENAMED_EVENT_METADATA, SCROLL_CHANGED_EVENT_METADATA, STATUS_EVENT_METADATA, SURFACE_EXITED_EVENT_METADATA, SURFACE_OUTPUT_EVENT_METADATA, SURFACE_RESIZE_FAILED_EVENT_METADATA, SURFACE_RESIZED_EVENT_METADATA, TAB_ADDED_EVENT_METADATA, TAB_CLOSED_EVENT_METADATA, TAB_RENAMED_EVENT_METADATA, TERMINAL_REGISTRY_CHANGED_EVENT_METADATA, TITLE_CHANGED_EVENT_METADATA, TREE_CHANGED_EVENT_METADATA, VT_STATE_EVENT_METADATA, WINDOW_TITLE_REQUESTED_EVENT_METADATA, WORKSPACE_ADDED_EVENT_METADATA, WORKSPACE_CLOSED_EVENT_METADATA, WORKSPACE_MOVED_EVENT_METADATA, WORKSPACE_RENAMED_EVENT_METADATA]; diff --git a/cmux-tui/bindings/rust/src/generated/mod.rs b/cmux-tui/bindings/rust/src/generated/mod.rs index c72ab600a9e1..5bded75177af 100644 --- a/cmux-tui/bindings/rust/src/generated/mod.rs +++ b/cmux-tui/bindings/rust/src/generated/mod.rs @@ -1,5 +1,5 @@ // This file is generated. Do not edit by hand. -// cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. // The emitter owns this layout so generation is independent of the installed rustfmt. mod commands; diff --git a/cmux-tui/bindings/rust/src/generated/types.rs b/cmux-tui/bindings/rust/src/generated/types.rs index 6cd7eb5a7516..ece2cd7c06ad 100644 --- a/cmux-tui/bindings/rust/src/generated/types.rs +++ b/cmux-tui/bindings/rust/src/generated/types.rs @@ -1,5 +1,5 @@ // This file is generated. Do not edit by hand. -// cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. +// cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. // The emitter owns this layout so generation is independent of the installed rustfmt. use crate::{Nullable, Optional}; diff --git a/cmux-tui/bindings/typescript/src/raw/generated/.cmux-sdk-manifest.json b/cmux-tui/bindings/typescript/src/raw/generated/.cmux-sdk-manifest.json index 5965f07d61c4..10727befe39c 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/typescript/src/raw/generated/.cmux-sdk-manifest.json @@ -2,32 +2,32 @@ "files": [ { "path": "commands.ts", - "sha256": "62257435bfe662ed5efdc0b82a681807fd9944380a9af61dc93017f6a7bad989", + "sha256": "7ea918e7426f53cf7ca60e0542600abfedc6af71b29bce4ad8eebe847e2e4ca3", "size": 46645 }, { "path": "events.ts", - "sha256": "a6d52584380b673ef0d8f717374e753798a3b559e0d81d059a78a854dc8674d4", - "size": 14850 + "sha256": "cbecc99627badbfa3956aff44f773e12dd95b870f3b42d1ca7e7fddd3eb8879b", + "size": 15149 }, { "path": "index.ts", - "sha256": "5d790fd5cf36e8bc931542fcefa137cfa9a93ac1d0754deaff4da07d572d3888", + "sha256": "123553c22a15288466badfe9d4e399ec35da08f731c9ef4220a1e1315e51b816", "size": 272 }, { "path": "metadata.ts", - "sha256": "e39b59636c1b260cbcc9a1afd9b93ee5942b386d49bfed3a2dcb01cc6b9d1790", - "size": 262824 + "sha256": "6aa9a9271189d0ecb99779a9c20160dc7ebcbcdaf5b2b749bdcf72382de23908", + "size": 264114 }, { "path": "types.ts", - "sha256": "f00d4ad0853bd05f179dd86fe40f9020da87674a44c5a34e942a02671a8f6697", + "sha256": "a95690bff88219bf026b85290d6d9e41cccbc5b2649f452cb96454429b95d9e2", "size": 16346 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "typescript", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/typescript/src/raw/generated/commands.ts b/cmux-tui/bindings/typescript/src/raw/generated/commands.ts index 76face51bfb2..589f7cff408f 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/commands.ts +++ b/cmux-tui/bindings/typescript/src/raw/generated/commands.ts @@ -1,5 +1,5 @@ /* This file is generated. Do not edit by hand. */ -/* cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. */ +/* cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. */ import type * as T from "./types.js"; diff --git a/cmux-tui/bindings/typescript/src/raw/generated/events.ts b/cmux-tui/bindings/typescript/src/raw/generated/events.ts index 8c4e9287720e..22f7e8111ed1 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/events.ts +++ b/cmux-tui/bindings/typescript/src/raw/generated/events.ts @@ -1,9 +1,18 @@ /* This file is generated. Do not edit by hand. */ -/* cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. */ +/* cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. */ import type * as T from "./types.js"; +/** Protocol v11; emission: emitted; streams: subscribe. */ +export type AgentChangedEvent = { event: "agent-changed" } & { + "session": (string) | null; + "source": T.AgentSource; + "state": T.AgentState; + "surface": T.Id; + "updated_at_ms": bigint; +}; + /** Protocol v5; emission: emitted; streams: subscribe. */ export type BellEvent = { event: "bell" } & { "surface": T.Id; @@ -384,6 +393,7 @@ export interface UnknownEvent { /** Every event emitted by protocol v11. */ export type KnownCmuxEvent = + | AgentChangedEvent | BellEvent | BrowserStateEvent | ClientAttachedEvent @@ -435,6 +445,7 @@ export type SerializedButNotEmittedEvent = /** Known subscribe stream events. */ export type KnownSubscribeEvent = + | AgentChangedEvent | BellEvent | ClientAttachedEvent | ClientChangedEvent diff --git a/cmux-tui/bindings/typescript/src/raw/generated/index.ts b/cmux-tui/bindings/typescript/src/raw/generated/index.ts index 82b5de1b55e1..707480857b80 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/index.ts +++ b/cmux-tui/bindings/typescript/src/raw/generated/index.ts @@ -1,5 +1,5 @@ /* This file is generated. Do not edit by hand. */ -/* cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. */ +/* cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. */ export * from "./types.js"; export * from "./commands.js"; diff --git a/cmux-tui/bindings/typescript/src/raw/generated/metadata.ts b/cmux-tui/bindings/typescript/src/raw/generated/metadata.ts index c8b0ecddbc07..7d1b58e3b243 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/metadata.ts +++ b/cmux-tui/bindings/typescript/src/raw/generated/metadata.ts @@ -1,10 +1,10 @@ /* This file is generated. Do not edit by hand. */ -/* cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. */ +/* cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. */ export const SDK_SCHEMA_VERSION = 2 as const; export const MUX_PROTOCOL_VERSION = 11 as const; -export const SDK_IR_SHA256 = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1" as const; +export const SDK_IR_SHA256 = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3" as const; export const PROTOCOL = { "id_type": "uint64", "javascript_id_policy": "All protocol identifiers are uint64 JSON numbers. JavaScript and TypeScript SDKs must decode them losslessly as bigint (or validated decimal strings at their public boundary), and must not expose IEEE-754 number ids. Pairing request ids, revisions, timestamps, frame sequences, and reservation ids follow the same rule.", @@ -1070,6 +1070,7 @@ export const COMMAND_METADATA = { }, "stream": { "event_names": [ + "agent-changed", "bell", "client-attached", "client-changed", @@ -1194,6 +1195,14 @@ export const COMMAND_METADATA = { } } as const; export const EVENT_METADATA = { + "agent-changed": { + "since": 11, + "capability": null, + "streams": [ + "subscribe" + ], + "emission": "emitted" + }, "bell": { "since": 5, "capability": null, @@ -9944,6 +9953,60 @@ export const COMMAND_SCHEMAS: Readonly> = { } }; export const EVENT_SCHEMAS: Readonly> = { + "agent-changed": { + "additional_properties": false, + "fields": { + "event": { + "nullable": false, + "presence": "required", + "type": { + "kind": "literal", + "value": "agent-changed" + } + }, + "session": { + "nullable": true, + "presence": "required", + "type": { + "kind": "scalar", + "name": "string" + } + }, + "source": { + "nullable": false, + "presence": "required", + "type": { + "kind": "ref", + "name": "AgentSource" + } + }, + "state": { + "nullable": false, + "presence": "required", + "type": { + "kind": "ref", + "name": "AgentState" + } + }, + "surface": { + "nullable": false, + "presence": "required", + "type": { + "kind": "ref", + "name": "Id" + } + }, + "updated_at_ms": { + "nullable": false, + "presence": "required", + "type": { + "kind": "scalar", + "name": "uint64" + } + } + }, + "kind": "object" + }, "bell": { "additional_properties": false, "fields": { diff --git a/cmux-tui/bindings/typescript/src/raw/generated/types.ts b/cmux-tui/bindings/typescript/src/raw/generated/types.ts index 0d56ac868581..bba583e9fdc0 100644 --- a/cmux-tui/bindings/typescript/src/raw/generated/types.ts +++ b/cmux-tui/bindings/typescript/src/raw/generated/types.ts @@ -1,5 +1,5 @@ /* This file is generated. Do not edit by hand. */ -/* cmux-tui mux protocol 11, IR 5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1. */ +/* cmux-tui mux protocol 11, IR 6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3. */ /** JSON accepted by the wire codec. bigint is serialized as an exact JSON integer. */ diff --git a/cmux-tui/bindings/typescript/test/generated.test.ts b/cmux-tui/bindings/typescript/test/generated.test.ts index 9166c16bf825..150a3267738d 100644 --- a/cmux-tui/bindings/typescript/test/generated.test.ts +++ b/cmux-tui/bindings/typescript/test/generated.test.ts @@ -13,7 +13,7 @@ test("generated protocol coverage matches the canonical v11 IR", () => { assert.equal(MUX_PROTOCOL_VERSION, 11); assert.equal(SDK_SCHEMA_VERSION, 2); assert.equal(Object.keys(COMMAND_METADATA).length, 97); - assert.equal(Object.keys(EVENT_METADATA).length, 45); + assert.equal(Object.keys(EVENT_METADATA).length, 46); assert.equal(SDK_IR_SHA256.length, 64); assert.deepEqual(Object.keys(PROFILES).sort(), [ "control", @@ -27,7 +27,7 @@ test("generated active events exclude serialized-only shapes", () => { const emitted = Object.entries(EVENT_METADATA) .filter(([, metadata]) => metadata.emission === "emitted") .map(([name]) => name); - assert.equal(emitted.length, 44); + assert.equal(emitted.length, 45); assert.equal(EVENT_METADATA["client-list-invalidated"].emission, "serialized-never-emitted"); assert.equal(emitted.includes("client-list-invalidated"), false); }); diff --git a/cmux-tui/bindings/zig/examples/watch.zig b/cmux-tui/bindings/zig/examples/watch.zig index f1b1fce95863..5707965de4a7 100644 --- a/cmux-tui/bindings/zig/examples/watch.zig +++ b/cmux-tui/bindings/zig/examples/watch.zig @@ -130,7 +130,7 @@ test "package consumer imports handwritten root and generated raw module" { cmux.raw.protocol.command_count, ); try std.testing.expectEqual( - @as(usize, 45), + @as(usize, 46), cmux.raw.protocol.event_count, ); try std.testing.expect( diff --git a/cmux-tui/bindings/zig/src/raw.zig b/cmux-tui/bindings/zig/src/raw.zig index 8957c918201f..083e58a22679 100644 --- a/cmux-tui/bindings/zig/src/raw.zig +++ b/cmux-tui/bindings/zig/src/raw.zig @@ -64,5 +64,5 @@ test { } try std.testing.expect(found); } - try std.testing.expectEqual(@as(usize, 45), protocol.event_count); + try std.testing.expectEqual(@as(usize, 46), protocol.event_count); } diff --git a/cmux-tui/bindings/zig/src/raw/generated/.cmux-sdk-manifest.json b/cmux-tui/bindings/zig/src/raw/generated/.cmux-sdk-manifest.json index 14ddecfd0253..6b7d8b031855 100644 --- a/cmux-tui/bindings/zig/src/raw/generated/.cmux-sdk-manifest.json +++ b/cmux-tui/bindings/zig/src/raw/generated/.cmux-sdk-manifest.json @@ -7,12 +7,12 @@ }, { "path": "protocol.zig", - "sha256": "b3bd2dd7e9720fc50dab7d2b26afee8ea2716474e7ba9e201c6fbfe73dbacb3a", - "size": 149880 + "sha256": "ea1c1903be392f575a5da5d3c7beabc8b4b21163eeb0678207a4235b4f03df79", + "size": 150529 } ], "format": 1, - "ir_sha256": "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1", + "ir_sha256": "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3", "language": "zig", "mux_protocol": 11, "schema_version": 2 diff --git a/cmux-tui/bindings/zig/src/raw/generated/protocol.zig b/cmux-tui/bindings/zig/src/raw/generated/protocol.zig index e5a61292e155..036551a61766 100644 --- a/cmux-tui/bindings/zig/src/raw/generated/protocol.zig +++ b/cmux-tui/bindings/zig/src/raw/generated/protocol.zig @@ -7,7 +7,7 @@ const client_runtime = @import("../client.zig"); pub const schema_version: u16 = 2; pub const mux_protocol: u16 = 11; -pub const ir_sha256 = "5299d9228d2d800423d244630722c8606297370f5962458962b88af542fd5cc1"; +pub const ir_sha256 = "6c7f42663c8059b5e8c1cb0a1df201c1949665b925845653e46f5ef7f5742eb3"; pub const AgentRecord = struct { session: wire.Nullable([]const u8), @@ -3854,6 +3854,15 @@ pub fn zoomPane(client: anytype, request: ZoomPaneRequest) !wire.Decoded(ZoomPan ); } +pub const AgentChangedEvent = struct { + event: []const u8, + session: wire.Nullable([]const u8), + source: AgentSource, + state: AgentState, + surface: Id, + updated_at_ms: u64, +}; + pub const BellEvent = struct { event: []const u8, surface: Id, @@ -4367,6 +4376,7 @@ pub const UnknownEvent = struct { }; pub const Event = union(enum) { + agent_changed: AgentChangedEvent, bell: BellEvent, browser_state: BrowserStateEvent, client_attached: ClientAttachedEvent, @@ -4417,6 +4427,7 @@ pub const Event = union(enum) { pub fn eventWireName(event: Event) []const u8 { return switch (event) { + .agent_changed => "agent-changed", .bell => "bell", .browser_state => "browser-state", .client_attached => "client-attached", @@ -4480,6 +4491,10 @@ pub fn decodeEvent(allocator: std.mem.Allocator, value: wire.Value) !DecodedEven const name = try wire.eventName(value); var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); + if (std.mem.eql(u8, name, "agent-changed")) { + const decoded = try wire.decodeLeaky(AgentChangedEvent, arena.allocator(), value); + return .{ .arena = arena, .value = .{ .agent_changed = decoded } }; + } if (std.mem.eql(u8, name, "bell")) { const decoded = try wire.decodeLeaky(BellEvent, arena.allocator(), value); return .{ .arena = arena, .value = .{ .bell = decoded } }; @@ -4794,96 +4809,98 @@ pub const EventDescriptor = struct { }; const event_streams_0 = [_][]const u8{"subscribe"}; -const event_streams_1 = [_][]const u8{"attach-browser"}; -const event_streams_2 = [_][]const u8{"subscribe"}; +const event_streams_1 = [_][]const u8{"subscribe"}; +const event_streams_2 = [_][]const u8{"attach-browser"}; const event_streams_3 = [_][]const u8{"subscribe"}; const event_streams_4 = [_][]const u8{"subscribe"}; const event_streams_5 = [_][]const u8{"subscribe"}; -const event_streams_6 = [_][]const u8{"attach-byte"}; -const event_streams_7 = [_][]const u8{"subscribe"}; -const event_streams_8 = [_][]const u8{ "attach-byte", "attach-render", "attach-browser" }; -const event_streams_9 = [_][]const u8{"subscribe"}; -const event_streams_10 = [_][]const u8{"attach-browser"}; -const event_streams_11 = [_][]const u8{"subscribe"}; +const event_streams_6 = [_][]const u8{"subscribe"}; +const event_streams_7 = [_][]const u8{"attach-byte"}; +const event_streams_8 = [_][]const u8{"subscribe"}; +const event_streams_9 = [_][]const u8{ "attach-byte", "attach-render", "attach-browser" }; +const event_streams_10 = [_][]const u8{"subscribe"}; +const event_streams_11 = [_][]const u8{"attach-browser"}; const event_streams_12 = [_][]const u8{"subscribe"}; const event_streams_13 = [_][]const u8{"subscribe"}; -const event_streams_14 = [_][]const u8{ "subscribe", "attach-byte", "attach-browser" }; -const event_streams_15 = [_][]const u8{"attach-byte"}; -const event_streams_16 = [_][]const u8{ "subscribe", "attach-byte", "attach-render", "attach-browser" }; -const event_streams_17 = [_][]const u8{"subscribe"}; +const event_streams_14 = [_][]const u8{"subscribe"}; +const event_streams_15 = [_][]const u8{ "subscribe", "attach-byte", "attach-browser" }; +const event_streams_16 = [_][]const u8{"attach-byte"}; +const event_streams_17 = [_][]const u8{ "subscribe", "attach-byte", "attach-render", "attach-browser" }; const event_streams_18 = [_][]const u8{"subscribe"}; -const event_streams_19 = [_][]const u8{"subscribe-deltas"}; +const event_streams_19 = [_][]const u8{"subscribe"}; const event_streams_20 = [_][]const u8{"subscribe-deltas"}; -const event_streams_21 = [_][]const u8{"attach-render"}; +const event_streams_21 = [_][]const u8{"subscribe-deltas"}; const event_streams_22 = [_][]const u8{"attach-render"}; -const event_streams_23 = [_][]const u8{"attach-byte"}; -const event_streams_24 = [_][]const u8{"subscribe-deltas"}; +const event_streams_23 = [_][]const u8{"attach-render"}; +const event_streams_24 = [_][]const u8{"attach-byte"}; const event_streams_25 = [_][]const u8{"subscribe-deltas"}; const event_streams_26 = [_][]const u8{"subscribe-deltas"}; -const event_streams_27 = [_][]const u8{ "subscribe", "attach-byte", "attach-render", "attach-browser" }; -const event_streams_28 = [_][]const u8{"subscribe"}; +const event_streams_27 = [_][]const u8{"subscribe-deltas"}; +const event_streams_28 = [_][]const u8{ "subscribe", "attach-byte", "attach-render", "attach-browser" }; const event_streams_29 = [_][]const u8{"subscribe"}; const event_streams_30 = [_][]const u8{"subscribe"}; const event_streams_31 = [_][]const u8{"subscribe"}; const event_streams_32 = [_][]const u8{"subscribe"}; -const event_streams_33 = [_][]const u8{"subscribe-deltas"}; +const event_streams_33 = [_][]const u8{"subscribe"}; const event_streams_34 = [_][]const u8{"subscribe-deltas"}; const event_streams_35 = [_][]const u8{"subscribe-deltas"}; -const event_streams_36 = [_][]const u8{"subscribe"}; +const event_streams_36 = [_][]const u8{"subscribe-deltas"}; const event_streams_37 = [_][]const u8{"subscribe"}; const event_streams_38 = [_][]const u8{"subscribe"}; -const event_streams_39 = [_][]const u8{"attach-byte"}; -const event_streams_40 = [_][]const u8{"subscribe"}; -const event_streams_41 = [_][]const u8{"subscribe-deltas"}; +const event_streams_39 = [_][]const u8{"subscribe"}; +const event_streams_40 = [_][]const u8{"attach-byte"}; +const event_streams_41 = [_][]const u8{"subscribe"}; const event_streams_42 = [_][]const u8{"subscribe-deltas"}; const event_streams_43 = [_][]const u8{"subscribe-deltas"}; const event_streams_44 = [_][]const u8{"subscribe-deltas"}; +const event_streams_45 = [_][]const u8{"subscribe-deltas"}; -pub const event_count: usize = 45; +pub const event_count: usize = 46; pub const events = [_]EventDescriptor{ - .{ .name = "bell", .since = 5, .capability = null, .streams = &event_streams_0 }, - .{ .name = "browser-state", .since = 6, .capability = null, .streams = &event_streams_1 }, - .{ .name = "client-attached", .since = 6, .capability = null, .streams = &event_streams_2 }, - .{ .name = "client-changed", .since = 6, .capability = null, .streams = &event_streams_3 }, - .{ .name = "client-detached", .since = 6, .capability = null, .streams = &event_streams_4 }, - .{ .name = "client-list-invalidated", .since = 9, .capability = null, .streams = &event_streams_5 }, - .{ .name = "colors-changed", .since = 6, .capability = null, .streams = &event_streams_6 }, - .{ .name = "config-reload-requested", .since = 6, .capability = null, .streams = &event_streams_7 }, - .{ .name = "detached", .since = 5, .capability = null, .streams = &event_streams_8 }, - .{ .name = "empty", .since = 5, .capability = null, .streams = &event_streams_9 }, - .{ .name = "frame", .since = 6, .capability = null, .streams = &event_streams_10 }, - .{ .name = "frontend-projection-changed", .since = 7, .capability = null, .streams = &event_streams_11 }, - .{ .name = "graphics-status", .since = 10, .capability = null, .streams = &event_streams_12 }, - .{ .name = "layout-changed", .since = 6, .capability = null, .streams = &event_streams_13 }, - .{ .name = "notification", .since = 6, .capability = null, .streams = &event_streams_14 }, - .{ .name = "output", .since = 5, .capability = null, .streams = &event_streams_15 }, - .{ .name = "overflow", .since = 7, .capability = null, .streams = &event_streams_16 }, - .{ .name = "pairing-requested", .since = 7, .capability = null, .streams = &event_streams_17 }, - .{ .name = "pairing-resolved", .since = 7, .capability = null, .streams = &event_streams_18 }, - .{ .name = "pane-added", .since = 7, .capability = null, .streams = &event_streams_19 }, - .{ .name = "pane-closed", .since = 7, .capability = null, .streams = &event_streams_20 }, - .{ .name = "render-delta", .since = 7, .capability = null, .streams = &event_streams_21 }, - .{ .name = "render-state", .since = 7, .capability = null, .streams = &event_streams_22 }, - .{ .name = "resized", .since = 6, .capability = null, .streams = &event_streams_23 }, - .{ .name = "screen-added", .since = 7, .capability = null, .streams = &event_streams_24 }, - .{ .name = "screen-closed", .since = 7, .capability = null, .streams = &event_streams_25 }, - .{ .name = "screen-renamed", .since = 7, .capability = null, .streams = &event_streams_26 }, - .{ .name = "scroll-changed", .since = 6, .capability = null, .streams = &event_streams_27 }, - .{ .name = "status", .since = 5, .capability = null, .streams = &event_streams_28 }, - .{ .name = "surface-exited", .since = 5, .capability = null, .streams = &event_streams_29 }, - .{ .name = "surface-output", .since = 5, .capability = null, .streams = &event_streams_30 }, - .{ .name = "surface-resize-failed", .since = 7, .capability = null, .streams = &event_streams_31 }, - .{ .name = "surface-resized", .since = 5, .capability = null, .streams = &event_streams_32 }, - .{ .name = "tab-added", .since = 7, .capability = null, .streams = &event_streams_33 }, - .{ .name = "tab-closed", .since = 7, .capability = null, .streams = &event_streams_34 }, - .{ .name = "tab-renamed", .since = 7, .capability = null, .streams = &event_streams_35 }, - .{ .name = "terminal-registry-changed", .since = 9, .capability = null, .streams = &event_streams_36 }, - .{ .name = "title-changed", .since = 5, .capability = null, .streams = &event_streams_37 }, - .{ .name = "tree-changed", .since = 5, .capability = null, .streams = &event_streams_38 }, - .{ .name = "vt-state", .since = 5, .capability = null, .streams = &event_streams_39 }, - .{ .name = "window-title-requested", .since = 6, .capability = null, .streams = &event_streams_40 }, - .{ .name = "workspace-added", .since = 7, .capability = null, .streams = &event_streams_41 }, - .{ .name = "workspace-closed", .since = 7, .capability = null, .streams = &event_streams_42 }, - .{ .name = "workspace-moved", .since = 7, .capability = null, .streams = &event_streams_43 }, - .{ .name = "workspace-renamed", .since = 7, .capability = null, .streams = &event_streams_44 }, + .{ .name = "agent-changed", .since = 11, .capability = null, .streams = &event_streams_0 }, + .{ .name = "bell", .since = 5, .capability = null, .streams = &event_streams_1 }, + .{ .name = "browser-state", .since = 6, .capability = null, .streams = &event_streams_2 }, + .{ .name = "client-attached", .since = 6, .capability = null, .streams = &event_streams_3 }, + .{ .name = "client-changed", .since = 6, .capability = null, .streams = &event_streams_4 }, + .{ .name = "client-detached", .since = 6, .capability = null, .streams = &event_streams_5 }, + .{ .name = "client-list-invalidated", .since = 9, .capability = null, .streams = &event_streams_6 }, + .{ .name = "colors-changed", .since = 6, .capability = null, .streams = &event_streams_7 }, + .{ .name = "config-reload-requested", .since = 6, .capability = null, .streams = &event_streams_8 }, + .{ .name = "detached", .since = 5, .capability = null, .streams = &event_streams_9 }, + .{ .name = "empty", .since = 5, .capability = null, .streams = &event_streams_10 }, + .{ .name = "frame", .since = 6, .capability = null, .streams = &event_streams_11 }, + .{ .name = "frontend-projection-changed", .since = 7, .capability = null, .streams = &event_streams_12 }, + .{ .name = "graphics-status", .since = 10, .capability = null, .streams = &event_streams_13 }, + .{ .name = "layout-changed", .since = 6, .capability = null, .streams = &event_streams_14 }, + .{ .name = "notification", .since = 6, .capability = null, .streams = &event_streams_15 }, + .{ .name = "output", .since = 5, .capability = null, .streams = &event_streams_16 }, + .{ .name = "overflow", .since = 7, .capability = null, .streams = &event_streams_17 }, + .{ .name = "pairing-requested", .since = 7, .capability = null, .streams = &event_streams_18 }, + .{ .name = "pairing-resolved", .since = 7, .capability = null, .streams = &event_streams_19 }, + .{ .name = "pane-added", .since = 7, .capability = null, .streams = &event_streams_20 }, + .{ .name = "pane-closed", .since = 7, .capability = null, .streams = &event_streams_21 }, + .{ .name = "render-delta", .since = 7, .capability = null, .streams = &event_streams_22 }, + .{ .name = "render-state", .since = 7, .capability = null, .streams = &event_streams_23 }, + .{ .name = "resized", .since = 6, .capability = null, .streams = &event_streams_24 }, + .{ .name = "screen-added", .since = 7, .capability = null, .streams = &event_streams_25 }, + .{ .name = "screen-closed", .since = 7, .capability = null, .streams = &event_streams_26 }, + .{ .name = "screen-renamed", .since = 7, .capability = null, .streams = &event_streams_27 }, + .{ .name = "scroll-changed", .since = 6, .capability = null, .streams = &event_streams_28 }, + .{ .name = "status", .since = 5, .capability = null, .streams = &event_streams_29 }, + .{ .name = "surface-exited", .since = 5, .capability = null, .streams = &event_streams_30 }, + .{ .name = "surface-output", .since = 5, .capability = null, .streams = &event_streams_31 }, + .{ .name = "surface-resize-failed", .since = 7, .capability = null, .streams = &event_streams_32 }, + .{ .name = "surface-resized", .since = 5, .capability = null, .streams = &event_streams_33 }, + .{ .name = "tab-added", .since = 7, .capability = null, .streams = &event_streams_34 }, + .{ .name = "tab-closed", .since = 7, .capability = null, .streams = &event_streams_35 }, + .{ .name = "tab-renamed", .since = 7, .capability = null, .streams = &event_streams_36 }, + .{ .name = "terminal-registry-changed", .since = 9, .capability = null, .streams = &event_streams_37 }, + .{ .name = "title-changed", .since = 5, .capability = null, .streams = &event_streams_38 }, + .{ .name = "tree-changed", .since = 5, .capability = null, .streams = &event_streams_39 }, + .{ .name = "vt-state", .since = 5, .capability = null, .streams = &event_streams_40 }, + .{ .name = "window-title-requested", .since = 6, .capability = null, .streams = &event_streams_41 }, + .{ .name = "workspace-added", .since = 7, .capability = null, .streams = &event_streams_42 }, + .{ .name = "workspace-closed", .since = 7, .capability = null, .streams = &event_streams_43 }, + .{ .name = "workspace-moved", .since = 7, .capability = null, .streams = &event_streams_44 }, + .{ .name = "workspace-renamed", .since = 7, .capability = null, .streams = &event_streams_45 }, }; diff --git a/cmux-tui/crates/cmux-remote/src/provider/ssh.rs b/cmux-tui/crates/cmux-remote/src/provider/ssh.rs index 5f60e885ace5..6329a7a9fc76 100644 --- a/cmux-tui/crates/cmux-remote/src/provider/ssh.rs +++ b/cmux-tui/crates/cmux-remote/src/provider/ssh.rs @@ -2,6 +2,7 @@ use std::fmt; use std::process::Stdio; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; use async_trait::async_trait; use bytes::Bytes; @@ -16,6 +17,8 @@ use crate::provider::{ sanitized_route, }; +const SSH_GRACEFUL_CLOSE_TIMEOUT: Duration = Duration::from_secs(2); + #[derive(Debug, Clone)] pub struct SshProviderConfig { pub ssh_binary: String, @@ -243,8 +246,14 @@ impl FrameLink for SshProcessLink { async fn close(&self) -> Result<(), LinkError> { let _ = self.inner.close().await; if let Some(mut child) = self.child.lock().await.take() { - let _ = child.kill().await; - let _ = child.wait().await; + let exited = matches!( + tokio::time::timeout(SSH_GRACEFUL_CLOSE_TIMEOUT, child.wait()).await, + Ok(Ok(_)) + ); + if !exited { + let _ = child.kill().await; + let _ = child.wait().await; + } } Ok(()) } @@ -265,6 +274,32 @@ fn validate_remote_word(value: &str) -> Result<(), ProviderError> { mod tests { use super::*; + #[cfg(unix)] + #[tokio::test] + async fn close_lets_the_remote_command_observe_eof_before_reaping_ssh() { + let directory = tempfile::tempdir().unwrap(); + let outcome = directory.path().join("outcome"); + let mut command = Command::new("/bin/sh"); + command + .args(["-c", "cat >/dev/null; printf graceful > \"$CMUX_TEST_OUTCOME\""]) + .env("CMUX_TEST_OUTCOME", &outcome) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true); + let mut child = command.spawn().unwrap(); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let link = SshProcessLink { + inner: LengthDelimitedLink::new("ssh://test", 1024, stdout, stdin), + child: Mutex::new(Some(child)), + }; + + link.close().await.unwrap(); + + assert_eq!(std::fs::read_to_string(outcome).unwrap(), "graceful"); + } + #[test] fn destination_preserves_user_for_dial_but_description_redacts_it() { let endpoint = url::Url::parse("ssh://alice@example.com:2222").unwrap(); diff --git a/cmux-tui/crates/cmux-remote/src/provider/stream.rs b/cmux-tui/crates/cmux-remote/src/provider/stream.rs index c77ad2e51d2a..11735e459ec9 100644 --- a/cmux-tui/crates/cmux-remote/src/provider/stream.rs +++ b/cmux-tui/crates/cmux-remote/src/provider/stream.rs @@ -16,7 +16,7 @@ pub struct LengthDelimitedLink { description: String, maximum: usize, reader: Mutex, - writer: Mutex, + writer: Mutex>, } impl LengthDelimitedLink { @@ -25,7 +25,7 @@ impl LengthDelimitedLink { description: description.into(), maximum, reader: Mutex::new(reader), - writer: Mutex::new(writer), + writer: Mutex::new(Some(writer)), } } } @@ -63,6 +63,7 @@ where maximum: u32::MAX as usize, })?; let mut writer = self.writer.lock().await; + let writer = writer.as_mut().ok_or(LinkError::Closed)?; writer.write_all(&length.to_be_bytes()).await.map_err(map_io)?; writer.write_all(&frame).await.map_err(map_io)?; writer.flush().await.map_err(map_io) @@ -86,7 +87,11 @@ where } async fn close(&self) -> Result<(), LinkError> { - self.writer.lock().await.shutdown().await.map_err(map_io) + let writer = self.writer.lock().await.take(); + match writer { + Some(mut writer) => writer.shutdown().await.map_err(map_io), + None => Ok(()), + } } } diff --git a/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs b/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs index c793cdea0256..eb6c2c840b22 100644 --- a/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs +++ b/cmux-tui/crates/cmux-remote/src/ssh_bootstrap.rs @@ -1,6 +1,7 @@ use std::fmt; +use std::path::{Path, PathBuf}; use std::process::Stdio; -use std::time::Duration; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use cmux_remote_protocol::REMOTE_PROTOCOL_VERSION; use serde::{Deserialize, Serialize}; @@ -29,6 +30,9 @@ pub struct SshBootstrapConfig { pub package_version: String, pub package_installable: bool, pub build_identity: String, + /// Exact local executable used to bootstrap unpublished same-platform + /// builds. Published distributions continue to install through npm. + pub local_binary: Option, pub auto_install: bool, pub timeout: Duration, } @@ -45,6 +49,7 @@ impl SshBootstrapConfig { package_version: NPM_BOOTSTRAP_VERSION.unwrap_or(DISTRIBUTION_VERSION).into(), package_installable: NPM_BOOTSTRAP_VERSION.is_some(), build_identity: BUILD_IDENTITY.into(), + local_binary: std::env::current_exe().ok(), auto_install: true, timeout: Duration::from_secs(60), } @@ -109,13 +114,19 @@ impl SshBootstrapper { } pub async fn probe(&self) -> Result, BootstrapError> { - let output = - self.run_remote([self.config.remote_binary.as_str(), "remote-probe", "--json"]).await?; + self.probe_binary(&self.config.remote_binary).await + } + + async fn probe_binary(&self, binary: &str) -> Result, BootstrapError> { + let output = self.run_remote([binary, "remote-probe", "--json"]).await?; if output.status == 127 || output.status == 126 { return Ok(None); } if output.status != 0 { let stderr = String::from_utf8_lossy(&output.stderr); + if windows_command_shell_error(&stderr) { + return Err(BootstrapError::WindowsRequiresWsl); + } if stderr.contains("not found") || stderr.contains("No such file") { return Ok(None); } @@ -151,7 +162,7 @@ impl SshBootstrapper { /// answer `remote-probe`. This is reserved for an explicit upgrade. pub async fn install_verified(&self) -> Result { if !self.config.package_installable { - return Err(BootstrapError::PackageUnavailable(self.config.package_version.clone())); + return self.install_local_binary().await; } let npm_package = &self.config.npm_package; let package_version = &self.config.package_version; @@ -185,6 +196,116 @@ impl SshBootstrapper { Ok(BootstrapOutcome::Installed) } + async fn install_local_binary(&self) -> Result { + let source = self.config.local_binary.as_deref().ok_or_else(|| { + BootstrapError::PackageUnavailable(self.config.package_version.clone()) + })?; + let remote = self.remote_platform().await?; + let local = Platform::local(); + if !local.compatible_with(&remote) { + return Err(BootstrapError::LocalBinaryIncompatible { + local: local.display(), + remote: remote.display(), + }); + } + let temporary = self.temporary_upload_path(); + let parent = self + .config + .remote_binary + .rsplit_once('/') + .map_or(".", |(parent, _)| if parent.is_empty() { "/" } else { parent }); + let command = + format!("umask 077; mkdir -p {parent} && cat > {temporary} && chmod 755 {temporary}"); + let output = match self.run_remote_with_input(&command, source).await { + Ok(output) => output, + Err(error) => { + self.cleanup_remote_file(&temporary).await; + return Err(error); + } + }; + if output.status != 0 { + self.cleanup_remote_file(&temporary).await; + return Err(BootstrapError::Install { + status: output.status, + stderr: sanitize(&String::from_utf8_lossy(&output.stderr)), + }); + } + let probe = match self.probe_binary(&temporary).await { + Ok(Some(probe)) => probe, + Ok(None) => { + self.cleanup_remote_file(&temporary).await; + return Err(BootstrapError::Install { + status: 126, + stderr: "uploaded binary could not run remote-probe".into(), + }); + } + Err(error) => { + self.cleanup_remote_file(&temporary).await; + return Err(error); + } + }; + if !self.compatible(&probe) { + self.cleanup_remote_file(&temporary).await; + return Err(BootstrapError::Incompatible { + version: probe.version, + protocol: probe.remote_protocol, + }); + } + let output = match self + .run_remote(["mv", "-f", temporary.as_str(), self.config.remote_binary.as_str()]) + .await + { + Ok(output) => output, + Err(error) => { + self.cleanup_remote_file(&temporary).await; + return Err(error); + } + }; + if output.status != 0 { + self.cleanup_remote_file(&temporary).await; + return Err(BootstrapError::Install { + status: output.status, + stderr: sanitize(&String::from_utf8_lossy(&output.stderr)), + }); + } + let probe = self.probe().await?.ok_or(BootstrapError::Install { + status: 0, + stderr: "upload completed but the remote binary is absent".into(), + })?; + if !self.compatible(&probe) { + return Err(BootstrapError::Incompatible { + version: probe.version, + protocol: probe.remote_protocol, + }); + } + Ok(BootstrapOutcome::Installed) + } + + fn temporary_upload_path(&self) -> String { + let now = + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |duration| duration.as_nanos()); + format!("{}.cmux-upload-{}-{now}", self.config.remote_binary, std::process::id()) + } + + async fn cleanup_remote_file(&self, path: &str) { + let _ = self.run_remote(["rm", "-f", path]).await; + } + + async fn remote_platform(&self) -> Result { + let output = self.run_remote(["uname", "-s", "-m"]).await?; + if output.status != 0 { + let stderr = String::from_utf8_lossy(&output.stderr); + if windows_command_shell_error(&stderr) { + return Err(BootstrapError::WindowsRequiresWsl); + } + return Err(BootstrapError::Remote { + status: output.status, + stderr: sanitize(&stderr), + }); + } + Platform::from_uname(&String::from_utf8_lossy(&output.stdout)) + } + /// Explicitly stops the named remote daemon so the next carrier launch /// starts the already verified binary. This is never called by automatic /// installation alone. @@ -315,6 +436,119 @@ impl SshBootstrapper { }; Ok(RemoteOutput { status: status.code().unwrap_or(255), stdout, stderr }) } + + async fn run_remote_with_input( + &self, + remote_command: &str, + source: &Path, + ) -> Result { + let source = std::fs::File::open(source).map_err(BootstrapError::Io)?; + let mut command = Command::new(&self.config.ssh_binary); + command.arg("-T"); + if let Some(port) = self.config.port { + command.arg("-p").arg(port.to_string()); + } + command.args(&self.config.extra_args).arg(&self.config.destination).arg(remote_command); + let mut child = command + .stdin(Stdio::from(source)) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true) + .spawn() + .map_err(BootstrapError::Io)?; + let stdout = match child.stdout.take() { + Some(stdout) => stdout, + None => { + terminate_and_reap(&mut child).await; + return Err(BootstrapError::Io(std::io::Error::other( + "SSH stdout pipe is unavailable", + ))); + } + }; + let stderr = match child.stderr.take() { + Some(stderr) => stderr, + None => { + terminate_and_reap(&mut child).await; + return Err(BootstrapError::Io(std::io::Error::other( + "SSH stderr pipe is unavailable", + ))); + } + }; + let completion = tokio::time::timeout(self.config.timeout, async { + tokio::try_join!( + read_bounded(stdout, "stdout"), + read_bounded(stderr, "stderr"), + async { child.wait().await.map_err(BootstrapError::Io) }, + ) + }) + .await; + let (stdout, stderr, status) = match completion { + Ok(Ok(result)) => result, + Ok(Err(error)) => { + terminate_and_reap(&mut child).await; + return Err(error); + } + Err(_) => { + terminate_and_reap(&mut child).await; + return Err(BootstrapError::Timeout); + } + }; + Ok(RemoteOutput { status: status.code().unwrap_or(255), stdout, stderr }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Platform { + os: String, + arch: String, +} + +impl Platform { + fn local() -> Self { + Self { + os: normalize_os(std::env::consts::OS), + arch: normalize_arch(std::env::consts::ARCH), + } + } + + fn from_uname(value: &str) -> Result { + let mut fields = value.split_whitespace(); + let Some(os) = fields.next() else { + return Err(BootstrapError::PlatformProbe("uname returned no operating system".into())); + }; + let Some(arch) = fields.next() else { + return Err(BootstrapError::PlatformProbe("uname returned no architecture".into())); + }; + Ok(Self { os: normalize_os(os), arch: normalize_arch(arch) }) + } + + fn compatible_with(&self, other: &Self) -> bool { + self == other + } + + fn display(&self) -> String { + format!("{}-{}", self.os, self.arch) + } +} + +fn normalize_os(value: &str) -> String { + match value.to_ascii_lowercase().as_str() { + "darwin" | "macos" => "macos".into(), + "linux" => "linux".into(), + other => other.to_string(), + } +} + +fn normalize_arch(value: &str) -> String { + match value.to_ascii_lowercase().as_str() { + "arm64" | "aarch64" => "aarch64".into(), + "amd64" | "x86_64" => "x86_64".into(), + other => other.to_string(), + } +} + +fn windows_command_shell_error(stderr: &str) -> bool { + stderr.to_ascii_lowercase().contains("is not recognized as an internal or external command") } async fn read_bounded( @@ -370,6 +604,9 @@ pub enum BootstrapError { Remote { status: i32, stderr: String }, Install { status: i32, stderr: String }, PackageUnavailable(String), + PlatformProbe(String), + LocalBinaryIncompatible { local: String, remote: String }, + WindowsRequiresWsl, Incompatible { version: String, protocol: u8 }, } @@ -394,6 +631,14 @@ impl fmt::Display for BootstrapError { formatter, "this cmux-tui build is not backed by a published npm package ({version}); preinstall the matching remote binary or use an npm release build" ), + Self::PlatformProbe(message) => write!(formatter, "remote platform probe failed: {message}"), + Self::LocalBinaryIncompatible { local, remote } => write!( + formatter, + "this unpublished cmux-tui build cannot be uploaded from {local} to {remote}; use a published build or preinstall a matching remote binary" + ), + Self::WindowsRequiresWsl => formatter.write_str( + "native Windows cannot host the cmux-tui remote daemon yet; install a WSL 2 Linux distro with `wsl --install -d Ubuntu`, then connect through that Linux environment" + ), Self::Incompatible { version, protocol } => write!( formatter, "remote cmux-tui {version} uses remote protocol {protocol}, expected {REMOTE_PROTOCOL_VERSION}" @@ -422,6 +667,9 @@ impl BootstrapError { | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::UnexpectedEof ), + Self::PlatformProbe(_) + | Self::LocalBinaryIncompatible { .. } + | Self::WindowsRequiresWsl => false, _ => false, } } @@ -471,6 +719,15 @@ mod tests { ); } + #[test] + fn native_windows_shell_failure_reports_the_wsl_prerequisite() { + assert!(windows_command_shell_error( + "'~' is not recognized as an internal or external command, operable program or batch file." + )); + assert!(!BootstrapError::WindowsRequiresWsl.is_retryable_carrier_failure()); + assert!(BootstrapError::WindowsRequiresWsl.to_string().contains("wsl --install")); + } + #[test] fn option_like_destination_is_rejected_by_bootstrap_config() { let Err(error) = @@ -543,6 +800,7 @@ mod tests { let mut config = SshBootstrapConfig::defaults("host"); config.package_version = "0.0.0-r2.test".into(); config.package_installable = false; + config.local_binary = None; let error = SshBootstrapper::new(config).unwrap().install_verified().await.unwrap_err(); assert!(matches!( @@ -551,6 +809,195 @@ mod tests { )); } + #[cfg(unix)] + #[tokio::test] + async fn raw_build_uploads_the_exact_binary_to_a_matching_platform() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let script = directory.path().join("ssh"); + let installed = directory.path().join("installed"); + let staged = directory.path().join("staged"); + let source = directory.path().join("cmux-tui"); + fs::write(&source, b"exact unpublished build").unwrap(); + let uname_os = if std::env::consts::OS == "macos" { "Darwin" } else { "Linux" }; + let uname_arch = + if std::env::consts::ARCH == "aarch64" { "arm64" } else { std::env::consts::ARCH }; + let probe = serde_json::json!({ + "app": "cmux-tui", + "version": DISTRIBUTION_VERSION, + "distribution_version": DISTRIBUTION_VERSION, + "build_identity": BUILD_IDENTITY, + "remote_protocol": REMOTE_PROTOCOL_VERSION, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + }); + fs::write( + &script, + format!( + "#!/bin/sh\ncase \"$*\" in\n *\"uname -s -m\"*) printf '%s\\n' '{uname_os} {uname_arch}' ;;\n *\".cmux-upload-\"*\" remote-probe --json\"*)\n [ -f '{staged}' ] || exit 127\n printf '%s' '{probe}'\n ;;\n *\"remote-probe --json\"*)\n [ -f '{installed}' ] || exit 127\n printf '%s' '{probe}'\n ;;\n *\"cat > \"*\".cmux-upload-\"*) cat >'{staged}' ;;\n *\"mv -f \"*\".cmux-upload-\"*) mv '{staged}' '{installed}' ;;\n *\"rm -f \"*\".cmux-upload-\"*) rm -f '{staged}' ;;\n *) exit 2 ;;\nesac\n", + installed = installed.display(), + staged = staged.display(), + ), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let mut config = SshBootstrapConfig::defaults("host"); + config.ssh_binary = script.to_string_lossy().into_owned(); + config.package_installable = false; + config.local_binary = Some(source); + config.remote_binary = "~/.local/bin/cmux-upload".into(); + + assert_eq!( + SshBootstrapper::new(config).unwrap().ensure_installed().await.unwrap(), + BootstrapOutcome::Installed + ); + assert_eq!(fs::read(installed).unwrap(), b"exact unpublished build"); + } + + #[cfg(unix)] + #[tokio::test] + async fn raw_build_keeps_existing_remote_binary_when_staged_probe_is_incompatible() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let script = directory.path().join("ssh"); + let installed = directory.path().join("installed"); + let staged = directory.path().join("staged"); + let moved = directory.path().join("moved"); + let source = directory.path().join("cmux-tui"); + fs::write(&installed, b"existing remote binary").unwrap(); + fs::write(&source, b"incompatible unpublished build").unwrap(); + let uname_os = if std::env::consts::OS == "macos" { "Darwin" } else { "Linux" }; + let uname_arch = + if std::env::consts::ARCH == "aarch64" { "arm64" } else { std::env::consts::ARCH }; + let installed_probe = serde_json::json!({ + "app": "cmux-tui", + "version": DISTRIBUTION_VERSION, + "distribution_version": DISTRIBUTION_VERSION, + "build_identity": "older-build", + "remote_protocol": REMOTE_PROTOCOL_VERSION, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + }); + let staged_probe = serde_json::json!({ + "app": "cmux-tui", + "version": DISTRIBUTION_VERSION, + "distribution_version": DISTRIBUTION_VERSION, + "build_identity": "wrong-upload", + "remote_protocol": REMOTE_PROTOCOL_VERSION, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + }); + fs::write( + &script, + format!( + "#!/bin/sh\ncase \"$*\" in\n *\"uname -s -m\"*) printf '%s\\n' '{uname_os} {uname_arch}' ;;\n *\".cmux-upload-\"*\" remote-probe --json\"*)\n [ -f '{staged}' ] || exit 127\n printf '%s' '{staged_probe}'\n ;;\n *\"remote-probe --json\"*)\n [ -f '{installed}' ] || exit 127\n printf '%s' '{installed_probe}'\n ;;\n *\"cat > \"*\".cmux-upload-\"*) cat >'{staged}' ;;\n *\"mv -f \"*\".cmux-upload-\"*) touch '{moved}'; mv '{staged}' '{installed}' ;;\n *\"rm -f \"*\".cmux-upload-\"*) rm -f '{staged}' ;;\n *) exit 2 ;;\nesac\n", + installed = installed.display(), + staged = staged.display(), + moved = moved.display(), + ), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let mut config = SshBootstrapConfig::defaults("host"); + config.ssh_binary = script.to_string_lossy().into_owned(); + config.package_installable = false; + config.local_binary = Some(source); + config.remote_binary = "~/.local/bin/cmux-upload".into(); + + let error = SshBootstrapper::new(config).unwrap().ensure_installed().await.unwrap_err(); + assert!(matches!(error, BootstrapError::Incompatible { .. })); + assert_eq!(fs::read(installed).unwrap(), b"existing remote binary"); + assert!(!staged.exists()); + assert!(!moved.exists()); + } + + #[cfg(unix)] + #[tokio::test] + async fn raw_build_removes_staged_upload_after_upload_stream_failure() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let script = directory.path().join("ssh"); + let staged = directory.path().join("staged"); + let source = directory.path().join("cmux-tui"); + fs::write(&source, b"exact unpublished build").unwrap(); + let uname_os = if std::env::consts::OS == "macos" { "Darwin" } else { "Linux" }; + let uname_arch = + if std::env::consts::ARCH == "aarch64" { "arm64" } else { std::env::consts::ARCH }; + fs::write( + &script, + format!( + "#!/bin/sh\ncase \"$*\" in\n *\"uname -s -m\"*) printf '%s\\n' '{uname_os} {uname_arch}' ;;\n *\"cat > \"*\".cmux-upload-\"*) cat >'{staged}'; head -c 5000 /dev/zero ;;\n *\"rm -f \"*\".cmux-upload-\"*) rm -f '{staged}' ;;\n *) exit 2 ;;\nesac\n", + staged = staged.display(), + ), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let mut config = SshBootstrapConfig::defaults("host"); + config.ssh_binary = script.to_string_lossy().into_owned(); + config.package_installable = false; + config.local_binary = Some(source); + config.remote_binary = "~/.local/bin/cmux-upload".into(); + + let error = SshBootstrapper::new(config).unwrap().install_verified().await.unwrap_err(); + + assert!(matches!(error, BootstrapError::OutputLimit { stream: "stdout", .. })); + assert!(!staged.exists()); + } + + #[cfg(unix)] + #[tokio::test] + async fn raw_build_removes_staged_upload_after_move_transport_failure() { + use std::fs; + use std::os::unix::fs::PermissionsExt; + + let directory = tempfile::tempdir().unwrap(); + let script = directory.path().join("ssh"); + let staged = directory.path().join("staged"); + let source = directory.path().join("cmux-tui"); + fs::write(&source, b"exact unpublished build").unwrap(); + let uname_os = if std::env::consts::OS == "macos" { "Darwin" } else { "Linux" }; + let uname_arch = + if std::env::consts::ARCH == "aarch64" { "arm64" } else { std::env::consts::ARCH }; + let probe = serde_json::json!({ + "app": "cmux-tui", + "version": DISTRIBUTION_VERSION, + "distribution_version": DISTRIBUTION_VERSION, + "build_identity": BUILD_IDENTITY, + "remote_protocol": REMOTE_PROTOCOL_VERSION, + "os": std::env::consts::OS, + "arch": std::env::consts::ARCH, + }); + fs::write( + &script, + format!( + "#!/bin/sh\ncase \"$*\" in\n *\"uname -s -m\"*) printf '%s\\n' '{uname_os} {uname_arch}' ;;\n *\".cmux-upload-\"*\" remote-probe --json\"*) printf '%s' '{probe}' ;;\n *\"cat > \"*\".cmux-upload-\"*) cat >'{staged}' ;;\n *\"mv -f \"*\".cmux-upload-\"*) head -c 5000 /dev/zero ;;\n *\"rm -f \"*\".cmux-upload-\"*) rm -f '{staged}' ;;\n *) exit 2 ;;\nesac\n", + staged = staged.display(), + ), + ) + .unwrap(); + fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); + + let mut config = SshBootstrapConfig::defaults("host"); + config.ssh_binary = script.to_string_lossy().into_owned(); + config.package_installable = false; + config.local_binary = Some(source); + config.remote_binary = "~/.local/bin/cmux-upload".into(); + + let error = SshBootstrapper::new(config).unwrap().install_verified().await.unwrap_err(); + + assert!(matches!(error, BootstrapError::OutputLimit { stream: "stdout", .. })); + assert!(!staged.exists()); + } + #[cfg(unix)] #[tokio::test] async fn no_install_distinguishes_an_incompatible_binary_from_a_missing_one() { diff --git a/cmux-tui/crates/cmux-terminal-client/src/lib.rs b/cmux-tui/crates/cmux-terminal-client/src/lib.rs index cf55d3c788a7..86a6a1f87af2 100644 --- a/cmux-tui/crates/cmux-terminal-client/src/lib.rs +++ b/cmux-tui/crates/cmux-terminal-client/src/lib.rs @@ -1671,6 +1671,14 @@ pub unsafe extern "C" fn cmux_terminal_client_copy_frame( /// Copies the row indexes changed by the latest materialized frame. A null /// buffer or undersized capacity returns the required number of entries. +/// +/// # Safety +/// +/// The client pointer may be null. A non-null value must be a live handle +/// returned by cmux_terminal_client_connect, and it must not be disconnected +/// during this call. The buffer pointer may be null; otherwise, when capacity is +/// nonzero, it must point to capacity writable u16 values that do not overlap +/// memory owned by the client. #[unsafe(no_mangle)] pub unsafe extern "C" fn cmux_terminal_client_copy_frame_dirty_rows( client: *const CmuxTerminalClient, @@ -1693,6 +1701,12 @@ pub unsafe extern "C" fn cmux_terminal_client_copy_frame_dirty_rows( } /// Returns the number of rows in the latest materialized viewport frame. +/// +/// # Safety +/// +/// The client pointer may be null. A non-null value must be a live handle +/// returned by cmux_terminal_client_connect, and it must not be disconnected +/// during this call. #[unsafe(no_mangle)] pub unsafe extern "C" fn cmux_terminal_client_frame_row_count( client: *const CmuxTerminalClient, @@ -1707,6 +1721,14 @@ pub unsafe extern "C" fn cmux_terminal_client_frame_row_count( /// Copies one row from the latest materialized frame as a NUL-terminated /// UTF-8 string. The row index is zero-based. +/// +/// # Safety +/// +/// The client pointer may be null. A non-null value must be a live handle +/// returned by cmux_terminal_client_connect, and it must not be disconnected +/// during this call. The buffer pointer may be null; otherwise, when capacity is +/// nonzero, it must point to capacity writable bytes that do not overlap memory +/// owned by the client. #[unsafe(no_mangle)] pub unsafe extern "C" fn cmux_terminal_client_copy_frame_row( client: *const CmuxTerminalClient, diff --git a/cmux-tui/crates/cmux-tui-core/src/event_bus.rs b/cmux-tui/crates/cmux-tui-core/src/event_bus.rs index f3a554da5692..458b840308be 100644 --- a/cmux-tui/crates/cmux-tui-core/src/event_bus.rs +++ b/cmux-tui/crates/cmux-tui-core/src/event_bus.rs @@ -55,6 +55,7 @@ struct MuxEventMailboxState { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum CoalescedEventKey { + Agent(SurfaceId), Title(SurfaceId), SurfaceOutput(SurfaceId), Scroll(SurfaceId), @@ -148,6 +149,7 @@ impl SurfaceSessionScope { | MuxEvent::Bell(surface) => *surface == self.surface, MuxEvent::SurfaceResized { surface, .. } | MuxEvent::SurfaceResizeFailed { surface, .. } + | MuxEvent::AgentChanged { surface, .. } | MuxEvent::TitleChanged { surface, .. } | MuxEvent::ScrollChanged { surface, .. } => *surface == self.surface, MuxEvent::Notification(notification) => { @@ -223,6 +225,9 @@ impl MuxEventMailbox { let sequence = state.next_sequence; state.next_sequence = state.next_sequence.saturating_add(1); let accepted = match event { + event @ MuxEvent::AgentChanged { surface, .. } => { + state.push_coalesced(sequence, CoalescedEventKey::Agent(surface), event) + } event @ MuxEvent::TitleChanged { surface, .. } => { state.push_coalesced(sequence, CoalescedEventKey::Title(surface), event) } @@ -308,6 +313,7 @@ impl MuxEventMailboxState { } fn discard_surface_state(&mut self, surface: SurfaceId) { + self.discard_coalesced(CoalescedEventKey::Agent(surface)); self.discard_coalesced(CoalescedEventKey::Title(surface)); self.discard_coalesced(CoalescedEventKey::SurfaceOutput(surface)); self.discard_coalesced(CoalescedEventKey::Scroll(surface)); @@ -432,6 +438,52 @@ mod tests { } } + #[test] + fn agent_churn_keeps_one_latest_value_per_surface() { + let broadcaster = MuxEventBroadcaster::default(); + let events = broadcaster.subscribe(); + + for index in 0..10_000 { + broadcaster.emit(MuxEvent::AgentChanged { + surface: 1, + state: format!("one-{index}").into(), + source: "hook".into(), + session: None, + updated_at_ms: index, + }); + broadcaster.emit(MuxEvent::AgentChanged { + surface: 2, + state: format!("two-{index}").into(), + source: "socket".into(), + session: Some("agent-session".into()), + updated_at_ms: index, + }); + } + + assert!(matches!( + events.recv().unwrap(), + MuxEvent::AgentChanged { + surface: 1, + state, + updated_at_ms: 9_999, + .. + } if state.as_ref() == "one-9999" + )); + assert!(matches!( + events.recv().unwrap(), + MuxEvent::AgentChanged { + surface: 2, + state, + source, + session: Some(session), + updated_at_ms: 9_999, + } if state.as_ref() == "two-9999" + && source.as_ref() == "socket" + && session.as_ref() == "agent-session" + )); + assert!(matches!(events.try_recv(), Err(TryRecvError::Empty))); + } + #[test] fn title_fanout_shares_the_payload_allocation() { let broadcaster = MuxEventBroadcaster::default(); @@ -479,6 +531,24 @@ mod tests { assert!(matches!(events.try_recv(), Err(TryRecvError::Empty))); } + #[test] + fn surface_exit_discards_its_pending_agent_state() { + let broadcaster = MuxEventBroadcaster::default(); + let events = broadcaster.subscribe(); + + broadcaster.emit(MuxEvent::AgentChanged { + surface: 4, + state: "working".into(), + source: "hook".into(), + session: None, + updated_at_ms: 1, + }); + broadcaster.emit(MuxEvent::SurfaceExited(4)); + + assert!(matches!(events.recv().unwrap(), MuxEvent::SurfaceExited(4))); + assert!(matches!(events.try_recv(), Err(TryRecvError::Empty))); + } + #[test] fn surface_output_churn_keeps_one_latest_position_per_surface() { let broadcaster = MuxEventBroadcaster::default(); diff --git a/cmux-tui/crates/cmux-tui-core/src/mux.rs b/cmux-tui/crates/cmux-tui-core/src/mux.rs index 2f033f6f29eb..d3c0caaa8000 100644 --- a/cmux-tui/crates/cmux-tui-core/src/mux.rs +++ b/cmux-tui/crates/cmux-tui-core/src/mux.rs @@ -709,6 +709,14 @@ pub enum MuxEvent { surface: SurfaceId, title: Arc, }, + /// The latest agent state for one surface changed. + AgentChanged { + surface: SurfaceId, + state: Arc, + source: Arc, + session: Option>, + updated_at_ms: u64, + }, Bell(SurfaceId), Notification(NotificationEvent), GraphicsStatus(GraphicsStatus), @@ -7321,20 +7329,25 @@ impl Mux { drop(records); drop(state); drop(registry); + let agent = AgentRecord { + surface, + terminal_id, + state: record.state, + source: record.source, + session: record.session, + updated_at_ms: record.updated_at_ms, + }; if !commit.replayed { self.publish_resource_event(); + self.emit(MuxEvent::AgentChanged { + surface: agent.surface, + state: Arc::from(agent.state.as_str()), + source: Arc::from(agent.source.as_str()), + session: agent.session.as_deref().map(Arc::from), + updated_at_ms: agent.updated_at_ms, + }); } - Ok(( - commit, - Some(AgentRecord { - surface, - terminal_id, - state: record.state, - source: record.source, - session: record.session, - updated_at_ms: record.updated_at_ms, - }), - )) + Ok((commit, Some(agent))) } /// Drop per-surface metadata for a surface that has left the tree. @@ -19335,6 +19348,7 @@ mod tests { fn agent_reports_apply_hook_authority() { let mux = test_mux(); let surface = mux.new_workspace(None, None).unwrap(); + let events = mux.subscribe(); let initial_revision = mux.with_state(|state| state.resource_revision); let initial_epoch = mux.resource_event_epoch(); let socket = mux @@ -19347,6 +19361,19 @@ mod tests { .unwrap(); assert_eq!(socket.state, AgentState::Working); assert_eq!(socket.source, AgentSource::Socket); + assert!(matches!( + events.recv_timeout(Duration::from_millis(100)), + Ok(MuxEvent::AgentChanged { + surface: event_surface, + state, + source, + session: Some(session), + .. + }) if event_surface == surface.id + && state.as_ref() == "working" + && source.as_ref() == "socket" + && session.as_ref() == "socket-session" + )); let hook = mux .report_agent( @@ -19377,13 +19404,30 @@ mod tests { assert_eq!(mux.with_state(|state| state.resource_revision), initial_revision + 3); assert_eq!(mux.resource_event_epoch(), initial_epoch + 3); assert_eq!(mux.resource_agent_projection_count_for_test().unwrap(), 1); - let events = mux.resource_events_after(initial_revision).unwrap(); - assert_eq!(events.batches.len(), 3); - assert_eq!(events.batches[0].changes[0]["value"]["source"], "socket"); - assert_eq!(events.batches[1].changes[0]["value"]["source"], "hook"); - assert_eq!(events.batches[2].changes[0]["value"]["source"], "hook"); - assert_eq!(events.batches[2].changes[0]["value"]["state"], "blocked"); - assert_eq!(events.batches[2].changes[0]["value"]["source_session"], "hook-session"); + let resource_events = mux.resource_events_after(initial_revision).unwrap(); + assert_eq!(resource_events.batches.len(), 3); + assert_eq!(resource_events.batches[0].changes[0]["value"]["source"], "socket"); + assert_eq!(resource_events.batches[1].changes[0]["value"]["source"], "hook"); + assert_eq!(resource_events.batches[2].changes[0]["value"]["source"], "hook"); + assert_eq!(resource_events.batches[2].changes[0]["value"]["state"], "blocked"); + assert_eq!( + resource_events.batches[2].changes[0]["value"]["source_session"], + "hook-session" + ); + assert!(matches!( + events.recv_timeout(Duration::from_millis(100)), + Ok(MuxEvent::AgentChanged { + surface: event_surface, + state, + source, + session: Some(session), + .. + }) if event_surface == surface.id + && state.as_ref() == "blocked" + && source.as_ref() == "hook" + && session.as_ref() == "hook-session" + )); + assert!(!events.try_iter().any(|event| matches!(event, MuxEvent::TreeChanged))); } #[test] @@ -23087,7 +23131,7 @@ mod tests { }, ResourceChange::SetScreenOrder { workspace_id: workspace.public_id.clone(), - screen_ids: vec![screen.clone()], + screen_ids: vec![screen], }, ResourceChange::SetTabOrder { pane_id: pane.clone(), diff --git a/cmux-tui/crates/cmux-tui-core/src/resource_router/content.rs b/cmux-tui/crates/cmux-tui-core/src/resource_router/content.rs index ce7321f4b05d..cb298559a98d 100644 --- a/cmux-tui/crates/cmux-tui-core/src/resource_router/content.rs +++ b/cmux-tui/crates/cmux-tui-core/src/resource_router/content.rs @@ -2108,7 +2108,7 @@ mod tests { .unwrap_err(); assert_eq!(error.code, "selector.not_found"); - let mut unknown = selectors.clone(); + let mut unknown = selectors; unknown.terminal = Some("term_ffffffffffffffffffffffffffffffff".into()); let error = dispatch( &mux, diff --git a/cmux-tui/crates/cmux-tui-core/src/server.rs b/cmux-tui/crates/cmux-tui-core/src/server.rs index 8b048a1d1c8b..1910ae47afc1 100644 --- a/cmux-tui/crates/cmux-tui-core/src/server.rs +++ b/cmux-tui/crates/cmux-tui-core/src/server.rs @@ -10851,6 +10851,14 @@ fn subscribed_event_json(event: &MuxEvent) -> Value { MuxEvent::TitleChanged { surface, title } => { json!({"event": "title-changed", "surface": surface, "title": title.as_ref()}) } + MuxEvent::AgentChanged { surface, state, source, session, updated_at_ms } => json!({ + "event": "agent-changed", + "surface": surface, + "state": state.as_ref(), + "source": source.as_ref(), + "session": session.as_deref(), + "updated_at_ms": updated_at_ms, + }), MuxEvent::Bell(id) => json!({"event": "bell", "surface": id}), MuxEvent::Notification(notification) => json!({ "event": "notification", @@ -18235,6 +18243,27 @@ mod tests { ); } + #[test] + fn agent_changed_event_preserves_the_scoped_agent_state() { + assert_eq!( + subscribed_event_json(&MuxEvent::AgentChanged { + surface: 7, + state: Arc::::from("working"), + source: Arc::::from("hook"), + session: Some(Arc::::from("review")), + updated_at_ms: 41, + }), + json!({ + "event": "agent-changed", + "surface": 7, + "state": "working", + "source": "hook", + "session": "review", + "updated_at_ms": 41, + }) + ); + } + #[test] fn graphics_status_events_preserve_structured_localization_data() { assert_eq!( diff --git a/cmux-tui/crates/cmux-tui-core/src/terminal_host_protocol.rs b/cmux-tui/crates/cmux-tui-core/src/terminal_host_protocol.rs index a8df3915bd02..7e0e301fd54a 100644 --- a/cmux-tui/crates/cmux-tui-core/src/terminal_host_protocol.rs +++ b/cmux-tui/crates/cmux-tui-core/src/terminal_host_protocol.rs @@ -359,7 +359,9 @@ pub enum MessageKind { /// Targeted response to `SetKittyGraphicsLimits`; payload is the applied /// four-field resource limit tuple. KittyGraphicsLimitsAck = 19, - /// Response to `Launch` when the hidden host cannot publish a PTY. + /// Bootstrap-pipe response when the host could not create its PTY or + /// child. The bounded UTF-8 payload preserves the owning process's error + /// instead of making the launcher infer failure from EOF. LaunchFailed = 20, /// Targeted confirmation that `Terminate` reached the authoritative host. /// The PTY group shutdown continues asynchronously after this receipt. diff --git a/cmux-tui/crates/cmux-tui-core/src/terminal_host_runtime.rs b/cmux-tui/crates/cmux-tui-core/src/terminal_host_runtime.rs index c92d2fd1a273..cd6a339cff10 100644 --- a/cmux-tui/crates/cmux-tui-core/src/terminal_host_runtime.rs +++ b/cmux-tui/crates/cmux-tui-core/src/terminal_host_runtime.rs @@ -3581,7 +3581,7 @@ mod unix { let master = self.master.lock().unwrap(); if let Err(error) = master.resize(next_size) { self.smart.close_failed_transition(source_cursor); - return Err(error.into()); + return Err(error); } if let Err(error) = term.resize(size.0, size.1, u32::from(next.0), u32::from(next.1)) diff --git a/cmux-tui/crates/cmux-tui-core/src/workspace_registry/tests.rs b/cmux-tui/crates/cmux-tui-core/src/workspace_registry/tests.rs index 0d5c1e421812..66b36cd13c6d 100644 --- a/cmux-tui/crates/cmux-tui-core/src/workspace_registry/tests.rs +++ b/cmux-tui/crates/cmux-tui-core/src/workspace_registry/tests.rs @@ -569,6 +569,7 @@ fn terminal_host_reset_holds_structured_live_marker_lock() { workspace_key: String::new(), supports_set_defaults: true, supports_clear_history: true, + supports_terminate_ack: false, }; let record_path = record.record_path(&root); let live_path = terminal_host_live_marker_path(&record_path, &record); @@ -661,6 +662,7 @@ fn terminal_host_reset_checks_legacy_live_marker_as_orphan() { workspace_key: String::new(), supports_set_defaults: false, supports_clear_history: false, + supports_terminate_ack: false, }; let record_path = record.record_path(&root); let live_path = terminal_host_live_marker_path(&record_path, &record); @@ -767,6 +769,7 @@ fn reset_accepts_dead_v2_terminal_host_without_creating_live_marker() { workspace_key: String::new(), supports_set_defaults: true, supports_clear_history: true, + supports_terminate_ack: false, }; let record_path = record.record_path(&host_root); let live_path = terminal_host_live_marker_path(&record_path, &record); diff --git a/cmux-tui/crates/cmux-tui/Cargo.toml b/cmux-tui/crates/cmux-tui/Cargo.toml index 41aff5924e03..2f5b0e0b194b 100644 --- a/cmux-tui/crates/cmux-tui/Cargo.toml +++ b/cmux-tui/crates/cmux-tui/Cargo.toml @@ -29,6 +29,7 @@ serde_json.workspace = true toml.workspace = true base64.workspace = true getrandom.workspace = true +glob.workspace = true libc.workspace = true smallvec.workspace = true zeroize.workspace = true diff --git a/cmux-tui/crates/cmux-tui/src/app.rs b/cmux-tui/crates/cmux-tui/src/app.rs index 46ad3a47e5bd..b955d659adb5 100644 --- a/cmux-tui/crates/cmux-tui/src/app.rs +++ b/cmux-tui/crates/cmux-tui/src/app.rs @@ -45,22 +45,26 @@ use ghostty_vt::{ }; use ratatui::Terminal as RatatuiTerminal; use ratatui::backend::{Backend, CrosstermBackend}; +use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use crate::browser_input::{ BrowserInputDispatcher, BrowserInputEvent, BrowserInputKind, BrowserKey, BrowserResizeFailure, }; -use crate::config::{Action, ChromeTheme, Config, ScrollbarPosition, SidebarView}; +use crate::config::{ + Action, ChromeTheme, Config, ScrollbarPosition, SidebarColumn, SidebarColumnKind, + SidebarResourceKind, SidebarView, +}; use crate::keys; use crate::localization; use crate::machine::{ DurableNoticeDelivery, DurableProviderNotice, MachineActionResult, MachineConnectRoute, - MachineController, MachineKey, MachineRailSelection, MachineRailTarget, MachineRequest, - MachineSession, MachineSnapshot, MachineUiState, MachineUpdate, MachineUpdateStream, - ManagedMachineDescriptor, ManagedMachineStatus, ManagedWorkspaceDescriptor, - ManagedWorkspaceSessionMutation, ManagedWorkspaceStatus, ProviderActionContext, - ProviderActionInputError, ProviderPresentation, WorkspaceCreationMode, WorkspaceCreationPolicy, - validate_machine_session, + MachineConnectionPhase, MachineController, MachineKey, MachineRailSelection, MachineRailTarget, + MachineRequest, MachineSession, MachineSnapshot, MachineUiState, MachineUpdate, + MachineUpdateStream, ManagedMachineDescriptor, ManagedMachineStatus, + ManagedWorkspaceDescriptor, ManagedWorkspaceSessionMutation, ManagedWorkspaceStatus, + ProviderActionContext, ProviderActionInputError, ProviderPresentation, WorkspaceCreationMode, + WorkspaceCreationPolicy, validate_machine_session, }; use crate::pty_input::{ PTY_OPERATION_QUEUE_CAPACITY, PtyInputBytes, PtyInputDispatcher, PtyInputEnqueueResult, @@ -69,11 +73,14 @@ use crate::pty_input::{ }; use crate::session::tree::{PaneView, ScreenView}; use crate::session::{ - AmbiguousCreation, CLEAR_HISTORY_UNSUPPORTED_ERROR, ClientInfo, CreationReceipt, Session, - SidebarPluginSurface, SurfaceAttach, SurfaceHandle, TreeView, is_remote_surface_unavailable, - is_remote_timeout, is_remote_transport_failure, + AgentInfo, AmbiguousCreation, CLEAR_HISTORY_UNSUPPORTED_ERROR, ClientInfo, CreationReceipt, + Session, SidebarPluginSurface, SurfaceAttach, SurfaceHandle, TreeView, + is_remote_surface_unavailable, is_remote_timeout, is_remote_transport_failure, }; use crate::sidebar_files::{FileBrowser, FileCommand, file_url, shell_single_quote}; +use crate::sidebar_projection::{ + ProjectionBranch, ProjectionRailState, ProjectionRow, ProjectionTarget, +}; use crate::ui::graphics::{ GraphicPlacement, GraphicSourceRect, kitty_graphic_image, kitty_graphic_placement, }; @@ -289,6 +296,7 @@ impl SessionEventSender { | MuxEvent::Bell(surface) => *surface == filter, MuxEvent::SurfaceResized { surface, .. } | MuxEvent::SurfaceResizeFailed { surface, .. } + | MuxEvent::AgentChanged { surface, .. } | MuxEvent::TitleChanged { surface, .. } | MuxEvent::ScrollChanged { surface, .. } => *surface == filter, MuxEvent::Notification(notification) => { @@ -1787,6 +1795,10 @@ impl OrderedSession { self.inner.tree() } + fn agents(&self) -> Vec { + self.inner.agents() + } + fn respond_pairing(&self, request: u64, approve: bool) -> anyhow::Result<()> { self.inner.respond_pairing(request, approve) } @@ -3463,10 +3475,9 @@ impl RenderAction { } enum MachineRailCommand { - Switch(MachineKey), + Activate(MachineKey), Rename(MachineKey), Delete(MachineKey), - Restore(MachineKey), Purge(MachineKey), OpenScopes, OpenActions, @@ -3479,36 +3490,24 @@ pub(crate) enum WorkspaceRailSelection { #[default] Workspace, Recoverable, - SessionCreation, - ManagedCreation(WorkspaceCreationMode), + Action(SidebarActionTarget), } impl WorkspaceRailSelection { - pub(crate) fn matches_mode(self, mode: Option) -> bool { - matches!( - (self, mode), - (Self::SessionCreation, None) - | ( - Self::ManagedCreation(WorkspaceCreationMode::Isolated), - Some(WorkspaceCreationMode::Isolated) - ) - | ( - Self::ManagedCreation(WorkspaceCreationMode::Host), - Some(WorkspaceCreationMode::Host) - ) - ) + pub(crate) fn matches_action(self, target: SidebarActionTarget) -> bool { + self == Self::Action(target) } } fn workspace_creation_selection(mode: Option) -> WorkspaceRailSelection { - mode.map_or(WorkspaceRailSelection::SessionCreation, WorkspaceRailSelection::ManagedCreation) + WorkspaceRailSelection::Action(SidebarActionTarget::CreateWorkspace(mode)) } #[derive(Debug, Clone, PartialEq, Eq)] enum WorkspaceRailTarget { Workspace(WorkspaceId), Recoverable(String), - Create(Option), + Action(SidebarActionTarget), } fn rail_page_size(area: Option) -> usize { @@ -3560,6 +3559,30 @@ pub enum Hit { index: usize, id: WorkspaceId, }, + /// A tab shown in the native detail column for the selected workspace. + SidebarTab { + workspace: usize, + screen: usize, + pane: PaneId, + index: usize, + surface: SurfaceId, + }, + /// A row in a configurable multi-level native projection. + ProjectionRow { + view: usize, + row: usize, + target: ProjectionTarget, + }, + ProjectionToggle { + view: usize, + branch: ProjectionBranch, + }, + /// A rail header, the explicit pointer entrypoint for sidebar focus. + RailHeader(RailKind), + SidebarAction { + view: usize, + action: SidebarActionTarget, + }, RecoverableWorkspace { index: usize, }, @@ -3577,6 +3600,10 @@ pub enum Hit { index: usize, id: ScreenId, }, + /// Visible status text on the final row. + StatusMessage, + /// Visible copy control next to the status text. + CopyStatusMessage, NewScreen, /// Pane tab-bar entry. Tab { @@ -3619,10 +3646,36 @@ pub enum Hit { }, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum SidebarActionTarget { + Run(Action), + CreateWorkspace(Option), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SidebarActionRow { + pub label: String, + pub target: SidebarActionTarget, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum RailKind { Machine, Workspace, + Tabs, + Projection(usize), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct SidebarTabTarget { + pub workspace: usize, + pub screen: usize, + pub pane: PaneId, + pub index: usize, + pub surface: SurfaceId, + pub name: String, + pub subtitle: String, + pub active: bool, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -3631,24 +3684,41 @@ pub enum FocusTarget { Pane, MachineRail, WorkspaceRail, + TabsRail, + ProjectionRail(usize), } -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RailPlacement { + pub kind: RailKind, + pub view_index: usize, + pub rect: Rect, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SidebarLayout { pub machine: Option, pub workspace: Option, + pub tabs: Option, + pub ordered: Vec, pub content: Rect, } impl SidebarLayout { - pub fn total_width(self) -> u16 { + pub fn total_width(&self) -> u16 { self.content.x } - pub fn rail(self, kind: RailKind) -> Option { + pub fn rail(&self, kind: RailKind) -> Option { match kind { RailKind::Machine => self.machine, RailKind::Workspace => self.workspace, + RailKind::Tabs => self.tabs, + RailKind::Projection(_) => self + .ordered + .iter() + .find(|placement| placement.kind == kind) + .map(|placement| placement.rect), } } } @@ -3766,6 +3836,7 @@ pub enum OmnibarHit { /// A context-menu entry: what activating it does (the label is derived). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum MenuAction { + RenameClientMachine(MachineKey), RenameManagedMachine(MachineKey), DeleteManagedMachine(MachineKey), RestoreManagedMachine(MachineKey), @@ -3786,8 +3857,10 @@ pub enum MenuAction { BrowserCopyUrl(PaneId), BrowserActivate(PaneId), RenameTab(PaneId), + RenameSurface(SurfaceId), CopyTabId(PaneId), CopyPaneId(PaneId), + CopyStatusMessage, NewPaneSmart(PaneId), NewTab(PaneId), NewBrowserTab(PaneId), @@ -3799,6 +3872,8 @@ pub enum MenuAction { ToggleSidebar { visible: bool }, ToggleSidebarCompact { compact: bool }, FocusSidebar, + ActivateSidebarProfile(usize), + SetSidebarViewVisible { view: usize, visible: bool }, ShowShortcuts, SetClientSizing { surface: SurfaceId, client: u64, enabled: bool }, UseClientSize { surface: SurfaceId, client: u64 }, @@ -3806,13 +3881,18 @@ pub enum MenuAction { DisconnectClient(u64), SelectProviderScope(usize), InvokeProviderAction(usize), + CreateMachineFrom(usize), + ConnectMachineTarget(usize), + ConnectOtherMachine, } impl MenuAction { pub fn label(&self) -> &'static str { let menu = &localization::catalog().menu; match self { - MenuAction::RenameManagedMachine(_) => localization::catalog().sidebar.rename_machine, + MenuAction::RenameClientMachine(_) | MenuAction::RenameManagedMachine(_) => { + localization::catalog().sidebar.rename_machine + } MenuAction::DeleteManagedMachine(_) => localization::catalog().sidebar.delete_machine, MenuAction::RestoreManagedMachine(_) => localization::catalog().sidebar.restore_machine, MenuAction::PurgeManagedMachine(_) => localization::catalog().sidebar.purge_machine, @@ -3849,9 +3929,12 @@ impl MenuAction { } MenuAction::BrowserCopyUrl(_) => "Copy URL", MenuAction::BrowserActivate(_) => "Show in Chrome", - MenuAction::RenameTab(_) => localization::catalog().action_label(Action::RenameTab), + MenuAction::RenameTab(_) | MenuAction::RenameSurface(_) => { + localization::catalog().action_label(Action::RenameTab) + } MenuAction::CopyTabId(_) => "Copy tab id", MenuAction::CopyPaneId(_) => "Copy pane id", + MenuAction::CopyStatusMessage => menu.copy_message, MenuAction::NewPaneSmart(_) => { localization::catalog().action_label(Action::NewPaneSmart) } @@ -3870,6 +3953,9 @@ impl MenuAction { MenuAction::ToggleSidebarCompact { compact: false } => menu.compact_sidebar, MenuAction::ToggleSidebarCompact { compact: true } => menu.full_sidebar, MenuAction::FocusSidebar => menu.focus_sidebar, + MenuAction::ActivateSidebarProfile(_) => menu.sidebar_profiles, + MenuAction::SetSidebarViewVisible { visible: true, .. } => menu.show_sidebar_view, + MenuAction::SetSidebarViewVisible { visible: false, .. } => menu.hide_sidebar_view, MenuAction::ShowShortcuts => { localization::catalog().action_label(Action::ShowShortcuts) } @@ -3881,6 +3967,9 @@ impl MenuAction { MenuAction::SelectProviderScope(_) | MenuAction::InvokeProviderAction(_) => { "Provider action" } + MenuAction::CreateMachineFrom(_) => localization::catalog().sidebar.new_machine, + MenuAction::ConnectMachineTarget(_) => localization::catalog().sidebar.connect_machine, + MenuAction::ConnectOtherMachine => localization::catalog().sidebar.other_host, } } } @@ -3963,6 +4052,16 @@ impl MenuItem { } } +fn menu_scrollbar_track(rect: Rect, total_rows: usize) -> Option { + let visible_rows = usize::from(rect.height.saturating_sub(2)); + (rect.width >= 3 && visible_rows > 0 && total_rows > visible_rows).then_some(Rect { + x: rect.x + rect.width - 2, + y: rect.y + 1, + width: 1, + height: visible_rows as u16, + }) +} + pub struct MenuLevel { pub items: Arc<[MenuItem]>, all_items: Arc<[MenuItem]>, @@ -4050,16 +4149,79 @@ impl MenuLevel { self.scroll_offset = self.scroll_offset.min(self.items.len().saturating_sub(self.visible_rows)); } + + fn set_scroll_offset(&mut self, offset: usize) -> bool { + let offset = offset.min(self.items.len().saturating_sub(self.visible_rows)); + if self.scroll_offset == offset { + return false; + } + self.scroll_offset = offset; + let end = offset.saturating_add(self.visible_rows).min(self.items.len()); + if (self.selected < offset || self.selected >= end) + && let Some(relative) = self.items[offset..end].iter().position(MenuItem::selectable) + { + self.selected = offset + relative; + } + true + } + + fn scroll_rows(&mut self, delta: isize) -> bool { + self.set_scroll_offset(self.scroll_offset.saturating_add_signed(delta)) + } + + pub(crate) fn scrollbar_track(&self) -> Option { + menu_scrollbar_track(self.rect, self.items.len()) + } + + pub(crate) fn scrollbar(&self) -> Option<(Rect, (u16, u16))> { + let track = self.scrollbar_track()?; + let thumb = viewport_thumb_geometry( + self.items.len(), + self.visible_rows, + self.scroll_offset, + track.height, + ); + Some((track, thumb)) + } + + fn replace_items(&mut self, items: Vec) { + let items: Arc<[MenuItem]> = items.into(); + self.all_items = items.clone(); + self.items = items; + self.selected = self.items.iter().position(MenuItem::selectable).unwrap_or(0); + self.scroll_offset = 0; + self.visible_rows = self.items.len(); + self.fitted_rows = None; + self.rect.height = self.items.len() as u16 + 2; + } +} + +pub(crate) struct MenuSearch { + pub label: String, + pub placeholder: String, + pub input: TextInput, + items: Arc<[MenuItem]>, + lowered_labels: Arc<[String]>, + fallback: Arc<[MenuItem]>, +} + +#[derive(Clone, Copy)] +struct MenuScrollbarDrag { + depth: usize, + anchor_y: u16, + anchor_offset: usize, } /// Right-click context menu overlay. The rect includes the border chrome; /// action rows get a one-cell padding column on each side inside that border, /// groups are divided by separator rows, and the hover/selection highlight -/// spans the full inner row including those padding cells. +/// spans the content row including padding, leaving room for an overflow thumb. pub struct ContextMenu { pub levels: Vec, + pub(crate) search: Option, right_press: (u16, u16), right_drag_moved: bool, + scrollbar_drag: Option, captured_resources: Vec<(MenuAction, Option)>, } @@ -4089,12 +4251,100 @@ impl ContextMenu { } ContextMenu { levels: vec![MenuLevel::new(x.saturating_sub(1), y.saturating_sub(1), items)], + search: None, right_press: (x, y), right_drag_moved: false, + scrollbar_drag: None, captured_resources: Vec::new(), } } + fn searchable( + x: u16, + y: u16, + label: impl Into, + placeholder: impl Into, + items: Vec, + fallback: Vec, + ) -> Self { + let label = label.into(); + let placeholder = placeholder.into(); + let search_items: Arc<[MenuItem]> = items.into(); + let lowered_labels = search_items + .iter() + .map(|item| item.label().unwrap_or_default().to_lowercase()) + .collect::>(); + let fallback: Arc<[MenuItem]> = fallback.into(); + let mut visible = fallback.to_vec(); + if !visible.is_empty() && !search_items.is_empty() { + visible.push(MenuItem::Separator); + } + visible.extend(search_items.iter().cloned()); + let mut level = MenuLevel::new(x.saturating_sub(1), y.saturating_sub(1), visible); + let search_width = label.width() + placeholder.width() + 9; + level.rect.width = level.rect.width.max(search_width.min(u16::MAX as usize) as u16); + ContextMenu { + levels: vec![level], + search: Some(MenuSearch { + label, + placeholder, + input: TextInput::new(String::new()), + items: search_items, + lowered_labels, + fallback, + }), + right_press: (x, y), + right_drag_moved: false, + scrollbar_drag: None, + captured_resources: Vec::new(), + } + } + + fn refresh_search(&mut self) { + let Some(search) = self.search.as_ref() else { return }; + let query = search.input.as_str().trim().to_lowercase(); + let terms = query.split_whitespace().collect::>(); + let matches = search + .items + .iter() + .zip(search.lowered_labels.iter()) + .filter(|(_, label)| terms.is_empty() || terms.iter().all(|term| label.contains(term))) + .map(|(item, _)| item.clone()) + .collect::>(); + let mut visible = search.fallback.to_vec(); + if !matches.is_empty() && !search.fallback.is_empty() { + visible.push(MenuItem::Separator); + } + let first_match = (!terms.is_empty() && !matches.is_empty()).then_some(visible.len()); + visible.extend(matches); + self.levels.truncate(1); + self.scrollbar_drag = None; + if let Some(level) = self.levels.first_mut() { + level.replace_items(visible); + if let Some(first_match) = first_match { + level.selected = first_match; + level.ensure_selection_visible(); + } + } + } + + fn insert_search_text(&mut self, text: &str) -> bool { + let changed = self.search.as_mut().is_some_and(|search| search.input.insert_str(text)); + if changed { + self.refresh_search(); + } + changed + } + + fn handle_search_key(&mut self, key: &KeyEvent) -> bool { + let Some(search) = self.search.as_mut() else { return false }; + let changed = search.input.handle_key(key) == InputEvent::Changed; + if changed { + self.refresh_search(); + } + true + } + fn actions(&self) -> Vec { fn collect(items: &[MenuItem], actions: &mut Vec) { for item in items { @@ -4107,7 +4357,10 @@ impl ContextMenu { } let mut actions = Vec::new(); - if let Some(level) = self.levels.first() { + if let Some(search) = self.search.as_ref() { + collect(&search.items, &mut actions); + collect(&search.fallback, &mut actions); + } else if let Some(level) = self.levels.first() { collect(&level.all_items, &mut actions); } actions @@ -4129,6 +4382,9 @@ impl ContextMenu { pub fn hit_at(&self, x: u16, y: u16) -> Option<(usize, usize)> { let (depth, level) = self.levels.iter().enumerate().rev().find(|(_, level)| level.rect.contains(x, y))?; + if level.scrollbar_track().is_some_and(|track| track.contains(x, y)) { + return None; + } let rect = level.rect; let right = rect.x + rect.width.saturating_sub(1); let bottom = rect.y + rect.height.saturating_sub(1); @@ -4143,6 +4399,81 @@ impl ContextMenu { self.levels.iter().any(|level| level.rect.contains(x, y)) } + fn scrollbar_at(&self, x: u16, y: u16) -> Option<(usize, Rect)> { + self.levels.iter().enumerate().rev().find_map(|(depth, level)| { + level.scrollbar_track().filter(|track| track.contains(x, y)).map(|track| (depth, track)) + }) + } + + fn scroll_at(&mut self, x: u16, y: u16, down: bool) -> bool { + let Some(depth) = self + .levels + .iter() + .enumerate() + .rev() + .find(|(_, level)| level.rect.contains(x, y)) + .map(|(depth, _)| depth) + else { + return false; + }; + self.levels.truncate(depth + 1); + self.scrollbar_drag = None; + self.levels[depth].scroll_rows(if down { 3 } else { -3 }) + } + + fn start_scrollbar_drag(&mut self, x: u16, y: u16) -> bool { + let Some((depth, track)) = self.scrollbar_at(x, y) else { + return false; + }; + self.levels.truncate(depth + 1); + let level = &mut self.levels[depth]; + let relative = y.saturating_sub(track.y).min(track.height.saturating_sub(1)); + let (thumb_y, thumb_height) = viewport_thumb_geometry( + level.items.len(), + level.visible_rows, + level.scroll_offset, + track.height, + ); + if relative < thumb_y || relative >= thumb_y.saturating_add(thumb_height) { + let offset = + viewport_jump_offset(level.items.len(), level.visible_rows, track.height, relative); + level.set_scroll_offset(offset); + } + self.scrollbar_drag = + Some(MenuScrollbarDrag { depth, anchor_y: y, anchor_offset: level.scroll_offset }); + true + } + + fn drag_scrollbar(&mut self, y: u16) -> bool { + let Some(drag) = self.scrollbar_drag else { + return false; + }; + let Some(level) = self.levels.get_mut(drag.depth) else { + self.scrollbar_drag = None; + return false; + }; + let Some(track) = level.scrollbar_track() else { + self.scrollbar_drag = None; + return false; + }; + let offset = viewport_drag_offset( + level.items.len(), + level.visible_rows, + track.height, + drag.anchor_offset, + y as i128 - drag.anchor_y as i128, + ); + level.set_scroll_offset(offset) + } + + fn finish_scrollbar_drag(&mut self) -> bool { + self.scrollbar_drag.take().is_some() + } + + pub(crate) fn scrollbar_dragging(&self, depth: usize) -> bool { + self.scrollbar_drag.is_some_and(|drag| drag.depth == depth) + } + fn selected_action(&self) -> Option { let level = self.levels.last()?; level.items.get(level.selected).and_then(MenuItem::action) @@ -4185,7 +4516,11 @@ impl ContextMenu { } } - self.levels.iter().any(|level| level.all_items.iter().any(item_targets_provider)) + if let Some(search) = self.search.as_ref() { + search.items.iter().chain(search.fallback.iter()).any(item_targets_provider) + } else { + self.levels.iter().any(|level| level.all_items.iter().any(item_targets_provider)) + } } fn action_at(&self, depth: usize, item: usize) -> Option { @@ -4213,6 +4548,9 @@ impl ContextMenu { fn close_submenu(&mut self) -> bool { if self.levels.len() > 1 { self.levels.pop(); + if self.scrollbar_drag.is_some_and(|drag| drag.depth >= self.levels.len()) { + self.scrollbar_drag = None; + } true } else { false @@ -4357,6 +4695,7 @@ fn client_menu_item(clients: &[ClientInfo], surface: SurfaceId) -> Option Self { Self { challenge, rect: Rect::default(), approve: Rect::default(), deny: Rect::default() } @@ -4535,6 +4890,47 @@ pub struct Selection { pub head: (u16, u64), } +#[derive(Debug, Clone, PartialEq, Eq)] +struct StatusMessageSelection { + text: String, + anchor: u16, + head: u16, +} + +impl StatusMessageSelection { + fn range(&self) -> (u16, u16) { + if self.anchor <= self.head { (self.anchor, self.head) } else { (self.head, self.anchor) } + } + + fn contains(&self, text: &str, cell: u16) -> bool { + self.text == text && { + let (start, end) = self.range(); + cell >= start && cell <= end + } + } + + fn selected_text(&self) -> String { + let (start, end) = self.range(); + let mut cell = 0usize; + self.text + .graphemes(true) + .filter(|grapheme| { + let width = grapheme.width(); + let grapheme_start = cell; + let grapheme_end = cell.saturating_add(width); + cell = grapheme_end; + width > 0 && grapheme_start <= usize::from(end) && grapheme_end > usize::from(start) + }) + .collect() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct RenderedStatusMessage { + rect: Rect, + text: String, +} + impl Selection { /// Normalized (start, end) in row-major order, inclusive. pub fn range(&self) -> ((u16, u64), (u16, u64)) { @@ -4604,18 +5000,18 @@ enum PaneResizeDragTarget { /// Mouse drag in progress. enum Drag { - /// Left press on a machine entry; switching occurs on release. - MachineArm { target: MachinePointerTarget, at: (u16, u16) }, /// Left press on a tab chip; becomes `Tab` after moving cells. TabArm { surface: SurfaceId, at: (u16, u16) }, /// Tab drag with the current drop target. Tab { surface: SurfaceId, target: Option<(PaneId, usize)> }, - /// Left press on a workspace entry; becomes `Workspace` after moving cells. + /// Workspace reorder gesture armed after the entry activated on press. WorkspaceArm { workspace: WorkspaceId, at: (u16, u16) }, /// Workspace drag with the current insertion index. Workspace { workspace: WorkspaceId, target: Option }, /// Text selection inside a pane's content rect. Select { content: Rect, source_x: u16, auto_scroll: Option, col: u16 }, + /// Text selection inside the final-row status message. + StatusMessage { rect: Rect }, /// Browser mouse drag inside a pane's content rect. Browser { surface: SurfaceId, content: Rect, position: (u16, u16), frame_seq: u64 }, /// Mouse reporting owned by the PTY application in this pane. @@ -4717,6 +5113,7 @@ enum PromptPointerRegion { #[derive(Clone, Debug, PartialEq, Eq)] enum MenuPointerRegion { Item { depth: usize, index: usize }, + Scrollbar { depth: usize }, Chrome { depth: usize }, Outside, } @@ -4777,9 +5174,20 @@ struct RenderedMenuLevel { resources: Arc<[Option]>, } +impl RenderedMenuLevel { + fn scrollbar_track(&self) -> Option { + menu_scrollbar_track(self.rect, self.items.len()) + } +} + #[derive(Clone, Debug, PartialEq, Eq)] enum MenuActionResource { Surface(SurfaceId), + StatusMessage(String), + MachineCreationSource(String), + MachineConnectionTarget(String), + SidebarProfile(String), + SidebarView { profile: String, view: String }, ManagedWorkspace { machine: MachineKey, id: String, version: u64 }, ProviderScope { machine: Option, id: String }, ProviderAction { machine: Option, id: String }, @@ -4927,6 +5335,7 @@ struct RenderedPointerFrame { sidebar_plugin: Option<(Rect, Option)>, machine_rail: Option, workspace_rail: Option, + tabs_rail: Option, hits: Arc<[RenderedHitRoute]>, panes: Arc<[RenderedPaneRoute]>, terminal_pointer_semantics: Arc>, @@ -4973,6 +5382,9 @@ impl RenderedPointerFrame { .rev() .find(|(_, level)| level.rect.contains(x, y)) .map_or((MenuPointerRegion::Outside, None), |(depth, level)| { + if level.scrollbar_track().is_some_and(|track| track.contains(x, y)) { + return (MenuPointerRegion::Scrollbar { depth }, None); + } let right = level.rect.x + level.rect.width.saturating_sub(1); let bottom = level.rect.y + level.rect.height.saturating_sub(1); if x == level.rect.x || y == level.rect.y || x == right || y == bottom { @@ -5026,9 +5438,11 @@ impl RenderedPointerFrame { row: y.saturating_sub(route.rect.y), }; } - for (kind, rect) in - [(RailKind::Machine, self.machine_rail), (RailKind::Workspace, self.workspace_rail)] - { + for (kind, rect) in [ + (RailKind::Machine, self.machine_rail), + (RailKind::Workspace, self.workspace_rail), + (RailKind::Tabs, self.tabs_rail), + ] { if let Some(rect) = rect.filter(|rect| rect.contains(x, y)) { return PointerRouteIdentity::Rail { kind, @@ -5893,6 +6307,12 @@ pub struct App { machine_action_worker: Option, machine_action_in_flight: bool, machine_action_request: Option, + machine_action_connection_attempt: Option, + canceled_machine_connection_attempt: Option, + machine_action_intent_generation: Option, + machine_selection_intent: Option, + machine_selection_generation: u64, + machine_presented: Option, machine_provider_reconnect_attempts: u8, machine_provider_reconnect_retry_at: Option, pending_machine_replacement: Option, @@ -5979,12 +6399,18 @@ pub struct App { pub(crate) machine_footer_scroll: usize, pub(crate) workspace_rail_scroll: usize, pub(crate) workspace_footer_scroll: usize, + pub(crate) tabs_rail_selection: usize, + pub(crate) tabs_rail_scroll: usize, + pub(crate) tabs_footer_scroll: usize, + projection_rails: HashMap, pub(crate) machine_rail_follow_selection: bool, pub(crate) workspace_rail_follow_selection: bool, + pub(crate) tabs_rail_follow_selection: bool, sidebar_followed_surface: Option, /// Width of the sidebar in the current frame (0 when hidden). pub sidebar_width: u16, pub machine_sidebar_width: u16, + pub tabs_sidebar_width: u16, pub sidebar_layout: SidebarLayout, pub sidebar_plugin_surface: Option, pub sidebar_plugin_error: Option, @@ -5992,6 +6418,10 @@ pub struct App { sidebar_plugin_retry_at: Option, sidebar_width_override: Option, machine_sidebar_width_override: Option, + tabs_sidebar_width_override: Option, + projection_sidebar_width_overrides: HashMap, + /// Session-local visibility overrides, keyed by profile and stable view id. + hidden_sidebar_views: HashMap>, /// Pane region of the current frame (screen minus sidebar/status). pub content_area: Rect, /// Clickable regions of the current frame, rebuilt by the renderers. @@ -6006,6 +6436,8 @@ pub struct App { pub clients: Vec, pub client_border_labels: HashMap, pub prompt: Option, + pub(crate) connection_transaction: Option, + next_connection_attempt: u64, pending_provider_action: Option, pub pairing_dialog: Option, pairing_queue: VecDeque, @@ -6015,6 +6447,8 @@ pub struct App { pub(crate) shake_frames: u8, pub selection: Option, selection_generation: u64, + status_selection: Option, + rendered_status_message: Option, input_revision: u64, pub status_message: Option, pub cell_pixels: (u16, u16), @@ -6138,6 +6572,14 @@ fn preserve_client_view(previous: &TreeView, next: &mut TreeView) { const MIN_RAIL_WIDTH: u16 = 10; const MIN_CONTENT_WIDTH: u16 = 40; const MIN_TABBED_PANE_HEIGHT: u16 = 3; +const RAIL_REVEAL_HYSTERESIS: u16 = 4; + +#[derive(Clone, Copy, Default)] +struct SidebarWidthOverrides { + workspace: Option, + machine: Option, + tabs: Option, +} fn clamp_rail_width(desired: u16, configured_max: u16, available: u16) -> Option { let configured_max = if configured_max > 0 { configured_max } else { u16::MAX }; @@ -6148,6 +6590,30 @@ fn clamp_rail_width(desired: u16, configured_max: u16, available: u16) -> Option } fn sidebar_layout_for( + config: &Config, + visible: bool, + compact: bool, + machine_visible: bool, + size: (u16, u16), + overrides: SidebarWidthOverrides, +) -> SidebarLayout { + sidebar_layout_for_state( + config, + visible, + compact, + machine_visible, + size, + overrides.workspace, + overrides.machine, + overrides.tabs, + &HashMap::new(), + &HashSet::new(), + None, + ) +} + +#[allow(clippy::too_many_arguments)] +fn sidebar_layout_for_state( config: &Config, visible: bool, compact: bool, @@ -6155,6 +6621,10 @@ fn sidebar_layout_for( size: (u16, u16), workspace_override: Option, machine_override: Option, + tabs_override: Option, + projection_overrides: &HashMap, + hidden_views: &HashSet, + previous: Option<&SidebarLayout>, ) -> SidebarLayout { let (width, height) = size; let content_height = height.saturating_sub(1); @@ -6165,63 +6635,140 @@ fn sidebar_layout_for( }; } - let workspace_desired = if compact { - config.sidebar.compact_width - } else { - workspace_override.unwrap_or(config.sidebar.width) - }; - let machine_can_fit = machine_visible - && width >= MIN_CONTENT_WIDTH.saturating_add(MIN_RAIL_WIDTH.saturating_mul(2)); - let workspace_reserve = if machine_can_fit { MIN_RAIL_WIDTH } else { 0 }; - let workspace_available = - width.saturating_sub(MIN_CONTENT_WIDTH).saturating_sub(workspace_reserve); - let workspace_width = - clamp_rail_width(workspace_desired, config.sidebar.max_width, workspace_available) - .unwrap_or(0); + #[derive(Clone, Copy)] + struct Spec { + kind: RailKind, + view_index: usize, + desired: u16, + max_width: u16, + priority: u16, + } - let machine_width = if machine_can_fit && workspace_width >= MIN_RAIL_WIDTH { - let available = width.saturating_sub(MIN_CONTENT_WIDTH).saturating_sub(workspace_width); - clamp_rail_width( - machine_override.unwrap_or(config.machine_sidebar.width), - config.machine_sidebar.max_width, - available, - ) - .unwrap_or(0) - } else { - 0 - }; + let mut specs = config + .sidebar + .views + .iter() + .enumerate() + .filter_map(|(view_index, view)| { + if hidden_views.contains(&view.id) { + return None; + } + if view.includes(SidebarResourceKind::Machines) && !machine_visible { + return None; + } + let kind = match view.legacy_kind() { + Some(SidebarColumnKind::Machines) => RailKind::Machine, + Some(SidebarColumnKind::Workspaces) => RailKind::Workspace, + Some(SidebarColumnKind::Tabs) => RailKind::Tabs, + None => RailKind::Projection(view_index), + }; + let width_override = match kind { + RailKind::Machine => machine_override, + RailKind::Workspace => workspace_override, + RailKind::Tabs => tabs_override, + RailKind::Projection(_) => projection_overrides.get(&view.id).copied(), + }; + let legacy_width = match kind { + RailKind::Machine => config.machine_sidebar.width, + RailKind::Workspace => config.sidebar.width, + RailKind::Tabs | RailKind::Projection(_) => view.width, + }; + let desired = if compact && kind == RailKind::Workspace { + config.sidebar.compact_width + } else { + width_override.unwrap_or(if config.sidebar.views_explicit { + view.width + } else { + legacy_width + }) + }; + let max_width = if config.sidebar.views_explicit { + view.max_width + } else { + match kind { + RailKind::Machine => config.machine_sidebar.max_width, + RailKind::Workspace => config.sidebar.max_width, + RailKind::Tabs | RailKind::Projection(_) => view.max_width, + } + }; + Some(Spec { kind, view_index, desired, max_width, priority: view.collapse_priority }) + }) + .collect::>(); - let machine = (machine_width > 0).then_some(Rect { x: 0, y: 0, width: machine_width, height }); - let workspace = (workspace_width > 0).then_some(Rect { - x: machine_width, - y: 0, - width: workspace_width, - height, - }); - let sidebar_width = machine_width.saturating_add(workspace_width); - SidebarLayout { - machine, - workspace, - content: Rect { - x: sidebar_width, - y: 0, - width: width.saturating_sub(sidebar_width), - height: content_height, - }, + while width + < MIN_CONTENT_WIDTH.saturating_add(MIN_RAIL_WIDTH.saturating_mul(specs.len() as u16)) + { + let Some((index, _)) = specs.iter().enumerate().min_by_key(|(_, spec)| spec.priority) + else { + break; + }; + specs.remove(index); + } + + if let Some(previous) = previous { + while specs.iter().any(|spec| previous.rail(spec.kind).is_none()) + && width + < MIN_CONTENT_WIDTH + .saturating_add(MIN_RAIL_WIDTH.saturating_mul(specs.len() as u16)) + .saturating_add(RAIL_REVEAL_HYSTERESIS) + { + let Some((index, _)) = specs + .iter() + .enumerate() + .filter(|(_, spec)| previous.rail(spec.kind).is_none()) + .min_by_key(|(_, spec)| spec.priority) + else { + break; + }; + specs.remove(index); + } + } + + let mut layout = SidebarLayout::default(); + let mut x = 0u16; + for (index, spec) in specs.iter().enumerate() { + let remaining = specs.len().saturating_sub(index + 1) as u16; + let available = width + .saturating_sub(MIN_CONTENT_WIDTH) + .saturating_sub(x) + .saturating_sub(MIN_RAIL_WIDTH.saturating_mul(remaining)); + let Some(rail_width) = clamp_rail_width(spec.desired, spec.max_width, available) else { + continue; + }; + let rect = Rect { x, y: 0, width: rail_width, height }; + match spec.kind { + RailKind::Machine => layout.machine = Some(rect), + RailKind::Workspace => layout.workspace = Some(rect), + RailKind::Tabs => layout.tabs = Some(rect), + RailKind::Projection(_) => {} + } + layout.ordered.push(RailPlacement { kind: spec.kind, view_index: spec.view_index, rect }); + x = x.saturating_add(rail_width); } + layout.content = Rect { x, y: 0, width: width.saturating_sub(x), height: content_height }; + layout } -fn rail_drag_width(config: &Config, layout: SidebarLayout, kind: RailKind, x: u16) -> Option { +fn rail_drag_width(config: &Config, layout: &SidebarLayout, kind: RailKind, x: u16) -> Option { let rail = layout.rail(kind)?; let terminal_width = layout.content.x.saturating_add(layout.content.width); - let other_width = match kind { - RailKind::Machine => layout.workspace.map_or(0, |rect| rect.width), - RailKind::Workspace => layout.machine.map_or(0, |rect| rect.width), - }; + let other_width = layout + .ordered + .iter() + .filter(|placement| placement.kind != kind) + .map(|placement| placement.rect.width) + .fold(0u16, u16::saturating_add); let available = terminal_width.saturating_sub(MIN_CONTENT_WIDTH).saturating_sub(other_width); - let configured_max = match kind { - RailKind::Machine => config.machine_sidebar.max_width, - RailKind::Workspace => config.sidebar.max_width, + let view_index = layout.ordered.iter().find(|placement| placement.kind == kind)?.view_index; + let view = config.sidebar.views.get(view_index)?; + let configured_max = if config.sidebar.views_explicit { + view.max_width + } else { + match kind { + RailKind::Machine => config.machine_sidebar.max_width, + RailKind::Workspace => config.sidebar.max_width, + RailKind::Tabs | RailKind::Projection(_) => view.max_width, + } }; let desired = x.saturating_sub(rail.x).saturating_add(1); clamp_rail_width(desired, configured_max, available) @@ -6409,7 +6956,7 @@ enum MachineControllerCommand { Perform { request: MachineRequest, preparation: Box }, SubscribeUpdates, AcknowledgeDurableNotice(DurableNoticeDelivery), - CommitReplacement(u64), + CommitReplacement { action_id: u64, present: bool }, AbortReplacement(u64), } @@ -6431,6 +6978,7 @@ struct PreparedMachineSession { label: String, session_available: bool, color_error: Option, + machine: Option, } pub(crate) struct PreparedMachineAction { @@ -6442,6 +6990,7 @@ pub(crate) struct PreparedMachineAction { struct PendingMachineReplacement { action_id: u64, + present: bool, action: PreparedMachineAction, } @@ -6573,11 +7122,11 @@ impl MachineActionWorker { result, } } - MachineControllerCommand::CommitReplacement(action_id) => { + MachineControllerCommand::CommitReplacement { action_id, present } => { match pending_replacement.take() { Some((pending_id, restart_updates)) if pending_id == action_id => { let committed = controller - .commit_replacement() + .commit_replacement(present) .map(|()| true) .map_err(|error| error.to_string()); if committed.is_err() { @@ -6674,7 +7223,7 @@ impl MachineActionWorker { MachineControllerCommand::AcknowledgeDurableNotice(_) => { unreachable!("perform returned a durable notice acknowledgement") } - MachineControllerCommand::CommitReplacement(_) + MachineControllerCommand::CommitReplacement { .. } | MachineControllerCommand::AbortReplacement(_) => { unreachable!("perform returned a replacement decision") } @@ -6688,7 +7237,7 @@ impl MachineActionWorker { MachineControllerCommand::AcknowledgeDurableNotice(_) => { unreachable!("perform returned a durable notice acknowledgement") } - MachineControllerCommand::CommitReplacement(_) + MachineControllerCommand::CommitReplacement { .. } | MachineControllerCommand::AbortReplacement(_) => { unreachable!("perform returned a replacement decision") } @@ -6724,9 +7273,11 @@ impl MachineActionWorker { } } - fn commit_replacement(&self, action_id: u64) -> bool { + fn commit_replacement(&self, action_id: u64, present: bool) -> bool { self.sender.as_ref().is_some_and(|sender| { - sender.try_send(MachineControllerCommand::CommitReplacement(action_id)).is_ok() + sender + .try_send(MachineControllerCommand::CommitReplacement { action_id, present }) + .is_ok() }) } @@ -6793,6 +7344,7 @@ fn prepare_machine_session( label: replacement.label, session_available, color_error, + machine: replacement.machine, }) } @@ -6913,6 +7465,29 @@ fn ensure_initial_for_machine_ui( Ok(()) } +fn recover_initial_workspace_failure( + result: anyhow::Result<()>, + machine_ui: Option<&MachineUiState>, +) -> anyhow::Result> { + match result { + Ok(()) => Ok(None), + Err(error) if machine_ui.is_some() => { + let error = error.to_string(); + let message = if error.contains("failed to open PTY:") + && (error.contains("Device not configured") + || error.contains("No space left on device") + || error.contains("Resource temporarily unavailable")) + { + localization::catalog().runtime.terminal_capacity_exhausted.to_string() + } else { + error + }; + Ok(Some(message)) + } + Err(error) => Err(error), + } +} + fn uses_provider_managed_workspaces(machine_ui: Option<&MachineUiState>) -> bool { matches!( machine_ui.and_then(MachineUiState::workspace_creation_policy), @@ -6996,13 +7571,22 @@ fn run_with_machine_updates_inner( if surface_only.is_some() { return (w.max(1), h.max(1)); } - let pane = - sidebar_layout_for(&config, true, false, machine_ui.is_some(), (w, h), None, None) - .content; + let pane = sidebar_layout_for( + &config, + true, + false, + machine_ui.is_some(), + (w, h), + SidebarWidthOverrides::default(), + ) + .content; content_size_for_rect(pane, config.scrollbar.position).unwrap_or((1, 1)) }); ensure_managed_workspace_guard(&session, machine_ui.as_ref())?; - ensure_initial_for_machine_ui(&session, initial_size, machine_ui.as_ref())?; + let initial_workspace_error = recover_initial_workspace_failure( + ensure_initial_for_machine_ui(&session, initial_size, machine_ui.as_ref()), + machine_ui.as_ref(), + )?; let encoder = KeyEncoder::new()?; let (tx, rx) = sync_channel::(APP_EVENT_CAPACITY); let host_input = HostInputRuntime::new(); @@ -7170,7 +7754,10 @@ fn run_with_machine_updates_inner( }; let sidebar_view = config.sidebar.view; let fallback_cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); - let initial_machine_notice = machine_ui.as_ref().and_then(|machine| machine.notice.clone()); + let initial_machine_notice = initial_workspace_error + .or_else(|| machine_ui.as_ref().and_then(|machine| machine.notice.clone())); + let machine_selection_intent = machine_ui.as_ref().and_then(|machine| machine.snapshot.active); + let machine_presented = machine_ui.as_ref().and_then(|machine| machine.snapshot.active); let mut app = App { session, session_event_worker: Some(session_event_worker), @@ -7180,6 +7767,12 @@ fn run_with_machine_updates_inner( machine_action_worker, machine_action_in_flight: false, machine_action_request: None, + machine_action_connection_attempt: None, + canceled_machine_connection_attempt: None, + machine_action_intent_generation: None, + machine_selection_intent, + machine_selection_generation: 0, + machine_presented, machine_provider_reconnect_attempts: 0, machine_provider_reconnect_retry_at: None, pending_machine_replacement: None, @@ -7246,11 +7839,17 @@ fn run_with_machine_updates_inner( machine_footer_scroll: 0, workspace_rail_scroll: 0, workspace_footer_scroll: 0, + tabs_rail_selection: 0, + tabs_rail_scroll: 0, + tabs_footer_scroll: 0, + projection_rails: HashMap::new(), machine_rail_follow_selection: true, workspace_rail_follow_selection: true, + tabs_rail_follow_selection: true, sidebar_followed_surface: None, sidebar_width: 0, machine_sidebar_width: 0, + tabs_sidebar_width: 0, sidebar_layout: SidebarLayout::default(), sidebar_plugin_surface: None, sidebar_plugin_error: None, @@ -7258,6 +7857,9 @@ fn run_with_machine_updates_inner( sidebar_plugin_retry_at: None, sidebar_width_override: None, machine_sidebar_width_override: None, + tabs_sidebar_width_override: None, + projection_sidebar_width_overrides: HashMap::new(), + hidden_sidebar_views: HashMap::new(), content_area: Rect::default(), hits: Vec::new(), tab_scroll: HashMap::new(), @@ -7266,6 +7868,8 @@ fn run_with_machine_updates_inner( clients: Vec::new(), client_border_labels: HashMap::new(), prompt: None, + connection_transaction: None, + next_connection_attempt: 1, pending_provider_action: None, pairing_dialog: None, pairing_queue: VecDeque::new(), @@ -7275,6 +7879,8 @@ fn run_with_machine_updates_inner( shake_frames: 0, selection: None, selection_generation: 0, + status_selection: None, + rendered_status_message: None, input_revision: 0, status_message: initial_machine_notice, cell_pixels, @@ -7695,7 +8301,41 @@ impl App { } pub fn session_available(&self) -> bool { - self.machine_ui.as_ref().is_none_or(|machine| machine.session_available) + self.machine_ui.as_ref().is_none_or(|machine| { + machine.session_available && self.machine_selection_intent == self.machine_presented + }) + } + + pub(crate) fn selected_machine(&self) -> Option { + self.machine_selection_intent.or(self.machine_presented) + } + + pub(crate) fn machine_transition(&self) -> Option<(&str, MachineConnectionPhase)> { + let selected = self.machine_selection_intent?; + let ui = self.machine_ui.as_ref()?; + if self.machine_presented == Some(selected) && ui.session_available { + return None; + } + let name = + ui.snapshot.machines.iter().find(|machine| machine.key == selected)?.name.as_str(); + Some((name, ui.connection_phase(selected))) + } + + fn select_machine_intent(&mut self, machine: MachineKey) { + if self.machine_selection_intent != Some(machine) { + self.cancel_pointer_interaction(); + self.machine_selection_generation = + self.machine_selection_generation.wrapping_add(1).max(1); + self.machine_selection_intent = Some(machine); + } + if let Some(ui) = self.machine_ui.as_mut() { + let phase = if self.machine_presented == Some(machine) { + MachineConnectionPhase::Ready + } else { + MachineConnectionPhase::Connecting + }; + ui.set_connection_phase(machine, phase); + } } pub fn workspace_creation_policy(&self) -> Option { @@ -7725,19 +8365,21 @@ impl App { } fn reconcile_workspace_rail_selection(&mut self) { - let modes = self.workspace_creation_modes(); + let actions = self.workspace_sidebar_action_rows(); let selection_is_valid = match self.workspace_rail_selection { WorkspaceRailSelection::Workspace => true, WorkspaceRailSelection::Recoverable => self.machine_ui.as_ref().is_some_and(|ui| { self.sidebar_recoverable_workspace_selection < ui.recoverable_workspaces().len() }), - _ => modes.iter().copied().any(|mode| self.workspace_rail_selection.matches_mode(mode)), + WorkspaceRailSelection::Action(target) => { + actions.iter().any(|action| action.target == target) + } }; if self.workspace_rail_selection != WorkspaceRailSelection::Workspace && !selection_is_valid { - self.workspace_rail_selection = self - .default_workspace_creation_mode() - .map(workspace_creation_selection) + self.workspace_rail_selection = actions + .first() + .map(|action| WorkspaceRailSelection::Action(action.target)) .unwrap_or(WorkspaceRailSelection::Workspace); } } @@ -7750,26 +8392,288 @@ impl App { self.focus == FocusTarget::MachineRail } + pub fn tabs_sidebar_focused(&self) -> bool { + self.focus == FocusTarget::TabsRail + } + + fn sidebar_rail_focused(&self) -> bool { + matches!( + self.focus, + FocusTarget::MachineRail + | FocusTarget::WorkspaceRail + | FocusTarget::TabsRail + | FocusTarget::ProjectionRail(_) + ) + } + + fn focused_rail_kind(&self) -> Option { + match self.focus { + FocusTarget::MachineRail => Some(RailKind::Machine), + FocusTarget::WorkspaceRail => Some(RailKind::Workspace), + FocusTarget::TabsRail => Some(RailKind::Tabs), + FocusTarget::ProjectionRail(index) => Some(RailKind::Projection(index)), + FocusTarget::Pane => None, + } + } + + fn focused_sidebar_view_id(&self) -> Option { + let rail = self.focused_rail_kind()?; + self.view_index_for_rail(rail) + .and_then(|index| self.config.sidebar.views.get(index)) + .map(|view| view.id.clone()) + } + + fn fallback_sidebar_area(&self, kind: RailKind, height: u16) -> Option { + let width_for = |candidate| match candidate { + RailKind::Machine => self.machine_sidebar_width, + RailKind::Workspace => self.sidebar_width, + RailKind::Tabs => self.tabs_sidebar_width, + RailKind::Projection(_) => 0, + }; + let width = width_for(kind); + if width == 0 { + return None; + } + let mut x = 0u16; + for column in &self.config.sidebar.columns { + let candidate = match column.kind { + SidebarColumnKind::Machines => RailKind::Machine, + SidebarColumnKind::Workspaces => RailKind::Workspace, + SidebarColumnKind::Tabs => RailKind::Tabs, + }; + if candidate == kind { + return Some(Rect { x, y: 0, width, height }); + } + x = x.saturating_add(width_for(candidate)); + } + None + } + pub fn machine_sidebar_area(&self, height: u16) -> Option { - self.sidebar_layout.machine.or_else(|| { - (self.machine_sidebar_width > 0).then_some(Rect { - x: 0, - y: 0, - width: self.machine_sidebar_width, - height, - }) - }) + self.sidebar_layout + .machine + .or_else(|| self.fallback_sidebar_area(RailKind::Machine, height)) } pub fn workspace_sidebar_area(&self, height: u16) -> Option { - self.sidebar_layout.workspace.or_else(|| { - (self.sidebar_width > 0).then_some(Rect { - x: self.machine_sidebar_width, - y: 0, - width: self.sidebar_width, - height, + self.sidebar_layout + .workspace + .or_else(|| self.fallback_sidebar_area(RailKind::Workspace, height)) + } + + pub fn tabs_sidebar_area(&self, height: u16) -> Option { + self.sidebar_layout.tabs.or_else(|| self.fallback_sidebar_area(RailKind::Tabs, height)) + } + + pub(crate) fn projection_sidebar_area(&self, index: usize) -> Option { + self.sidebar_layout.rail(RailKind::Projection(index)) + } + + pub(crate) fn projection_sidebar_focused(&self, index: usize) -> bool { + self.focus == FocusTarget::ProjectionRail(index) + } + + pub(crate) fn projection_rows(&self, index: usize) -> Vec { + let Some(spec) = self.config.sidebar.views.get(index) else { return Vec::new() }; + let empty_collapsed = HashSet::new(); + let collapsed = self + .projection_rails + .get(&spec.id) + .map(|state| &state.collapsed) + .unwrap_or(&empty_collapsed); + let agents = if spec.includes(SidebarResourceKind::Agents) { + // Finished reports are historical records, not active agents. + // Otherwise detached "surface..." rows remain forever after exit. + self.session + .agents() + .into_iter() + .filter(|agent| !matches!(agent.state.as_str(), "done" | "unknown")) + .collect::>() + } else { + Vec::new() + }; + crate::sidebar_projection::rows( + spec, + &self.tree, + &agents, + self.sidebar_workspace_selection, + collapsed, + ) + } + + pub(crate) fn sidebar_action_rows(&self, index: usize) -> Vec { + let Some(spec) = self.config.sidebar.views.get(index) else { return Vec::new() }; + let messages = &localization::catalog().sidebar; + spec.actions + .iter() + .copied() + .flat_map(|action| { + if action == Action::NewWorkspace { + return self + .workspace_creation_modes() + .into_iter() + .map(|mode| SidebarActionRow { + label: match mode { + None => messages.new_workspace.to_string(), + Some(WorkspaceCreationMode::Isolated) => { + messages.new_isolated_workspace.to_string() + } + Some(WorkspaceCreationMode::Host) => { + messages.new_shared_workspace.to_string() + } + }, + target: SidebarActionTarget::CreateWorkspace(mode), + }) + .collect::>(); + } + self.action_available(action) + .then(|| SidebarActionRow { + label: localization::catalog().action_label(action).to_string(), + target: SidebarActionTarget::Run(action), + }) + .into_iter() + .collect() }) - }) + .collect() + } + + pub(crate) fn projection_rail_state_mut(&mut self, index: usize) -> &mut ProjectionRailState { + let id = self + .config + .sidebar + .views + .get(index) + .map(|view| view.id.clone()) + .unwrap_or_else(|| format!("missing-{index}")); + self.projection_rails.entry(id).or_default() + } + + fn invoke_sidebar_action( + &mut self, + target: SidebarActionTarget, + ) -> anyhow::Result { + match target { + SidebarActionTarget::Run(action) => self.run_action(action), + SidebarActionTarget::CreateWorkspace(mode) => { + self.create_workspace(mode, None)?; + Ok(RenderAction::Draw) + } + } + } + + pub(crate) fn sidebar_tab_targets(&self) -> Vec { + if self.workspace_rail_selection != WorkspaceRailSelection::Workspace { + return Vec::new(); + } + let workspace_index = + self.sidebar_workspace_selection.min(self.tree.workspaces.len().saturating_sub(1)); + let Some(workspace) = self.tree.workspaces.get(workspace_index) else { + return Vec::new(); + }; + workspace + .screens + .iter() + .enumerate() + .flat_map(|(screen_index, screen)| { + screen.panes.iter().flat_map(move |pane| { + pane.tabs.iter().enumerate().map(move |(tab_index, tab)| { + let name = tab + .name + .as_deref() + .filter(|name| !name.is_empty()) + .or_else(|| (!tab.title.is_empty()).then_some(tab.title.as_str())) + .unwrap_or(tab.short_id.as_str()) + .to_string(); + let subtitle = if workspace.screens.len() > 1 { + format!("{} · {}", screen.display_name(screen_index), pane.short_id) + } else { + pane.short_id.clone() + }; + let active = workspace_index == self.tree.active_workspace + && screen_index == workspace.active_screen + && pane.id == screen.active_pane + && tab_index == pane.active_tab; + SidebarTabTarget { + workspace: workspace_index, + screen: screen_index, + pane: pane.id, + index: tab_index, + surface: tab.surface, + name, + subtitle, + active, + } + }) + }) + }) + .collect() + } + + fn activate_sidebar_tab(&mut self, target: &SidebarTabTarget) -> anyhow::Result<()> { + if !self.prepare_pty_input_before_mutation() { + return Ok(()); + } + if !self.tree.select_surface(target.surface) { + return Ok(()); + } + self.follow_sidebar_workspace(target.workspace); + self.pane_focus_history.record(target.pane); + self.claim_active_terminal_geometry(true); + Ok(()) + } + + fn follow_sidebar_workspace(&mut self, index: usize) { + if self.sidebar_workspace_selection != index { + self.tabs_rail_selection = 0; + self.tabs_rail_scroll = 0; + } + self.sidebar_workspace_selection = index; + self.workspace_rail_selection = WorkspaceRailSelection::Workspace; + } + + fn activate_workspace(&mut self, index: usize) { + if index >= self.tree.workspaces.len() || !self.prepare_pty_input_before_mutation() { + return; + } + self.follow_sidebar_workspace(index); + self.tree.active_workspace = index; + self.select_workspace_for_client(Some(index), None); + } + + fn activate_projection_target(&mut self, target: ProjectionTarget) -> anyhow::Result<()> { + match target { + ProjectionTarget::Workspace { index, .. } => { + self.activate_workspace(index); + } + ProjectionTarget::Pane { workspace, screen, pane } => { + if !self.prepare_pty_input_before_mutation() { + return Ok(()); + } + self.follow_sidebar_workspace(workspace); + self.tree.active_workspace = workspace; + if let Some(workspace_view) = self.tree.workspaces.get_mut(workspace) { + workspace_view.active_screen = screen; + if let Some(screen_view) = workspace_view.screens.get_mut(screen) { + screen_view.active_pane = pane; + } + } + self.pane_focus_history.record(pane); + self.claim_active_terminal_geometry(true); + } + ProjectionTarget::Surface { workspace, screen, pane, index, surface, .. } => { + self.activate_sidebar_tab(&SidebarTabTarget { + workspace, + screen, + pane, + index, + surface, + name: String::new(), + subtitle: String::new(), + active: false, + })?; + } + } + Ok(()) } pub fn total_sidebar_width(&self) -> u16 { @@ -7777,12 +8681,134 @@ impl App { if layout_width > 0 { layout_width } else { - self.machine_sidebar_width.saturating_add(self.sidebar_width) + self.machine_sidebar_width + .saturating_add(self.sidebar_width) + .saturating_add(self.tabs_sidebar_width) + } + } + + fn visible_rail_order(&self) -> Vec { + self.sidebar_layout.ordered.iter().map(|placement| placement.kind).collect() + } + + fn focusable_rail_order(&self) -> Vec { + let order = self.visible_rail_order(); + if !order.is_empty() { + return order; + } + let size = ( + self.sidebar_layout.content.x.saturating_add(self.sidebar_layout.content.width), + self.sidebar_layout.content.height.saturating_add(1), + ); + if size.0 == 0 || size.1 == 0 { + return Vec::new(); } + let hidden_views = self + .hidden_sidebar_views + .get(&self.config.sidebar.active_profile) + .cloned() + .unwrap_or_default(); + sidebar_layout_for_state( + &self.config, + true, + self.sidebar_compact, + self.machine_ui.is_some(), + size, + self.sidebar_width_override, + self.machine_sidebar_width_override, + self.tabs_sidebar_width_override, + &self.projection_sidebar_width_overrides, + &hidden_views, + None, + ) + .ordered + .iter() + .map(|placement| placement.kind) + .collect() + } + + fn rail_kind_for_view(&self, index: usize) -> RailKind { + self.config.sidebar.views.get(index).and_then(|view| view.legacy_kind()).map_or( + RailKind::Projection(index), + |kind| match kind { + SidebarColumnKind::Machines => RailKind::Machine, + SidebarColumnKind::Workspaces => RailKind::Workspace, + SidebarColumnKind::Tabs => RailKind::Tabs, + }, + ) + } + + pub(crate) fn view_index_for_rail(&self, kind: RailKind) -> Option { + self.sidebar_layout + .ordered + .iter() + .find(|placement| placement.kind == kind) + .map(|placement| placement.view_index) + .or_else(|| { + self.config.sidebar.views.iter().enumerate().find_map(|(index, _)| { + (self.rail_kind_for_view(index) == kind).then_some(index) + }) + }) + } + + pub(crate) fn workspace_sidebar_action_rows(&self) -> Vec { + self.view_index_for_rail(RailKind::Workspace) + .map(|index| self.sidebar_action_rows(index)) + .unwrap_or_default() + } + + fn focus_rail(&mut self, kind: RailKind) { + self.focus = match kind { + RailKind::Machine => FocusTarget::MachineRail, + RailKind::Workspace => FocusTarget::WorkspaceRail, + RailKind::Tabs => FocusTarget::TabsRail, + RailKind::Projection(index) => FocusTarget::ProjectionRail(index), + }; + } + + fn focus_adjacent_rail(&mut self, kind: RailKind, delta: isize) -> bool { + let order = self.visible_rail_order(); + let Some(index) = order.iter().position(|candidate| *candidate == kind) else { + return false; + }; + let next = index as isize + delta; + let Some(next) = usize::try_from(next).ok().filter(|next| *next < order.len()) else { + return false; + }; + self.focus_rail(order[next]); + true + } + + fn move_focus_between_sidebar_rails(&mut self, direction: Direction) -> bool { + let Some(kind) = self.focused_rail_kind() else { return false }; + match direction { + Direction::Left => { + self.focus_adjacent_rail(kind, -1); + true + } + Direction::Right => { + if !self.focus_adjacent_rail(kind, 1) { + self.focus = FocusTarget::Pane; + } + true + } + Direction::Up | Direction::Down => false, + } + } + + fn focus_rightmost_sidebar_rail(&mut self) -> bool { + if !self.sidebar_visible || self.surface_only.is_some() { + return false; + } + let Some(kind) = self.visible_rail_order().last().copied() else { + return false; + }; + self.focus_rail(kind); + true } fn leave_workspace_sidebar(&mut self) { - if self.workspace_sidebar_focused() { + if self.sidebar_rail_focused() { self.focus = FocusTarget::Pane; } } @@ -8056,6 +9082,9 @@ impl App { let Some(request) = self.machine_ui.as_mut().and_then(|ui| ui.request.take()) else { return RenderAction::None; }; + if let MachineRequest::Switch(machine) = &request { + self.select_machine_intent(*machine); + } let Some(worker) = self.machine_action_worker.as_ref() else { if let Some(ui) = self.machine_ui.as_mut() { ui.request = Some(request); @@ -8072,8 +9101,20 @@ impl App { }; match worker.perform(request.clone(), preparation) { Ok(()) => { + self.machine_action_connection_attempt = self + .connection_transaction + .as_ref() + .filter(|transaction| { + matches!( + &request, + MachineRequest::Connect { target, route } + if target == &transaction.target && route == &transaction.route + ) + }) + .map(|transaction| transaction.attempt); self.machine_action_in_flight = true; self.machine_action_request = Some(request); + self.machine_action_intent_generation = Some(self.machine_selection_generation); } Err(MachineSubmitError::Busy(request)) => { if let Some(ui) = self.machine_ui.as_mut() { @@ -8111,8 +9152,103 @@ impl App { self.machine_provider_reconnect_retry_at = None; } - fn take_machine_action_was_provider_reconnect(&mut self) -> bool { - matches!(self.machine_action_request.take(), Some(MachineRequest::ReconnectProvider)) + fn connection_attempt_was_canceled(&self, attempt: Option) -> bool { + attempt.is_some() && self.canceled_machine_connection_attempt == attempt + } + + fn take_machine_action_request(&mut self) -> (Option, Option, bool) { + self.machine_action_intent_generation = None; + let request = self.machine_action_request.take(); + let attempt = self.machine_action_connection_attempt.take(); + let canceled = self.connection_attempt_was_canceled(attempt); + if canceled { + self.canceled_machine_connection_attempt = None; + } + (request, attempt, canceled) + } + + fn connection_request_matches( + &self, + request: Option<&MachineRequest>, + attempt: Option, + ) -> bool { + let Some(transaction) = self.connection_transaction.as_ref() else { return false }; + attempt == Some(transaction.attempt) + && matches!( + request, + Some(MachineRequest::Connect { target, route }) + if target == &transaction.target && route == &transaction.route + ) + } + + fn advance_connection_transaction( + &mut self, + request: Option<&MachineRequest>, + attempt: Option, + phase: ConnectionDialogPhase, + ) { + if self.connection_request_matches(request, attempt) + && let Some(transaction) = self.connection_transaction.as_mut() + { + transaction.phase = phase; + } + } + + fn fail_connection_transaction( + &mut self, + request: Option<&MachineRequest>, + attempt: Option, + error: String, + ) -> bool { + if !self.connection_request_matches(request, attempt) { + return false; + } + self.advance_connection_transaction( + request, + attempt, + ConnectionDialogPhase::Failed(error.clone()), + ); + self.status_message = Some(error); + true + } + + fn report_machine_action_failure( + &mut self, + request: Option<&MachineRequest>, + attempt: Option, + message: String, + ) { + let is_connection = matches!(request, Some(MachineRequest::Connect { .. })); + let matched = self.fail_connection_transaction(request, attempt, message.clone()); + if !matched && (!is_connection || self.connection_transaction.is_none()) { + self.status_message = Some(message); + } + } + + fn complete_connection_transaction( + &mut self, + request: Option<&MachineRequest>, + attempt: Option, + ) { + if !self.connection_request_matches(request, attempt) { + return; + } + self.connection_transaction = None; + if self + .prompt + .as_ref() + .is_some_and(|prompt| matches!(prompt.target, PromptTarget::ConnectMachine(_))) + { + self.prompt = None; + } + } + + fn fail_machine_action(&mut self, request: Option<&MachineRequest>) { + if let Some(MachineRequest::Switch(machine)) = request + && let Some(ui) = self.machine_ui.as_mut() + { + ui.set_connection_phase(*machine, MachineConnectionPhase::Failed); + } } fn apply_machine_controller_completion( @@ -8163,17 +9299,30 @@ impl App { } MachineControllerCompletion::Action { result, updates } => { self.machine_action_in_flight = false; - let reconnecting = self.take_machine_action_was_provider_reconnect(); + let (request, connection_attempt, connection_canceled) = + self.take_machine_action_request(); + let reconnecting = + matches!(request.as_ref(), Some(MachineRequest::ReconnectProvider)); + if connection_canceled { + drop((result, updates)); + return RenderAction::Draw; + } let result = match result { Ok(result) => result, Err(error) => { + self.fail_machine_action(request.as_ref()); if reconnecting { self.schedule_machine_provider_reconnect(); } - self.status_message = Some(format!( + let message = format!( "{}: {error}", localization::catalog().sidebar.machine_action_failed - )); + ); + self.report_machine_action_failure( + request.as_ref(), + connection_attempt, + message, + ); return RenderAction::Draw; } }; @@ -8209,44 +9358,83 @@ impl App { )); action = action.merge(RenderAction::Draw); } + self.complete_connection_transaction(request.as_ref(), connection_attempt); action } MachineControllerCompletion::ReplacementPrepared { action_id, action } => { + let connection_canceled = + self.connection_attempt_was_canceled(self.machine_action_connection_attempt); if self.pending_machine_replacement.is_some() { if let Some(worker) = self.machine_action_worker.as_ref() { let _ = worker.abort_replacement(action_id); } self.machine_action_in_flight = false; - if self.take_machine_action_was_provider_reconnect() { + let (request, connection_attempt, connection_canceled) = + self.take_machine_action_request(); + self.fail_machine_action(request.as_ref()); + if matches!(request.as_ref(), Some(MachineRequest::ReconnectProvider)) { self.schedule_machine_provider_reconnect(); } - self.status_message = Some(format!( + let message = format!( "{}: {}", localization::catalog().sidebar.machine_action_failed, localization::catalog().sidebar.machine_replacement_pending - )); + ); + if !connection_canceled { + self.report_machine_action_failure( + request.as_ref(), + connection_attempt, + message, + ); + } return RenderAction::Draw; } + let request = self.machine_action_request.clone(); + self.advance_connection_transaction( + request.as_ref(), + self.machine_action_connection_attempt, + ConnectionDialogPhase::Starting, + ); + let present = !connection_canceled + && self.machine_action_intent_generation + == Some(self.machine_selection_generation) + && match self.machine_action_request.as_ref() { + Some(MachineRequest::Switch(_)) => action + .session + .machine + .is_none_or(|machine| self.machine_selection_intent == Some(machine)), + _ => true, + }; self.pending_machine_replacement = - Some(PendingMachineReplacement { action_id, action: *action }); + Some(PendingMachineReplacement { action_id, present, action: *action }); if self .machine_action_worker .as_ref() - .is_none_or(|worker| !worker.commit_replacement(action_id)) + .is_none_or(|worker| !worker.commit_replacement(action_id, present)) { self.pending_machine_replacement.take(); self.machine_action_in_flight = false; - if self.take_machine_action_was_provider_reconnect() { + let (request, connection_attempt, connection_canceled) = + self.take_machine_action_request(); + self.fail_machine_action(request.as_ref()); + if matches!(request.as_ref(), Some(MachineRequest::ReconnectProvider)) { self.schedule_machine_provider_reconnect(); } - self.status_message = Some(format!( + let message = format!( "{}: {}", localization::catalog().sidebar.machine_action_failed, localization::catalog().sidebar.machine_replacement_worker_stopped - )); + ); + if !connection_canceled { + self.report_machine_action_failure( + request.as_ref(), + connection_attempt, + message, + ); + } return RenderAction::Draw; } - RenderAction::None + RenderAction::Draw } MachineControllerCompletion::ReplacementSettled { action_id, committed, updates } => { if self @@ -8266,24 +9454,45 @@ impl App { .take() .expect("matching pending replacement was checked"); self.machine_action_in_flight = false; - let reconnecting = self.take_machine_action_was_provider_reconnect(); + let (request, connection_attempt, connection_canceled) = + self.take_machine_action_request(); + let reconnecting = + matches!(request.as_ref(), Some(MachineRequest::ReconnectProvider)); let mut action = RenderAction::None; match committed { Ok(true) => { if reconnecting { self.clear_machine_provider_reconnect(); } + let PendingMachineReplacement { present, action: prepared, .. } = pending; + let present = present && !connection_canceled; let PreparedMachineAction { ui, session_mutation, session_label, session } = - pending.action; - self.install_prepared_machine_session(session); - if let Some(label) = session_label { - self.session_label = label; - } - action = action.merge(self.apply_machine_ui_update(ui)); - // Provider notices apply before local mirror errors so they cannot mask them. - if let Some(mutation) = session_mutation { - self.apply_managed_workspace_session_mutation(mutation); + prepared; + let target = session.machine; + if present { + self.machine_presented = target.or(ui.snapshot.active); + self.install_prepared_machine_session(session, false); + if let Some(label) = session_label { + self.session_label = label; + } + action = action.merge(self.apply_machine_ui_update(ui)); + // Provider notices apply before local mirror errors so they cannot mask them. + if let Some(mutation) = session_mutation { + self.apply_managed_workspace_session_mutation(mutation); + } + if self.tree.active_surface().is_some() { + self.focus = FocusTarget::Pane; + } + } else { + if let Some(target) = target + && let Some(ui) = self.machine_ui.as_mut() + { + ui.set_connection_phase(target, MachineConnectionPhase::Ready); + } + drop((ui, session_mutation, session_label, session)); + action = action.merge(RenderAction::Draw); } + self.complete_connection_transaction(request.as_ref(), connection_attempt); } Ok(false) => { drop(pending); @@ -8293,13 +9502,21 @@ impl App { } Err(error) => { drop(pending); + self.fail_machine_action(request.as_ref()); if reconnecting { self.schedule_machine_provider_reconnect(); } - self.status_message = Some(format!( - "{}: {error}", - localization::catalog().sidebar.machine_action_failed - )); + if !connection_canceled { + let message = format!( + "{}: {error}", + localization::catalog().sidebar.machine_action_failed + ); + self.report_machine_action_failure( + request.as_ref(), + connection_attempt, + message, + ); + } action = action.merge(RenderAction::Draw); } } @@ -8356,6 +9573,16 @@ impl App { } fn apply_machine_ui_update(&mut self, mut update: MachineUiState) -> RenderAction { + if self.machine_ui.is_none() + && self.machine_selection_intent.is_none() + && self.machine_presented.is_none() + { + self.machine_selection_intent = update.snapshot.active; + self.machine_presented = update.snapshot.active; + } + update.snapshot.active = self.machine_presented.filter(|presented| { + update.snapshot.machines.iter().any(|machine| machine.key == *presented) + }); let guard_error = (uses_provider_managed_workspaces(Some(&update)) && !self.session.workspaces_are_provider_managed()) .then(|| self.session.mark_workspaces_provider_managed().err()) @@ -8394,6 +9621,12 @@ impl App { } } if let Some(previous) = self.machine_ui.as_ref() { + if let Some(MachineRequest::Switch(machine)) = previous.request.as_ref() + && self.machine_selection_intent == Some(*machine) + { + update.request = Some(MachineRequest::Switch(*machine)); + } + update.extend_connection_phases_from(previous); update.reconcile_navigation_from(previous); } let notice = update.notice.clone(); @@ -8534,7 +9767,11 @@ impl App { } } - fn install_prepared_machine_session(&mut self, prepared: PreparedMachineSession) { + fn install_prepared_machine_session( + &mut self, + prepared: PreparedMachineSession, + retire_previous: bool, + ) { self.cancel_pointer_interaction(); let PreparedMachineSession { session, @@ -8546,6 +9783,7 @@ impl App { label, session_available, color_error, + machine: _, } = prepared; self.pty_input.activate_session_generation(generation); self.session_generation = generation; @@ -8575,7 +9813,9 @@ impl App { if let Some(mut previous_worker) = previous_worker { previous_worker.stop_and_join(); } - previous_session.begin_shutdown(); + if retire_previous { + previous_session.begin_shutdown(); + } } fn reset_session_presentation(&mut self, tree: TreeView) { @@ -8613,6 +9853,9 @@ impl App { self.tree.active_workspace.min(self.tree.workspaces.len().saturating_sub(1)); self.sidebar_recoverable_workspace_selection = 0; self.workspace_rail_selection = WorkspaceRailSelection::Workspace; + self.tabs_rail_selection = 0; + self.tabs_rail_scroll = 0; + self.tabs_rail_follow_selection = true; self.sidebar_followed_surface = None; self.sidebar_plugin_surface = None; self.sidebar_plugin_error = None; @@ -8724,12 +9967,6 @@ impl App { self.machine_pointer_context_cache.clone() } - fn machine_pointer_target(&mut self, machine: MachineKey) -> Option { - let context = self.refresh_machine_pointer_context()?; - let managed = self.machine_ui.as_ref().and_then(|ui| ui.managed_machine(machine)).cloned(); - Some(MachinePointerTarget { context, machine, managed }) - } - fn pointer_hit_identity( &self, hit: Hit, @@ -8740,7 +9977,8 @@ impl App { | Hit::ConnectMachine | Hit::ProviderScope | Hit::ProviderActions - | Hit::CreateWorkspace { .. } => { + | Hit::CreateWorkspace { .. } + | Hit::SidebarAction { action: SidebarActionTarget::CreateWorkspace(_), .. } => { machine_context.cloned().map(PointerHitIdentity::MachineContext) } Hit::Machine { key, .. } => machine_context.cloned().map(|context| { @@ -8775,8 +10013,18 @@ impl App { .pane(pane) .and_then(|pane| pane.tabs.get(index)) .map(|tab| PointerHitIdentity::Tab(tab.surface)), + Hit::SidebarTab { surface, .. } => Some(PointerHitIdentity::Tab(surface)), + Hit::ProjectionRow { target: ProjectionTarget::Surface { surface, .. }, .. } => { + Some(PointerHitIdentity::Tab(surface)) + } Hit::Workspace { .. } + | Hit::ProjectionRow { .. } + | Hit::ProjectionToggle { .. } + | Hit::RailHeader(_) + | Hit::SidebarAction { .. } | Hit::ScreenEntry { .. } + | Hit::StatusMessage + | Hit::CopyStatusMessage | Hit::NewTab { .. } | Hit::Clients { .. } | Hit::Scrollbar { .. } @@ -8790,6 +10038,10 @@ impl App { fn menu_action_resource(&self, action: MenuAction) -> Option { match action { + MenuAction::RenameSurface(surface) => Some(MenuActionResource::Surface(surface)), + MenuAction::CopyStatusMessage => { + self.status_message.clone().map(MenuActionResource::StatusMessage) + } MenuAction::BrowserBack(pane) | MenuAction::BrowserForward(pane) | MenuAction::BrowserReload(pane) @@ -8832,6 +10084,29 @@ impl App { } }) } + MenuAction::CreateMachineFrom(index) => self + .machine_ui + .as_ref()? + .creation_sources + .get(index) + .map(|source| MenuActionResource::MachineCreationSource(source.id.clone())), + MenuAction::ConnectMachineTarget(index) => { + self.machine_ui.as_ref()?.connection_targets.get(index).map(|target| { + MenuActionResource::MachineConnectionTarget(target.target.clone()) + }) + } + MenuAction::ActivateSidebarProfile(index) => self + .config + .sidebar + .profiles + .get(index) + .map(|profile| MenuActionResource::SidebarProfile(profile.id.clone())), + MenuAction::SetSidebarViewVisible { view, .. } => { + self.config.sidebar.views.get(view).map(|view| MenuActionResource::SidebarView { + profile: self.config.sidebar.active_profile.clone(), + view: view.id.clone(), + }) + } _ => None, } } @@ -8905,6 +10180,7 @@ impl App { .then(|| (self.sidebar_plugin_rect(), self.sidebar_plugin_surface)); let machine_rail = self.sidebar_layout.machine; let workspace_rail = self.sidebar_layout.workspace; + let tabs_rail = self.sidebar_layout.tabs; let pointer_map_generation = self.session.pointer_map_generation(); let reuse_owners = action == RenderAction::Paint && self.rendered_pointer_frame.pointer_map_generation == pointer_map_generation; @@ -8987,6 +10263,7 @@ impl App { sidebar_plugin, machine_rail, workspace_rail, + tabs_rail, hits, panes, terminal_pointer_semantics, @@ -10283,6 +11560,12 @@ impl App { } fn reload_config(&mut self) { + let focused_projection_id = match self.focus { + FocusTarget::ProjectionRail(index) => { + self.config.sidebar.views.get(index).map(|view| view.id.clone()) + } + _ => None, + }; let mut config = crate::config::load(); config.apply_chrome_defaults(self.chrome); let shortcut_rows = self @@ -10295,6 +11578,25 @@ impl App { self.session.apply_config(config.clone()); self.sidebar_view = config.sidebar.view; self.config = config; + let valid_view_ids = + self.config.sidebar.views.iter().map(|view| view.id.clone()).collect::>(); + self.projection_rails.retain(|id, _| valid_view_ids.contains(id)); + self.projection_sidebar_width_overrides.retain(|id, _| valid_view_ids.contains(id)); + if let Some(id) = focused_projection_id { + if let Some((index, view)) = + self.config.sidebar.views.iter().enumerate().find(|(_, view)| view.id == id) + { + let kind = + view.legacy_kind().map_or(RailKind::Projection(index), |kind| match kind { + SidebarColumnKind::Machines => RailKind::Machine, + SidebarColumnKind::Workspaces => RailKind::Workspace, + SidebarColumnKind::Tabs => RailKind::Tabs, + }); + self.focus_rail(kind); + } else { + self.focus = FocusTarget::Pane; + } + } if let (Some(help), Some(rows)) = (self.shortcut_help.as_mut(), shortcut_rows) { help.rows = rows; help.scroll_offset = help.scroll_offset.min(help.max_scroll(help.rows.len())); @@ -10468,13 +11770,20 @@ impl App { /// content sizes to surfaces. fn sync_layout(&mut self, size: (u16, u16)) { let (width, height) = size; - self.sidebar_layout = if self.surface_only.is_some() { + let sidebar_layout = if self.surface_only.is_some() { SidebarLayout { content: Rect { x: 0, y: 0, width, height }, ..SidebarLayout::default() } } else { - sidebar_layout_for( + let hidden_views = self + .hidden_sidebar_views + .get(&self.config.sidebar.active_profile) + .cloned() + .unwrap_or_default(); + let previous = + (!self.sidebar_layout.ordered.is_empty()).then_some(&self.sidebar_layout); + sidebar_layout_for_state( &self.config, self.sidebar_visible, self.sidebar_compact, @@ -10482,16 +11791,30 @@ impl App { size, self.sidebar_width_override, self.machine_sidebar_width_override, + self.tabs_sidebar_width_override, + &self.projection_sidebar_width_overrides, + &hidden_views, + previous, ) }; + self.sidebar_layout = sidebar_layout; self.sidebar_width = self.sidebar_layout.workspace.map_or(0, |rect| rect.width); self.machine_sidebar_width = self.sidebar_layout.machine.map_or(0, |rect| rect.width); + self.tabs_sidebar_width = self.sidebar_layout.tabs.map_or(0, |rect| rect.width); if self.sidebar_width == 0 && self.focus == FocusTarget::WorkspaceRail { self.focus = FocusTarget::Pane; } if self.machine_sidebar_width == 0 && self.focus == FocusTarget::MachineRail { self.focus = FocusTarget::Pane; } + if self.tabs_sidebar_width == 0 && self.focus == FocusTarget::TabsRail { + self.focus = FocusTarget::Pane; + } + if let FocusTarget::ProjectionRail(index) = self.focus + && self.sidebar_layout.rail(RailKind::Projection(index)).is_none() + { + self.focus = FocusTarget::Pane; + } let area = self.sidebar_layout.content; self.content_area = area; if self.surface_only.is_none() { @@ -11286,7 +12609,10 @@ impl App { } AppEvent::Mux(MuxEvent::SurfaceResized { surface, cols, rows, reservation_id }) => { self.session.confirm_surface_resize(surface, (cols, rows), reservation_id); - Ok(RenderAction::Draw) + // This acknowledges geometry already computed by the host-resize draw. + // Re-running layout here creates an acknowledgement feedback loop while + // the outer terminal is being dragged; only repaint terminal content. + Ok(RenderAction::Paint) } AppEvent::Mux(MuxEvent::SurfaceResizeFailed { surface, @@ -11848,7 +13174,12 @@ impl App { text: String, destination: Option, ) -> anyhow::Result { - self.status_message = None; + // A context menu acts on the resources visible when it opened. Keep a + // status message alive while the menu owns input so status actions can + // still validate and copy that exact message. + if self.menu.is_none() && !self.status_message_hovered() { + self.status_message = None; + } if self.pairing_dialog.is_some() || self.shortcut_help.is_some() { Ok(RenderAction::Draw) } else if let Some(prompt) = self.prompt.as_mut() { @@ -11858,7 +13189,10 @@ impl App { clear_omnibar_selection(state); state.input.insert_str(&text); Ok(RenderAction::Draw) - } else if self.machine_sidebar_focused() { + } else if let Some(menu) = self.menu.as_mut() { + menu.insert_search_text(&text); + Ok(RenderAction::Draw) + } else if self.machine_sidebar_focused() || self.tabs_sidebar_focused() { Ok(RenderAction::Draw) } else if self.workspace_sidebar_focused() { if self.config.sidebar.plugin.is_some() { @@ -11957,7 +13291,14 @@ impl App { kind: MouseEventKind::Up(MouseButton::Left), .. }), - Some(Drag::WorkspaceArm { .. } | Drag::TabArm { .. }) + Some(Drag::TabArm { .. }) + ) | ( + TerminalInput::Mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left) + | MouseEventKind::Up(MouseButton::Left), + .. + }), + Some(Drag::WorkspaceArm { .. } | Drag::Workspace { .. }) ) ) } @@ -12841,6 +14182,56 @@ impl App { self.selection = selection; } + pub(crate) fn reset_rendered_status_message(&mut self) { + self.rendered_status_message = None; + } + + pub(crate) fn present_status_message(&mut self, rect: Rect, text: String) { + if self.status_selection.as_ref().is_some_and(|selection| selection.text != text) { + self.status_selection = None; + if matches!(self.drag, Some(Drag::StatusMessage { .. })) { + self.drag = None; + } + } + self.rendered_status_message = Some(RenderedStatusMessage { rect, text }); + } + + pub(crate) fn hide_status_message(&mut self) { + self.rendered_status_message = None; + self.status_selection = None; + if matches!(self.drag, Some(Drag::StatusMessage { .. })) { + self.drag = None; + } + } + + pub(crate) fn status_message_cell_selected(&self, text: &str, cell: u16) -> bool { + self.status_selection.as_ref().is_some_and(|selection| selection.contains(text, cell)) + } + + fn status_message_hovered(&self) -> bool { + self.hover.is_some_and(|(x, y)| { + self.rendered_status_message + .as_ref() + .is_some_and(|rendered| rendered.rect.contains(x, y)) + || self + .hits + .iter() + .any(|(rect, hit)| *hit == Hit::CopyStatusMessage && rect.contains(x, y)) + }) + } + + fn begin_status_message_selection(&mut self, x: u16) -> bool { + let Some(rendered) = self.rendered_status_message.clone() else { return false }; + if rendered.rect.width == 0 || !rendered.rect.contains(x, rendered.rect.y) { + return false; + } + let cell = x.saturating_sub(rendered.rect.x).min(rendered.rect.width - 1); + self.status_selection = + Some(StatusMessageSelection { text: rendered.text, anchor: cell, head: cell }); + self.drag = Some(Drag::StatusMessage { rect: rendered.rect }); + true + } + fn selection_auto_scroll_active(&self) -> bool { matches!(self.drag, Some(Drag::Select { auto_scroll: Some(_), .. })) } @@ -13091,6 +14482,15 @@ impl App { self.machine_ui.as_ref()?.managed_machine(key).cloned() } + fn request_rename_client_machine(&mut self, key: MachineKey, name: String) { + if !self.machine_ui.as_ref().is_some_and(|ui| ui.is_client_machine_renamable(key)) { + return; + } + if let Some(ui) = self.machine_ui.as_mut() { + ui.request = Some(MachineRequest::RenameClientMachine { machine: key, name }); + } + } + fn request_rename_managed_machine(&mut self, key: MachineKey, name: String) { let Some(machine) = self.managed_machine(key).filter(|machine| { machine.status == ManagedMachineStatus::Active && machine.capabilities.rename @@ -13134,6 +14534,25 @@ impl App { } } + fn activate_machine(&mut self, key: MachineKey) { + self.select_machine_intent(key); + if self.managed_machine(key).is_some_and(|machine| { + machine.status == ManagedMachineStatus::Recoverable && machine.capabilities.restore + }) { + self.request_restore_managed_machine(key); + } else { + let needs_switch = self.machine_presented != Some(key) + || self.machine_ui.as_ref().is_some_and(|ui| !ui.session_available); + if let Some(ui) = self.machine_ui.as_mut() { + if needs_switch { + ui.request = Some(MachineRequest::Switch(key)); + } else if matches!(ui.request, Some(MachineRequest::Switch(_))) { + ui.request = None; + } + } + } + } + fn request_purge_managed_machine(&mut self, key: MachineKey) { let Some(machine) = self.managed_machine(key).filter(|machine| { machine.status == ManagedMachineStatus::Recoverable && machine.capabilities.purge @@ -13162,6 +14581,36 @@ impl App { )); } + fn open_rename_client_machine_prompt(&mut self, key: MachineKey) { + let Some(ui) = self.machine_ui.as_ref().filter(|ui| ui.is_client_machine_renamable(key)) + else { + return; + }; + let Some(name) = ui + .snapshot + .machines + .iter() + .find(|machine| machine.key == key) + .map(|machine| machine.name.clone()) + else { + return; + }; + self.cancel_pty_mouse_drag(); + self.prompt = Some(Prompt::new( + localization::catalog().sidebar.rename_machine, + name, + PromptTarget::ClientMachine(key), + )); + } + + fn open_rename_machine_prompt(&mut self, key: MachineKey) { + if self.managed_machine(key).is_some() { + self.open_rename_managed_machine_prompt(key); + } else { + self.open_rename_client_machine_prompt(key); + } + } + fn open_delete_managed_machine_prompt(&mut self, key: MachineKey) { if self.managed_machine(key).is_some_and(|machine| { machine.status == ManagedMachineStatus::Active && machine.capabilities.delete @@ -13348,8 +14797,11 @@ impl App { .flat_map(MachineUiState::recoverable_workspaces) .map(|workspace| WorkspaceRailTarget::Recoverable(workspace.id.clone())), ); - targets - .extend(self.workspace_creation_modes().into_iter().map(WorkspaceRailTarget::Create)); + targets.extend( + self.workspace_sidebar_action_rows() + .into_iter() + .map(|action| WorkspaceRailTarget::Action(action.target)), + ); targets } @@ -13369,10 +14821,7 @@ impl App { .copied() }) .map(|workspace| WorkspaceRailTarget::Recoverable(workspace.id.clone())), - WorkspaceRailSelection::SessionCreation => Some(WorkspaceRailTarget::Create(None)), - WorkspaceRailSelection::ManagedCreation(mode) => { - Some(WorkspaceRailTarget::Create(Some(mode))) - } + WorkspaceRailSelection::Action(action) => Some(WorkspaceRailTarget::Action(action)), } } @@ -13382,6 +14831,10 @@ impl App { if let Some(index) = self.tree.workspaces.iter().position(|workspace| workspace.id == id) { + if self.sidebar_workspace_selection != index { + self.tabs_rail_selection = 0; + self.tabs_rail_scroll = 0; + } self.sidebar_workspace_selection = index; self.workspace_rail_selection = WorkspaceRailSelection::Workspace; } @@ -13394,8 +14847,8 @@ impl App { self.workspace_rail_selection = WorkspaceRailSelection::Recoverable; } } - WorkspaceRailTarget::Create(mode) => { - self.workspace_rail_selection = workspace_creation_selection(mode); + WorkspaceRailTarget::Action(action) => { + self.workspace_rail_selection = WorkspaceRailSelection::Action(action); } } } @@ -13417,7 +14870,9 @@ impl App { if input.is_composing() || input.is_modifier_only() || input.is_release() { return KeyboardIngress::Ignored; } - self.status_message = None; + if self.menu.is_none() && !self.status_message_hovered() { + self.status_message = None; + } if self.pairing_dialog.is_some() || self.shortcut_help.is_some() || self.prompt.is_some() @@ -13524,6 +14979,15 @@ impl App { destination: Option, ) -> anyhow::Result { let key = input.ui_key(); + if key.kind == KeyEventKind::Release { + return Ok(RenderAction::None); + } + // A context menu acts on the resources visible when it opened. Keep a + // status message alive while the menu owns input so status actions can + // still validate and copy that exact message. + if self.menu.is_none() && !self.status_message_hovered() { + self.status_message = None; + } if self.pairing_dialog.is_some() { return self.handle_pairing_key(key); } @@ -13537,6 +15001,11 @@ impl App { return self.handle_prompt_key(key); } if self.menu.is_some() { + if let Some(text) = input.text_for_direct_input() + && self.menu.as_mut().is_some_and(|menu| menu.insert_search_text(text)) + { + return Ok(RenderAction::Draw); + } return self.handle_menu_key(key); } if self.omnibar.is_some() { @@ -13548,6 +15017,12 @@ impl App { if self.machine_sidebar_focused() { return Ok(self.handle_machine_sidebar_key(&key)); } + if self.tabs_sidebar_focused() { + return self.handle_tabs_sidebar_key(&key); + } + if let FocusTarget::ProjectionRail(index) = self.focus { + return self.handle_projection_sidebar_key(index, &key); + } if self.workspace_sidebar_focused() { if self.config.sidebar.plugin.is_some() { self.forward_sidebar_key(input); @@ -13577,9 +15052,13 @@ impl App { } fn handle_machine_sidebar_key(&mut self, key: &KeyEvent) -> RenderAction { + if matches!(key.code, KeyCode::Left | KeyCode::Char('h')) { + self.focus_adjacent_rail(RailKind::Machine, -1); + return RenderAction::Draw; + } if matches!(key.code, KeyCode::Right | KeyCode::Char('l')) { - if self.sidebar_layout.workspace.is_some() { - self.focus = FocusTarget::WorkspaceRail; + if !self.focus_adjacent_rail(RailKind::Machine, 1) { + self.focus = FocusTarget::Pane; } return RenderAction::Draw; } @@ -13587,6 +15066,20 @@ impl App { self.focus = FocusTarget::Pane; return RenderAction::Draw; } + if key.code == KeyCode::Enter + && self.machine_ui.as_ref().is_some_and(|machine| { + matches!( + machine.rail_target(), + Some(MachineRailTarget::Machine(key)) + if Some(key) == machine.snapshot.active && machine.session_available + ) + }) + { + // Enter on the open machine means "enter the machine", not + // "remain trapped in its rail row". + self.focus = FocusTarget::Pane; + return RenderAction::Draw; + } if matches!( key.code, KeyCode::Up @@ -13619,12 +15112,14 @@ impl App { targets.get(current).copied() { let managed = machine.managed_machine(machine_key); + let client_renamable = machine.is_client_machine_renamable(machine_key); match key.code { KeyCode::Char('r') - if managed.is_some_and(|managed| { - managed.status == ManagedMachineStatus::Active - && managed.capabilities.rename - }) => + if client_renamable + || managed.is_some_and(|managed| { + managed.status == ManagedMachineStatus::Active + && managed.capabilities.rename + }) => { Some(MachineRailCommand::Rename(machine_key)) } @@ -13645,15 +15140,13 @@ impl App { Some(MachineRailCommand::Purge(machine_key)) } KeyCode::Enter - if managed.is_some_and(|managed| { - managed.status == ManagedMachineStatus::Recoverable - && managed.capabilities.restore - }) => + if Some(machine_key) != machine.snapshot.active + || managed.is_some_and(|managed| { + managed.status == ManagedMachineStatus::Recoverable + && managed.capabilities.restore + }) => { - Some(MachineRailCommand::Restore(machine_key)) - } - KeyCode::Enter if Some(machine_key) != machine.snapshot.active => { - Some(MachineRailCommand::Switch(machine_key)) + Some(MachineRailCommand::Activate(machine_key)) } _ => None, } @@ -13670,53 +15163,243 @@ impl App { } }; match command { - Some(MachineRailCommand::Switch(machine)) => { - if let Some(ui) = self.machine_ui.as_mut() { - ui.request = Some(MachineRequest::Switch(machine)); - } + Some(MachineRailCommand::Activate(machine)) => { + self.activate_machine(machine); + self.focus = FocusTarget::Pane; } Some(MachineRailCommand::Rename(machine)) => { - self.open_rename_managed_machine_prompt(machine); + self.open_rename_machine_prompt(machine); } Some(MachineRailCommand::Delete(machine)) => { self.open_delete_managed_machine_prompt(machine); } - Some(MachineRailCommand::Restore(machine)) => { - self.request_restore_managed_machine(machine); - } Some(MachineRailCommand::Purge(machine)) => { self.open_purge_managed_machine_prompt(machine); } Some(MachineRailCommand::OpenScopes) => self.open_provider_scope_menu(1, 2), Some(MachineRailCommand::OpenActions) => self.open_provider_actions_menu(1, 3), Some(MachineRailCommand::Create) => { - if let Some(ui) = self.machine_ui.as_mut() { - ui.request = Some(MachineRequest::Create); - } + self.open_machine_creation_menu(1, 3); } Some(MachineRailCommand::Connect) => { - self.prompt = Some(self.connect_machine_prompt()); + self.open_machine_connection_menu(1, 3); } None => {} } RenderAction::Draw } - fn connect_machine_prompt(&self) -> Prompt { - let messages = &localization::catalog().sidebar; + fn handle_projection_sidebar_key( + &mut self, + view_index: usize, + key: &KeyEvent, + ) -> anyhow::Result { + if key.code == KeyCode::Esc { + self.focus = FocusTarget::Pane; + return Ok(RenderAction::Draw); + } + let rows = self.projection_rows(view_index); + let actions = self.sidebar_action_rows(view_index); + let selectable_rows = rows.len().saturating_add(actions.len()); + let current = self + .config + .sidebar + .views + .get(view_index) + .and_then(|view| self.projection_rails.get(&view.id)) + .map_or(0, |state| match state.selected_action { + Some(index) if index < actions.len() => rows.len().saturating_add(index), + Some(_) => selectable_rows, + None => state.selected.min(selectable_rows.saturating_sub(1)), + }); + let selected = rows.get(current).cloned(); + if matches!(key.code, KeyCode::Left | KeyCode::Char('h')) { + if !key.modifiers.contains(KeyModifiers::ALT) + && let Some(branch) = selected.as_ref().and_then(|row| row.branch) + && selected.as_ref().is_some_and(|row| row.expanded) + { + self.projection_rail_state_mut(view_index).collapsed.insert(branch); + } else { + self.focus_adjacent_rail(RailKind::Projection(view_index), -1); + } + return Ok(RenderAction::Draw); + } + if matches!(key.code, KeyCode::Right | KeyCode::Char('l')) { + if !key.modifiers.contains(KeyModifiers::ALT) + && let Some(branch) = selected.as_ref().and_then(|row| row.branch) + && selected.as_ref().is_some_and(|row| !row.expanded) + { + self.projection_rail_state_mut(view_index).collapsed.remove(&branch); + } else if !self.focus_adjacent_rail(RailKind::Projection(view_index), 1) { + self.focus = FocusTarget::Pane; + } + return Ok(RenderAction::Draw); + } + let page = self + .projection_sidebar_area(view_index) + .map_or(1, |area| usize::from(area.height.saturating_sub(2)).max(1)); + if let Some(next) = rail_navigation_index(key, current, selectable_rows, page) { + let state = self.projection_rail_state_mut(view_index); + if next < rows.len() { + state.selected = next; + state.selected_action = None; + } else { + state.selected_action = Some(next.saturating_sub(rows.len())); + } + state.follow_selection = true; + return Ok(RenderAction::Draw); + } + if matches!(key.code, KeyCode::Char(' ')) + && let Some(branch) = selected.as_ref().and_then(|row| row.branch) + { + let state = self.projection_rail_state_mut(view_index); + if !state.collapsed.remove(&branch) { + state.collapsed.insert(branch); + } + return Ok(RenderAction::Draw); + } + if key.code == KeyCode::Enter { + if let Some(row) = selected { + self.activate_projection_target(row.target)?; + self.focus = FocusTarget::Pane; + } else if let Some(action) = current + .checked_sub(rows.len()) + .and_then(|index| actions.get(index)) + .map(|action| action.target) + { + return self.invoke_sidebar_action(action); + } + } + Ok(RenderAction::Draw) + } + + fn open_machine_creation_menu(&mut self, x: u16, y: u16) { + let sources = + self.machine_ui.as_ref().map(|ui| ui.creation_sources.clone()).unwrap_or_default(); + match sources.as_slice() { + [] => { + if let Some(ui) = self.machine_ui.as_mut() { + ui.request = Some(MachineRequest::Create); + } + } + [source] => { + if let Some(ui) = self.machine_ui.as_mut() { + ui.request = Some(MachineRequest::CreateFrom { source_id: source.id.clone() }); + } + } + _ => { + let items = sources + .iter() + .enumerate() + .map(|(index, source)| MenuItem::LabeledAction { + label: if source.subtitle.is_empty() { + source.name.clone() + } else { + format!("{} · {}", source.name, source.subtitle) + }, + action: MenuAction::CreateMachineFrom(index), + }) + .collect::>(); + self.menu = Some(ContextMenu::with_groups(x, y, vec![items])); + self.capture_menu_resources(); + } + } + } + + fn open_machine_connection_menu(&mut self, x: u16, y: u16) { if self.machine_ui.as_ref().is_some_and(|ui| ui.connect_accepts_pairing_code) { - Prompt::new( - messages.connect_prompt, - String::new(), - PromptTarget::ConnectMachine(MachineConnectRoute::Provider), - ) - } else { - Prompt::new( - messages.connect_host_prompt, - String::new(), - PromptTarget::ConnectMachine(MachineConnectRoute::Local), - ) + let prompt = self.connect_machine_prompt(); + self.prompt = Some(prompt); + return; + } + let targets = + self.machine_ui.as_ref().map(|ui| ui.connection_targets.clone()).unwrap_or_default(); + if targets.is_empty() { + let prompt = self.connect_machine_prompt(); + self.prompt = Some(prompt); + return; } + let targets = targets + .iter() + .enumerate() + .map(|(index, target)| MenuItem::LabeledAction { + label: target.name.clone(), + action: MenuAction::ConnectMachineTarget(index), + }) + .collect::>(); + let messages = &localization::catalog().sidebar; + self.menu = Some(ContextMenu::searchable( + x, + y, + messages.ssh_hosts, + messages.type_to_filter, + targets, + vec![MenuItem::Action(MenuAction::ConnectOtherMachine)], + )); + self.capture_menu_resources(); + } + + fn connect_machine_prompt(&mut self) -> Prompt { + let messages = &localization::catalog().sidebar; + let (label, route) = + if self.machine_ui.as_ref().is_some_and(|ui| ui.connect_accepts_pairing_code) { + (messages.connect_prompt, MachineConnectRoute::Provider) + } else { + (messages.connect_host_prompt, MachineConnectRoute::Local) + }; + self.connection_transaction = Some(ConnectionTransaction { + attempt: self.next_connection_attempt, + target: String::new(), + route, + phase: ConnectionDialogPhase::Editing, + }); + Prompt::new(label, String::new(), PromptTarget::ConnectMachine(route)) + } + + fn begin_machine_connection(&mut self, target: String, route: MachineConnectRoute) { + let target = target.trim().to_string(); + if target.is_empty() { + return; + } + if let Some(ConnectionTransaction { phase: ConnectionDialogPhase::Failed(error), .. }) = + self.connection_transaction.as_ref() + && self.status_message.as_deref() == Some(error.as_str()) + { + self.status_message = None; + self.status_selection = None; + } + let attempt = self.next_connection_attempt; + self.next_connection_attempt = self.next_connection_attempt.wrapping_add(1).max(1); + self.connection_transaction = Some(ConnectionTransaction { + attempt, + target: target.clone(), + route, + phase: ConnectionDialogPhase::Connecting, + }); + let label = match route { + MachineConnectRoute::Local => localization::catalog().sidebar.connect_host_prompt, + MachineConnectRoute::Provider => localization::catalog().sidebar.connect_prompt, + }; + self.prompt = Some(Prompt::new(label, target.clone(), PromptTarget::ConnectMachine(route))); + if let Some(machine) = self.machine_ui.as_mut() { + machine.request = Some(MachineRequest::Connect { target, route }); + } + } + + fn retry_machine_connection(&mut self) { + let Some(transaction) = self.connection_transaction.clone() else { return }; + self.begin_machine_connection(transaction.target, transaction.route); + } + + fn copy_connection_error(&mut self) { + let Some(ConnectionTransaction { phase: ConnectionDialogPhase::Failed(error), .. }) = + self.connection_transaction.as_ref() + else { + return; + }; + let error = error.clone(); + self.copy_text_to_clipboard(&error); + self.show_toast("Copied".to_string()); } fn open_provider_scope_menu(&mut self, x: u16, y: u16) { @@ -13874,10 +15557,22 @@ impl App { if key.code == KeyCode::Tab { return self.run_action(Action::ToggleSidebarView); } - if matches!(key.code, KeyCode::Left | KeyCode::Char('h')) - && self.sidebar_layout.machine.is_some() + if matches!(key.code, KeyCode::Left | KeyCode::Char('h')) { + let moved = self.focus_adjacent_rail(RailKind::Workspace, -1); + if moved + || self.sidebar_view == SidebarView::Workspaces + || key.modifiers.contains(KeyModifiers::ALT) + { + return Ok(RenderAction::Draw); + } + } + if (self.sidebar_view == SidebarView::Workspaces + || key.modifiers.contains(KeyModifiers::ALT)) + && matches!(key.code, KeyCode::Right | KeyCode::Char('l')) { - self.focus = FocusTarget::MachineRail; + if !self.focus_adjacent_rail(RailKind::Workspace, 1) { + self.focus = FocusTarget::Pane; + } return Ok(RenderAction::Draw); } if key.code == KeyCode::Esc { @@ -13920,13 +15615,15 @@ impl App { self.tree.workspaces.iter().position(|workspace| workspace.id == id) { self.select_workspace_for_client(Some(index), None); + self.focus = FocusTarget::Pane; } } - Some(WorkspaceRailTarget::Create(mode)) => { - self.create_workspace(mode, None)?; + Some(WorkspaceRailTarget::Action(action)) => { + return self.invoke_sidebar_action(action); } Some(WorkspaceRailTarget::Recoverable(id)) => { self.request_restore_managed_workspace(&id); + self.focus = FocusTarget::Pane; } None => {} } @@ -13936,6 +15633,49 @@ impl App { Ok(RenderAction::Draw) } + fn handle_tabs_sidebar_key(&mut self, key: &KeyEvent) -> anyhow::Result { + if matches!(key.code, KeyCode::Left | KeyCode::Char('h')) { + self.focus_adjacent_rail(RailKind::Tabs, -1); + return Ok(RenderAction::Draw); + } + if matches!(key.code, KeyCode::Right | KeyCode::Char('l')) { + if !self.focus_adjacent_rail(RailKind::Tabs, 1) { + self.focus = FocusTarget::Pane; + } + return Ok(RenderAction::Draw); + } + if key.code == KeyCode::Esc { + self.focus = FocusTarget::Pane; + return Ok(RenderAction::Draw); + } + if matches!( + key.code, + KeyCode::Up + | KeyCode::Down + | KeyCode::Char('j' | 'k') + | KeyCode::Home + | KeyCode::End + | KeyCode::PageUp + | KeyCode::PageDown + ) { + self.tabs_rail_follow_selection = true; + } + let targets = self.sidebar_tab_targets(); + self.tabs_rail_selection = self.tabs_rail_selection.min(targets.len().saturating_sub(1)); + let page = rail_page_size(self.sidebar_layout.tabs); + if let Some(next) = + rail_navigation_index(key, self.tabs_rail_selection, targets.len(), page) + { + self.tabs_rail_selection = next; + } else if key.code == KeyCode::Enter + && let Some(target) = targets.get(self.tabs_rail_selection) + { + self.activate_sidebar_tab(target)?; + self.focus = FocusTarget::Pane; + } + Ok(RenderAction::Draw) + } + fn run_file_command(&mut self, command: FileCommand) { if !self.session_available() { self.sidebar_files.set_message(localization::catalog().sidebar.no_active_session); @@ -14003,14 +15743,20 @@ impl App { /// Commit the open rename dialog (Enter or the OK button). fn commit_prompt(&mut self) { + if let Some((route, input)) = self.prompt.as_ref().and_then(|prompt| { + matches!(prompt.target, PromptTarget::ConnectMachine(_)).then(|| { + let PromptTarget::ConnectMachine(route) = prompt.target else { unreachable!() }; + (route, prompt.input.as_str().to_string()) + }) + }) { + self.begin_machine_connection(input, route); + return; + } let Some(prompt) = self.take_prompt() else { return }; let input = prompt.input.as_str().to_string(); - if let PromptTarget::ConnectMachine(route) = prompt.target { - if !input.trim().is_empty() - && let Some(machine) = self.machine_ui.as_mut() - { - machine.request = - Some(MachineRequest::Connect { target: input.trim().to_string(), route }); + if let PromptTarget::ClientMachine(key) = prompt.target { + if !input.trim().is_empty() { + self.request_rename_client_machine(key, input); } return; } @@ -14136,6 +15882,7 @@ impl App { PromptTarget::Screen(id) => self.session.rename_screen(id, input), PromptTarget::Surface(id) => self.session.rename_surface(id, input), PromptTarget::ConnectMachine(_) + | PromptTarget::ClientMachine(_) | PromptTarget::ManagedMachine(_) | PromptTarget::ConfirmDeleteManagedMachine(_) | PromptTarget::ConfirmPurgeManagedMachine(_) @@ -14157,10 +15904,52 @@ impl App { fn close_prompt(&mut self) { self.shake_frames = 0; self.prompt = None; + if let Some(transaction) = self.connection_transaction.take() { + if let Some(machine) = self.machine_ui.as_mut() + && machine.request.as_ref().is_some_and(|request| { + matches!( + request, + MachineRequest::Connect { target, route } + if target == &transaction.target && route == &transaction.route + ) + }) + { + machine.request = None; + } + if self.machine_action_connection_attempt == Some(transaction.attempt) { + self.canceled_machine_connection_attempt = Some(transaction.attempt); + } + } self.pending_provider_action = None; } fn handle_prompt_key(&mut self, key: KeyEvent) -> anyhow::Result { + if let Some(phase) = + self.connection_transaction.as_ref().map(|transaction| transaction.phase.clone()) + { + match phase { + ConnectionDialogPhase::Editing => {} + ConnectionDialogPhase::Connecting | ConnectionDialogPhase::Starting => { + if key.code == KeyCode::Esc { + self.close_prompt(); + } + return Ok(RenderAction::Draw); + } + ConnectionDialogPhase::Failed(_) => { + match key.code { + KeyCode::Enter => self.retry_machine_connection(), + KeyCode::Esc => self.close_prompt(), + KeyCode::Char('c' | 'C') + if key.modifiers.contains(KeyModifiers::CONTROL) => + { + self.copy_connection_error(); + } + _ => {} + } + return Ok(RenderAction::Draw); + } + } + } let Some(prompt) = self.prompt.as_mut() else { return Ok(RenderAction::None) }; match prompt.input.handle_key(&key) { InputEvent::Commit => self.commit_prompt(), @@ -14171,6 +15960,13 @@ impl App { } fn handle_prompt_text(&mut self, text: &str) -> anyhow::Result { + if self + .connection_transaction + .as_ref() + .is_some_and(|transaction| !matches!(transaction.phase, ConnectionDialogPhase::Editing)) + { + return Ok(RenderAction::Draw); + } let Some(prompt) = self.prompt.as_mut() else { return Ok(RenderAction::None) }; prompt.input.insert_str(text); Ok(RenderAction::Draw) @@ -14291,6 +16087,30 @@ impl App { /// Clicks while the rename dialog is open: OK commits, Cancel (or a /// click outside the dialog) dismisses; clicks inside are swallowed. fn handle_prompt_click(&mut self, x: u16, y: u16) -> anyhow::Result { + if let Some(phase) = + self.connection_transaction.as_ref().map(|transaction| transaction.phase.clone()) + { + let Some(prompt) = self.prompt.as_ref() else { return Ok(RenderAction::None) }; + match phase { + ConnectionDialogPhase::Editing => {} + ConnectionDialogPhase::Connecting | ConnectionDialogPhase::Starting => { + if prompt.cancel.contains(x, y) || !prompt.rect.contains(x, y) { + self.close_prompt(); + } + return Ok(RenderAction::Draw); + } + ConnectionDialogPhase::Failed(_) => { + if prompt.ok.contains(x, y) { + self.retry_machine_connection(); + } else if prompt.clear.contains(x, y) { + self.copy_connection_error(); + } else if prompt.cancel.contains(x, y) || !prompt.rect.contains(x, y) { + self.close_prompt(); + } + return Ok(RenderAction::Draw); + } + } + } let Some(prompt) = self.prompt.as_mut() else { return Ok(RenderAction::None) }; if prompt.ok.contains(x, y) { self.commit_prompt(); @@ -14366,6 +16186,7 @@ impl App { fn handle_menu_key(&mut self, key: KeyEvent) -> anyhow::Result { let Some(menu) = self.menu.as_mut() else { return Ok(RenderAction::None) }; + menu.finish_scrollbar_drag(); match key.code { KeyCode::Esc => { if !menu.close_submenu() { @@ -14381,10 +16202,18 @@ impl App { menu.select_next(); Ok(RenderAction::Draw) } + KeyCode::Left if menu.search.is_some() => { + menu.handle_search_key(&key); + Ok(RenderAction::Draw) + } KeyCode::Left => { menu.close_submenu(); Ok(RenderAction::Draw) } + KeyCode::Right if menu.search.is_some() => { + menu.handle_search_key(&key); + Ok(RenderAction::Draw) + } KeyCode::Right => { menu.open_selected_submenu(); Ok(RenderAction::Draw) @@ -14403,7 +16232,10 @@ impl App { } Ok(RenderAction::Draw) } - _ => Ok(RenderAction::Draw), // swallow while a menu is open + _ => { + menu.handle_search_key(&key); + Ok(RenderAction::Draw) // swallow while a menu is open + } } } @@ -14646,17 +16478,43 @@ impl App { return Ok(RenderAction::None); } } - self.status_message = None; + if !self.status_message_hovered() { + self.status_message = None; + } Ok(RenderAction::Draw) } fn open_rename_tab_prompt(&mut self, pane: Option) { let Some(pane) = pane else { return }; - let Some(tab) = self.tree.pane(pane).and_then(|p| p.tabs.get(p.active_tab)) else { + let Some(surface) = self + .tree + .pane(pane) + .and_then(|pane| pane.tabs.get(pane.active_tab)) + .map(|tab| tab.surface) + else { return; }; - let buffer = tab.name.clone().unwrap_or_default(); - let prompt = Prompt::new("Rename tab", buffer, PromptTarget::Surface(tab.surface)); + self.open_rename_surface_prompt(surface); + } + + fn open_rename_surface_prompt(&mut self, surface: SurfaceId) { + let Some(buffer) = self + .tree + .workspaces + .iter() + .flat_map(|workspace| workspace.screens.iter()) + .flat_map(|screen| screen.panes.iter()) + .flat_map(|pane| pane.tabs.iter()) + .find(|tab| tab.surface == surface) + .map(|tab| tab.name.clone().unwrap_or_default()) + else { + return; + }; + let prompt = Prompt::new( + localization::catalog().action_label(Action::RenameTab), + buffer, + PromptTarget::Surface(surface), + ); self.cancel_pty_mouse_drag(); self.prompt = Some(prompt); } @@ -14808,7 +16666,9 @@ impl App { kind: BrowserInputKind, ) { if self.browser_input.enqueue(BrowserInputEvent { surface_id, surface, kind }) { - self.status_message = None; + if !self.status_message_hovered() { + self.status_message = None; + } } else { self.status_message = Some("browser is busy; command dropped".to_string()); } @@ -14902,6 +16762,14 @@ impl App { } return Ok(()); } + MenuAction::ActivateSidebarProfile(index) => { + self.activate_sidebar_profile(index); + return Ok(()); + } + MenuAction::SetSidebarViewVisible { view, visible } => { + self.set_sidebar_view_visible(view, visible); + return Ok(()); + } MenuAction::ShowShortcuts => { self.run_action(Action::ShowShortcuts)?; return Ok(()); @@ -14912,6 +16780,9 @@ impl App { return Ok(()); } match action { + MenuAction::RenameClientMachine(key) => { + self.open_rename_client_machine_prompt(key); + } MenuAction::RenameManagedMachine(key) => { self.open_rename_managed_machine_prompt(key); } @@ -14981,6 +16852,7 @@ impl App { self.enqueue_browser_command_for_pane(id, BrowserInputKind::Activate); } MenuAction::RenameTab(id) => self.open_rename_tab_prompt(Some(id)), + MenuAction::RenameSurface(surface) => self.open_rename_surface_prompt(surface), MenuAction::CopyTabId(id) => { if let Some(short_id) = self .tree @@ -14996,6 +16868,7 @@ impl App { self.copy_short_id(short_id); } } + MenuAction::CopyStatusMessage => self.copy_status_message(), MenuAction::NewPaneSmart(_) | MenuAction::NewTab(_) | MenuAction::NewBrowserTab(_) @@ -15011,6 +16884,8 @@ impl App { | MenuAction::ToggleSidebar { .. } | MenuAction::ToggleSidebarCompact { .. } | MenuAction::FocusSidebar + | MenuAction::ActivateSidebarProfile(_) + | MenuAction::SetSidebarViewVisible { .. } | MenuAction::ShowShortcuts => unreachable!("shared menu actions return above"), MenuAction::SetClientSizing { surface, client, enabled } => { self.session.set_client_sizing(surface, client, enabled); @@ -15051,15 +16926,48 @@ impl App { } } MenuAction::InvokeProviderAction(index) => self.begin_provider_action(index), + MenuAction::CreateMachineFrom(index) => { + let source_id = self + .machine_ui + .as_ref() + .and_then(|ui| ui.creation_sources.get(index)) + .map(|source| source.id.clone()); + if let (Some(ui), Some(source_id)) = (self.machine_ui.as_mut(), source_id) { + ui.request = Some(MachineRequest::CreateFrom { source_id }); + } + } + MenuAction::ConnectMachineTarget(index) => { + let target = self + .machine_ui + .as_ref() + .and_then(|ui| ui.connection_targets.get(index)) + .map(|target| target.target.clone()); + if let Some(target) = target { + self.begin_machine_connection(target, MachineConnectRoute::Local); + } + } + MenuAction::ConnectOtherMachine => { + let prompt = self.connect_machine_prompt(); + self.prompt = Some(prompt); + } } Ok(()) } fn move_focus(&mut self, direction: Direction) { + if self.move_focus_between_sidebar_rails(direction) { + return; + } let Some(screen) = self.tree.active_screen() else { + if matches!(direction, Direction::Left) { + self.focus_rightmost_sidebar_rail(); + } return; }; if screen.zoomed_pane.is_some() { + if matches!(direction, Direction::Left) { + self.focus_rightmost_sidebar_rail(); + } return; } let active = screen.active_pane; @@ -15079,6 +16987,8 @@ impl App { layout.neighbor_by_recency(active, dx, dy, |pane| self.pane_focus_history.recency(pane)) { self.focus_pane_after_input(next); + } else if matches!(direction, Direction::Left) { + self.focus_rightmost_sidebar_rail(); } } @@ -15126,7 +17036,7 @@ impl App { } fn toggle_sidebar_focus(&mut self) { - if self.workspace_sidebar_focused() { + if self.sidebar_rail_focused() { self.leave_workspace_sidebar(); self.sidebar_focus_pending = false; return; @@ -15139,13 +17049,25 @@ impl App { } fn focus_sidebar(&mut self) { - if self.workspace_sidebar_focused() || self.sidebar_focus_pending { + if self.sidebar_rail_focused() || self.sidebar_focus_pending { return; } self.sidebar_visible = true; let requested = self.config.sidebar.plugin.is_some() && self.sync_sidebar_plugin(true); if self.config.sidebar.plugin.is_none() || self.sidebar_plugin_surface.is_some() { - self.focus = FocusTarget::WorkspaceRail; + let order = self.focusable_rail_order(); + let preferred = order + .iter() + .copied() + .find(|kind| { + self.view_index_for_rail(*kind) + .and_then(|index| self.config.sidebar.views.get(index)) + .is_some_and(|view| view.includes(SidebarResourceKind::Workspaces)) + }) + .or_else(|| order.first().copied()); + if let Some(kind) = preferred { + self.focus_rail(kind); + } if self.config.sidebar.plugin.is_none() { if self.sidebar_view == SidebarView::Workspaces { self.sidebar_workspace_selection = self.tree.active_workspace; @@ -15541,10 +17463,6 @@ impl App { }) } - fn workspace_index(&self, workspace: WorkspaceId) -> Option { - self.tree.workspaces.iter().position(|ws| ws.id == workspace) - } - #[cfg(test)] fn handle_mouse(&mut self, mouse: MouseEvent) -> anyhow::Result { self.handle_mouse_with_sequence(mouse, None, None) @@ -16065,6 +17983,9 @@ impl App { } fn cancel_pointer_interaction(&mut self) { + if let Some(menu) = self.menu.as_mut() { + menu.finish_scrollbar_drag(); + } if matches!(self.drag, Some(Drag::PtyMouse { .. })) { self.cancel_pty_mouse_drag(); } else if let Some(Drag::Browser { surface, content, position, frame_seq }) = &self.drag { @@ -16137,6 +18058,9 @@ impl App { } fn finish_active_drag(&mut self) { + if let Some(menu) = self.menu.as_mut() { + menu.finish_scrollbar_drag(); + } if matches!(self.drag, Some(Drag::PtyMouse { .. })) { self.cancel_pty_mouse_drag(); return; @@ -16159,12 +18083,12 @@ impl App { } Some(Drag::ResizeSplit { .. }) => self.session.settle_split_ratio(), Some( - Drag::MachineArm { .. } - | Drag::TabArm { .. } + Drag::TabArm { .. } | Drag::Tab { .. } | Drag::WorkspaceArm { .. } | Drag::Workspace { .. } | Drag::Select { .. } + | Drag::StatusMessage { .. } | Drag::Scrollbar { .. } | Drag::HorizontalScrollbar { .. } | Drag::WorkspaceScrollbar { .. } @@ -16667,11 +18591,11 @@ impl App { || prompt.input_rect.contains(x, y); } if let Some(menu) = &self.menu { - // Everything inside the menu rect is menu territory: only item - // rows are clickable; border cells never inherit clickability - // from hits underneath. + // Everything inside the menu rect is menu territory: item rows + // and scrollbar tracks are clickable; border cells never inherit + // clickability from hits underneath. if menu.contains(x, y) { - return menu.hit_at(x, y).is_some(); + return menu.hit_at(x, y).is_some() || menu.scrollbar_at(x, y).is_some(); } } if self.omnibar_hit_at(x, y).is_some() { @@ -16715,13 +18639,18 @@ impl App { terminal_admission: Option, ) -> anyhow::Result { self.sync_pointer_shape(x, y); - if let Some(menu) = self.menu.as_mut() - && let Some((depth, item)) = menu.hit_at(x, y) - { - if menu.select_at(depth, item) { - return Ok(RenderAction::Draw); - } - return Ok(RenderAction::None); + if let Some(menu) = self.menu.as_mut() { + let before_scrollbar = + self.hover.and_then(|(px, py)| menu.scrollbar_at(px, py).map(|(depth, _)| depth)); + let after_scrollbar = menu.scrollbar_at(x, y).map(|(depth, _)| depth); + let selection_changed = + menu.hit_at(x, y).is_some_and(|(depth, item)| menu.select_at(depth, item)); + self.hover = Some((x, y)); + return Ok(if selection_changed || before_scrollbar != after_scrollbar { + RenderAction::Draw + } else { + RenderAction::None + }); } if self.menu.is_none() && self.prompt.is_none() && self.drag.is_none() { let _ = self.forward_pty_mouse_at_with_admission( @@ -16857,6 +18786,7 @@ impl App { terminal_admission: Option, ) -> anyhow::Result { self.replace_selection(None); + self.status_selection = None; self.finish_active_drag(); if self.pairing_dialog.is_some() { @@ -16870,7 +18800,9 @@ impl App { // An open menu captures the click: activate or dismiss. Clicks on // the border chrome keep it open without activating. if let Some(mut menu) = self.menu.take() { - if let Some((depth, item)) = menu.hit_at(x, y) { + if menu.start_scrollbar_drag(x, y) { + self.menu = Some(menu); + } else if let Some((depth, item)) = menu.hit_at(x, y) { let action = menu.action_at(depth, item); menu.select_at(depth, item); if let Some(action) = action { @@ -16958,34 +18890,29 @@ impl App { if let Some(hit) = self.hit_at(x, y) { match hit { Hit::Machine { index, key } => { - self.focus = FocusTarget::MachineRail; self.machine_rail_follow_selection = true; if let Some(machine) = self.machine_ui.as_mut() { machine.selection = index; machine.rail_selection = MachineRailSelection::Machine; } - self.drag = self - .machine_pointer_target(key) - .map(|target| Drag::MachineArm { target, at: (x, y) }); + self.focus = FocusTarget::Pane; + self.activate_machine(key); } Hit::NewVm => { - self.focus = FocusTarget::MachineRail; self.machine_rail_follow_selection = true; if let Some(machine) = self.machine_ui.as_mut() { machine.rail_selection = MachineRailSelection::NewVm; - machine.request = Some(MachineRequest::Create); } + self.open_machine_creation_menu(x, y); } Hit::ConnectMachine => { - self.focus = FocusTarget::MachineRail; self.machine_rail_follow_selection = true; if let Some(machine) = self.machine_ui.as_mut() { machine.rail_selection = MachineRailSelection::ConnectMachine; } - self.prompt = Some(self.connect_machine_prompt()); + self.open_machine_connection_menu(x, y); } Hit::ProviderScope => { - self.focus = FocusTarget::MachineRail; self.machine_rail_follow_selection = true; if let Some(machine) = self.machine_ui.as_mut() { machine.rail_selection = MachineRailSelection::Scope; @@ -16993,7 +18920,6 @@ impl App { self.open_provider_scope_menu(x, y); } Hit::ProviderActions => { - self.focus = FocusTarget::MachineRail; self.machine_rail_follow_selection = true; if let Some(machine) = self.machine_ui.as_mut() { machine.rail_selection = MachineRailSelection::Actions; @@ -17001,20 +18927,75 @@ impl App { self.open_provider_actions_menu(x, y); } Hit::Workspace { index, id } => { - self.focus = FocusTarget::WorkspaceRail; self.workspace_rail_follow_selection = true; - self.sidebar_workspace_selection = index; - self.workspace_rail_selection = WorkspaceRailSelection::Workspace; + self.focus = FocusTarget::Pane; + self.activate_workspace(index); self.drag = Some(Drag::WorkspaceArm { workspace: id, at: (x, y) }); } + Hit::SidebarTab { surface, .. } => { + let targets = self.sidebar_tab_targets(); + if let Some((index, target)) = + targets.iter().enumerate().find(|(_, target)| target.surface == surface) + { + self.tabs_rail_follow_selection = true; + self.tabs_rail_selection = index; + self.activate_sidebar_tab(target)?; + self.focus = FocusTarget::Pane; + } + } + Hit::ProjectionToggle { view, branch } => { + let state = self.projection_rail_state_mut(view); + if !state.collapsed.remove(&branch) { + state.collapsed.insert(branch); + } + } + Hit::ProjectionRow { view, row, target } => { + let state = self.projection_rail_state_mut(view); + state.selected = row; + state.selected_action = None; + state.follow_selection = true; + self.activate_projection_target(target)?; + self.focus = FocusTarget::Pane; + } + Hit::RailHeader(kind) => { + self.focus_rail(kind); + } + Hit::SidebarAction { view, action } => { + let kind = self.rail_kind_for_view(view); + match kind { + RailKind::Workspace => { + self.workspace_rail_selection = WorkspaceRailSelection::Action(action); + self.workspace_rail_follow_selection = true; + } + RailKind::Projection(_) => { + let action_index = self + .sidebar_action_rows(view) + .iter() + .position(|candidate| candidate.target == action) + .unwrap_or_default(); + let state = self.projection_rail_state_mut(view); + state.selected_action = Some(action_index); + state.follow_selection = true; + } + RailKind::Machine | RailKind::Tabs => {} + } + return self.invoke_sidebar_action(action); + } Hit::RecoverableWorkspace { index } => { - self.focus = FocusTarget::WorkspaceRail; self.workspace_rail_follow_selection = true; self.sidebar_recoverable_workspace_selection = index; self.workspace_rail_selection = WorkspaceRailSelection::Recoverable; + self.focus = FocusTarget::Pane; + let workspace_id = self + .machine_ui + .as_ref() + .and_then(|ui| ui.recoverable_workspaces().get(index).copied()) + .map(|workspace| workspace.id.clone()); + if let Some(workspace_id) = workspace_id { + self.request_restore_managed_workspace(&workspace_id); + } } Hit::CreateWorkspace { mode } => { - self.focus = FocusTarget::WorkspaceRail; self.workspace_rail_follow_selection = true; self.workspace_rail_selection = workspace_creation_selection(mode); self.create_workspace(mode, None)?; @@ -17040,6 +19021,10 @@ impl App { self.select_screen_for_client(Some(index), None); } } + Hit::StatusMessage => { + self.begin_status_message_selection(x); + } + Hit::CopyStatusMessage => self.copy_status_message(), Hit::NewScreen => { self.focus = FocusTarget::Pane; self.new_screen(None)?; @@ -17069,15 +19054,10 @@ impl App { self.start_horizontal_scrollbar_drag(track, x); } Hit::WorkspaceScrollbar { track, total_rows, visible_rows } => { - self.focus = FocusTarget::WorkspaceRail; self.workspace_rail_follow_selection = false; self.start_workspace_scrollbar_drag(track, total_rows, visible_rows, y); } Hit::RailResize(kind) => { - self.focus = match kind { - RailKind::Machine => FocusTarget::MachineRail, - RailKind::Workspace => FocusTarget::WorkspaceRail, - }; self.drag = Some(Drag::RailResize(kind)); } Hit::PaneResize { horizontal, vertical } => { @@ -17159,8 +19139,14 @@ impl App { } fn handle_left_drag(&mut self, x: u16, y: u16) -> anyhow::Result { + if let Some(menu) = self.menu.as_mut() + && menu.scrollbar_drag.is_some() + { + menu.drag_scrollbar(y); + self.hover = Some((x, y)); + return Ok(RenderAction::Draw); + } match &self.drag { - Some(Drag::MachineArm { .. }) => Ok(RenderAction::Draw), Some(Drag::TabArm { surface, at }) => { let (surface, at) = (*surface, *at); if (x, y) != at { @@ -17214,6 +19200,19 @@ impl App { self.drag = Some(Drag::Select { content, source_x, auto_scroll, col }); Ok(RenderAction::Draw) } + Some(Drag::StatusMessage { rect }) => { + let rect = *rect; + if rect.width == 0 { + self.drag = None; + self.status_selection = None; + return Ok(RenderAction::Draw); + } + let cell = x.clamp(rect.x, rect.x + rect.width - 1) - rect.x; + if let Some(selection) = self.status_selection.as_mut() { + selection.head = cell; + } + Ok(RenderAction::Draw) + } Some(Drag::Browser { surface, content, frame_seq, .. }) => { let (surface, frame_seq) = (*surface, *frame_seq); let content = self.current_browser_content(surface).unwrap_or(*content); @@ -17301,13 +19300,21 @@ impl App { } Some(Drag::RailResize(kind)) => { let kind = *kind; - if let Some(width) = rail_drag_width(&self.config, self.sidebar_layout, kind, x) { + if let Some(width) = rail_drag_width(&self.config, &self.sidebar_layout, kind, x) { match kind { RailKind::Machine => self.machine_sidebar_width_override = Some(width), RailKind::Workspace => { self.sidebar_compact = false; self.sidebar_width_override = Some(width); } + RailKind::Tabs => self.tabs_sidebar_width_override = Some(width), + RailKind::Projection(index) => { + if let Some(id) = + self.config.sidebar.views.get(index).map(|view| view.id.clone()) + { + self.projection_sidebar_width_overrides.insert(id, width); + } + } } } Ok(RenderAction::Draw) @@ -17327,26 +19334,10 @@ impl App { } fn handle_left_up(&mut self, x: u16, y: u16) -> anyhow::Result { - if matches!(self.drag, Some(Drag::MachineArm { .. })) { - let Some(Drag::MachineArm { target, at }) = self.drag.take() else { - unreachable!("machine arm matched before take"); - }; - if (x, y) == at - && self.machine_pointer_target(target.machine).as_ref() == Some(&target) - && let Some(ui) = self.machine_ui.as_mut() - { - if let Some(managed) = target.managed.as_ref().filter(|managed| { - managed.status == ManagedMachineStatus::Recoverable - && managed.capabilities.restore - }) { - ui.request = Some(MachineRequest::RestoreManagedMachine { - machine: target.machine, - expected_version: managed.version, - }); - } else if target.context.snapshot.active != Some(target.machine) { - ui.request = Some(MachineRequest::Switch(target.machine)); - } - } + if let Some(menu) = self.menu.as_mut() + && menu.finish_scrollbar_drag() + { + self.hover = Some((x, y)); return Ok(RenderAction::Draw); } if let Some(Drag::TabArm { surface, .. }) = self.drag { @@ -17368,13 +19359,8 @@ impl App { } return Ok(RenderAction::Draw); } - if let Some(Drag::WorkspaceArm { workspace, .. }) = self.drag { + if matches!(self.drag, Some(Drag::WorkspaceArm { .. })) { self.drag = None; - if let Some(index) = self.workspace_index(workspace) - && self.prepare_pty_input_before_mutation() - { - self.select_workspace_for_client(Some(index), None); - } return Ok(RenderAction::Draw); } if let Some(Drag::Workspace { workspace, .. }) = self.drag { @@ -17406,6 +19392,16 @@ impl App { self.session.settle_split_ratio(); return Ok(RenderAction::Draw); } + if matches!(self.drag, Some(Drag::StatusMessage { .. })) { + self.drag = None; + match self.status_selection.as_ref() { + Some(selection) if selection.anchor != selection.head => { + self.copy_status_message_selection(); + } + _ => self.status_selection = None, + } + return Ok(RenderAction::Draw); + } let was_select = matches!(self.drag, Some(Drag::Select { .. })); let was_drag = self.drag.is_some(); self.drag = None; @@ -17444,6 +19440,25 @@ impl App { self.show_toast("Copied".to_string()); } + fn copy_status_message_selection(&mut self) { + let Some(text) = self + .status_selection + .as_ref() + .map(StatusMessageSelection::selected_text) + .filter(|text| !text.is_empty()) + else { + return; + }; + self.copy_text_to_clipboard(&text); + self.show_toast("Copied".to_string()); + } + + fn copy_status_message(&mut self) { + let Some(message) = self.status_message.clone() else { return }; + self.copy_text_to_clipboard(&message); + self.show_toast("Copied".to_string()); + } + fn copy_text_to_clipboard(&self, text: &str) { let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes()); let lock = self.stdout_lock.clone(); @@ -17909,8 +19924,134 @@ impl App { ] } - fn global_menu_actions(&self) -> Vec { - vec![MenuAction::ShowShortcuts] + fn sidebar_view_name(&self, index: usize) -> String { + let messages = &localization::catalog().sidebar; + let Some(view) = self.config.sidebar.views.get(index) else { return String::new() }; + match view.levels.as_slice() { + [SidebarResourceKind::Machines] => messages.machines.to_string(), + [SidebarResourceKind::Workspaces] => messages.workspaces.to_string(), + [SidebarResourceKind::Tabs] => messages.tabs.to_string(), + _ => view.id.clone(), + } + } + + fn sidebar_view_visibility_item(&self, index: usize) -> Option { + let view = self.config.sidebar.views.get(index)?; + let hidden = self + .hidden_sidebar_views + .get(&self.config.sidebar.active_profile) + .is_some_and(|hidden| hidden.contains(&view.id)); + let template = if hidden { + localization::catalog().menu.show_sidebar_view + } else { + localization::catalog().menu.hide_sidebar_view + }; + Some(MenuItem::LabeledAction { + label: template.replace("{view}", &self.sidebar_view_name(index)), + action: MenuAction::SetSidebarViewVisible { view: index, visible: hidden }, + }) + } + + fn sidebar_presentation_menu_item(&self) -> MenuItem { + let mut items = Vec::new(); + if self.config.sidebar.profiles.len() > 1 { + items.push(MenuItem::Submenu { + label: localization::catalog().menu.sidebar_profiles.to_string(), + items: self + .config + .sidebar + .profiles + .iter() + .enumerate() + .map(|(index, profile)| MenuItem::LabeledAction { + label: format!( + "{}{}", + if profile.id == self.config.sidebar.active_profile { + "✓ " + } else { + " " + }, + profile.name + ), + action: MenuAction::ActivateSidebarProfile(index), + }) + .collect(), + }); + } + if !self.config.sidebar.views.is_empty() { + if !items.is_empty() { + items.push(MenuItem::Separator); + } + items.extend( + (0..self.config.sidebar.views.len()) + .filter_map(|index| self.sidebar_view_visibility_item(index)), + ); + } + MenuItem::Submenu { label: localization::catalog().menu.sidebar_layout.to_string(), items } + } + + fn global_menu_items(&self) -> Vec { + let mut items = + self.menu_group([MenuAction::ToggleSidebar { visible: self.sidebar_visible }]); + if self.surface_only.is_none() { + items.push(self.sidebar_presentation_menu_item()); + } + items.push(self.menu_item(MenuAction::ShowShortcuts)); + items + } + + fn set_sidebar_view_visible(&mut self, index: usize, visible: bool) { + let Some(view) = self.config.sidebar.views.get(index) else { return }; + let view_id = view.id.clone(); + let hides_focused = !visible && self.focused_sidebar_view_id().as_deref() == Some(&view_id); + let hidden = self + .hidden_sidebar_views + .entry(self.config.sidebar.active_profile.clone()) + .or_default(); + if visible { + hidden.remove(&view_id); + self.sidebar_visible = true; + } else { + hidden.insert(view_id); + if hides_focused { + self.focus = FocusTarget::Pane; + } + } + } + + fn activate_sidebar_profile(&mut self, index: usize) { + let Some(profile) = self.config.sidebar.profiles.get(index).cloned() else { return }; + let focused_view = self.focused_sidebar_view_id(); + self.config.sidebar.active_profile = profile.id; + self.config.sidebar.views = profile.views; + self.config.sidebar.columns = self + .config + .sidebar + .views + .iter() + .filter_map(|view| { + view.legacy_kind().map(|kind| SidebarColumn { + kind, + width: view.width, + max_width: view.max_width, + }) + }) + .collect(); + self.sidebar_visible = true; + if let Some(focused_view) = focused_view { + let hidden = self + .hidden_sidebar_views + .get(&self.config.sidebar.active_profile) + .is_some_and(|hidden| hidden.contains(&focused_view)); + if !hidden + && let Some(index) = + self.config.sidebar.views.iter().position(|view| view.id == focused_view) + { + self.focus_rail(self.rail_kind_for_view(index)); + return; + } + self.focus = FocusTarget::Pane; + } } fn open_context_menu(&mut self, x: u16, y: u16) { @@ -17936,6 +20077,14 @@ impl App { self.omnibar = None; self.session.refresh_clients_background(); let hit = self.hit_at(x, y); + if matches!(hit, Some(Hit::StatusMessage)) { + self.menu = Some(ContextMenu::with_groups( + x, + y, + vec![self.menu_group([MenuAction::CopyStatusMessage]), self.global_menu_items()], + )); + return; + } if self.total_sidebar_width() > 0 && x < self.total_sidebar_width() { let mut groups = Vec::new(); match hit { @@ -17961,6 +20110,12 @@ impl App { } } groups.push(self.menu_group(actions)); + } else if self + .machine_ui + .as_ref() + .is_some_and(|ui| ui.is_client_machine_renamable(key)) + { + groups.push(self.menu_group([MenuAction::RenameClientMachine(key)])); } } Some(Hit::Workspace { id, .. }) => { @@ -17999,14 +20154,93 @@ impl App { groups.push(self.menu_group(actions)); } } + Some(Hit::SidebarTab { surface, .. }) => { + groups.push(self.menu_group([MenuAction::RenameSurface(surface)])); + } + Some(Hit::ProjectionRow { + target: ProjectionTarget::Workspace { id, .. }, .. + }) + | Some(Hit::ProjectionToggle { branch: ProjectionBranch::Workspace(id), .. }) => { + if self.provider_manages_current_workspace_session() { + if let Some(workspace) = self.managed_workspace_for_view(id) { + let mut actions = Vec::new(); + if workspace.capabilities.rename { + actions.push(MenuAction::RenameManagedWorkspace(id)); + } + if workspace.capabilities.delete { + actions.push(MenuAction::DeleteManagedWorkspace(id)); + } + groups.push(self.menu_group(actions)); + } + } else { + groups.push(self.menu_group([ + MenuAction::RenameWorkspace(id), + MenuAction::CloseWorkspace(id), + ])); + groups.push(self.menu_group([MenuAction::CopyWorkspaceId(id)])); + } + } + Some(Hit::ProjectionRow { + target: ProjectionTarget::Surface { surface, .. }, + .. + }) => { + groups.push(self.menu_group([MenuAction::RenameSurface(surface)])); + } _ => {} } + if let Some(view_index) = self + .sidebar_layout + .ordered + .iter() + .find(|placement| placement.rect.contains(x, y)) + .map(|placement| placement.view_index) + && let Some(item) = self.sidebar_view_visibility_item(view_index) + { + groups.push(vec![item]); + } groups.push(self.menu_group(self.sidebar_menu_actions())); - groups.push(self.menu_group(self.global_menu_actions())); + groups.push(vec![self.sidebar_presentation_menu_item()]); + groups.push(self.menu_group([MenuAction::ShowShortcuts])); self.menu = Some(ContextMenu::with_groups(x, y, groups)); return; } match hit { + Some(Hit::Tab { pane, index }) => { + let Some(surface) = self + .tree + .pane(pane) + .and_then(|pane| pane.tabs.get(index)) + .map(|tab| tab.surface) + else { + return; + }; + let is_browser = self.surface_kind(surface) == Some(SurfaceKind::Browser); + let external_browser = + self.browser_source(surface) == Some(BrowserSource::External); + let mut actions = pane_context_menu_groups(pane, is_browser, external_browser); + if let Some(rename) = actions.first_mut().and_then(|group| group.first_mut()) { + *rename = MenuAction::RenameSurface(surface); + } + let mut groups = actions + .into_iter() + .map(|group| self.menu_group(group)) + .collect::>>(); + if self.surface_only.is_none() { + let zoomed = self + .tree + .active_screen() + .is_some_and(|screen| screen.zoomed_pane == Some(pane)); + groups.push(self.menu_group([MenuAction::TogglePaneZoom { pane, zoomed }])); + } + if self.surface_only.is_none() + && let Some(clients) = client_menu_item(&self.clients, surface) + { + groups.push(vec![clients]); + } + groups.push(self.global_menu_items()); + self.menu = Some(ContextMenu::with_groups(x, y, groups)); + return; + } Some(Hit::ScreenEntry { id, .. }) => { self.menu = Some(ContextMenu::with_groups( x, @@ -18016,7 +20250,7 @@ impl App { MenuAction::RenameScreen(id), MenuAction::CloseScreen(id), ]), - self.menu_group(self.global_menu_actions()), + self.global_menu_items(), ], )); return; @@ -18049,9 +20283,11 @@ impl App { { groups.push(vec![clients]); } - groups.push(self.menu_group(self.global_menu_actions())); + groups.push(self.global_menu_items()); self.menu = Some(ContextMenu::with_groups(x, y, groups)); + return; } + self.menu = Some(ContextMenu::with_groups(x, y, vec![self.global_menu_items()])); } fn replace_clients(&mut self, clients: Vec) { @@ -18061,9 +20297,12 @@ impl App { fn open_clients_menu(&mut self, x: u16, y: u16, surface: SurfaceId) { self.session.refresh_clients_background(); + let mut groups = Vec::new(); if let Some(MenuItem::Submenu { items, .. }) = client_menu_item(&self.clients, surface) { - self.menu = Some(ContextMenu::with_groups(x, y, vec![items])); + groups.push(items); } + groups.push(self.global_menu_items()); + self.menu = Some(ContextMenu::with_groups(x, y, groups)); } #[cfg(test)] @@ -18085,7 +20324,14 @@ impl App { modifiers: KeyModifiers, terminal_admission: Option, ) -> anyhow::Result { - if self.menu.is_some() || self.prompt.is_some() { + if let Some(menu) = self.menu.as_mut() { + return Ok(if menu.scroll_at(x, y, down) { + RenderAction::Draw + } else { + RenderAction::None + }); + } + if self.prompt.is_some() { return Ok(RenderAction::None); } if let Some(area) = self @@ -18119,7 +20365,7 @@ impl App { .flatten() .filter(|area| area.contains(x, y)) { - let footer_rows = self.workspace_creation_modes().len(); + let footer_rows = self.workspace_sidebar_action_rows().len(); let footer_is_clipped = footer_rows > usize::from(area.height.saturating_sub(2)); if footer_is_clipped { self.workspace_footer_scroll = if down { @@ -18137,6 +20383,45 @@ impl App { self.workspace_rail_follow_selection = false; return Ok(RenderAction::Draw); } + if let Some(_area) = self + .tabs_sidebar_area(self.content_area.height.saturating_add(1)) + .filter(|area| area.contains(x, y)) + { + self.tabs_rail_scroll = if down { + self.tabs_rail_scroll.saturating_add(3) + } else { + self.tabs_rail_scroll.saturating_sub(3) + }; + self.tabs_rail_follow_selection = false; + return Ok(RenderAction::Draw); + } + if let Some(view_index) = self.sidebar_layout.ordered.iter().find_map(|placement| { + matches!(placement.kind, RailKind::Projection(_)) + .then_some((placement.view_index, placement.rect)) + .filter(|(_, area)| area.contains(x, y)) + .map(|(view_index, _)| view_index) + }) { + let footer_rows = self.sidebar_action_rows(view_index).len(); + let footer_is_clipped = self + .projection_sidebar_area(view_index) + .is_some_and(|area| footer_rows > usize::from(area.height.saturating_sub(2))); + let state = self.projection_rail_state_mut(view_index); + if footer_is_clipped { + state.footer_scroll = if down { + state.footer_scroll.saturating_add(1) + } else { + state.footer_scroll.saturating_sub(1) + }; + } else { + state.scroll = if down { + state.scroll.saturating_add(3) + } else { + state.scroll.saturating_sub(3) + }; + } + state.follow_selection = false; + return Ok(RenderAction::Draw); + } let Some(area) = self.pane_area_at(x, y).copied() else { return Ok(RenderAction::None) }; if self.surface_kind(area.surface) == Some(SurfaceKind::Pty) && area.content.contains(x, y) @@ -18515,7 +20800,8 @@ fn action_prepares_pty_release(action: Action) -> bool { fn menu_action_prepares_pty_release(action: MenuAction) -> bool { !matches!( action, - MenuAction::RenameManagedMachine(_) + MenuAction::RenameClientMachine(_) + | MenuAction::RenameManagedMachine(_) | MenuAction::DeleteManagedMachine(_) | MenuAction::RestoreManagedMachine(_) | MenuAction::PurgeManagedMachine(_) @@ -18529,10 +20815,16 @@ fn menu_action_prepares_pty_release(action: MenuAction) -> bool { | MenuAction::BrowserEditUrl(_) | MenuAction::BrowserCopyUrl(_) | MenuAction::RenameTab(_) + | MenuAction::RenameSurface(_) | MenuAction::CopyTabId(_) | MenuAction::CopyPaneId(_) + | MenuAction::CopyStatusMessage | MenuAction::SelectProviderScope(_) | MenuAction::InvokeProviderAction(_) + | MenuAction::ConnectMachineTarget(_) + | MenuAction::ConnectOtherMachine + | MenuAction::ActivateSidebarProfile(_) + | MenuAction::SetSidebarViewVisible { .. } ) } @@ -18681,24 +20973,26 @@ mod tests { PendingSessionMutationState, PointerHitIdentity, PointerRouteIdentity, PointerRoutePhase, Prompt, PromptTarget, PtyFailureIngress, PtyMousePressResult, RailKind, RenderAction, RenderedMenuLevel, RenderedPaneRoute, RenderedPointerFrame, Selection, SessionCompletion, - SessionCompletionAction, SessionEventSender, ShortcutHelp, SidebarLayout, - SidebarPluginSyncClaim, SidebarPluginSyncState, StdoutLock, SurfaceAttachClaimState, - SurfaceResizeDecision, SurfaceResizeOwnership, TERMINAL_PAINT_CADENCE, TerminalInput, - TerminalPaintPacer, TerminalPointerAdmission, TerminalPointerAdmissionResult, - TerminalPointerEncoding, TextInput, VIEWPORT_ANIMATION_DURATION, ViewportMotion, - ViewportPaneAreaProjection, WorkspaceRailSelection, action_available_in_mode, - browser_content_size_for_rect, browser_frame_source_crop, browser_hover_forward_allowed, - browser_source_crop, canonical_terminal_content, catch_renderer_panic, - clamp_split_ratio_for_tab_bars, client_menu_item, clip_horizontal_rect, - disable_host_keyboard_protocol, enable_host_keyboard_protocol, forward_host_input, - forward_mux_event, forward_mux_events, keyboard_protocol_accepts, - layout_undo_error_completion, negotiate_host_keyboard_protocol_with, outer_cursor_escape, - outer_cursor_escape_if_changed, pane_area_projection_work, pane_context_menu_groups, - pane_parts_for_rect, prepare_ordered_session, preserve_client_view, rail_drag_width, - rebuild_pane_areas, record_surface_resize_dispatch_result, report_after_unwind, + SessionCompletionAction, SessionEventSender, ShortcutHelp, SidebarActionTarget, + SidebarLayout, SidebarPluginSyncClaim, SidebarPluginSyncState, SidebarWidthOverrides, + StdoutLock, SurfaceAttachClaimState, SurfaceResizeDecision, SurfaceResizeOwnership, + TERMINAL_PAINT_CADENCE, TerminalInput, TerminalPaintPacer, TerminalPointerAdmission, + TerminalPointerAdmissionResult, TerminalPointerEncoding, TextInput, + VIEWPORT_ANIMATION_DURATION, ViewportMotion, ViewportPaneAreaProjection, + WorkspaceRailSelection, action_available_in_mode, browser_content_size_for_rect, + browser_frame_source_crop, browser_hover_forward_allowed, browser_source_crop, + canonical_terminal_content, catch_renderer_panic, clamp_split_ratio_for_tab_bars, + client_menu_item, clip_horizontal_rect, disable_host_keyboard_protocol, + enable_host_keyboard_protocol, forward_host_input, forward_mux_event, forward_mux_events, + keyboard_protocol_accepts, layout_undo_error_completion, + negotiate_host_keyboard_protocol_with, outer_cursor_escape, outer_cursor_escape_if_changed, + pane_area_projection_work, pane_context_menu_groups, pane_parts_for_rect, + prepare_ordered_session, preserve_client_view, rail_drag_width, rebuild_pane_areas, + record_surface_resize_dispatch_result, report_after_unwind, reset_pane_area_projection_work, should_claim_clear_history_shortcut, sidebar_layout_for, - sidebar_plugin_status_settles_passive_claim, start_ordered_session, - swept_viewport_size_leases, thumb_geometry, with_panic_stdout_lock, + sidebar_layout_for_state, sidebar_plugin_status_settles_passive_claim, + start_ordered_session, swept_viewport_size_leases, thumb_geometry, with_panic_stdout_lock, + workspace_creation_selection, }; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::path::PathBuf; @@ -18708,9 +21002,9 @@ mod tests { use std::time::{Duration, Instant}; use cmux_tui_core::{ - BrowserFrame, BrowserStatus, Direction, LayoutUndoError, Mux, MuxEvent, Node, - PointerSnapshotProbe, Rect, SplitDir, SurfaceId, SurfaceKind, SurfaceOptions, VirtualRect, - ZoomMode, layout_screen, server, + AgentSource, AgentState, BrowserFrame, BrowserStatus, Direction, LayoutUndoError, Mux, + MuxEvent, Node, PointerSnapshotProbe, Rect, SplitDir, SurfaceId, SurfaceKind, + SurfaceOptions, VirtualRect, ZoomMode, layout_screen, server, }; use crossterm::event::{ EnhancedKeyEvent, Event, KeyCode, KeyEvent, KeyModifiers, KeyboardEnhancementFlags, @@ -18728,19 +21022,20 @@ mod tests { use crate::browser_input::{BrowserInputDispatcher, BrowserInputEvent, BrowserInputKind}; use crate::config::{ - Action, ChromeTheme, Config, ScrollbarPosition, SidebarView, action_definitions, + Action, ChromeTheme, Config, ScrollbarPosition, SidebarColumnKind, SidebarProfileSpec, + SidebarResourceKind, SidebarView, SidebarViewSpec, action_definitions, }; use crate::localization; use crate::machine::{ DurableNoticeDelivery, DurableNoticeLevel, DurableProviderNotice, MachineActionResult, - MachineCapabilities, MachineController, MachineDescriptor, MachineKey, - MachineRailSelection, MachineRequest, MachineSnapshot, MachineStatus, MachineUiState, - MachineUpdate, ManagedMachineCapabilities, ManagedMachineDescriptor, ManagedMachineStatus, - ManagedWorkspaceCapabilities, ManagedWorkspaceDescriptor, ManagedWorkspaceSessionMutation, - ManagedWorkspaceStatus, ProviderActionContext, ProviderActionDescriptor, - ProviderActionFieldDescriptor, ProviderActionFieldKind, ProviderActionTarget, - ProviderActionValue, ProviderPresentation, ProviderScopeDescriptor, ProviderScopeKind, - WorkspaceCreationMode, WorkspaceCreationPolicy, + MachineCapabilities, MachineConnectionTarget, MachineController, MachineCreationSource, + MachineDescriptor, MachineKey, MachineRailSelection, MachineRequest, MachineSnapshot, + MachineStatus, MachineUiState, MachineUpdate, ManagedMachineCapabilities, + ManagedMachineDescriptor, ManagedMachineStatus, ManagedWorkspaceCapabilities, + ManagedWorkspaceDescriptor, ManagedWorkspaceSessionMutation, ManagedWorkspaceStatus, + ProviderActionContext, ProviderActionDescriptor, ProviderActionFieldDescriptor, + ProviderActionFieldKind, ProviderActionTarget, ProviderActionValue, ProviderPresentation, + ProviderScopeDescriptor, ProviderScopeKind, WorkspaceCreationMode, WorkspaceCreationPolicy, }; use crate::pty_input::{ PtyInputBytes, PtyInputDispatcher, PtyInputEnqueueResult, PtyInputEvent, PtyInputKind, @@ -19101,6 +21396,26 @@ mod tests { assert!(!super::binding_matches(&alt_ampersand, &key, fallback.as_ref())); } + #[test] + fn enhanced_shifted_suffix_runs_uppercase_prefix_binding() { + let mux = Mux::new("enhanced-prefix-shift-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.sidebar_view = SidebarView::Workspaces; + app.sync_layout((80, 25)); + app.handle_key(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL)).unwrap(); + + app.handle_keyboard(crate::keys::KeyboardInput::from_enhanced(EnhancedKeyEvent { + key_event: KeyEvent::new(KeyCode::Char('s'), KeyModifiers::SHIFT), + shifted_key: Some('S'), + base_layout_key: Some('s'), + text: "S".to_string(), + })) + .unwrap(); + + assert_eq!(app.focus, FocusTarget::WorkspaceRail); + assert!(!app.prefix_armed); + } + #[test] fn option_generated_text_does_not_match_alt_modeless_bindings() { let input = crate::keys::KeyboardInput::from_enhanced(EnhancedKeyEvent { @@ -19398,7 +21713,14 @@ mod tests { #[test] fn zero_width_startup_hides_sidebar_without_panicking() { let config = Config::default(); - let layout = sidebar_layout_for(&config, true, false, false, (0, 24), None, None); + let layout = sidebar_layout_for( + &config, + true, + false, + false, + (0, 24), + SidebarWidthOverrides::default(), + ); assert!(layout.workspace.is_none()); assert_eq!(layout.content.width, 0); } @@ -19492,7 +21814,7 @@ mod tests { shortcut(MenuAction::TogglePaneZoom { pane: 2, zoomed: false }), Some("Ctrl-b z") ); - assert_eq!(shortcut(MenuAction::ToggleSidebar { visible: true }), None); + assert_eq!(shortcut(MenuAction::ToggleSidebar { visible: true }), Some("Ctrl-b s")); assert_eq!(shortcut(MenuAction::ToggleSidebarCompact { compact: false }), None); assert_eq!(shortcut(MenuAction::FocusSidebar), None); assert_eq!(shortcut(MenuAction::ShowShortcuts), Some("Ctrl-b ?")); @@ -19538,14 +21860,15 @@ mod tests { let items = &app.menu.as_ref().unwrap().levels[0].items; assert!(items.iter().any(|item| item.action() == Some(MenuAction::RenameScreen(screen)))); assert!(items.iter().any(|item| item.action() == Some(MenuAction::ShowShortcuts))); + assert!( + items + .iter() + .any(|item| item.action() == Some(MenuAction::ToggleSidebar { visible: true })) + ); assert!(!items.iter().any(|item| { matches!( item.action(), - Some( - MenuAction::ToggleSidebar { .. } - | MenuAction::ToggleSidebarCompact { .. } - | MenuAction::FocusSidebar - ) + Some(MenuAction::ToggleSidebarCompact { .. } | MenuAction::FocusSidebar) ) })); app.activate_menu(MenuAction::ShowShortcuts).unwrap(); @@ -19613,6 +21936,33 @@ mod tests { ); } + #[test] + fn every_context_menu_exposes_sidebar_visibility() { + let (mux, _) = test_mux("global-sidebar-context-menu-test", None); + let mut app = test_app(Session::Local(mux.clone())); + app.sidebar_visible = false; + app.replace_tree(app.session.tree()); + app.sync_layout((80, 20)); + let content = app.pane_areas[0].content; + + for point in [(content.x, content.y), (79, 19)] { + app.open_context_menu(point.0, point.1); + assert!( + app.menu.as_ref().is_some_and(|menu| { + menu.levels[0].items.iter().any(|item| { + item.action() == Some(MenuAction::ToggleSidebar { visible: false }) + }) + }), + "right-click at {point:?} must offer Show Sidebar" + ); + } + + let surfaces = mux.with_state(|state| state.surfaces.keys().copied().collect::>()); + for surface in surfaces { + mux.close_surface(surface).unwrap(); + } + } + #[test] fn pane_context_new_pane_runs_the_same_smart_layout_action_as_alt_n() { let (mux, _) = test_mux("context-new-pane-test", None); @@ -20654,11 +23004,13 @@ mod tests { let mut config = Config::default(); config.sidebar.width = 28; config.sidebar.compact_width = 10; - let full = sidebar_layout_for(&config, true, false, false, (100, 30), Some(35), None); + let overrides = + SidebarWidthOverrides { workspace: Some(35), ..SidebarWidthOverrides::default() }; + let full = sidebar_layout_for(&config, true, false, false, (100, 30), overrides); assert_eq!(full.workspace.map(|area| area.width), Some(35)); - let compact = sidebar_layout_for(&config, true, true, false, (100, 30), Some(35), None); + let compact = sidebar_layout_for(&config, true, true, false, (100, 30), overrides); assert_eq!(compact.workspace.map(|area| area.width), Some(10)); - let hidden = sidebar_layout_for(&config, false, true, false, (100, 30), Some(35), None); + let hidden = sidebar_layout_for(&config, false, true, false, (100, 30), overrides); assert_eq!(hidden.workspace, None); let mux = Mux::new("compact-sidebar-action-test", SurfaceOptions::default()); @@ -20671,6 +23023,176 @@ mod tests { assert!(!app.sidebar_compact); } + #[test] + fn configured_column_stack_preserves_order_and_drops_low_priority_rails_first() { + let mut config = Config::default(); + config.sidebar.columns_explicit = true; + config.sidebar.columns = vec![ + crate::config::SidebarColumn { + kind: SidebarColumnKind::Machines, + width: 18, + max_width: 0, + }, + crate::config::SidebarColumn { + kind: SidebarColumnKind::Workspaces, + width: 22, + max_width: 0, + }, + crate::config::SidebarColumn { kind: SidebarColumnKind::Tabs, width: 24, max_width: 0 }, + ]; + config.sidebar.views = config + .sidebar + .columns + .iter() + .map(|column| SidebarViewSpec::legacy(column.kind, column.width, column.max_width)) + .collect(); + config.sidebar.views_explicit = true; + + let full = sidebar_layout_for( + &config, + true, + false, + true, + (120, 30), + SidebarWidthOverrides::default(), + ); + assert_eq!(full.machine, Some(Rect { x: 0, y: 0, width: 18, height: 30 })); + assert_eq!(full.workspace, Some(Rect { x: 18, y: 0, width: 22, height: 30 })); + assert_eq!(full.tabs, Some(Rect { x: 40, y: 0, width: 24, height: 30 })); + assert_eq!(full.content.x, 64); + + let medium = sidebar_layout_for( + &config, + true, + false, + true, + (60, 30), + SidebarWidthOverrides::default(), + ); + assert_eq!(medium.machine, None); + assert!(medium.workspace.is_some()); + assert!(medium.tabs.is_some()); + + let narrow = sidebar_layout_for( + &config, + true, + false, + true, + (50, 30), + SidebarWidthOverrides::default(), + ); + assert_eq!(narrow.machine, None); + assert_eq!(narrow.tabs, None); + assert_eq!(narrow.workspace.map(|rect| rect.width), Some(10)); + assert_eq!(narrow.content.width, 40); + } + + #[test] + fn context_menu_switches_sidebar_profiles_and_keeps_per_profile_visibility() { + let mux = Mux::new("sidebar-profile-menu-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let full = vec![ + SidebarViewSpec::legacy(SidebarColumnKind::Workspaces, 22, 0), + SidebarViewSpec::legacy(SidebarColumnKind::Tabs, 22, 0), + ]; + let focused = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: vec![Action::NewWorkspace], + width: 30, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.profiles = vec![ + SidebarProfileSpec { id: "full".into(), name: "Full".into(), views: full.clone() }, + SidebarProfileSpec { + id: "focused".into(), + name: "Focused".into(), + views: focused.clone(), + }, + ]; + app.config.sidebar.active_profile = "full".into(); + app.config.sidebar.views = full; + app.config.sidebar.views_explicit = true; + app.sync_layout((120, 20)); + + app.open_context_menu(100, 10); + let actions = app.menu.as_ref().unwrap().actions(); + assert!(actions.contains(&MenuAction::ActivateSidebarProfile(1))); + assert!(actions.contains(&MenuAction::SetSidebarViewVisible { view: 1, visible: false })); + + app.focus = FocusTarget::TabsRail; + app.activate_menu(MenuAction::ActivateSidebarProfile(1)).unwrap(); + app.sync_layout((120, 20)); + assert_eq!(app.config.sidebar.views, focused); + assert!(app.sidebar_layout.tabs.is_none()); + assert_eq!(app.focus, FocusTarget::Pane); + + app.activate_sidebar_profile(0); + app.set_sidebar_view_visible(1, false); + app.sync_layout((120, 20)); + assert!(app.sidebar_layout.tabs.is_none()); + app.activate_sidebar_profile(1); + app.activate_sidebar_profile(0); + app.sync_layout((120, 20)); + assert!(app.sidebar_layout.tabs.is_none()); + } + + #[test] + fn collapsed_rail_requires_hysteresis_before_reappearing() { + let mut config = Config::default(); + config.sidebar.views = vec![ + SidebarViewSpec::legacy(SidebarColumnKind::Machines, 18, 0), + SidebarViewSpec::legacy(SidebarColumnKind::Workspaces, 22, 0), + SidebarViewSpec::legacy(SidebarColumnKind::Tabs, 24, 0), + ]; + config.sidebar.views_explicit = true; + let overrides = HashMap::new(); + let collapsed = sidebar_layout_for_state( + &config, + true, + false, + true, + (69, 30), + None, + None, + None, + &overrides, + &HashSet::new(), + None, + ); + assert!(collapsed.machine.is_none()); + + let at_boundary = sidebar_layout_for_state( + &config, + true, + false, + true, + (70, 30), + None, + None, + None, + &overrides, + &HashSet::new(), + Some(&collapsed), + ); + assert!(at_boundary.machine.is_none()); + let revealed = sidebar_layout_for_state( + &config, + true, + false, + true, + (74, 30), + None, + None, + None, + &overrides, + &HashSet::new(), + Some(&at_boundary), + ); + assert!(revealed.machine.is_some()); + } + #[test] fn single_surface_layout_uses_every_terminal_cell_without_chrome() { let (mux, surface) = test_mux("single-surface-layout-test", None); @@ -20973,7 +23495,13 @@ mod tests { let mut terminal = Terminal::new(TestBackend::new(80, 25)).unwrap(); terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); let buffer = terminal.backend().buffer(); - let expected = [(71, "復"), (73, "元"), (75, "失"), (77, "敗")]; + let status = app.rendered_status_message.clone().expect("rendered status message"); + let expected = [ + (status.rect.x, "復"), + (status.rect.x + 2, "元"), + (status.rect.x + 4, "失"), + (status.rect.x + 6, "敗"), + ]; for (x, symbol) in expected { assert_eq!(buffer[(x, 24)].symbol(), symbol); } @@ -20984,7 +23512,10 @@ mod tests { matches!(hit, super::Hit::HorizontalScrollbar { .. }).then_some(*rect) }) .expect("wide viewport should render a horizontal scrollbar"); - assert!(track.x + track.width < 70, "track must end before the 10-cell status label"); + assert!( + track.x.saturating_add(track.width) <= status.rect.x.saturating_sub(1), + "track must end before the status label" + ); app.status_message = Some("status failure details ".repeat(20)); terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); @@ -21001,6 +23532,161 @@ mod tests { } } + #[test] + fn status_message_renders_and_is_selectable_without_a_workspace() { + let mux = Mux::new("empty-status-message-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.sidebar_visible = false; + app.status_message = Some("initial terminal launch failed".to_string()); + app.sync_layout((80, 25)); + + let mut terminal = Terminal::new(TestBackend::new(80, 25)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let y = 24; + let start = (0..80) + .find(|x| terminal.backend().buffer()[(*x, y)].symbol() == "i") + .expect("status message must render without an active workspace"); + + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: start, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + + assert!(matches!(app.drag, Some(Drag::StatusMessage { .. }))); + } + + #[test] + fn status_message_drag_selection_highlights_the_visible_text() { + let (mux, _) = test_mux("status-message-selection-test", None); + let mut app = test_app(Session::Local(mux.clone())); + app.sidebar_visible = false; + app.status_message = Some("attach failed".to_string()); + app.sync_layout((80, 25)); + + let mut terminal = Terminal::new(TestBackend::new(80, 25)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let y = 24; + let start = (0..80) + .find(|x| terminal.backend().buffer()[(*x, y)].symbol() == "a") + .expect("status message must render on the final row"); + + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: start, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: start + 5, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: start + 5, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + for x in start..=start + 5 { + assert_eq!( + terminal.backend().buffer()[(x, y)].bg, + app.config.theme.selection_bg, + "status cell {x} must retain the native selection highlight" + ); + } + + let surfaces = mux.with_state(|state| state.surfaces.keys().copied().collect::>()); + for surface in surfaces { + mux.close_surface(surface).unwrap(); + } + } + + #[test] + fn status_message_context_menu_offers_full_message_copy() { + let (mux, _) = test_mux("status-message-copy-menu-test", None); + let mut app = test_app(Session::Local(mux.clone())); + app.sidebar_visible = false; + let message = "attach failed with details beyond the visible label"; + app.status_message = Some(message.to_string()); + app.sync_layout((80, 25)); + + let mut terminal = Terminal::new(TestBackend::new(80, 25)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let y = 24; + let x = (0..80) + .find(|x| terminal.backend().buffer()[(*x, y)].symbol() == "a") + .expect("status message must render on the final row"); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Right), + column: x, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + + let labels = app + .menu + .as_ref() + .expect("right-clicking the status message must open a menu") + .actions() + .into_iter() + .map(|action| action.label()) + .collect::>(); + assert!(labels.contains(&"Copy message"), "status menu actions: {labels:?}"); + + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Right), + column: x, + row: y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert_eq!(app.status_message.as_deref(), Some(message)); + assert_eq!(app.toast.as_ref().map(|toast| toast.text.as_str()), Some("Copied")); + + let surfaces = mux.with_state(|state| state.surfaces.keys().copied().collect::>()); + for surface in surfaces { + mux.close_surface(surface).unwrap(); + } + } + + #[test] + fn status_message_has_a_visible_copy_control_and_hover_pins_it() { + let mux = Mux::new("status-message-copy-button-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.sidebar_visible = false; + app.status_message = Some("SSH connection failed".to_string()); + app.sync_layout((80, 25)); + + let mut terminal = Terminal::new(TestBackend::new(80, 25)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(rendered.lines().last().unwrap().contains("Copy"), "{rendered}"); + let status = app.rendered_status_message.clone().expect("rendered status message"); + app.handle_mouse(MouseEvent { + kind: MouseEventKind::Moved, + column: status.rect.x, + row: status.rect.y, + modifiers: KeyModifiers::NONE, + }) + .unwrap(); + app.handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::ALT)).unwrap(); + + assert_eq!(app.status_message.as_deref(), Some("SSH connection failed")); + app.run_action(Action::ToggleSidebarCompact).unwrap(); + assert_eq!(app.status_message.as_deref(), Some("SSH connection failed")); + } + #[test] fn viewport_columns_resize_with_shortcuts_and_mouse_drag() { let mux = Mux::new("viewport-pane-resize-test", SurfaceOptions::default()); @@ -22679,6 +25365,105 @@ mod tests { assert!(!menu.close_submenu()); } + #[test] + fn searchable_context_menu_filters_large_catalogs_and_keeps_fallback() { + let items = (0..4_096) + .map(|index| MenuItem::LabeledAction { + label: format!("cloud-mac-{index:04}"), + action: MenuAction::ConnectMachineTarget(index), + }) + .collect::>(); + let mut menu = ContextMenu::searchable( + 10, + 5, + "SSH hosts", + "type to filter", + items, + vec![MenuItem::Action(MenuAction::ConnectOtherMachine)], + ); + + assert_eq!(menu.actions().len(), 4_097); + assert_eq!(menu.levels[0].items[0].action(), Some(MenuAction::ConnectOtherMachine)); + assert_eq!(menu.levels[0].items[1], MenuItem::Separator); + assert_eq!(menu.levels[0].items[2].label(), Some("cloud-mac-0000")); + assert!(menu.insert_search_text("3999")); + assert_eq!(menu.levels[0].items.len(), 3); + assert_eq!(menu.levels[0].items[0].action(), Some(MenuAction::ConnectOtherMachine)); + assert_eq!(menu.levels[0].items[1], MenuItem::Separator); + assert_eq!(menu.levels[0].items[2].label(), Some("cloud-mac-3999")); + assert_eq!(menu.selected_action(), Some(MenuAction::ConnectMachineTarget(3_999))); + + assert!(menu.handle_search_key(&KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL,))); + assert_eq!(menu.levels[0].items.len(), 4_098); + } + + #[test] + fn overflowing_connect_machine_menu_draws_and_wheels_a_scrollbar() { + let mux = Mux::new("connect-menu-scrollbar-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: Vec::new(), + active: None, + capabilities: MachineCapabilities { create: false, connect: true }, + }); + ui.connection_targets = (0..40) + .map(|index| MachineConnectionTarget { + target: format!("ssh-host-{index:02}"), + name: format!("ssh-host-{index:02}"), + }) + .collect(); + app.machine_ui = Some(ui); + app.open_machine_connection_menu(1, 3); + + let mut terminal = Terminal::new(TestBackend::new(40, 8)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rect = app.menu.as_ref().unwrap().levels[0].rect; + let track_x = rect.x + rect.width.saturating_sub(2); + let buffer = terminal.backend().buffer(); + assert!( + (rect.y + 1..rect.y + rect.height.saturating_sub(1)) + .any(|y| matches!(buffer[(track_x, y)].symbol(), "▕" | "▐")), + "overflowing SSH host picker must render its scrollbar thumb" + ); + + let action = app.handle_scroll(track_x, rect.y + 1, true, KeyModifiers::NONE).unwrap(); + assert_eq!(action, RenderAction::Draw); + assert!(app.menu.as_ref().unwrap().levels[0].scroll_offset > 0); + } + + #[test] + fn context_menu_scrollbar_track_clicks_and_drags() { + let mux = Mux::new("context-menu-scrollbar-pointer-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let items = (0..40) + .map(|index| MenuItem::LabeledAction { + label: format!("ssh-host-{index:02}"), + action: MenuAction::ConnectMachineTarget(index), + }) + .collect(); + app.menu = Some(ContextMenu::searchable( + 1, + 3, + "SSH hosts", + "type to filter", + items, + vec![MenuItem::Action(MenuAction::ConnectOtherMachine)], + )); + let mut terminal = Terminal::new(TestBackend::new(40, 8)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rect = app.menu.as_ref().unwrap().levels[0].rect; + let track_x = rect.x + rect.width.saturating_sub(2); + let track_top = rect.y + 1; + let track_bottom = rect.y + rect.height.saturating_sub(2); + + app.handle_left_down(track_x, track_bottom, KeyModifiers::NONE).unwrap(); + assert!(app.menu.as_ref().unwrap().levels[0].scroll_offset > 0); + app.handle_left_drag(track_x, track_top).unwrap(); + assert_eq!(app.menu.as_ref().unwrap().levels[0].scroll_offset, 0); + app.handle_left_up(track_x, track_top).unwrap(); + assert!(app.menu.is_some()); + } + #[test] fn topmost_menu_chrome_blocks_hits_on_overlapped_parent_actions() { let mut menu = ContextMenu::with_groups( @@ -25862,7 +28647,7 @@ mod tests { } #[test] - fn attached_workspace_mouse_click_uses_both_rendered_rows_and_survives_routing_refresh() { + fn attached_workspace_mouse_down_uses_both_rendered_rows_and_survives_routing_refresh() { let mux = Mux::new( "attached-workspace-mouse-test", SurfaceOptions { @@ -25910,10 +28695,15 @@ mod tests { }; app.handle(event(MouseEventKind::Down(MouseButton::Left))).unwrap(); + assert_eq!( + app.tree.active_workspace, 0, + "a sidebar workspace must activate on mouse-down" + ); assert!(matches!(app.drag, Some(Drag::WorkspaceArm { .. }))); // A concurrent frontend can invalidate routing after the press. - // The release still belongs to the armed stable workspace ID. + // The release still belongs to the reorder gesture, but does not + // own activation. app.pointer_route_phase = PointerRoutePhase::DrawPending; app.handle(event(MouseEventKind::Up(MouseButton::Left))).unwrap(); assert_eq!(app.tree.active_workspace, 0); @@ -26474,7 +29264,7 @@ mod tests { } #[test] - fn single_surface_mux_forwarder_drops_unrelated_output_and_titles() { + fn single_surface_mux_forwarder_drops_unrelated_output_titles_and_agents() { let (tx, rx) = std::sync::mpsc::sync_channel(4); let tx = SessionEventSender::filtered(tx, 41); let titles = MuxTitleIngress::default(); @@ -26491,6 +29281,20 @@ mod tests { forward_mux_event(MuxEvent::SurfaceOutput(42), &tx, &titles), ForwardMuxOutcome::Continue )); + assert!(matches!( + forward_mux_event( + MuxEvent::AgentChanged { + surface: 42, + state: "working".into(), + source: "hook".into(), + session: None, + updated_at_ms: 1, + }, + &tx, + &titles, + ), + ForwardMuxOutcome::Continue + )); assert!(rx.try_recv().is_err()); assert!(titles.take_dirty().is_empty()); @@ -26499,6 +29303,24 @@ mod tests { ForwardMuxOutcome::Continue )); assert!(matches!(rx.try_recv().unwrap(), AppEvent::Mux(MuxEvent::SurfaceOutput(41)))); + assert!(matches!( + forward_mux_event( + MuxEvent::AgentChanged { + surface: 41, + state: "working".into(), + source: "hook".into(), + session: None, + updated_at_ms: 2, + }, + &tx, + &titles, + ), + ForwardMuxOutcome::Continue + )); + assert!(matches!( + rx.try_recv().unwrap(), + AppEvent::Mux(MuxEvent::AgentChanged { surface: 41, .. }) + )); } #[test] @@ -26727,14 +29549,16 @@ mod tests { let mux = Mux::new("resize-client-refresh-test", SurfaceOptions::default()); let mut app = test_app(Session::Local(mux)); - app.handle(AppEvent::Mux(MuxEvent::SurfaceResized { - surface: 7, - cols: 80, - rows: 24, - reservation_id: None, - })) - .unwrap(); + let action = app + .handle(AppEvent::Mux(MuxEvent::SurfaceResized { + surface: 7, + cols: 80, + rows: 24, + reservation_id: None, + })) + .unwrap(); + assert_eq!(action, RenderAction::Paint); assert!(!app.session.client_refresh_queued.load(Ordering::Acquire)); } @@ -31386,7 +34210,9 @@ mod tests { let (mux, surface) = test_mux("focus-builtin-sidebar-test", None); let mut app = test_app(Session::Local(mux.clone())); app.tree = notify_tree(surface.id, false); + app.sync_layout((100, 16)); app.sidebar_visible = false; + app.sync_layout((100, 16)); app.run_action(Action::FocusSidebar).unwrap(); assert!(app.sidebar_visible); @@ -31397,6 +34223,25 @@ mod tests { mux.close_surface(surface.id).unwrap(); } + #[test] + fn focus_sidebar_uses_only_visible_rails() { + let mux = Mux::new("focus-visible-rails-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut machine_ui = provider_machine_ui(); + machine_ui.session_available = true; + app.machine_ui = Some(machine_ui); + app.hidden_sidebar_views + .entry(app.config.sidebar.active_profile.clone()) + .or_default() + .insert("workspaces".into()); + app.sync_layout((100, 16)); + assert_eq!(app.visible_rail_order(), vec![RailKind::Machine]); + + app.run_action(Action::FocusSidebar).unwrap(); + + assert_eq!(app.focus, FocusTarget::MachineRail); + } + #[test] fn sidebar_context_menu_focus_is_idempotent() { let (mux, surface) = test_mux("sidebar-menu-focus-test", None); @@ -31601,7 +34446,144 @@ mod tests { } #[test] - fn recoverable_machine_is_rendered_and_mouse_restorable_or_purgeable() { + fn active_machine_enter_returns_focus_to_pane() { + let mux = Mux::new("active-machine-enter-focus-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: vec![MachineDescriptor { + key: MachineKey(41), + id: "machine-41".into(), + name: "active".into(), + subtitle: "local".into(), + status: MachineStatus::Running, + }], + active: Some(MachineKey(41)), + capabilities: MachineCapabilities::default(), + }); + ui.session_available = true; + app.machine_ui = Some(ui); + app.machine_selection_intent = Some(MachineKey(41)); + app.machine_presented = Some(MachineKey(41)); + app.focus = FocusTarget::MachineRail; + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + + assert_eq!(app.focus, FocusTarget::Pane); + assert!(app.machine_ui.as_ref().unwrap().request.is_none()); + } + + #[test] + fn machine_keyboard_switch_returns_focus_to_pane() { + let mux = Mux::new("machine-keyboard-switch-focus-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: vec![ + MachineDescriptor { + key: MachineKey(41), + id: "machine-41".into(), + name: "active".into(), + subtitle: "local".into(), + status: MachineStatus::Running, + }, + MachineDescriptor { + key: MachineKey(42), + id: "machine-42".into(), + name: "remote".into(), + subtitle: "ssh".into(), + status: MachineStatus::Running, + }, + ], + active: Some(MachineKey(41)), + capabilities: MachineCapabilities::default(), + }); + ui.select_rail_target(crate::machine::MachineRailTarget::Machine(MachineKey(42))); + app.machine_ui = Some(ui); + app.machine_selection_intent = Some(MachineKey(41)); + app.machine_presented = Some(MachineKey(41)); + app.focus = FocusTarget::MachineRail; + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::Switch(MachineKey(42))) + ); + assert_eq!(app.focus, FocusTarget::Pane); + } + + #[test] + fn machine_switch_is_requested_on_mouse_down() { + let mux = Mux::new("machine-mouse-down-switch-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.machine_ui = Some(MachineUiState::new(MachineSnapshot { + machines: vec![ + MachineDescriptor { + key: MachineKey(41), + id: "machine-41".into(), + name: "active".into(), + subtitle: "local".into(), + status: MachineStatus::Running, + }, + MachineDescriptor { + key: MachineKey(42), + id: "machine-42".into(), + name: "remote".into(), + subtitle: "ssh".into(), + status: MachineStatus::Running, + }, + ], + active: Some(MachineKey(41)), + capabilities: MachineCapabilities::default(), + })); + app.machine_selection_intent = Some(MachineKey(41)); + app.machine_presented = Some(MachineKey(41)); + app.sync_layout((100, 14)); + + let mut terminal = Terminal::new(TestBackend::new(100, 14)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let hit = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::Machine { key: MachineKey(42), .. }).then_some(*rect) + }) + .unwrap(); + + app.handle_left_down(hit.x, hit.y, KeyModifiers::NONE).unwrap(); + + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::Switch(MachineKey(42))) + ); + assert_eq!(app.machine_ui.as_ref().unwrap().snapshot.active, Some(MachineKey(41))); + assert_eq!(app.focus, FocusTarget::Pane); + + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let selected = &terminal.backend().buffer()[(hit.x + 3, hit.y)]; + assert_eq!( + selected.style().bg, + Some(app.chrome.sidebar_selected_bg), + "mouse-down must paint the selected machine before its connection commits" + ); + + let active_hit = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::Machine { key: MachineKey(41), .. }).then_some(*rect) + }) + .unwrap(); + app.handle_left_down(active_hit.x, active_hit.y, KeyModifiers::NONE).unwrap(); + assert!( + app.machine_ui.as_ref().unwrap().request.is_none(), + "returning to the presented machine must cancel an unsubmitted remote switch" + ); + assert_eq!(app.selected_machine(), Some(MachineKey(41))); + assert!(app.session_available()); + } + + #[test] + fn recoverable_machine_activates_on_mouse_down_and_remains_purgeable() { let mux = Mux::new("managed-machine-mouse-test", SurfaceOptions::default()); let mut app = test_app(Session::Local(mux)); app.machine_ui = Some(provider_machine_ui_with_machine_lifecycle()); @@ -31622,6 +34604,13 @@ mod tests { .unwrap(); app.handle_left_down(hit.x, hit.y, KeyModifiers::NONE).unwrap(); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::RestoreManagedMachine { + machine: MachineKey(42), + expected_version: 12, + }) + ); app.handle_left_up(hit.x, hit.y).unwrap(); assert_eq!( app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), @@ -31633,30 +34622,17 @@ mod tests { app.machine_ui.as_mut().unwrap().request = None; app.open_context_menu(hit.x, hit.y); - assert_eq!( - app.menu.as_ref().map(|menu| menu.levels[0].items.to_vec()), - Some(vec![ - MenuItem::Action(MenuAction::RestoreManagedMachine(MachineKey(42))), - MenuItem::Action(MenuAction::PurgeManagedMachine(MachineKey(42))), - MenuItem::Separator, - MenuItem::ActionWithShortcut { - action: MenuAction::ToggleSidebar { visible: true }, - shortcut: "Ctrl-b s".into(), - }, - MenuItem::ActionWithShortcut { - action: MenuAction::ToggleSidebarCompact { compact: false }, - shortcut: "Ctrl-b m".into(), - }, - MenuItem::ActionWithShortcut { - action: MenuAction::FocusSidebar, - shortcut: "Ctrl-b S".into(), - }, - MenuItem::Separator, - MenuItem::ActionWithShortcut { - action: MenuAction::ShowShortcuts, - shortcut: "Ctrl-b ?".into(), - }, - ]) + let menu_items = app.menu.as_ref().unwrap().levels[0].items.to_vec(); + assert!( + matches!( + menu_items.as_slice(), + [ + MenuItem::Action(MenuAction::RestoreManagedMachine(MachineKey(42))), + MenuItem::Action(MenuAction::PurgeManagedMachine(MachineKey(42))), + .. + ] + ), + "recoverable machine actions: {menu_items:?}" ); app.activate_menu(MenuAction::PurgeManagedMachine(MachineKey(42))).unwrap(); app.prompt.as_mut().unwrap().input.insert_str("CONFIRM"); @@ -31705,13 +34681,13 @@ mod tests { app.replay_deferred_input().unwrap(); assert!( - !matches!(app.drag, Some(Drag::MachineArm { .. })), - "a press must not arm a machine row whose provider semantics changed" + app.machine_ui.as_ref().unwrap().request.is_none(), + "a deferred press must not activate a row whose provider semantics changed" ); } #[test] - fn held_machine_release_cannot_retarget_changed_provider_semantics() { + fn machine_release_does_not_reactivate_after_provider_update() { let mux = Mux::new("managed-machine-held-identity-test", SurfaceOptions::default()); let mut app = test_app(Session::Local(mux)); app.machine_ui = Some(provider_machine_ui_with_machine_lifecycle()); @@ -31733,7 +34709,13 @@ mod tests { modifiers: KeyModifiers::NONE, }))) .unwrap(); - assert!(matches!(app.drag, Some(Drag::MachineArm { .. }))); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::RestoreManagedMachine { + machine: MachineKey(42), + expected_version: 12, + }) + ); let action = app .handle(AppEvent::MachineUiUpdated(Box::new( @@ -31758,17 +34740,22 @@ mod tests { let mux = Mux::new("replayed-machine-action-submit-test", SurfaceOptions::default()); let (mut app, _events) = test_app_with_events(Session::Local(mux)); app.machine_ui = Some(provider_machine_ui_with_machine_lifecycle()); - let at = (4, 4); - let target = app.machine_pointer_target(MachineKey(42)).unwrap(); - app.drag = Some(Drag::MachineArm { target, at }); - app.active_pointer_buttons.insert(MouseButton::Left); + let mut terminal = Terminal::new(TestBackend::new(100, 14)).unwrap(); + app.render_action(&mut terminal, RenderAction::Draw).unwrap(); + let hit = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::Machine { key: MachineKey(42), .. }).then_some(*rect) + }) + .unwrap(); let (controller, _requests) = fake_controller(FakeMachineAction::Fail("expected failure")); install_machine_controller(&mut app, controller); app.deferred_input.push_back(queued_input( TerminalInput::Mouse(MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: at.0, - row: at.1, + kind: MouseEventKind::Down(MouseButton::Left), + column: hit.x, + row: hit.y, modifiers: KeyModifiers::NONE, }), None, @@ -32346,7 +35333,7 @@ mod tests { } #[test] - fn recoverable_workspace_is_mouse_visible_and_keyboard_restorable() { + fn recoverable_workspace_activates_on_mouse_down_and_keyboard() { let mux = Mux::new("recoverable-workspace-rail-test", SurfaceOptions::default()); let mut app = test_app(Session::Local(mux)); app.tree = notify_tree(1, false); @@ -32370,6 +35357,26 @@ mod tests { app.handle_left_down(hit.x, hit.y, KeyModifiers::NONE).unwrap(); assert_eq!(app.workspace_rail_selection, WorkspaceRailSelection::Recoverable); + assert_eq!(app.focus, FocusTarget::Pane); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::RestoreManagedWorkspace { + machine: MachineKey(41), + workspace_id: "00000000-0000-4000-8000-000000000099".into(), + expected_version: 12, + }) + ); + + app.machine_ui.as_mut().unwrap().request = None; + let header = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::RailHeader(RailKind::Workspace)).then_some(*rect) + }) + .unwrap(); + app.handle_left_down(header.x, header.y, KeyModifiers::NONE).unwrap(); + assert_eq!(app.focus, FocusTarget::WorkspaceRail); app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); assert_eq!( app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), @@ -32880,6 +35887,25 @@ mod tests { assert_eq!(app.focus, FocusTarget::WorkspaceRail); } + #[test] + fn machine_ui_survives_initial_pty_exhaustion_with_an_actionable_status() { + let machine_ui = provider_machine_ui(); + let failure = anyhow::anyhow!( + "remote command rejected: failed to open PTY: Device not configured (os error 6)" + ); + + let status = super::recover_initial_workspace_failure(Err(failure), Some(&machine_ui)) + .unwrap() + .expect("machine mode keeps the launch failure as status"); + assert_eq!(status, localization::catalog().runtime.terminal_capacity_exhausted); + + let plain_failure = anyhow::anyhow!("failed to open PTY: Device not configured"); + assert!( + super::recover_initial_workspace_failure(Err(plain_failure), None).is_err(), + "plain mode must still fail before switching the host terminal into raw mode" + ); + } + #[test] fn connect_machine_footer_captures_the_route_shown_by_each_entrypoint() { let mux = Mux::new("connect-machine-footer-input-test", SurfaceOptions::default()); @@ -32907,6 +35933,7 @@ mod tests { update.connect_accepts_pairing_code = false; app.apply_machine_ui_update(update); app.commit_prompt(); + assert!(app.prompt.is_some(), "connection prompt must become a loading dialog"); assert_eq!( app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), Some(&MachineRequest::Connect { @@ -32914,6 +35941,7 @@ mod tests { route: MachineConnectRoute::Provider, }) ); + app.close_prompt(); let machine = app.machine_ui.as_mut().unwrap(); machine.request = None; @@ -32930,6 +35958,7 @@ mod tests { update.connect_accepts_pairing_code = true; app.apply_machine_ui_update(update); app.commit_prompt(); + assert!(app.prompt.is_some(), "connection prompt must become a loading dialog"); assert_eq!( app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), Some(&MachineRequest::Connect { @@ -32939,6 +35968,85 @@ mod tests { ); } + #[test] + fn stale_connection_completion_cannot_settle_a_retry_to_the_same_host() { + let mux = Mux::new("connection-attempt-correlation-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let request = MachineRequest::Connect { + target: "mini.local".into(), + route: MachineConnectRoute::Local, + }; + app.connection_transaction = Some(super::ConnectionTransaction { + attempt: 2, + target: "mini.local".into(), + route: MachineConnectRoute::Local, + phase: super::ConnectionDialogPhase::Connecting, + }); + + app.report_machine_action_failure(Some(&request), Some(1), "old failure".into()); + assert_eq!( + app.connection_transaction.as_ref().map(|transaction| &transaction.phase), + Some(&super::ConnectionDialogPhase::Connecting) + ); + assert!(app.status_message.is_none()); + + app.report_machine_action_failure(Some(&request), Some(2), "current failure".into()); + assert!(matches!( + app.connection_transaction.as_ref().map(|transaction| &transaction.phase), + Some(super::ConnectionDialogPhase::Failed(error)) if error == "current failure" + )); + assert_eq!(app.status_message.as_deref(), Some("current failure")); + } + + #[test] + fn connection_dialog_renders_loading_error_retry_and_copy_states() { + let mux = Mux::new("connection-dialog-state-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.machine_ui = Some(provider_machine_ui()); + app.begin_machine_connection("mini.local".into(), MachineConnectRoute::Local); + app.sync_layout((100, 24)); + let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap(); + + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(rendered.contains("Connecting to mini.local"), "{rendered}"); + + let request = MachineRequest::Connect { + target: "mini.local".into(), + route: MachineConnectRoute::Local, + }; + let attempt = app.connection_transaction.as_ref().unwrap().attempt; + app.fail_connection_transaction( + Some(&request), + Some(attempt), + "permission denied by remote host".into(), + ); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(rendered.contains("Could not connect to mini.local"), "{rendered}"); + assert!(rendered.contains("permission denied by remote host"), "{rendered}"); + assert!(rendered.contains("Retry"), "{rendered}"); + assert!(rendered.contains("Copy message"), "{rendered}"); + let prompt = app.prompt.as_ref().unwrap(); + assert!(prompt.ok.width > 0); + assert!(prompt.clear.width > 0); + } + + #[test] + fn closing_connection_dialog_removes_the_queued_connect_request() { + let mux = Mux::new("connection-dialog-queued-cancel-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.machine_ui = Some(provider_machine_ui()); + app.begin_machine_connection("mini.local".into(), MachineConnectRoute::Local); + + app.close_prompt(); + + assert!(app.prompt.is_none()); + assert!(app.connection_transaction.is_none()); + assert!(app.machine_ui.as_ref().is_some_and(|ui| ui.request.is_none())); + assert!(!app.machine_action_in_flight); + } + #[test] fn provider_owned_workspace_policy_never_creates_an_untracked_session_workspace() { let mux = Mux::new("provider-owned-initial-workspace-test", SurfaceOptions::default()); @@ -33147,6 +36255,47 @@ mod tests { assert!(app.prompt.is_some()); } + #[test] + fn new_machine_opens_native_source_picker_and_routes_stable_source_id() { + let mux = Mux::new("machine-source-picker-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: vec![MachineDescriptor { + key: MachineKey(1), + id: "current".into(), + name: "local".into(), + subtitle: "local".into(), + status: MachineStatus::Running, + }], + active: Some(MachineKey(1)), + capabilities: MachineCapabilities { create: true, connect: false }, + }); + ui.creation_sources = vec![ + MachineCreationSource { + id: "docker".into(), + name: "Docker".into(), + subtitle: "container prototype".into(), + }, + MachineCreationSource { + id: "firecracker".into(), + name: "Firecracker".into(), + subtitle: "microVM prototype".into(), + }, + ]; + ui.rail_selection = MachineRailSelection::NewVm; + app.machine_ui = Some(ui); + app.focus = FocusTarget::MachineRail; + app.sync_layout((100, 12)); + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert!(app.menu.is_some()); + app.handle_menu_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::CreateFrom { source_id: "docker".into() }) + ); + } + #[test] fn keyboard_traverses_every_advertised_workspace_creation_mode() { let mux = Mux::new("workspace-rail-keyboard-test", SurfaceOptions::default()); @@ -33162,7 +36311,7 @@ mod tests { app.handle_key(KeyEvent::new(KeyCode::Home, KeyModifiers::NONE)).unwrap(); assert_eq!( app.workspace_rail_selection, - WorkspaceRailSelection::ManagedCreation(WorkspaceCreationMode::Host) + workspace_creation_selection(Some(WorkspaceCreationMode::Host)) ); app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); assert_eq!( @@ -33174,7 +36323,7 @@ mod tests { app.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)).unwrap(); assert_eq!( app.workspace_rail_selection, - WorkspaceRailSelection::ManagedCreation(WorkspaceCreationMode::Isolated) + workspace_creation_selection(Some(WorkspaceCreationMode::Isolated)) ); app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); assert_eq!( @@ -33207,6 +36356,85 @@ mod tests { })); } + #[test] + fn alt_directional_focus_traverses_sidebar_at_the_pane_boundary() { + let (mux, surface) = test_mux("alt-sidebar-boundary-test", None); + let mut app = test_app(Session::Local(mux.clone())); + let mut machine_ui = provider_machine_ui(); + machine_ui.session_available = true; + app.machine_ui = Some(machine_ui); + app.sidebar_view = SidebarView::Workspaces; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 16)); + + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::WorkspaceRail); + + app.handle_key(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::MachineRail); + app.handle_key(KeyEvent::new(KeyCode::Char('l'), KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::WorkspaceRail); + + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + + app.sidebar_view = SidebarView::Files; + app.focus = FocusTarget::WorkspaceRail; + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + + mux.close_surface(surface.id).unwrap(); + } + + #[test] + fn sidebar_headers_are_the_only_pointer_entrypoint_for_rail_focus() { + let (mux, surface) = test_mux("sidebar-pointer-focus-test", None); + let (mut app, events) = test_app_with_events(Session::Local(mux.clone())); + let mut machine_ui = provider_machine_ui(); + machine_ui.session_available = true; + app.machine_ui = Some(machine_ui); + app.sidebar_view = SidebarView::Workspaces; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 16)); + + let mut terminal = Terminal::new(TestBackend::new(100, 16)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let machine_row = app + .hits + .iter() + .find_map(|(rect, hit)| matches!(hit, super::Hit::Machine { .. }).then_some(*rect)) + .unwrap(); + let workspace_row = app + .hits + .iter() + .find_map(|(rect, hit)| matches!(hit, super::Hit::Workspace { .. }).then_some(*rect)) + .unwrap(); + let machine_area = app.sidebar_layout.machine.unwrap(); + let workspace_area = app.sidebar_layout.workspace.unwrap(); + + app.focus = FocusTarget::WorkspaceRail; + app.handle_left_down(workspace_row.x, workspace_row.y, KeyModifiers::NONE).unwrap(); + app.handle_left_up(workspace_row.x, workspace_row.y).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + while app.session.has_pending_mutations() { + app.handle(events.recv_timeout(Duration::from_secs(1)).unwrap()).unwrap(); + } + + app.handle_left_down(workspace_area.x + 1, workspace_area.y, KeyModifiers::NONE).unwrap(); + app.handle_left_up(workspace_area.x + 1, workspace_area.y).unwrap(); + assert_eq!(app.focus, FocusTarget::WorkspaceRail); + + app.handle_left_down(machine_row.x, machine_row.y, KeyModifiers::NONE).unwrap(); + app.handle_left_up(machine_row.x, machine_row.y).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + + app.handle_left_down(machine_area.x + 1, machine_area.y, KeyModifiers::NONE).unwrap(); + app.handle_left_up(machine_area.x + 1, machine_area.y).unwrap(); + assert_eq!(app.focus, FocusTarget::MachineRail); + + mux.close_surface(surface.id).unwrap(); + } + #[test] fn mouse_drag_resizes_machine_and_workspace_rails_independently() { let mux = Mux::new("rail-mouse-resize-test", SurfaceOptions::default()); @@ -33228,7 +36456,7 @@ mod tests { let rect = divider(&app, kind); let target_x = rect.x + 3; let expected = - rail_drag_width(&app.config, app.sidebar_layout, kind, target_x).unwrap(); + rail_drag_width(&app.config, &app.sidebar_layout, kind, target_x).unwrap(); app.handle_mouse(MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: rect.x, @@ -33259,6 +36487,10 @@ mod tests { RailKind::Workspace => { assert_eq!(app.sidebar_width_override, Some(expected)); } + RailKind::Tabs => unreachable!("tabs rail is not configured in this test"), + RailKind::Projection(_) => { + unreachable!("projection rail is not configured in this test") + } } } } @@ -33372,7 +36604,7 @@ mod tests { let jumped = app.workspace_rail_scroll; assert!(jumped > 0); assert!(!app.workspace_rail_follow_selection); - assert_eq!(app.focus, FocusTarget::WorkspaceRail); + assert_eq!(app.focus, FocusTarget::Pane); app.handle_mouse(MouseEvent { kind: MouseEventKind::Drag(MouseButton::Left), @@ -33421,6 +36653,640 @@ mod tests { ); } + #[test] + fn tabs_column_renders_selected_workspace_tabs_and_activates_through_native_focus() { + let (mux, first) = test_mux("tabs-column-test", None); + let pane = mux.with_state(|state| state.pane_of(first.id).unwrap()); + let second = mux.new_tab(Some(pane), None, Some((80, 24))).unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns_explicit = true; + app.config.sidebar.columns = vec![ + crate::config::SidebarColumn { + kind: SidebarColumnKind::Workspaces, + width: 22, + max_width: 0, + }, + crate::config::SidebarColumn { kind: SidebarColumnKind::Tabs, width: 24, max_width: 0 }, + ]; + app.config.sidebar.views = app + .config + .sidebar + .columns + .iter() + .map(|column| SidebarViewSpec::legacy(column.kind, column.width, column.max_width)) + .collect(); + app.config.sidebar.views_explicit = true; + app.sidebar_view = SidebarView::Workspaces; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + assert!(app.sidebar_layout.tabs.is_some()); + assert_eq!(app.sidebar_tab_targets().len(), 2); + assert!(app.hits.iter().any(|(_, hit)| { + matches!(hit, super::Hit::SidebarTab { surface, .. } if *surface == first.id) + })); + + let first_row = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::SidebarTab { surface, .. } if *surface == first.id) + .then_some(*rect) + }) + .unwrap(); + app.handle_left_down(first_row.x, first_row.y, KeyModifiers::NONE).unwrap(); + assert_eq!(app.tree.active_surface(), Some(first.id)); + assert_eq!(app.focus, FocusTarget::Pane); + + app.focus = FocusTarget::WorkspaceRail; + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::NONE)).unwrap(); + assert_eq!(app.focus, FocusTarget::TabsRail); + app.tabs_rail_selection = 0; + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert_eq!(app.tree.active_surface(), Some(first.id)); + assert_eq!(app.focus, FocusTarget::Pane); + + for surface in [first.id, second.id] { + mux.close_surface(surface).unwrap(); + } + } + + #[test] + fn projection_workspace_row_activates_on_mouse_down() { + let mux = Mux::new("projection-workspace-mouse-down-test", SurfaceOptions::default()); + let first = mux.new_workspace(Some("Alpha".into()), Some((80, 24))).unwrap(); + let second = mux.new_workspace(Some("Beta".into()), Some((80, 24))).unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: Vec::new(), + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + assert_eq!(app.tree.active_workspace, 1); + let first_row = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!( + hit, + super::Hit::ProjectionRow { + target: crate::sidebar_projection::ProjectionTarget::Workspace { + index: 0, + .. + }, + .. + } + ) + .then_some(*rect) + }) + .unwrap(); + + app.handle_left_down(first_row.x, first_row.y, KeyModifiers::NONE).unwrap(); + + assert_eq!(app.tree.active_workspace, 0); + assert_eq!(app.focus, FocusTarget::Pane); + + for surface in [first.id, second.id] { + mux.close_surface(surface).unwrap(); + } + } + + #[test] + fn workspace_keyboard_enter_returns_focus_to_pane() { + let mux = Mux::new("workspace-keyboard-enter-focus-test", SurfaceOptions::default()); + let first = mux.new_workspace(Some("Alpha".into()), Some((80, 24))).unwrap(); + let second = mux.new_workspace(Some("Beta".into()), Some((80, 24))).unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.sidebar_view = SidebarView::Workspaces; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + app.sidebar_workspace_selection = 0; + app.workspace_rail_selection = WorkspaceRailSelection::Workspace; + app.focus = FocusTarget::WorkspaceRail; + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + + assert_eq!(app.focus, FocusTarget::Pane); + + for surface in [first.id, second.id] { + mux.close_surface(surface).unwrap(); + } + } + + #[test] + fn projection_enter_on_active_surface_returns_focus_to_pane() { + let (mux, surface) = test_mux("projection-active-surface-enter-test", None); + mux.report_agent( + surface.id, + AgentState::Working, + AgentSource::Hook, + Some("agent-session".into()), + ) + .unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: Vec::new(), + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + app.projection_rail_state_mut(0).selected = 1; + app.focus = FocusTarget::ProjectionRail(0); + + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + + assert_eq!(app.tree.active_surface(), Some(surface.id)); + assert_eq!(app.focus, FocusTarget::Pane); + + mux.close_surface(surface.id).unwrap(); + } + + #[test] + fn projection_stale_action_selection_does_not_retarget_resource_row() { + let (mux, surface) = test_mux("projection-stale-action-selection-test", None); + mux.report_agent( + surface.id, + AgentState::Working, + AgentSource::Hook, + Some("agent-session".into()), + ) + .unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: Vec::new(), + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.replace_tree(app.session.tree()); + let state = app.projection_rail_state_mut(0); + state.selected = 0; + state.selected_action = Some(99); + app.focus = FocusTarget::ProjectionRail(0); + + app.handle_key(KeyEvent::new(KeyCode::Left, KeyModifiers::NONE)).unwrap(); + + assert!( + app.projection_rail_state_mut(0).collapsed.is_empty(), + "stale action selection must not collapse the selected resource row" + ); + + mux.close_surface(surface.id).unwrap(); + } + + #[test] + fn projection_agent_rows_hide_finished_reports() { + let (mux, surface) = test_mux("projection-finished-agent-test", None); + mux.report_agent( + surface.id, + AgentState::Done, + AgentSource::Hook, + Some("agent-session".into()), + ) + .unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "agents".into(), + levels: vec![SidebarResourceKind::Agents], + actions: Vec::new(), + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.replace_tree(app.session.tree()); + + assert!( + app.projection_rows(0).is_empty(), + "finished reports must not leave stale agent rows" + ); + + mux.close_surface(surface.id).unwrap(); + } + + #[test] + fn tabs_column_context_menu_renames_the_exact_clicked_tab() { + let (mux, first) = test_mux("tabs-column-rename-test", None); + let pane = mux.with_state(|state| state.pane_of(first.id).unwrap()); + let second = mux.new_tab(Some(pane), None, Some((80, 24))).unwrap(); + let (mut app, events) = test_app_with_events(Session::Local(mux.clone())); + app.config.sidebar.columns_explicit = true; + app.config.sidebar.columns = vec![ + crate::config::SidebarColumn { + kind: SidebarColumnKind::Workspaces, + width: 22, + max_width: 0, + }, + crate::config::SidebarColumn { kind: SidebarColumnKind::Tabs, width: 24, max_width: 0 }, + ]; + app.config.sidebar.views = app + .config + .sidebar + .columns + .iter() + .map(|column| SidebarViewSpec::legacy(column.kind, column.width, column.max_width)) + .collect(); + app.config.sidebar.views_explicit = true; + app.sidebar_view = SidebarView::Workspaces; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + assert_eq!(app.tree.active_surface(), Some(second.id)); + let clicked = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::SidebarTab { surface, .. } if *surface == first.id) + .then_some(*rect) + }) + .unwrap(); + + app.open_context_menu(clicked.x, clicked.y); + assert!( + app.menu.as_ref().unwrap().levels[0] + .items + .iter() + .any(|item| item.action() == Some(MenuAction::RenameSurface(first.id))) + ); + app.activate_menu(MenuAction::RenameSurface(first.id)).unwrap(); + assert_eq!( + app.prompt.as_ref().map(|prompt| prompt.target), + Some(PromptTarget::Surface(first.id)) + ); + app.prompt.as_mut().unwrap().input.insert_str("first renamed"); + app.commit_prompt(); + while app.session.has_pending_mutations() { + app.handle(events.recv_timeout(Duration::from_secs(1)).unwrap()).unwrap(); + } + + let tree = app.session.tree(); + let renamed = tree + .workspaces + .iter() + .flat_map(|workspace| workspace.screens.iter()) + .flat_map(|screen| screen.panes.iter()) + .flat_map(|pane| pane.tabs.iter()) + .find(|tab| tab.surface == first.id) + .and_then(|tab| tab.name.as_deref()); + assert_eq!(renamed, Some("first renamed")); + assert_eq!(mux.active_surface(), Some(second.id)); + } + + #[test] + fn pane_tab_context_menu_renames_the_exact_inactive_tab() { + let (mux, first) = test_mux("pane-tab-rename-test", None); + let pane = mux.with_state(|state| state.pane_of(first.id).unwrap()); + let second = mux.new_tab(Some(pane), None, Some((80, 24))).unwrap(); + let (mut app, events) = test_app_with_events(Session::Local(mux.clone())); + app.sidebar_visible = false; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + assert_eq!(app.tree.active_surface(), Some(second.id)); + let clicked = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::Tab { pane: hit_pane, index: 0 } if *hit_pane == pane) + .then_some(*rect) + }) + .unwrap(); + + app.open_context_menu(clicked.x, clicked.y); + assert!( + app.menu.as_ref().unwrap().levels[0] + .items + .iter() + .any(|item| item.action() == Some(MenuAction::RenameSurface(first.id))) + ); + app.activate_menu(MenuAction::RenameSurface(first.id)).unwrap(); + app.prompt.as_mut().unwrap().input.insert_str("inactive renamed"); + app.commit_prompt(); + while app.session.has_pending_mutations() { + app.handle(events.recv_timeout(Duration::from_secs(1)).unwrap()).unwrap(); + } + + let tree = app.session.tree(); + let renamed = tree + .workspaces + .iter() + .flat_map(|workspace| workspace.screens.iter()) + .flat_map(|screen| screen.panes.iter()) + .flat_map(|pane| pane.tabs.iter()) + .find(|tab| tab.surface == first.id) + .and_then(|tab| tab.name.as_deref()); + assert_eq!(renamed, Some("inactive renamed")); + assert_eq!(mux.active_surface(), Some(second.id)); + } + + #[test] + fn workspace_agent_tree_renders_collapses_and_renames_the_exact_surface() { + let (mux, surface) = test_mux("workspace-agent-tree-test", None); + mux.report_agent( + surface.id, + AgentState::Working, + AgentSource::Hook, + Some("agent-session".into()), + ) + .unwrap(); + let mut app = test_app(Session::Local(mux.clone())); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: vec![Action::NewWorkspace], + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.replace_tree(app.session.tree()); + app.sync_layout((100, 20)); + + let mut terminal = Terminal::new(TestBackend::new(100, 20)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(rendered.contains("workspaces › agents"), "{rendered}"); + assert!(rendered.contains("working · agent-session"), "{rendered}"); + assert!( + rendered.contains("new workspace"), + "a configured workspace representation must preserve its native creation action: {rendered}" + ); + assert!(app.hits.iter().any(|(_, hit)| matches!( + hit, + super::Hit::SidebarAction { + view: 0, + action: SidebarActionTarget::CreateWorkspace(None), + } + ))); + let surface_row = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!( + hit, + super::Hit::ProjectionRow { + target: crate::sidebar_projection::ProjectionTarget::Surface { + surface: hit_surface, + .. + }, + .. + } if *hit_surface == surface.id + ) + .then_some(*rect) + }) + .unwrap(); + app.open_context_menu(surface_row.x, surface_row.y); + assert!( + app.menu.as_ref().unwrap().levels[0] + .items + .iter() + .any(|item| item.action() == Some(MenuAction::RenameSurface(surface.id))) + ); + + app.menu = None; + let disclosure = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!( + hit, + super::Hit::ProjectionToggle { + branch: crate::sidebar_projection::ProjectionBranch::Workspace(_), + .. + } + ) + .then_some(*rect) + }) + .unwrap(); + app.handle_left_down(disclosure.x, disclosure.y, KeyModifiers::NONE).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + assert!(!app.hits.iter().any(|(_, hit)| matches!( + hit, + super::Hit::ProjectionRow { + target: crate::sidebar_projection::ProjectionTarget::Surface { + surface: hit_surface, + .. + }, + .. + } if *hit_surface == surface.id + ))); + + let area = app.sidebar_layout.rail(RailKind::Projection(0)).unwrap(); + app.handle_left_down(area.x + 1, area.y + 10, KeyModifiers::NONE).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + app.handle_left_down(area.x + 1, area.y, KeyModifiers::NONE).unwrap(); + assert_eq!(app.focus, FocusTarget::ProjectionRail(0)); + app.handle_key(KeyEvent::new(KeyCode::Right, KeyModifiers::ALT)).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + + mux.close_surface(surface.id).unwrap(); + } + + #[test] + fn workspace_projection_actions_expand_provider_capabilities_and_can_be_hidden() { + let mux = Mux::new("workspace-projection-action-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + app.machine_ui = Some(provider_machine_ui()); + app.config.sidebar.columns.clear(); + app.config.sidebar.views = vec![SidebarViewSpec { + id: "workspace-agents".into(), + levels: vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents], + actions: vec![Action::NewWorkspace], + width: 40, + max_width: 0, + collapse_priority: 30, + }]; + app.config.sidebar.views_explicit = true; + app.sync_layout((100, 12)); + + let mut terminal = Terminal::new(TestBackend::new(100, 12)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(rendered.contains("new isolated"), "{rendered}"); + assert!(rendered.contains("new shared"), "{rendered}"); + let isolated = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!( + hit, + super::Hit::SidebarAction { + action: SidebarActionTarget::CreateWorkspace(Some( + WorkspaceCreationMode::Isolated + )), + .. + } + ) + .then_some(*rect) + }) + .expect("isolated action hit"); + + app.handle_left_down(isolated.x, isolated.y, KeyModifiers::NONE).unwrap(); + assert_eq!(app.focus, FocusTarget::Pane); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::CreateManagedIsolatedWorkspace(MachineKey(41))) + ); + + app.machine_ui.as_mut().unwrap().request = None; + app.focus = FocusTarget::ProjectionRail(0); + app.handle_key(KeyEvent::new(KeyCode::End, KeyModifiers::NONE)).unwrap(); + app.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::CreateManagedHostWorkspace(MachineKey(41))) + ); + + app.config.sidebar.views[0].actions.clear(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let rendered = buffer_text(terminal.backend().buffer()); + assert!(!rendered.contains("new isolated"), "{rendered}"); + assert!(!rendered.contains("new shared"), "{rendered}"); + assert!(!app.hits.iter().any(|(_, hit)| matches!(hit, super::Hit::SidebarAction { .. }))); + } + + #[test] + fn client_machine_context_menu_renames_without_provider_mutation() { + let mux = Mux::new("client-machine-rename-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let key = MachineKey(7); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: vec![MachineDescriptor { + key, + id: "current".into(), + name: "Build host".into(), + subtitle: "local".into(), + status: MachineStatus::Running, + }], + active: Some(key), + capabilities: MachineCapabilities { create: false, connect: true }, + }); + ui.set_client_renamable_machines([key]); + app.machine_ui = Some(ui); + app.sync_layout((100, 14)); + let mut terminal = Terminal::new(TestBackend::new(100, 14)).unwrap(); + terminal.draw(|frame| crate::ui::draw(&mut app, frame)).unwrap(); + let clicked = app + .hits + .iter() + .find_map(|(rect, hit)| { + matches!(hit, super::Hit::Machine { key: hit_key, .. } if *hit_key == key) + .then_some(*rect) + }) + .unwrap(); + + app.open_context_menu(clicked.x, clicked.y); + assert!( + app.menu.as_ref().unwrap().levels[0] + .items + .iter() + .any(|item| item.action() == Some(MenuAction::RenameClientMachine(key))) + ); + app.activate_menu(MenuAction::RenameClientMachine(key)).unwrap(); + assert_eq!( + app.prompt.as_ref().map(|prompt| prompt.target), + Some(PromptTarget::ClientMachine(key)) + ); + app.prompt.as_mut().unwrap().input.clear(); + app.prompt.as_mut().unwrap().input.insert_str("Renamed host"); + app.commit_prompt(); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::RenameClientMachine { + machine: key, + name: "Renamed host".into(), + }) + ); + } + + #[test] + fn ssh_config_connection_menu_binds_the_selected_alias() { + let mux = Mux::new("ssh-config-picker-test", SurfaceOptions::default()); + let mut app = test_app(Session::Local(mux)); + let mut ui = MachineUiState::new(MachineSnapshot { + machines: Vec::new(), + active: None, + capabilities: MachineCapabilities { create: false, connect: true }, + }); + ui.connection_targets = vec![ + MachineConnectionTarget { target: "buildbox".into(), name: "buildbox".into() }, + MachineConnectionTarget { target: "mini".into(), name: "mini".into() }, + ]; + app.machine_ui = Some(ui); + + app.open_machine_connection_menu(1, 3); + let items = &app.menu.as_ref().unwrap().levels[0].items; + assert_eq!(items[0].label(), Some("Add SSH host…")); + assert_eq!(items[1], MenuItem::Separator); + assert_eq!(items[2].label(), Some("buildbox")); + assert_eq!(items.last().and_then(MenuItem::label), Some("mini")); + assert_eq!( + app.menu + .as_ref() + .and_then(|menu| menu.search.as_ref()) + .map(|search| search.label.as_str()), + Some("SSH hosts") + ); + assert!(matches!( + app.menu + .as_ref() + .and_then(|menu| menu.captured_resource(MenuAction::ConnectMachineTarget(0))), + Some(Some(super::MenuActionResource::MachineConnectionTarget(target))) + if target == "buildbox" + )); + for character in "mini".chars() { + app.handle_key(KeyEvent::new(KeyCode::Char(character), KeyModifiers::NONE)).unwrap(); + } + let items = &app.menu.as_ref().unwrap().levels[0].items; + assert_eq!(items[0].label(), Some("Add SSH host…")); + assert_eq!(items[1], MenuItem::Separator); + assert_eq!(items[2].label(), Some("mini")); + app.handle_menu_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)).unwrap(); + assert_eq!( + app.machine_ui.as_ref().and_then(|ui| ui.request.as_ref()), + Some(&MachineRequest::Connect { + target: "mini".into(), + route: MachineConnectRoute::Local, + }) + ); + + app.machine_ui.as_mut().unwrap().request = None; + app.activate_menu(MenuAction::ConnectOtherMachine).unwrap(); + assert_eq!( + app.prompt.as_ref().map(|prompt| prompt.target), + Some(PromptTarget::ConnectMachine(MachineConnectRoute::Local)) + ); + } + #[test] fn catalog_refresh_preserves_machine_and_workspace_selection_identity_and_scroll() { let descriptor = |key| MachineDescriptor { @@ -33542,6 +37408,7 @@ mod tests { let tree = session.tree(); super::PendingMachineReplacement { action_id, + present: true, action: super::PreparedMachineAction { ui: provider_machine_ui(), session_mutation: None, @@ -33556,6 +37423,7 @@ mod tests { label: label.into(), session_available: true, color_error: None, + machine: None, }, }, } @@ -33819,6 +37687,41 @@ mod tests { assert_eq!(requests.lock().unwrap().as_slice(), &[MachineRequest::Switch(MachineKey(41))]); } + #[test] + fn closing_connection_dialog_prevents_an_active_connect_from_replacing_the_session() { + let first = Mux::new("connection-dialog-active-cancel-first", SurfaceOptions::default()); + first.new_workspace(None, None).unwrap(); + let second = Mux::new("connection-dialog-active-cancel-second", SurfaceOptions::default()); + second.new_workspace(None, None).unwrap(); + let (mut app, events) = test_app_with_events(Session::Local(first)); + app.replace_tree(app.session.tree()); + app.machine_ui = Some(provider_machine_ui()); + let (controller, requests) = + fake_controller(FakeMachineAction::Return(Box::new(MachineActionResult::replace( + provider_machine_ui(), + Session::Local(second), + "second".into(), + )))); + install_machine_controller(&mut app, controller); + app.begin_machine_connection("mini.local".into(), MachineConnectRoute::Local); + let request = MachineRequest::Connect { + target: "mini.local".into(), + route: MachineConnectRoute::Local, + }; + + assert_eq!(app.process_machine_requests(), RenderAction::None); + assert!(app.machine_action_in_flight); + app.close_prompt(); + assert!(matches!(settle_machine_action(&mut app, &events), RenderAction::Draw)); + + assert_eq!(app.session_generation, 1); + assert_eq!(app.session_label, "test"); + assert!(app.prompt.is_none()); + assert!(app.connection_transaction.is_none()); + assert!(app.canceled_machine_connection_attempt.is_none()); + assert_eq!(requests.lock().unwrap().as_slice(), &[request]); + } + #[test] fn machine_session_replacement_settles_pointer_capture_on_the_old_session() { let first = Mux::new("machine-pointer-reset-first", SurfaceOptions::default()); @@ -33860,17 +37763,21 @@ mod tests { .unwrap(); let tree = session.tree(); - app.install_prepared_machine_session(super::PreparedMachineSession { - session, - event_worker, - generation: 2, - mux_titles, - mux_recovery_generation, - tree, - label: "second".into(), - session_available: true, - color_error: None, - }); + app.install_prepared_machine_session( + super::PreparedMachineSession { + session, + event_worker, + generation: 2, + mux_titles, + mux_recovery_generation, + tree, + label: "second".into(), + session_available: true, + color_error: None, + machine: None, + }, + true, + ); let pending_pointer_settlement = old_pending_pointer_mutations.load(Ordering::Acquire); release_tx.send(()).unwrap(); @@ -33934,17 +37841,21 @@ mod tests { .unwrap(); let tree = session.tree(); - app.install_prepared_machine_session(super::PreparedMachineSession { - session, - event_worker, - generation: 2, - mux_titles, - mux_recovery_generation, - tree, - label: "second".into(), - session_available: true, - color_error: None, - }); + app.install_prepared_machine_session( + super::PreparedMachineSession { + session, + event_worker, + generation: 2, + mux_titles, + mux_recovery_generation, + tree, + label: "second".into(), + session_available: true, + color_error: None, + machine: None, + }, + true, + ); assert_eq!( blocked.drain_mouse_lifetimes(), @@ -34023,17 +37934,21 @@ mod tests { .unwrap(); let tree = session.tree(); - app.install_prepared_machine_session(super::PreparedMachineSession { - session, - event_worker, - generation: 2, - mux_titles, - mux_recovery_generation, - tree, - label: "second".into(), - session_available: false, - color_error: Some("offline".into()), - }); + app.install_prepared_machine_session( + super::PreparedMachineSession { + session, + event_worker, + generation: 2, + mux_titles, + mux_recovery_generation, + tree, + label: "second".into(), + session_available: false, + color_error: Some("offline".into()), + machine: None, + }, + true, + ); assert_eq!( app.status_message.as_deref(), @@ -34077,17 +37992,21 @@ mod tests { ) .unwrap(); let tree = session.tree(); - app.install_prepared_machine_session(super::PreparedMachineSession { - session, - event_worker, - generation: 2, - mux_titles, - mux_recovery_generation, - tree, - label: "second".into(), - session_available: true, - color_error: None, - }); + app.install_prepared_machine_session( + super::PreparedMachineSession { + session, + event_worker, + generation: 2, + mux_titles, + mux_recovery_generation, + tree, + label: "second".into(), + session_available: true, + color_error: None, + machine: None, + }, + true, + ); release_tx.send(()).unwrap(); let deadline = Instant::now() + Duration::from_secs(1); @@ -34410,17 +38329,21 @@ mod tests { .unwrap(); let tree = session.tree(); - app.install_prepared_machine_session(super::PreparedMachineSession { - session, - event_worker, - generation: 2, - mux_titles, - mux_recovery_generation, - tree, - label: "second".into(), - session_available: true, - color_error: None, - }); + app.install_prepared_machine_session( + super::PreparedMachineSession { + session, + event_worker, + generation: 2, + mux_titles, + mux_recovery_generation, + tree, + label: "second".into(), + session_available: true, + color_error: None, + machine: None, + }, + true, + ); while app.session.has_pending_mutations() { let event = events.recv_timeout(Duration::from_secs(5)).unwrap(); app.handle(event).unwrap(); @@ -34892,6 +38815,12 @@ mod tests { machine_action_worker: None, machine_action_in_flight: false, machine_action_request: None, + machine_action_connection_attempt: None, + canceled_machine_connection_attempt: None, + machine_action_intent_generation: None, + machine_selection_intent: None, + machine_selection_generation: 0, + machine_presented: None, machine_provider_reconnect_attempts: 0, machine_provider_reconnect_retry_at: None, pending_machine_replacement: None, @@ -34958,11 +38887,17 @@ mod tests { machine_footer_scroll: 0, workspace_rail_scroll: 0, workspace_footer_scroll: 0, + tabs_rail_selection: 0, + tabs_rail_scroll: 0, + tabs_footer_scroll: 0, + projection_rails: HashMap::new(), machine_rail_follow_selection: true, workspace_rail_follow_selection: true, + tabs_rail_follow_selection: true, sidebar_followed_surface: None, sidebar_width: 0, machine_sidebar_width: 0, + tabs_sidebar_width: 0, sidebar_layout: SidebarLayout::default(), sidebar_plugin_surface: None, sidebar_plugin_error: None, @@ -34970,6 +38905,9 @@ mod tests { sidebar_plugin_retry_at: None, sidebar_width_override: None, machine_sidebar_width_override: None, + tabs_sidebar_width_override: None, + projection_sidebar_width_overrides: HashMap::new(), + hidden_sidebar_views: HashMap::new(), content_area: Rect::default(), hits: Vec::new(), tab_scroll: HashMap::new(), @@ -34978,6 +38916,8 @@ mod tests { clients: Vec::new(), client_border_labels: HashMap::new(), prompt: None, + connection_transaction: None, + next_connection_attempt: 1, pending_provider_action: None, pairing_dialog: None, pairing_queue: VecDeque::new(), @@ -34987,6 +38927,8 @@ mod tests { shake_frames: 0, selection: None, selection_generation: 0, + status_selection: None, + rendered_status_message: None, input_revision: 0, status_message: None, cell_pixels: (8, 16), diff --git a/cmux-tui/crates/cmux-tui/src/cli/command.rs b/cmux-tui/crates/cmux-tui/src/cli/command.rs index a32cb7fe32c9..8566f8b9e38c 100644 --- a/cmux-tui/crates/cmux-tui/src/cli/command.rs +++ b/cmux-tui/crates/cmux-tui/src/cli/command.rs @@ -1179,7 +1179,7 @@ fn parse_agent(words: &[String], flags: &mut Flags) -> Result Result, + profile: Option, width: Option, compact_width: Option, max_width: Option, + profiles: Option>, + views: Option>, + columns: Option>, plugin: Option, } +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSidebarProfile { + id: String, + name: Option, + views: Vec, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSidebarView { + id: String, + levels: Vec, + actions: Option>, + width: Option, + max_width: Option, + collapse_priority: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSidebarColumn { + kind: String, + width: Option, + max_width: Option, +} + #[derive(Debug, Default, Deserialize)] #[serde(deny_unknown_fields)] struct RawSidebarPlugin { @@ -453,6 +494,15 @@ struct RawMachineSidebar { enabled: Option, width: Option, max_width: Option, + create_sources: Option>, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct RawMachineCreationSource { + id: String, + name: String, + subtitle: Option, } #[derive(Debug)] @@ -709,28 +759,135 @@ pub struct Sidebar { pub width: u16, pub compact_width: u16, pub max_width: u16, + /// Ordered native columns. The legacy width fields remain the defaults for + /// machine/workspace columns when this list is omitted from the config. + pub columns: Vec, + pub columns_explicit: bool, + /// Ordered native projections. A one-level projection uses the existing + /// list behavior; multiple levels render as one native tree column. + pub views: Vec, + pub views_explicit: bool, + /// Named native layouts. `views` is always the currently selected + /// profile's resolved rail list so older consumers remain compatible. + pub profiles: Vec, + pub active_profile: String, pub plugin: Option, } impl Default for Sidebar { fn default() -> Self { + let views = vec![ + SidebarViewSpec::legacy(SidebarColumnKind::Machines, 22, 0), + SidebarViewSpec::legacy(SidebarColumnKind::Workspaces, 22, 0), + ]; Sidebar { view: SidebarView::Workspaces, width: 22, compact_width: 10, max_width: 0, + columns: vec![ + SidebarColumn { kind: SidebarColumnKind::Machines, width: 22, max_width: 0 }, + SidebarColumn { kind: SidebarColumnKind::Workspaces, width: 22, max_width: 0 }, + ], + columns_explicit: false, + views: views.clone(), + views_explicit: false, + profiles: vec![SidebarProfileSpec { + id: "default".to_string(), + name: "Default".to_string(), + views, + }], + active_profile: "default".to_string(), plugin: None, } } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SidebarProfileSpec { + pub id: String, + pub name: String, + pub views: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SidebarColumnKind { + Machines, + Workspaces, + Tabs, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SidebarColumn { + pub kind: SidebarColumnKind, + pub width: u16, + pub max_width: u16, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SidebarResourceKind { + Machines, + Workspaces, + Panes, + Tabs, + Agents, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SidebarViewSpec { + pub id: String, + pub levels: Vec, + /// Canonical native commands pinned below this view's resource rows. + pub actions: Vec, + pub width: u16, + pub max_width: u16, + /// Lower values collapse first when pane space becomes constrained. + pub collapse_priority: u16, +} + +impl SidebarViewSpec { + pub fn legacy(kind: SidebarColumnKind, width: u16, max_width: u16) -> Self { + let (id, level, collapse_priority) = match kind { + SidebarColumnKind::Machines => ("machines", SidebarResourceKind::Machines, 10), + SidebarColumnKind::Workspaces => ("workspaces", SidebarResourceKind::Workspaces, 30), + SidebarColumnKind::Tabs => ("tabs", SidebarResourceKind::Tabs, 20), + }; + let levels = vec![level]; + let actions = default_sidebar_actions(&levels); + Self { id: id.to_string(), levels, actions, width, max_width, collapse_priority } + } + + pub fn legacy_kind(&self) -> Option { + match self.levels.as_slice() { + [SidebarResourceKind::Machines] => Some(SidebarColumnKind::Machines), + [SidebarResourceKind::Workspaces] => Some(SidebarColumnKind::Workspaces), + [SidebarResourceKind::Tabs] if self.actions.is_empty() => Some(SidebarColumnKind::Tabs), + _ => None, + } + } + + pub fn includes(&self, kind: SidebarResourceKind) -> bool { + self.levels.contains(&kind) + } +} + /// Optional client-local rail listing connection targets. It is disabled for /// ordinary local cmux sessions and enabled by a machine provider or config. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct MachineSidebar { pub enabled: bool, pub width: u16, pub max_width: u16, + /// Session-local prototype sources. They exercise the native provider + /// picker without starting containers or consuming cloud resources. + pub create_sources: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachineCreationSourceConfig { + pub id: String, + pub name: String, + pub subtitle: String, } #[derive(Debug, Clone, PartialEq, Eq, Default)] @@ -784,7 +941,7 @@ pub enum MachineTargetConfig { impl Default for MachineSidebar { fn default() -> Self { - Self { enabled: false, width: 22, max_width: 0 } + Self { enabled: false, width: 22, max_width: 0, create_sources: Vec::new() } } } @@ -814,6 +971,190 @@ fn parse_sidebar_view(value: &str) -> Result { } } +fn parse_sidebar_column_kind(value: &str) -> Result { + match value { + "machines" => Ok(SidebarColumnKind::Machines), + "workspaces" => Ok(SidebarColumnKind::Workspaces), + "tabs" => Ok(SidebarColumnKind::Tabs), + _ => Err(format!( + "cmux-tui: ignoring unknown sidebar column {value:?}; expected \"machines\", \"workspaces\", or \"tabs\"" + )), + } +} + +fn parse_sidebar_resource_kind(value: &str) -> Result { + match value { + "machines" => Ok(SidebarResourceKind::Machines), + "workspaces" => Ok(SidebarResourceKind::Workspaces), + "panes" => Ok(SidebarResourceKind::Panes), + "tabs" => Ok(SidebarResourceKind::Tabs), + "agents" => Ok(SidebarResourceKind::Agents), + _ => Err(format!( + "cmux-tui: ignoring unknown sidebar resource {value:?}; expected \"machines\", \"workspaces\", \"panes\", \"tabs\", or \"agents\"" + )), + } +} + +fn validate_sidebar_levels(levels: &[SidebarResourceKind]) -> Result<(), &'static str> { + if levels.is_empty() { + return Err("levels cannot be empty"); + } + if levels.len() > 3 { + return Err("at most three resource levels are supported"); + } + let mut seen = HashSet::new(); + if levels.iter().any(|level| !seen.insert(*level)) { + return Err("resource levels cannot repeat"); + } + if levels.contains(&SidebarResourceKind::Machines) { + return (levels == [SidebarResourceKind::Machines]) + .then_some(()) + .ok_or("machines must be a one-level view"); + } + if let Some(index) = levels.iter().position(|level| *level == SidebarResourceKind::Workspaces) + && index != 0 + { + return Err("workspaces must be the first level"); + } + if let Some(index) = levels.iter().position(|level| *level == SidebarResourceKind::Panes) + && index > 1 + { + return Err("panes must be first or directly below workspaces"); + } + for leaf in [SidebarResourceKind::Tabs, SidebarResourceKind::Agents] { + if let Some(index) = levels.iter().position(|level| *level == leaf) + && index + 1 != levels.len() + { + return Err("tabs and agents must be the final level"); + } + } + Ok(()) +} + +fn default_sidebar_collapse_priority(levels: &[SidebarResourceKind]) -> u16 { + match levels { + [SidebarResourceKind::Machines] => 10, + [SidebarResourceKind::Workspaces] => 30, + _ => 20, + } +} + +fn default_sidebar_actions(levels: &[SidebarResourceKind]) -> Vec { + if levels.first() == Some(&SidebarResourceKind::Workspaces) { + vec![Action::NewWorkspace] + } else { + Vec::new() + } +} + +fn parse_sidebar_action(value: &str) -> Result { + action_definitions() + .iter() + .find(|definition| definition.config_key == value) + .map(|definition| definition.action) + .ok_or_else(|| format!("cmux-tui: ignoring unknown sidebar action {value:?}")) +} + +fn resolve_sidebar_view_specs( + views: &[RawSidebarView], + machine_width: u16, + machine_max_width: u16, + workspace_width: u16, + workspace_max_width: u16, + owner: &str, +) -> Vec { + let mut ids = HashSet::new(); + let mut legacy_kinds = HashSet::new(); + let mut resolved = Vec::new(); + for view in views { + let id = view.id.trim(); + if id.is_empty() || ids.contains(id) { + eprintln!("cmux-tui: ignoring {owner} view with an empty or duplicate id"); + continue; + } + let mut levels = Vec::with_capacity(view.levels.len()); + let mut valid = true; + for level in &view.levels { + match parse_sidebar_resource_kind(level.trim()) { + Ok(level) => levels.push(level), + Err(warning) => { + eprintln!("{warning}"); + valid = false; + break; + } + } + } + if !valid { + continue; + } + if let Err(reason) = validate_sidebar_levels(&levels) { + eprintln!("cmux-tui: ignoring {owner} view {id:?}: {reason}"); + continue; + } + let legacy_kind = SidebarViewSpec { + id: id.to_string(), + levels: levels.clone(), + actions: Vec::new(), + width: 0, + max_width: 0, + collapse_priority: 0, + } + .legacy_kind(); + if legacy_kind.is_some_and(|kind| !legacy_kinds.insert(kind)) { + eprintln!( + "cmux-tui: ignoring {owner} view {id:?}: a one-level view for that resource already exists" + ); + continue; + } + ids.insert(id.to_string()); + let (default_width, default_max_width) = match legacy_kind { + Some(SidebarColumnKind::Machines) => (machine_width, machine_max_width), + Some(SidebarColumnKind::Workspaces) => (workspace_width, workspace_max_width), + Some(SidebarColumnKind::Tabs) | None => (22, 0), + }; + let actions = if levels == [SidebarResourceKind::Machines] + && view.actions.as_ref().is_some_and(|actions| !actions.is_empty()) + { + eprintln!( + "cmux-tui: ignoring sidebar actions in {owner} machine view {id:?}; machine actions come from provider capabilities" + ); + Vec::new() + } else if let Some(raw_actions) = view.actions.as_ref() { + let mut seen = HashSet::new(); + raw_actions + .iter() + .filter_map(|raw_action| match parse_sidebar_action(raw_action.trim()) { + Ok(action) if seen.insert(action) => Some(action), + Ok(_) => { + eprintln!( + "cmux-tui: ignoring duplicate sidebar action {:?} in {owner} view {id:?}", + raw_action.trim() + ); + None + } + Err(warning) => { + eprintln!("{warning} in {owner} view {id:?}"); + None + } + }) + .collect() + } else { + default_sidebar_actions(&levels) + }; + resolved.push(SidebarViewSpec { + id: id.to_string(), + collapse_priority: view + .collapse_priority + .unwrap_or_else(|| default_sidebar_collapse_priority(&levels)), + levels, + actions, + width: view.width.unwrap_or(default_width).clamp(10, 60), + max_width: view.max_width.unwrap_or(default_max_width), + }); + } + resolved +} + #[derive(Debug, Clone)] pub struct Browser { pub chrome_binary: Option, @@ -2360,6 +2701,182 @@ pub fn load() -> Config { if let Some(max_width) = raw.machine_sidebar.max_width { config.machine_sidebar.max_width = max_width; } + if let Some(sources) = raw.machine_sidebar.create_sources { + let mut source_ids = HashSet::new(); + for source in sources { + let id = source.id.trim().to_string(); + let name = source.name.trim().to_string(); + if id.is_empty() || name.is_empty() || !source_ids.insert(id.clone()) { + eprintln!( + "cmux-tui: ignoring machine creation source with an empty or duplicate id/name" + ); + continue; + } + let subtitle = + source.subtitle.map(|subtitle| subtitle.trim().to_string()).unwrap_or_default(); + config.machine_sidebar.create_sources.push(MachineCreationSourceConfig { + id, + name, + subtitle, + }); + } + } + if let Some(columns) = raw.sidebar.columns.as_ref() { + let mut seen = HashSet::new(); + let mut resolved = Vec::new(); + for column in columns { + let kind = match parse_sidebar_column_kind(column.kind.trim()) { + Ok(kind) => kind, + Err(warning) => { + eprintln!("{warning}"); + continue; + } + }; + if !seen.insert(kind) { + eprintln!("cmux-tui: ignoring duplicate sidebar column {:?}", column.kind); + continue; + } + let (default_width, default_max_width) = match kind { + SidebarColumnKind::Machines => { + (config.machine_sidebar.width, config.machine_sidebar.max_width) + } + SidebarColumnKind::Workspaces => (config.sidebar.width, config.sidebar.max_width), + SidebarColumnKind::Tabs => (22, 0), + }; + resolved.push(SidebarColumn { + kind, + width: column.width.unwrap_or(default_width).clamp(10, 60), + max_width: column.max_width.unwrap_or(default_max_width), + }); + } + if resolved.is_empty() { + eprintln!("cmux-tui: sidebar.columns had no usable entries; keeping defaults"); + } else { + config.sidebar.columns = resolved; + config.sidebar.columns_explicit = true; + } + } else { + config.sidebar.columns = vec![ + SidebarColumn { + kind: SidebarColumnKind::Machines, + width: config.machine_sidebar.width, + max_width: config.machine_sidebar.max_width, + }, + SidebarColumn { + kind: SidebarColumnKind::Workspaces, + width: config.sidebar.width, + max_width: config.sidebar.max_width, + }, + ]; + } + config.sidebar.views = config + .sidebar + .columns + .iter() + .map(|column| SidebarViewSpec::legacy(column.kind, column.width, column.max_width)) + .collect(); + config.sidebar.views_explicit = config.sidebar.columns_explicit; + if let Some(views) = raw.sidebar.views.as_ref() { + if raw.sidebar.columns.is_some() { + eprintln!("cmux-tui: sidebar.views overrides sidebar.columns"); + } + let resolved = resolve_sidebar_view_specs( + views, + config.machine_sidebar.width, + config.machine_sidebar.max_width, + config.sidebar.width, + config.sidebar.max_width, + "sidebar", + ); + if resolved.is_empty() { + eprintln!("cmux-tui: sidebar.views had no usable entries; keeping defaults"); + } else { + config.sidebar.columns = resolved + .iter() + .filter_map(|view| { + view.legacy_kind().map(|kind| SidebarColumn { + kind, + width: view.width, + max_width: view.max_width, + }) + }) + .collect(); + config.sidebar.views = resolved; + config.sidebar.columns_explicit = false; + config.sidebar.views_explicit = true; + } + } + config.sidebar.profiles[0].views.clone_from(&config.sidebar.views); + if let Some(raw_profiles) = raw.sidebar.profiles.as_ref() { + if raw.sidebar.views.is_some() || raw.sidebar.columns.is_some() { + eprintln!("cmux-tui: sidebar.profiles overrides sidebar.views and sidebar.columns"); + } + let mut ids = HashSet::new(); + let mut profiles = Vec::new(); + for raw_profile in raw_profiles { + let id = raw_profile.id.trim(); + if id.is_empty() || !ids.insert(id.to_string()) { + eprintln!("cmux-tui: ignoring sidebar profile with an empty or duplicate id"); + continue; + } + let owner = format!("sidebar profile {id:?}"); + let views = resolve_sidebar_view_specs( + &raw_profile.views, + config.machine_sidebar.width, + config.machine_sidebar.max_width, + config.sidebar.width, + config.sidebar.max_width, + &owner, + ); + if views.is_empty() { + eprintln!("cmux-tui: ignoring sidebar profile {id:?} with no usable views"); + continue; + } + let name = raw_profile + .name + .as_deref() + .map(str::trim) + .filter(|name| !name.is_empty()) + .unwrap_or(id) + .to_string(); + profiles.push(SidebarProfileSpec { id: id.to_string(), name, views }); + } + if profiles.is_empty() { + eprintln!("cmux-tui: sidebar.profiles had no usable entries; keeping defaults"); + } else { + let requested = + raw.sidebar.profile.as_deref().map(str::trim).filter(|id| !id.is_empty()); + let selected = requested + .and_then(|id| profiles.iter().position(|profile| profile.id == id)) + .unwrap_or_else(|| { + if let Some(requested) = requested { + eprintln!( + "cmux-tui: sidebar.profile {requested:?} was not found; using the first profile" + ); + } + 0 + }); + config.sidebar.active_profile = profiles[selected].id.clone(); + config.sidebar.views = profiles[selected].views.clone(); + config.sidebar.columns = config + .sidebar + .views + .iter() + .filter_map(|view| { + view.legacy_kind().map(|kind| SidebarColumn { + kind, + width: view.width, + max_width: view.max_width, + }) + }) + .collect(); + config.sidebar.columns_explicit = false; + config.sidebar.views_explicit = true; + config.sidebar.profiles = profiles; + } + } else if raw.sidebar.profile.is_some() { + eprintln!("cmux-tui: ignoring sidebar.profile without sidebar.profiles"); + } let cloud = raw.machine_provider.cloud; if let Some(enabled) = cloud.enabled { config.machine_provider.cloud.enabled = enabled; @@ -2414,7 +2931,7 @@ pub fn load() -> Config { .unwrap_or_else(|| "main".to_string()), binary: binary .filter(|value| !value.trim().is_empty()) - .unwrap_or_else(|| "cmux-tui".to_string()), + .unwrap_or_else(|| "~/.local/bin/cmux-tui".to_string()), } } _ => { @@ -2645,7 +3162,7 @@ fn ghostty_defaults() -> DefaultColors { } enum GhosttyHelperDefaults { - Resolved(DefaultColors), + Resolved(Box), Unavailable, TimedOut, } @@ -2656,7 +3173,7 @@ fn ghostty_defaults_from_sources( helper_defaults: GhosttyHelperDefaults, ) -> DefaultColors { let parsed = match helper_defaults { - GhosttyHelperDefaults::Resolved(defaults) => defaults, + GhosttyHelperDefaults::Resolved(defaults) => *defaults, GhosttyHelperDefaults::Unavailable => { parse_ghostty_defaults_from_paths(config_paths, theme_dirs).unwrap_or_default() } @@ -2725,7 +3242,7 @@ pub(crate) fn run_ghostty_config_helper() -> i32 { platform::ghostty_theme_dirs(), ) { GhosttyConfigParseOutcome::Parsed(defaults) => { - print!("{}", serialize_ghostty_defaults(defaults)); + print!("{}", serialize_ghostty_defaults(*defaults)); 0 } GhosttyConfigParseOutcome::Missing => 1, @@ -2787,7 +3304,9 @@ fn ghostty_defaults_from_helper_command( return GhosttyHelperDefaults::Unavailable; } match output_reader.wait() { - Some(output) => GhosttyHelperDefaults::Resolved(parse_resolved_ghostty_defaults(&output)), + Some(output) => { + GhosttyHelperDefaults::Resolved(Box::new(parse_resolved_ghostty_defaults(&output))) + } None => GhosttyHelperDefaults::Unavailable, } } @@ -2961,13 +3480,13 @@ fn parse_ghostty_defaults_from_paths( theme_dirs: Vec, ) -> Option { match parse_ghostty_defaults_from_paths_result(config_paths, theme_dirs) { - GhosttyConfigParseOutcome::Parsed(defaults) => Some(defaults), + GhosttyConfigParseOutcome::Parsed(defaults) => Some(*defaults), GhosttyConfigParseOutcome::Missing | GhosttyConfigParseOutcome::TimedOut => None, } } enum GhosttyConfigParseOutcome { - Parsed(DefaultColors), + Parsed(Box), Missing, TimedOut, } @@ -3007,7 +3526,7 @@ fn parse_ghostty_defaults_with_theme_dirs(text: &str, theme_dirs: &[PathBuf]) -> #[cfg(test)] fn parse_ghostty_defaults_from_path(path: &Path, theme_dirs: &[PathBuf]) -> Option { match parse_ghostty_defaults_from_path_result(path, theme_dirs) { - GhosttyConfigParseOutcome::Parsed(defaults) => Some(defaults), + GhosttyConfigParseOutcome::Parsed(defaults) => Some(*defaults), GhosttyConfigParseOutcome::Missing | GhosttyConfigParseOutcome::TimedOut => None, } } @@ -3029,15 +3548,15 @@ fn parse_ghostty_defaults_from_path_result_until( let mut theme_candidates = Vec::new(); let overrides = match parse_ghostty_config_file_until(path, &mut theme_candidates, deadline_at) { - GhosttyConfigParseOutcome::Parsed(overrides) => overrides, + GhosttyConfigParseOutcome::Parsed(overrides) => *overrides, outcome => return outcome, }; - GhosttyConfigParseOutcome::Parsed(resolve_parsed_ghostty_defaults( + GhosttyConfigParseOutcome::Parsed(Box::new(resolve_parsed_ghostty_defaults( theme_candidates, theme_dirs, overrides, deadline_at, - )) + ))) } const GHOSTTY_CONFIG_MAX_FILES: usize = 64; @@ -3123,7 +3642,7 @@ fn parse_ghostty_config_file_until( } if loaded_root { - GhosttyConfigParseOutcome::Parsed(overrides) + GhosttyConfigParseOutcome::Parsed(Box::new(overrides)) } else { GhosttyConfigParseOutcome::Missing } @@ -3309,11 +3828,7 @@ fn desktop_theme_command_output( } let command_deadline = Instant::now() + timeout; let mut command = Command::new(program); - command - .args(args) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::null()); + command.args(args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); #[cfg(unix)] command.process_group(0); let mut child = command.spawn().ok()?; @@ -4003,6 +4518,43 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + #[cfg(unix)] + #[test] + fn ghostty_resolver_drains_output_while_the_child_is_running() { + use std::os::unix::fs::PermissionsExt; + + let root = std::env::temp_dir().join(format!( + "cmux-tui-ghostty-large-output-{}-{}", + std::process::id(), + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() + )); + let binary = root.join("ghostty-config-helper"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write( + &binary, + "#!/bin/sh\n\ + i=0\n\ + while [ \"$i\" -lt 2048 ]; do\n\ + printf 'palette = 1=#010203\\n'\n\ + i=$((i + 1))\n\ + done\n\ + printf 'background = #272822\\nforeground = #fdfff1\\n'\n", + ) + .unwrap(); + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap(); + + let mut command = Command::new(&binary); + command.stdout(Stdio::piped()).stderr(Stdio::null()); + let defaults = match ghostty_defaults_from_helper_command(command, Duration::from_secs(2)) { + GhosttyHelperDefaults::Resolved(defaults) => defaults, + GhosttyHelperDefaults::Unavailable => panic!("helper output was not parsed"), + GhosttyHelperDefaults::TimedOut => panic!("helper output timed out"), + }; + assert_eq!(defaults.bg, Some(Rgb { r: 0x27, g: 0x28, b: 0x22 })); + assert_eq!(defaults.fg, Some(Rgb { r: 0xfd, g: 0xff, b: 0xf1 })); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn unusable_packaged_ghostty_resolver_falls_through() { let broken = PathBuf::from("/cmux-test/copied-app-binary"); @@ -5314,7 +5866,7 @@ mod tests { let defaults = ghostty_defaults_from_sources( vec![config], Vec::new(), - GhosttyHelperDefaults::Resolved(helper), + GhosttyHelperDefaults::Resolved(Box::new(helper)), ); let _ = std::fs::remove_dir_all(dir); @@ -5762,6 +6314,11 @@ mod tests { "width": 30, "compact_width": 12, "max_width": 38, + "columns": [ + {"kind": "machines", "width": 18}, + {"kind": "workspaces", "width": 24}, + {"kind": "tabs", "width": 26, "max_width": 40} + ], "plugin": { "command": ["/tmp/sidebar-plugin", "--mode", "test"], "cwd": "/tmp" @@ -5770,7 +6327,11 @@ mod tests { "machine_sidebar": { "enabled": true, "width": 26, - "max_width": 34 + "max_width": 34, + "create_sources": [ + {"id": "docker", "name": "Docker", "subtitle": "container prototype"}, + {"id": "e2b", "name": "E2B"} + ] }, "machine_provider": { "cloud": { @@ -5825,9 +6386,43 @@ mod tests { assert_eq!(config.sidebar.compact_width, 12); assert_eq!(config.sidebar.max_width, 38); assert_eq!(config.sidebar.view, SidebarView::Workspaces); + assert!(config.sidebar.columns_explicit); + assert_eq!( + config.sidebar.columns, + vec![ + SidebarColumn { kind: SidebarColumnKind::Machines, width: 18, max_width: 34 }, + SidebarColumn { kind: SidebarColumnKind::Workspaces, width: 24, max_width: 38 }, + SidebarColumn { kind: SidebarColumnKind::Tabs, width: 26, max_width: 40 }, + ] + ); + assert!(config.sidebar.views_explicit); + assert_eq!( + config.sidebar.views, + vec![ + SidebarViewSpec::legacy(SidebarColumnKind::Machines, 18, 34), + SidebarViewSpec::legacy(SidebarColumnKind::Workspaces, 24, 38), + SidebarViewSpec::legacy(SidebarColumnKind::Tabs, 26, 40), + ] + ); assert_eq!( config.machine_sidebar, - MachineSidebar { enabled: true, width: 26, max_width: 34 } + MachineSidebar { + enabled: true, + width: 26, + max_width: 34, + create_sources: vec![ + MachineCreationSourceConfig { + id: "docker".into(), + name: "Docker".into(), + subtitle: "container prototype".into(), + }, + MachineCreationSourceConfig { + id: "e2b".into(), + name: "E2B".into(), + subtitle: String::new(), + }, + ], + } ); assert_eq!( config.machine_provider.cloud, @@ -5844,8 +6439,11 @@ mod tests { assert_eq!(config.machines[0].name, "Mac mini"); assert!(matches!( &config.machines[0].target, - MachineTargetConfig::Ssh { host, user: Some(user), session, .. } - if host == "mini.local" && user == "lawrence" && session == "main" + MachineTargetConfig::Ssh { host, user: Some(user), session, binary, .. } + if host == "mini.local" + && user == "lawrence" + && session == "main" + && binary == "~/.local/bin/cmux-tui" )); let plugin = config.sidebar.plugin.as_ref().expect("sidebar plugin config"); assert_eq!(plugin.command, vec!["/tmp/sidebar-plugin", "--mode", "test"]); @@ -5881,6 +6479,163 @@ mod tests { assert_eq!(config.theme.border_inactive, Theme::default().border_inactive); } + #[test] + fn sidebar_views_parse_flat_columns_and_nested_resource_trees() { + let _guard = CONFIG_ENV_LOCK.lock().unwrap(); + let old_mux_config = std::env::var_os("CMUX_MUX_CONFIG"); + let dir = + std::env::temp_dir().join(format!("cmux-sidebar-views-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cmux-tui.json"); + std::fs::write( + &path, + r#"{ + "sidebar": { + "views": [ + { + "id": "hosts", + "levels": ["machines"], + "width": 18, + "collapse_priority": 7 + }, + { + "id": "workspace-agents", + "levels": ["workspaces", "agents"], + "actions": ["new-workspace", "new-tab"], + "width": 28 + }, + { + "id": "workspace-pane-tabs", + "levels": ["workspaces", "panes", "tabs"], + "actions": [], + "width": 32, + "max_width": 44 + } + ] + } + }"#, + ) + .unwrap(); + // SAFETY: env mutation in tests is serialized by CONFIG_ENV_LOCK. + unsafe { std::env::set_var("CMUX_MUX_CONFIG", &path) }; + + let config = load(); + + restore_env_var("CMUX_MUX_CONFIG", old_mux_config); + let _ = std::fs::remove_dir_all(&dir); + assert!(config.sidebar.views_explicit); + assert!(!config.sidebar.columns_explicit); + assert_eq!(config.sidebar.views.len(), 3); + assert_eq!(config.sidebar.views[0].id, "hosts"); + assert_eq!(config.sidebar.views[0].levels, vec![SidebarResourceKind::Machines]); + assert_eq!(config.sidebar.views[0].width, 18); + assert_eq!(config.sidebar.views[0].collapse_priority, 7); + assert_eq!( + config.sidebar.views[1].levels, + vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents] + ); + assert_eq!(config.sidebar.views[1].collapse_priority, 20); + assert_eq!(config.sidebar.views[1].actions, vec![Action::NewWorkspace, Action::NewTab]); + assert_eq!( + config.sidebar.views[2].levels, + vec![ + SidebarResourceKind::Workspaces, + SidebarResourceKind::Panes, + SidebarResourceKind::Tabs, + ] + ); + assert_eq!(config.sidebar.views[2].max_width, 44); + assert!(config.sidebar.views[2].actions.is_empty()); + assert_eq!( + config.sidebar.columns, + vec![SidebarColumn { kind: SidebarColumnKind::Machines, width: 18, max_width: 0 }] + ); + } + + #[test] + fn sidebar_profiles_select_one_named_native_layout() { + let _guard = CONFIG_ENV_LOCK.lock().unwrap(); + let old_mux_config = std::env::var_os("CMUX_MUX_CONFIG"); + let dir = std::env::temp_dir() + .join(format!("cmux-sidebar-profiles-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("cmux-tui.json"); + std::fs::write( + &path, + r#"{ + "sidebar": { + "profile": "focused", + "profiles": [ + { + "id": "full", + "name": "Full", + "views": [ + {"id": "machines", "levels": ["machines"]}, + {"id": "workspaces", "levels": ["workspaces"]}, + {"id": "tabs", "levels": ["tabs"]} + ] + }, + { + "id": "focused", + "name": "Focused", + "views": [ + {"id": "machines", "levels": ["machines"]}, + { + "id": "workspace-tree", + "levels": ["workspaces", "agents"] + } + ] + } + ] + } + }"#, + ) + .unwrap(); + // SAFETY: env mutation in tests is serialized by CONFIG_ENV_LOCK. + unsafe { std::env::set_var("CMUX_MUX_CONFIG", &path) }; + + let config = load(); + + restore_env_var("CMUX_MUX_CONFIG", old_mux_config); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!( + config.sidebar.views.iter().map(|view| view.id.as_str()).collect::>(), + vec!["machines", "workspace-tree"] + ); + assert!(config.sidebar.views.iter().all(|view| !view.includes(SidebarResourceKind::Tabs))); + } + + #[test] + fn sidebar_resources_are_hidden_when_their_view_is_omitted() { + let sidebar = Sidebar::default(); + assert!(sidebar.views.iter().all(|view| !view.includes(SidebarResourceKind::Agents))); + assert_eq!(sidebar.views[1].actions, vec![Action::NewWorkspace]); + } + + #[test] + fn sidebar_view_paths_reject_ambiguous_hierarchies() { + assert!(validate_sidebar_levels(&[]).is_err()); + assert!( + validate_sidebar_levels(&[ + SidebarResourceKind::Machines, + SidebarResourceKind::Workspaces, + ]) + .is_err() + ); + assert!( + validate_sidebar_levels(&[SidebarResourceKind::Tabs, SidebarResourceKind::Workspaces,]) + .is_err() + ); + assert!( + validate_sidebar_levels(&[ + SidebarResourceKind::Workspaces, + SidebarResourceKind::Tabs, + SidebarResourceKind::Panes, + ]) + .is_err() + ); + } + #[test] fn browser_mode_defaults_headful_parses_headless_and_rejects_invalid_values() { let raw: RawConfig = serde_json::from_str(r##"{}"##).unwrap(); diff --git a/cmux-tui/crates/cmux-tui/src/localization.rs b/cmux-tui/crates/cmux-tui/src/localization.rs index 95875e160810..0eac2435de03 100644 --- a/cmux-tui/crates/cmux-tui/src/localization.rs +++ b/cmux-tui/crates/cmux-tui/src/localization.rs @@ -199,6 +199,7 @@ impl MachineAgentMessages { #[derive(Debug, PartialEq, Eq)] pub(crate) struct MenuMessages { + pub copy_message: &'static str, pub maximize_pane: &'static str, pub restore_pane_layout: &'static str, pub show_sidebar: &'static str, @@ -206,6 +207,10 @@ pub(crate) struct MenuMessages { pub compact_sidebar: &'static str, pub full_sidebar: &'static str, pub focus_sidebar: &'static str, + pub sidebar_layout: &'static str, + pub sidebar_profiles: &'static str, + pub show_sidebar_view: &'static str, + pub hide_sidebar_view: &'static str, } #[derive(Debug, PartialEq, Eq)] @@ -344,6 +349,7 @@ impl LayoutMessages { #[derive(Debug, PartialEq, Eq)] pub(crate) struct RuntimeMessages { pub unknown_panic: &'static str, + pub terminal_capacity_exhausted: &'static str, renderer_panicked: &'static str, host_input_failed: &'static str, signal_handlers_failed: &'static str, @@ -716,9 +722,17 @@ impl AttachMessages { pub(crate) struct SidebarMessages { pub machines: &'static str, pub workspaces: &'static str, + pub panes: &'static str, + pub tabs: &'static str, + pub agents: &'static str, + pub projection_path_separator: &'static str, pub new_machine: &'static str, pub connect_machine: &'static str, pub no_machines: &'static str, + pub no_workspaces: &'static str, + pub no_panes: &'static str, + pub no_tabs: &'static str, + pub no_agents: &'static str, pub recoverable_machine: &'static str, pub rename_machine: &'static str, pub delete_machine: &'static str, @@ -745,8 +759,21 @@ pub(crate) struct SidebarMessages { pub sleeping: &'static str, pub stopped: &'static str, pub unavailable: &'static str, + pub working: &'static str, + pub blocked: &'static str, + pub idle: &'static str, + pub done: &'static str, + pub unknown: &'static str, pub connect_prompt: &'static str, pub connect_host_prompt: &'static str, + pub connecting_to: &'static str, + pub starting_on: &'static str, + pub failed_to_connect: &'static str, + pub retry_connection: &'static str, + pub close_dialog: &'static str, + pub ssh_hosts: &'static str, + pub type_to_filter: &'static str, + pub other_host: &'static str, pub personal_scope: &'static str, pub team_scope: &'static str, pub scope: &'static str, @@ -787,6 +814,10 @@ pub(crate) struct SidebarMessages { pub machine_managed_authority_unsupported: &'static str, pub machine_managed_authority_invalid: &'static str, pub machine_catalog_create_unsupported: &'static str, + pub machine_creation_source_unavailable: &'static str, + pub machine_name_required: &'static str, + pub client_machine_unavailable: &'static str, + pub prototype_machine_added: &'static str, pub machine_catalog_provider_actions_unsupported: &'static str, pub machine_catalog_updates_failed: &'static str, pub machine_catalog_restart_failed: &'static str, @@ -795,9 +826,22 @@ pub(crate) struct SidebarMessages { pub machine_replacement_stale: &'static str, pub machine_replacement_not_pending: &'static str, pub machine_replacement_target_missing: &'static str, + pub managed_ssh_requires_unix: &'static str, } impl SidebarMessages { + pub(crate) fn connecting_to_message(&self, target: &str) -> String { + self.connecting_to.replace("{target}", target) + } + + pub(crate) fn starting_on_message(&self, target: &str) -> String { + self.starting_on.replace("{target}", target) + } + + pub(crate) fn failed_to_connect_message(&self, target: &str) -> String { + self.failed_to_connect.replace("{target}", target) + } + pub(crate) fn provider_action_label(&self, action_id: &str) -> Option<&'static str> { match action_id { provider_action_id::LIST_WORKSPACE_PORTS => Some(self.action_list_workspace_ports), @@ -1053,6 +1097,7 @@ edits shell files. Authenticate with the configured host before retrying. unknown_argument: "Unknown machine-agent argument: {argument}", }, menu: MenuMessages { + copy_message: "Copy message", maximize_pane: "Maximize pane", restore_pane_layout: "Restore pane layout", show_sidebar: "Show sidebar", @@ -1060,6 +1105,10 @@ edits shell files. Authenticate with the configured host before retrying. compact_sidebar: "Use compact sidebar", full_sidebar: "Use full sidebar", focus_sidebar: "Focus sidebar", + sidebar_layout: "Sidebar", + sidebar_profiles: "Layouts", + show_sidebar_view: "Show {view}", + hide_sidebar_view: "Hide {view}", }, shortcuts: ShortcutMessages { title: "Keyboard shortcuts", @@ -1116,6 +1165,7 @@ edits shell files. Authenticate with the configured host before retrying. }, runtime: RuntimeMessages { unknown_panic: "unknown panic", + terminal_capacity_exhausted: "No pseudo-terminals are available. Close an unused terminal session, then retry.", renderer_panicked: "terminal renderer panicked: {message}", host_input_failed: "host terminal input failed: {error}", signal_handlers_failed: "failed to install signal handlers: {error}", @@ -1356,9 +1406,17 @@ OPTIONS: sidebar: SidebarMessages { machines: "machines", workspaces: "workspaces", + panes: "panes", + tabs: "tabs", + agents: "agents", + projection_path_separator: " › ", new_machine: "new machine", connect_machine: "connect machine", no_machines: "no machines", + no_workspaces: "no workspaces", + no_panes: "no panes", + no_tabs: "no tabs", + no_agents: "no agents", recoverable_machine: "recoverable", rename_machine: "Rename machine", delete_machine: "Delete machine", @@ -1385,8 +1443,21 @@ OPTIONS: sleeping: "sleeping", stopped: "stopped", unavailable: "unavailable", + working: "working", + blocked: "blocked", + idle: "idle", + done: "done", + unknown: "unknown", connect_prompt: "Host address or pairing code", - connect_host_prompt: "Host address", + connect_host_prompt: "SSH host or user@host", + connecting_to: "Connecting to {target}…", + starting_on: "Starting a session on {target}…", + failed_to_connect: "Could not connect to {target}", + retry_connection: "Retry", + close_dialog: "Close", + ssh_hosts: "SSH hosts", + type_to_filter: "type to filter", + other_host: "Add SSH host…", personal_scope: "personal", team_scope: "team", scope: "scope", @@ -1427,6 +1498,10 @@ OPTIONS: machine_managed_authority_unsupported: "This provider cannot authorize managed workspace mirrors; upgrade the machine provider", machine_managed_authority_invalid: "The machine provider returned an invalid managed workspace authority binding", machine_catalog_create_unsupported: "This machine catalog cannot create machines", + machine_creation_source_unavailable: "This machine creation source is unavailable", + machine_name_required: "Enter a machine name", + client_machine_unavailable: "This client-owned machine is unavailable", + prototype_machine_added: "Added prototype machine", machine_catalog_provider_actions_unsupported: "This machine catalog has no provider actions", machine_catalog_updates_failed: "Machine catalog updates could not start", machine_catalog_restart_failed: "Machine switched without live catalog updates", @@ -1435,6 +1510,7 @@ OPTIONS: machine_replacement_stale: "Machine replacement decision is stale", machine_replacement_not_pending: "Machine replacement is no longer pending", machine_replacement_target_missing: "Machine replacement target is missing", + managed_ssh_requires_unix: "Managed SSH machine connections require Unix", }, }; @@ -1570,6 +1646,7 @@ cmux machine-agent - ローカルの cmux セッションをリモートサー unknown_argument: "不明な machine-agent 引数です: {argument}", }, menu: MenuMessages { + copy_message: "メッセージをコピー", maximize_pane: "ペインを最大化", restore_pane_layout: "ペイン配置を復元", show_sidebar: "サイドバーを表示", @@ -1577,6 +1654,10 @@ cmux machine-agent - ローカルの cmux セッションをリモートサー compact_sidebar: "サイドバーをコンパクト表示", full_sidebar: "サイドバーを通常表示", focus_sidebar: "サイドバーにフォーカス", + sidebar_layout: "サイドバー", + sidebar_profiles: "レイアウト", + show_sidebar_view: "{view}を表示", + hide_sidebar_view: "{view}を非表示", }, shortcuts: ShortcutMessages { title: "キーボードショートカット", @@ -1633,6 +1714,7 @@ cmux machine-agent - ローカルの cmux セッションをリモートサー }, runtime: RuntimeMessages { unknown_panic: "不明なパニック", + terminal_capacity_exhausted: "疑似ターミナルの空きがありません。不要なターミナルセッションを閉じてから再試行してください。", renderer_panicked: "ターミナル描画処理でパニックが発生しました: {message}", host_input_failed: "ホストターミナルの入力に失敗しました: {error}", signal_handlers_failed: "シグナルハンドラーの設定に失敗しました: {error}", @@ -1870,9 +1952,17 @@ ID とセッション: sidebar: SidebarMessages { machines: "マシン", workspaces: "ワークスペース", + panes: "ペイン", + tabs: "タブ", + agents: "エージェント", + projection_path_separator: " › ", new_machine: "新規マシン", connect_machine: "マシンを接続", no_machines: "マシンがありません", + no_workspaces: "ワークスペースがありません", + no_panes: "ペインがありません", + no_tabs: "タブがありません", + no_agents: "エージェントがありません", recoverable_machine: "復元可能", rename_machine: "マシン名を変更", delete_machine: "マシンを削除", @@ -1899,8 +1989,21 @@ ID とセッション: sleeping: "スリープ中", stopped: "停止", unavailable: "利用不可", + working: "作業中", + blocked: "ブロック中", + idle: "待機中", + done: "完了", + unknown: "不明", connect_prompt: "ホストアドレスまたはペアリングコード", - connect_host_prompt: "ホストアドレス", + connect_host_prompt: "SSH ホストまたは user@host", + connecting_to: "{target} に接続中…", + starting_on: "{target} でセッションを開始中…", + failed_to_connect: "{target} に接続できませんでした", + retry_connection: "再試行", + close_dialog: "閉じる", + ssh_hosts: "SSH ホスト", + type_to_filter: "入力して絞り込み", + other_host: "SSH ホストを追加…", personal_scope: "個人", team_scope: "チーム", scope: "スコープ", @@ -1941,6 +2044,10 @@ ID とセッション: machine_managed_authority_unsupported: "このプロバイダーは管理ワークスペースのミラーを認可できません。マシンプロバイダーをアップグレードしてください", machine_managed_authority_invalid: "マシンプロバイダーから無効な管理ワークスペース権限バインディングが返されました", machine_catalog_create_unsupported: "このマシンカタログではマシンを作成できません", + machine_creation_source_unavailable: "このマシン作成元は利用できません", + machine_name_required: "マシン名を入力してください", + client_machine_unavailable: "このクライアント管理マシンは利用できません", + prototype_machine_added: "プロトタイプマシンを追加しました", machine_catalog_provider_actions_unsupported: "このマシンカタログにはプロバイダーアクションがありません", machine_catalog_updates_failed: "マシンカタログの更新を開始できませんでした", machine_catalog_restart_failed: "マシンは切り替わりましたが、カタログのライブ更新を再開できませんでした", @@ -1949,6 +2056,7 @@ ID とセッション: machine_replacement_stale: "マシン切り替えの状態が古くなっています", machine_replacement_not_pending: "保留中のマシン切り替えがありません", machine_replacement_target_missing: "マシン切り替え先が見つかりません", + managed_ssh_requires_unix: "管理 SSH マシン接続には Unix が必要です", }, }; @@ -2156,8 +2264,28 @@ mod tests { catalog_for_locale("ja_JP.UTF-8").sidebar.connect_prompt, "ホストアドレスまたはペアリングコード" ); - assert_eq!(catalog_for_locale("en_US.UTF-8").sidebar.connect_host_prompt, "Host address"); - assert_eq!(catalog_for_locale("ja_JP.UTF-8").sidebar.connect_host_prompt, "ホストアドレス"); + assert_eq!( + catalog_for_locale("en_US.UTF-8").sidebar.connect_host_prompt, + "SSH host or user@host" + ); + assert_eq!( + catalog_for_locale("ja_JP.UTF-8").sidebar.connect_host_prompt, + "SSH ホストまたは user@host" + ); + assert_eq!(catalog_for_locale("en_US.UTF-8").sidebar.ssh_hosts, "SSH hosts"); + assert_eq!(catalog_for_locale("ja_JP.UTF-8").sidebar.ssh_hosts, "SSH ホスト"); + assert_eq!(catalog_for_locale("en_US.UTF-8").sidebar.type_to_filter, "type to filter"); + assert_eq!(catalog_for_locale("ja_JP.UTF-8").sidebar.type_to_filter, "入力して絞り込み"); + assert_eq!(catalog_for_locale("en_US.UTF-8").sidebar.other_host, "Add SSH host…"); + assert_eq!(catalog_for_locale("ja_JP.UTF-8").sidebar.other_host, "SSH ホストを追加…"); + assert_eq!( + catalog_for_locale("en_US.UTF-8").sidebar.machine_name_required, + "Enter a machine name" + ); + assert_eq!( + catalog_for_locale("ja_JP.UTF-8").sidebar.machine_name_required, + "マシン名を入力してください" + ); assert_eq!( catalog_for_locale("ja_JP.UTF-8").sidebar.machine_action_failed, "マシン操作に失敗しました" diff --git a/cmux-tui/crates/cmux-tui/src/machine.rs b/cmux-tui/crates/cmux-tui/src/machine.rs index 88c97d0f818f..49fa02827d78 100644 --- a/cmux-tui/crates/cmux-tui/src/machine.rs +++ b/cmux-tui/crates/cmux-tui/src/machine.rs @@ -5,7 +5,7 @@ //! presentation snapshot so cloud, SSH, local-socket, and future transports //! can share the same Ratatui rail without sharing provider implementation. -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::Receiver; @@ -28,6 +28,18 @@ pub enum MachineStatus { Unavailable, } +/// Client-side transport state. Provider lifecycle state remains in +/// [`MachineStatus`], so selecting a running VM never has to imply that its +/// terminal transport has finished opening. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum MachineConnectionPhase { + #[default] + Disconnected, + Connecting, + Ready, + Failed, +} + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct MachineCapabilities { pub create: bool, @@ -333,6 +345,11 @@ pub enum MachineRequest { /// before reopening the selected machine. ReconnectProvider, Create, + /// Select one native creation source advertised by the client-local + /// catalog. Dynamic providers continue to own the source-less `Create`. + CreateFrom { + source_id: String, + }, Connect { target: String, route: MachineConnectRoute, @@ -349,6 +366,12 @@ pub enum MachineRequest { expected_version: u64, name: String, }, + /// Rename a row owned by the client-local catalog. This changes only the + /// current process's presentation; it never rewrites SSH or cmux config. + RenameClientMachine { + machine: MachineKey, + name: String, + }, DeleteManagedMachine { machine: MachineKey, expected_version: u64, @@ -398,6 +421,7 @@ pub(crate) enum ManagedWorkspaceSessionMutation { pub(crate) struct MachineSession { pub session: Session, pub label: String, + pub machine: Option, } /// The result of one machine-side action. Most actions only update the rail; @@ -422,9 +446,10 @@ impl MachineActionResult { } pub(crate) fn replace(ui: MachineUiState, session: Session, label: String) -> Self { + let machine = ui.snapshot.active; Self { ui, - replacement: Some(MachineSession { session, label }), + replacement: Some(MachineSession { session, label, machine }), restart_updates: false, session_mutation: None, session_label: None, @@ -471,7 +496,7 @@ pub(crate) trait MachineController: Send { /// Commit controller-side ownership changes for a replacement only after /// the replacement session has passed the shared workspace guard. - fn commit_replacement(&mut self) -> anyhow::Result<()> { + fn commit_replacement(&mut self, _present: bool) -> anyhow::Result<()> { Ok(()) } @@ -505,6 +530,21 @@ pub enum MachineRailTarget { ConnectMachine, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachineCreationSource { + pub id: String, + pub name: String, + pub subtitle: String, +} + +/// A client-local destination advertised by a native connection source. +/// `target` is opaque to the picker and is passed back to the owning route. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachineConnectionTarget { + pub target: String, + pub name: String, +} + #[derive(Debug, Clone)] pub struct MachineUiState { pub snapshot: MachineSnapshot, @@ -515,7 +555,11 @@ pub struct MachineUiState { pub provider: Option, pub connect_accepts_pairing_code: bool, pub rail_selection: MachineRailSelection, + pub creation_sources: Vec, + pub connection_targets: Vec, + connection_phases: HashMap, workspace_creation: HashMap, + client_renamable_machines: HashSet, managed_machines: Vec, managed_workspaces: HashMap>, } @@ -597,6 +641,11 @@ impl MachineUiState { pub fn new(snapshot: MachineSnapshot) -> Self { let selection = snapshot.active_index().unwrap_or_default(); let session_available = snapshot.active_index().is_some(); + let connection_phases = snapshot + .active + .map(|active| (active, MachineConnectionPhase::Ready)) + .into_iter() + .collect(); let mut state = Self { snapshot, selection, @@ -606,7 +655,11 @@ impl MachineUiState { provider: None, connect_accepts_pairing_code: false, rail_selection: MachineRailSelection::Machine, + creation_sources: Vec::new(), + connection_targets: Vec::new(), + connection_phases, workspace_creation: HashMap::new(), + client_renamable_machines: HashSet::new(), managed_machines: Vec::new(), managed_workspaces: HashMap::new(), }; @@ -614,6 +667,31 @@ impl MachineUiState { state } + pub fn connection_phase(&self, machine: MachineKey) -> MachineConnectionPhase { + self.connection_phases.get(&machine).copied().unwrap_or_default() + } + + pub fn set_connection_phase(&mut self, machine: MachineKey, phase: MachineConnectionPhase) { + self.connection_phases.insert(machine, phase); + } + + pub fn set_connection_phases( + &mut self, + phases: impl IntoIterator, + ) { + self.connection_phases = phases.into_iter().collect(); + } + + pub fn extend_connection_phases_from(&mut self, previous: &Self) { + let visible = + self.snapshot.machines.iter().map(|machine| machine.key).collect::>(); + for (machine, phase) in &previous.connection_phases { + if visible.contains(machine) { + self.connection_phases.entry(*machine).or_insert(*phase); + } + } + } + pub fn selected(&self) -> Option<&MachineDescriptor> { self.snapshot.machines.get(self.selection) } @@ -658,6 +736,24 @@ impl MachineUiState { self.workspace_creation.contains_key(&machine) } + pub fn set_client_renamable_machines( + &mut self, + machines: impl IntoIterator, + ) { + self.client_renamable_machines = machines.into_iter().collect(); + } + + pub fn extend_client_renamable_machines( + &mut self, + machines: impl IntoIterator, + ) { + self.client_renamable_machines.extend(machines); + } + + pub fn is_client_machine_renamable(&self, machine: MachineKey) -> bool { + self.client_renamable_machines.contains(&machine) + } + pub fn set_managed_machines(&mut self, machines: Vec) { self.managed_machines = machines; } diff --git a/cmux-tui/crates/cmux-tui/src/machine_agent/runtime.rs b/cmux-tui/crates/cmux-tui/src/machine_agent/runtime.rs index 8e6b44f42db9..6add5e224774 100644 --- a/cmux-tui/crates/cmux-tui/src/machine_agent/runtime.rs +++ b/cmux-tui/crates/cmux-tui/src/machine_agent/runtime.rs @@ -2115,8 +2115,16 @@ mod tests { let _ = oversized.read(); oversized.write(registered(1, None)); - oversized.writer.write_all(&vec![b'x'; protocol::MAX_FRAME_BYTES + 1]).unwrap(); - oversized.writer.write_all(b"\n").unwrap(); + let oversized_write = oversized + .writer + .write_all(&vec![b'x'; protocol::MAX_FRAME_BYTES + 1]) + .and_then(|()| oversized.writer.write_all(b"\n")); + if let Err(error) = oversized_write { + assert!(matches!( + error.kind(), + io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset + )); + } let Message::Hello(reconnected) = malformed.read().message else { panic!("oversized input did not reconnect"); diff --git a/cmux-tui/crates/cmux-tui/src/machine_provider_runtime.rs b/cmux-tui/crates/cmux-tui/src/machine_provider_runtime.rs index 71b9c1eab0b3..e5f947500dfa 100644 --- a/cmux-tui/crates/cmux-tui/src/machine_provider_runtime.rs +++ b/cmux-tui/crates/cmux-tui/src/machine_provider_runtime.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; #[cfg(test)] use std::path::Path; use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, mpsc}; use std::time::Duration; @@ -30,17 +30,39 @@ use crate::machine_provider_client::UnixProviderConnector; use crate::machine_provider_client::{ MachineProviderConnector, ProviderClient, ProviderClientError, }; -use crate::machine_runtime::MachineRuntime; +use crate::machine_runtime::{ + MachineConnectFn, MachineConnection, MachineConnectionHub, MachineRuntime, +}; use crate::session::{RemoteSession, Session}; const PROVIDER_REFRESH_QUEUE_CAPACITY: usize = 64; +#[derive(Clone)] struct OpenConnection { client: Arc, connection_id: protocol::OpaqueId, machine_id: protocol::OpaqueId, } +struct ProviderMachineConnectionLease { + open: OpenConnection, + key: MachineKey, + registry: Arc>>, +} + +impl Drop for ProviderMachineConnectionLease { + fn drop(&mut self) { + if let Ok(mut registry) = self.registry.lock() + && registry + .get(&self.key) + .is_some_and(|open| open.connection_id == self.open.connection_id) + { + registry.remove(&self.key); + } + let _ = self.open.client.close_machine(self.open.connection_id.clone()); + } +} + struct ProviderSelectionRollback { selected_machine_id: Option, workspace_snapshot: Option, @@ -148,6 +170,8 @@ pub(crate) struct ProviderMachineRuntime { mutation_nonce: String, mutation_sequence: AtomicU64, open: Option, + connections: MachineConnectionHub, + connection_registry: Arc>>, pending: Option, pending_external_connect: Option, accepted_selection: Option, @@ -164,21 +188,43 @@ pub(crate) struct ProviderMachineController { provider: ProviderMachineRuntime, local: MachineRuntime, active_local: Option, + local_connections: MachineConnectionHub, pending_active_local: Option>, pending_provider_switch: bool, } impl ProviderMachineController { + #[cfg(test)] + fn for_test( + provider: ProviderMachineRuntime, + local: MachineRuntime, + active_local: Option, + pending_provider_switch: bool, + ) -> Self { + let local_connections = MachineConnectionHub::new(local.connection_connectors()); + Self { + provider, + local, + active_local, + local_connections, + pending_active_local: None, + pending_provider_switch, + } + } + pub(crate) fn connect_with( connector: Arc, configured: Vec, connect_external: bool, state_root: Option, ) -> anyhow::Result { + let local = MachineRuntime::external(configured, connect_external); + let local_connections = MachineConnectionHub::new(local.connection_connectors()); Ok(Self { provider: ProviderMachineRuntime::connect_with(connector, state_root)?, - local: MachineRuntime::external(configured, connect_external), + local, active_local: None, + local_connections, pending_active_local: None, pending_provider_switch: false, }) @@ -189,6 +235,10 @@ impl ProviderMachineController { Ok((session, label, self.merge_local_ui(ui))) } + pub(crate) fn sync_connections(&self) { + self.provider.sync_connections(); + } + pub(crate) fn placeholder( &mut self, notice: impl Into, @@ -206,8 +256,25 @@ impl ProviderMachineController { } MachineRequest::Connect { target, route: MachineConnectRoute::Local } => { let key = self.local.connect_machine(&target)?; + self.register_local(key)?; self.switch_local(key) } + MachineRequest::RenameClientMachine { machine, name } + if self.local.contains(machine) => + { + let name = self.local.rename_machine(machine, &name)?; + let ui = self.provider.ui_state_for_open_connection(); + let mut result = MachineActionResult::ui(self.merge_local_ui(ui)); + // Provider update streams capture the local overlay at + // subscription time. Replace that capture before a later + // provider refresh can restore the old display name. + result.restart_updates = true; + Ok(if self.active_local == Some(machine) { + result.with_session_label(name) + } else { + result + }) + } MachineRequest::Switch(key) if self.local.contains(key) => self.switch_local(key), MachineRequest::ReconnectProvider if self.active_local.is_some() => { let switching_provider = self.pending_provider_switch; @@ -263,7 +330,8 @@ impl ProviderMachineController { fn switch_local(&mut self, key: MachineKey) -> anyhow::Result { // Open the candidate first. Failed SSH or socket authentication leaves // the current provider/local session untouched. - let session = self.local.connect(key)?; + self.register_local(key)?; + let session = self.local_connections.connect(key)?; let label = self.local.name(key).unwrap_or("machine").to_string(); self.provider.stage_connection(None, None)?; self.pending_active_local = Some(Some(key)); @@ -277,7 +345,7 @@ impl ProviderMachineController { fn merge_local_ui(&self, ui: MachineUiState) -> MachineUiState { merge_local_machine_ui_for_provider_switch( ui, - &self.local.snapshot_with_active(self.active_local), + &self.local_ui(self.active_local), self.active_local, self.pending_provider_switch, ) @@ -288,16 +356,16 @@ impl ProviderMachineController { ui: MachineUiState, active_local: Option, ) -> MachineUiState { - merge_local_machine_ui(ui, &self.local.snapshot_with_active(active_local), active_local) + merge_local_machine_ui(ui, &self.local_ui(active_local), active_local) } fn subscribe_ui_updates(&self) -> anyhow::Result { let provider_updates = self.provider.subscribe_ui_updates()?; let (provider_receiver, provider_stop, provider_worker) = provider_updates.into_parts(); - let local_snapshot = self.local.snapshot_with_active(self.active_local); + let local_ui = self.local_ui(self.active_local); let active_local = self.active_local; let pending_provider_switch = self.pending_provider_switch; - let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop = Arc::new(AtomicBool::new(false)); let worker_stop = stop.clone(); let (sender, receiver) = mpsc::sync_channel(8); let worker = @@ -309,7 +377,7 @@ impl ProviderMachineController { MachineUpdate::Ui(ui) => MachineUpdate::Ui(Box::new( merge_local_machine_ui_for_provider_switch( *ui, - &local_snapshot, + &local_ui, active_local, pending_provider_switch, ), @@ -336,13 +404,19 @@ impl ProviderMachineController { fn close(&mut self) { self.abort_replacement(); self.provider.close(); + self.local_connections.close(); } - fn commit_replacement(&mut self) -> anyhow::Result<()> { + fn commit_replacement(&mut self, present: bool) -> anyhow::Result<()> { + if !present { + self.provider.commit_replacement(false)?; + self.pending_active_local = None; + return Ok(()); + } let active_local = self.pending_active_local.as_ref().copied().ok_or_else(|| { anyhow::anyhow!(localization::catalog().sidebar.machine_replacement_target_missing) })?; - self.provider.commit_replacement()?; + self.provider.commit_replacement(true)?; self.pending_active_local.take(); self.active_local = active_local; self.pending_provider_switch = false; @@ -351,7 +425,25 @@ impl ProviderMachineController { fn abort_replacement(&mut self) { self.provider.abort_replacement(); - self.pending_active_local = None; + if let Some(Some(machine)) = self.pending_active_local.take() + && self.active_local != Some(machine) + { + self.local_connections.remove(machine); + } + } + + fn register_local(&self, machine: MachineKey) -> anyhow::Result<()> { + let connector = self.local.connection_connector(machine).ok_or_else(|| { + anyhow::anyhow!(localization::catalog().sidebar.client_machine_unavailable) + })?; + self.local_connections.register(machine, connector); + Ok(()) + } + + fn local_ui(&self, active: Option) -> MachineUiState { + let mut ui = self.local.ui_state_with_active(active); + ui.set_connection_phases(self.local_connections.phases()); + ui } } @@ -371,8 +463,8 @@ impl MachineController for ProviderMachineController { self.provider.acknowledge_durable_notice(delivery) } - fn commit_replacement(&mut self) -> anyhow::Result<()> { - ProviderMachineController::commit_replacement(self) + fn commit_replacement(&mut self, present: bool) -> anyhow::Result<()> { + ProviderMachineController::commit_replacement(self, present) } fn abort_replacement(&mut self) { @@ -451,6 +543,11 @@ impl ProviderMachineRuntime { mutation_nonce: random_mutation_nonce()?, mutation_sequence: AtomicU64::new(1), open: None, + connections: MachineConnectionHub::new(std::iter::empty::<( + MachineKey, + MachineConnectFn, + )>()), + connection_registry: Arc::new(Mutex::new(HashMap::new())), pending: None, pending_external_connect: None, accepted_selection: None, @@ -464,6 +561,7 @@ impl ProviderMachineRuntime { surface_initial_snapshot_notice, ); runtime.reconcile_keys(); + runtime.sync_connection_hub(); Ok(runtime) } @@ -507,12 +605,12 @@ impl ProviderMachineRuntime { self.accepted_selection = None; } self.reconcile_keys(); + self.sync_connection_hub(); Ok(()) } pub(crate) fn open_selected(&mut self) -> anyhow::Result<(Session, String, MachineUiState)> { let (session, label, open) = self.open_selected_candidate()?; - self.close_open_connection(); let session_available = open.is_some(); self.open = open; let mut ui = self.ui_state(session_available); @@ -524,7 +622,7 @@ impl ProviderMachineRuntime { &mut self, notice: impl Into, ) -> (Session, String, MachineUiState) { - self.close_open_connection(); + self.open = None; let label = self .snapshot .selected_machine_id @@ -584,6 +682,9 @@ impl ProviderMachineRuntime { )?; Ok(self.finish_accepted_machine_selection(created.machine_id, created.notice)) } + MachineRequest::CreateFrom { .. } => { + anyhow::bail!(localization::catalog().sidebar.machine_creation_source_unavailable) + } MachineRequest::Connect { .. } => { unreachable!("external connect requests are routed by ProviderMachineController") } @@ -678,6 +779,9 @@ impl ProviderMachineRuntime { }, )) } + MachineRequest::RenameClientMachine { .. } => { + anyhow::bail!(localization::catalog().sidebar.client_machine_unavailable) + } MachineRequest::DeleteManagedMachine { machine, expected_version } => { let machine_id = self.machine_id(machine)?; let deletes_open_session = @@ -910,7 +1014,8 @@ impl ProviderMachineRuntime { pub(crate) fn close(&mut self) { self.abort_replacement(); - self.close_open_connection(); + self.open = None; + self.connections.close(); } fn acknowledge_durable_notice(&self, delivery: &DurableNoticeDelivery) -> anyhow::Result<()> { @@ -925,6 +1030,8 @@ impl ProviderMachineRuntime { let events = self.client.subscribe_events()?; let client = self.client.clone(); let keys = self.keys.clone(); + let connections = self.connections.clone(); + let connection_registry = self.connection_registry.clone(); let provider_connect_supported = client .supports_capability(protocol::EXTERNAL_MACHINE_CONNECT_CAPABILITY) .unwrap_or(false); @@ -932,7 +1039,7 @@ impl ProviderMachineRuntime { client.supports_capability(protocol::DURABLE_NOTICES_CAPABILITY).unwrap_or(false); let mut connected_session = self.open.as_ref().map(|open| (open.connection_id.clone(), open.machine_id.clone())); - let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop = Arc::new(AtomicBool::new(false)); let thread_stop = stop.clone(); let (sender, receiver) = mpsc::sync_channel(PROVIDER_REFRESH_QUEUE_CAPACITY); let mut last_snapshot = self.snapshot.clone(); @@ -942,9 +1049,9 @@ impl ProviderMachineRuntime { let (mut desired_scope_id, mut desired_machine_id) = self.desired_selection(); let (refresh_sender, refresh_receiver) = mpsc::sync_channel(PROVIDER_REFRESH_QUEUE_CAPACITY); - let refresh_overflowed = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let refresh_overflowed = Arc::new(AtomicBool::new(false)); let worker_refresh_overflowed = refresh_overflowed.clone(); - let snapshot_refresh_pending = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let snapshot_refresh_pending = Arc::new(AtomicBool::new(false)); let worker_snapshot_refresh_pending = snapshot_refresh_pending.clone(); let refresh_stop = stop.clone(); let refresh_output = sender.clone(); @@ -1023,13 +1130,24 @@ impl ProviderMachineRuntime { let mut notice = None; let had_connected_session = connected_session.is_some(); if let Some(protocol::ProviderEvent::ConnectionClosed(closed)) = event.as_ref() - && connected_session.as_ref().is_some_and(|(connection_id, machine_id)| { + { + let closed_key = connection_registry.lock().ok().and_then(|registry| { + registry.iter().find_map(|(key, open)| { + (open.connection_id == closed.connection_id + && open.machine_id == closed.machine_id) + .then_some(*key) + }) + }); + if let Some(key) = closed_key { + connections.remove(key); + } + if connected_session.as_ref().is_some_and(|(connection_id, machine_id)| { connection_id == &closed.connection_id && machine_id == &closed.machine_id - }) - { - connected_session = None; - notice = Some(closed.reason.clone()); + }) { + connected_session = None; + notice = Some(closed.reason.clone()); + } } if let Some(protocol::ProviderEvent::Notice(provider_notice)) = event.as_ref() { notice = Some(provider_notice.message.clone()); @@ -1117,9 +1235,19 @@ impl ProviderMachineRuntime { break; } }; + reconcile_keys(&keys, &snapshot, &last_machine_lifecycle_snapshot); + sync_provider_connection_hub( + &snapshot, + Arc::clone(&client), + &keys, + &connections, + &connection_registry, + ); let session_available = snapshot.selected_machine_id.is_some() && connected_session.as_ref().is_some_and(|(_, machine_id)| { snapshot.selected_machine_id.as_ref() == Some(machine_id) + && key_for_id(&keys, machine_id) + .is_some_and(|key| connections.is_ready(key)) }); let mut ui = machine_ui_state( &snapshot, @@ -1129,6 +1257,7 @@ impl ProviderMachineRuntime { session_available, provider_connect_supported, ); + ui.set_connection_phases(connections.phases()); ui.notice = notice; if let Some(snapshot_notice) = changed_snapshot_notice { append_notice_once(&mut ui.notice, snapshot_notice.message); @@ -1315,6 +1444,7 @@ impl ProviderMachineRuntime { self.accepted_selection = None; } self.reconcile_keys(); + self.sync_connection_hub(); Ok(()) } @@ -1331,53 +1461,23 @@ impl ProviderMachineRuntime { if !machine.connectable { anyhow::bail!(localization::catalog().sidebar.machine_not_ready_to_connect); } - let provider_managed = - matches!(machine.workspace_create, protocol::WorkspaceCreatePolicy::Provider { .. }); - if provider_managed - && !self.client.supports_capability(protocol::WORKSPACE_MIRROR_AUTHORITY_CAPABILITY)? - { - anyhow::bail!(localization::catalog().sidebar.machine_managed_authority_unsupported); - } - - let opened = self.client.open_machine(machine.id.clone(), provider_managed)?; - let connection_id = opened.connection_id.clone(); - let workspace_mirror_authority = opened.workspace_mirror_authority; - let authority_is_valid = workspace_mirror_authority.as_ref().is_some_and(|authority| { - authority.expose().len() >= protocol::MIN_WORKSPACE_MIRROR_AUTHORITY_BYTES - }); - if provider_managed != workspace_mirror_authority.is_some() - || (provider_managed && !authority_is_valid) - { - let _ = self.client.close_machine(connection_id); - anyhow::bail!(localization::catalog().sidebar.machine_managed_authority_invalid); - } - let transport = match self.client.consume_transport(opened.transport) { - Ok(transport) => transport, - Err(error) => { - let _ = self.client.close_machine(connection_id); - return Err(error.into()); - } - }; - let remote = match workspace_mirror_authority { - Some(authority) => RemoteSession::connect_provider_transport(transport, authority), - None => RemoteSession::connect_transport(transport), - }; - let remote = match remote { - Ok(remote) => remote, - Err(error) => { - let _ = self.client.close_machine(connection_id); - return Err(error); - } - }; - Ok(( - Session::Remote(remote), - machine.display_name, - Some(OpenConnection { - client: self.client.clone(), - connection_id, - machine_id: machine.id, - }), - )) + let key = key_for_id(&self.keys, &machine.id).ok_or_else(|| { + anyhow::anyhow!(localization::catalog().sidebar.machine_not_ready_to_connect) + })?; + self.sync_connection_hub(); + let session = self.connections.connect(key)?; + let open = self + .connection_registry + .lock() + .map_err(|_| { + anyhow::anyhow!(localization::catalog().sidebar.machine_provider_update_failed) + })? + .get(&key) + .cloned() + .ok_or_else(|| { + anyhow::anyhow!(localization::catalog().sidebar.machine_not_ready_to_connect) + })?; + Ok((session, machine.display_name, Some(open))) } fn create_workspace( @@ -1474,8 +1574,12 @@ impl ProviderMachineRuntime { .unwrap_or_else(|| "machines".to_string()); self.stage_mandatory_replacement(None); result.ui.session_available = false; - result.replacement = - Some(crate::machine::MachineSession { session: placeholder_session(), label }); + let machine = result.ui.snapshot.active; + result.replacement = Some(crate::machine::MachineSession { + session: placeholder_session(), + label, + machine, + }); result.restart_updates = true; } result @@ -1487,9 +1591,6 @@ impl ProviderMachineRuntime { rollback: Option, ) -> anyhow::Result<()> { if self.pending.is_some() { - if let Some(candidate) = candidate { - Self::close_connection(candidate); - } if let Some(rollback) = rollback { self.restore_selection(rollback); } @@ -1506,11 +1607,27 @@ impl ProviderMachineRuntime { Some(PendingConnection { candidate, rollback: None, retire_open_on_abort: true }); } - fn commit_replacement(&mut self) -> anyhow::Result<()> { + fn commit_replacement(&mut self, present: bool) -> anyhow::Result<()> { + if !present { + let pending = self.pending.take().ok_or_else(|| { + anyhow::anyhow!(localization::catalog().sidebar.machine_replacement_not_pending) + })?; + if let Some(rollback) = pending.rollback { + self.restore_selection(rollback); + } + if pending.retire_open_on_abort { + if let Some(key) = + self.open.as_ref().and_then(|open| key_for_id(&self.keys, &open.machine_id)) + { + self.connections.remove(key); + } + self.open = None; + } + return Ok(()); + } let pending = self.pending.take().ok_or_else(|| { anyhow::anyhow!(localization::catalog().sidebar.machine_replacement_not_pending) })?; - self.close_open_connection(); self.open = pending.candidate; Ok(()) } @@ -1519,14 +1636,23 @@ impl ProviderMachineRuntime { let Some(pending) = self.pending.take() else { return; }; - if let Some(candidate) = pending.candidate { - Self::close_connection(candidate); + if let Some(key) = pending + .candidate + .as_ref() + .and_then(|candidate| key_for_id(&self.keys, &candidate.machine_id)) + { + self.connections.remove(key); } if let Some(rollback) = pending.rollback { self.restore_selection(rollback); } if pending.retire_open_on_abort { - self.close_open_connection(); + if let Some(key) = + self.open.as_ref().and_then(|open| key_for_id(&self.keys, &open.machine_id)) + { + self.connections.remove(key); + } + self.open = None; } } @@ -1535,16 +1661,6 @@ impl ProviderMachineRuntime { self.workspace_snapshot = rollback.workspace_snapshot; } - fn close_connection(open: OpenConnection) { - let _ = open.client.close_machine(open.connection_id); - } - - fn close_open_connection(&mut self) { - if let Some(open) = self.open.take() { - Self::close_connection(open); - } - } - fn machine_id(&self, key: MachineKey) -> anyhow::Result { self.keys .lock() @@ -1572,8 +1688,22 @@ impl ProviderMachineRuntime { reconcile_keys(&self.keys, &self.snapshot, &self.machine_lifecycle_snapshot); } + fn sync_connection_hub(&self) { + sync_provider_connection_hub( + &self.snapshot, + Arc::clone(&self.client), + &self.keys, + &self.connections, + &self.connection_registry, + ); + } + + fn sync_connections(&self) { + self.sync_connection_hub(); + } + fn ui_state(&self, session_available: bool) -> MachineUiState { - machine_ui_state( + let mut ui = machine_ui_state( &self.snapshot, &self.machine_lifecycle_snapshot, self.workspace_snapshot.as_ref(), @@ -1582,12 +1712,16 @@ impl ProviderMachineRuntime { self.client .supports_capability(protocol::EXTERNAL_MACHINE_CONNECT_CAPABILITY) .unwrap_or(false), - ) + ); + ui.set_connection_phases(self.connections.phases()); + ui } fn ui_state_for_open_connection(&mut self) -> MachineUiState { let session_available = self.open.as_ref().is_some_and(|open| { self.snapshot.selected_machine_id.as_ref() == Some(&open.machine_id) + && key_for_id(&self.keys, &open.machine_id) + .is_some_and(|key| self.connections.is_ready(key)) }); let mut ui = self.ui_state(session_available); ui.notice = self.take_notice(); @@ -1665,11 +1799,22 @@ fn append_notice_once(notice: &mut Option, message: impl Into) { fn merge_local_machine_ui( mut ui: MachineUiState, - local: &MachineSnapshot, + local: &MachineUiState, active_local: Option, ) -> MachineUiState { - ui.snapshot.machines.extend(local.machines.iter().cloned()); - ui.snapshot.capabilities.connect |= local.capabilities.connect; + ui.snapshot.machines.extend(local.snapshot.machines.iter().cloned()); + ui.snapshot.capabilities.create |= local.snapshot.capabilities.create; + ui.snapshot.capabilities.connect |= local.snapshot.capabilities.connect; + ui.creation_sources.extend(local.creation_sources.iter().cloned()); + ui.connection_targets.extend(local.connection_targets.iter().cloned()); + ui.extend_client_renamable_machines( + local + .snapshot + .machines + .iter() + .filter(|machine| local.is_client_machine_renamable(machine.key)) + .map(|machine| machine.key), + ); if let Some(active) = active_local { ui.snapshot.active = Some(active); ui.session_available = true; @@ -1685,7 +1830,7 @@ fn merge_local_machine_ui( fn merge_local_machine_ui_for_provider_switch( ui: MachineUiState, - local: &MachineSnapshot, + local: &MachineUiState, active_local: Option, pending_provider_switch: bool, ) -> MachineUiState { @@ -1733,8 +1878,8 @@ impl MachineController for ProviderMachineRuntime { ProviderMachineRuntime::acknowledge_durable_notice(self, delivery) } - fn commit_replacement(&mut self) -> anyhow::Result<()> { - ProviderMachineRuntime::commit_replacement(self) + fn commit_replacement(&mut self, present: bool) -> anyhow::Result<()> { + ProviderMachineRuntime::commit_replacement(self, present) } fn abort_replacement(&mut self) { @@ -1878,6 +2023,113 @@ fn key_for_id(keys: &Arc>, id: &protocol::OpaqueId) -> Option keys.lock().ok()?.by_id.get(id).copied() } +fn sync_provider_connection_hub( + snapshot: &protocol::SnapshotResult, + client: Arc, + keys: &Arc>, + connections: &MachineConnectionHub, + registry: &Arc>>, +) { + let visible = + snapshot.machines.iter().map(|machine| machine.id.clone()).collect::>(); + // A provider may temporarily mark a running machine non-connectable while + // preserving an already-open transport. Do not wake such a machine, but + // keep its existing session until the provider closes or removes it. + let mut keep = registry.lock().ok().map_or_else(HashSet::new, |registry| { + registry + .iter() + .filter_map(|(key, open)| visible.contains(&open.machine_id).then_some(*key)) + .collect() + }); + for machine in snapshot.machines.iter().filter(|machine| machine.connectable) { + let Some(key) = key_for_id(keys, &machine.id) else { continue }; + keep.insert(key); + connections.register( + key, + provider_machine_connector( + Arc::clone(&client), + machine.clone(), + key, + Arc::clone(registry), + ), + ); + } + connections.retain(&keep); +} + +fn provider_machine_connector( + client: Arc, + machine: protocol::MachineDescriptor, + key: MachineKey, + registry: Arc>>, +) -> MachineConnectFn { + Arc::new(move || { + connect_provider_machine(Arc::clone(&client), machine.clone(), key, Arc::clone(®istry)) + }) +} + +fn connect_provider_machine( + client: Arc, + machine: protocol::MachineDescriptor, + key: MachineKey, + registry: Arc>>, +) -> anyhow::Result { + let provider_managed = + matches!(machine.workspace_create, protocol::WorkspaceCreatePolicy::Provider { .. }); + if provider_managed + && !client.supports_capability(protocol::WORKSPACE_MIRROR_AUTHORITY_CAPABILITY)? + { + anyhow::bail!(localization::catalog().sidebar.machine_managed_authority_unsupported); + } + + let opened = client.open_machine(machine.id.clone(), provider_managed)?; + let connection_id = opened.connection_id.clone(); + let workspace_mirror_authority = opened.workspace_mirror_authority; + let authority_is_valid = workspace_mirror_authority.as_ref().is_some_and(|authority| { + authority.expose().len() >= protocol::MIN_WORKSPACE_MIRROR_AUTHORITY_BYTES + }); + if provider_managed != workspace_mirror_authority.is_some() + || (provider_managed && !authority_is_valid) + { + let _ = client.close_machine(connection_id); + anyhow::bail!(localization::catalog().sidebar.machine_managed_authority_invalid); + } + let transport = match client.consume_transport(opened.transport) { + Ok(transport) => transport, + Err(error) => { + let _ = client.close_machine(connection_id); + return Err(error.into()); + } + }; + let remote = match workspace_mirror_authority { + Some(authority) => RemoteSession::connect_provider_transport(transport, authority), + None => RemoteSession::connect_transport(transport), + }; + let remote = match remote { + Ok(remote) => remote, + Err(error) => { + let _ = client.close_machine(connection_id); + return Err(error); + } + }; + let session = Session::Remote(remote); + let open = OpenConnection { client, connection_id, machine_id: machine.id }; + let mut connections = match registry.lock() { + Ok(connections) => connections, + Err(_) => { + session.begin_shutdown(); + let _ = open.client.close_machine(open.connection_id); + anyhow::bail!(localization::catalog().sidebar.machine_provider_update_failed); + } + }; + connections.insert(key, open.clone()); + drop(connections); + Ok(MachineConnection { + session, + _lease: Some(Box::new(ProviderMachineConnectionLease { open, key, registry })), + }) +} + fn machine_ui_state( snapshot: &protocol::SnapshotResult, machine_lifecycle_snapshot: &protocol::MachineLifecycleSnapshotResult, @@ -2182,6 +2434,56 @@ mod tests { protocol::BearerToken::new("runtime-test-token").unwrap() } + fn cache_test_connection( + runtime: &mut ProviderMachineRuntime, + connection_id: &str, + machine_id: &str, + close_on_drop: bool, + ) -> OpenConnection { + let machine_id = id(machine_id); + let key = key_for_id(&runtime.keys, &machine_id).expect("test machine has a stable key"); + let open = OpenConnection { + client: runtime.client.clone(), + connection_id: id(connection_id), + machine_id, + }; + let connector: MachineConnectFn = + Arc::new(|| anyhow::bail!("test connection must be served from the ready cache")); + runtime.connections.register(key, connector); + runtime.connection_registry.lock().unwrap().insert(key, open.clone()); + let lease = close_on_drop.then(|| { + Box::new(ProviderMachineConnectionLease { + open: open.clone(), + key, + registry: runtime.connection_registry.clone(), + }) as Box + }); + runtime.connections.insert_ready( + key, + MachineConnection { + session: Session::Local(Mux::new( + format!( + "provider-test-connection-{}", + NEXT_SOCKET_ID.fetch_add(1, Ordering::Relaxed) + ), + SurfaceOptions::default(), + )), + _lease: lease, + }, + ); + open + } + + fn install_test_connection( + runtime: &mut ProviderMachineRuntime, + connection_id: &str, + machine_id: &str, + close_on_drop: bool, + ) { + let open = cache_test_connection(runtime, connection_id, machine_id, close_on_drop); + runtime.open = Some(open); + } + fn provider_connect(target: &str) -> MachineRequest { MachineRequest::Connect { target: target.into(), route: MachineConnectRoute::Provider } } @@ -2756,11 +3058,7 @@ mod tests { let mut rejected = Vec::new(); for kind in AcceptedMutationKind::ALL { if matches!(kind, AcceptedMutationKind::RenameMachine) { - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("open-machine"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "open-machine", "machine-1", false); } match runtime.perform_request(accepted_mutation_request(kind, machine)) { Ok(result) => { @@ -3105,11 +3403,7 @@ mod tests { let mut runtime = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); let machine = key_for_id(&runtime.keys, &id("machine-1")).unwrap(); - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("deleted-open"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "deleted-open", "machine-1", true); let result = runtime .perform_request(MachineRequest::DeleteManagedMachine { machine, expected_version: 1 }) .unwrap(); @@ -3570,13 +3864,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: Some(MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START)), - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + Some(MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START)), + false, + ); let result = controller.perform_request(provider_connect("PAIR 4J7K;$(opaque)")).unwrap(); let paired = result @@ -3667,13 +3960,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: Some(MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START)), - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + Some(MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START)), + false, + ); let accepted = controller.perform_request(provider_connect("PAIR 4J7K")).unwrap(); assert_eq!(accepted.ui.request, Some(MachineRequest::ReconnectProvider)); @@ -3853,13 +4145,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); let Err(error) = controller.perform_request(provider_connect("PAIR 4J7K")) else { panic!("revoked provider unexpectedly handled external connect"); }; @@ -3930,13 +4221,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); let Err(first_error) = controller.perform_request(provider_connect("PAIR 4J7K")) else { panic!("invalid provider response unexpectedly completed external connect"); }; @@ -4011,13 +4301,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); assert!(controller.perform_request(provider_connect("PAIR 4J7K")).is_err()); controller.provider.reconnect_control().unwrap(); @@ -4057,13 +4346,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); let Err(error) = controller.perform_request(local_connect("PAIR 4J7K")) else { panic!("unnegotiated provider unexpectedly handled local connect input"); }; @@ -4098,13 +4386,12 @@ mod tests { thread::yield_now(); } assert!(!provider.client.is_live(), "provider reader did not observe disconnect"); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); let Err(error) = controller.perform_request(provider_connect("ABCD-EFGH")) else { panic!("disconnected provider unexpectedly completed external connect"); @@ -4133,13 +4420,12 @@ mod tests { }); let provider = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - let mut controller = ProviderMachineController { + let mut controller = ProviderMachineController::for_test( provider, - local: MachineRuntime::external(Vec::new(), true), - active_local: None, - pending_active_local: None, - pending_provider_switch: false, - }; + MachineRuntime::external(Vec::new(), true), + None, + false, + ); let Err(error) = controller.perform_request(provider_connect("ABCD-EFGH")) else { panic!("refresh-disconnected provider unexpectedly handled external connect"); }; @@ -4165,7 +4451,7 @@ mod tests { let provider_key = provider.snapshot.active.unwrap(); provider.request = Some(MachineRequest::Switch(provider_key)); let local_key = MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START); - let local = MachineSnapshot { + let mut local = MachineUiState::new(MachineSnapshot { machines: vec![MachineDescriptor { key: local_key, id: "mini".into(), @@ -4175,7 +4461,8 @@ mod tests { }], active: Some(local_key), capabilities: MachineCapabilities { create: false, connect: true }, - }; + }); + local.set_client_renamable_machines([local_key]); let merged = merge_local_machine_ui(provider, &local, Some(local_key)); @@ -4198,7 +4485,7 @@ mod tests { }); provider.request = Some(MachineRequest::ReconnectProvider); let local_key = MachineKey(crate::machine_runtime::CLIENT_MACHINE_KEY_START); - let local = MachineSnapshot { + let mut local = MachineUiState::new(MachineSnapshot { machines: vec![MachineDescriptor { key: local_key, id: "mini".into(), @@ -4208,7 +4495,8 @@ mod tests { }], active: Some(local_key), capabilities: MachineCapabilities::default(), - }; + }); + local.set_client_renamable_machines([local_key]); let merged = merge_local_machine_ui(provider, &local, Some(local_key)); @@ -4245,7 +4533,7 @@ mod tests { let result = controller.perform_request(MachineRequest::ReconnectProvider).unwrap(); assert!(result.replacement.is_some()); - let committed = controller.commit_replacement(); + let committed = controller.commit_replacement(true); controller.abort_replacement(); controller.close(); @@ -4357,11 +4645,7 @@ mod tests { ) .unwrap(); let machine = key_for_id(&controller.provider.keys, &id("machine-1")).unwrap(); - controller.provider.open = Some(OpenConnection { - client: controller.provider.client.clone(), - connection_id: id("deleted-open"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut controller.provider, "deleted-open", "machine-1", true); let result = controller .perform_request(MachineRequest::DeleteManagedMachine { machine, expected_version: 1 }) @@ -4445,13 +4729,12 @@ mod tests { let local_snapshot = local.snapshot_with_active(None); let local_key = local_snapshot.machines[0].key; let offline_key = local_snapshot.machines[1].key; - let mut controller = ProviderMachineController { - provider: ProviderMachineRuntime::connect(&provider_socket.path, token()).unwrap(), + let mut controller = ProviderMachineController::for_test( + ProviderMachineRuntime::connect(&provider_socket.path, token()).unwrap(), local, - active_local: None, - pending_active_local: None, - pending_provider_switch: true, - }; + None, + true, + ); let result = controller.perform_request(MachineRequest::Switch(local_key)).unwrap(); @@ -4464,12 +4747,30 @@ mod tests { controller.pending_provider_switch, "an uncommitted local candidate cannot cancel the pairing handoff" ); - controller.commit_replacement().unwrap(); + controller.commit_replacement(true).unwrap(); assert_eq!(controller.active_local, Some(local_key)); assert!( !controller.pending_provider_switch, "the committed local selection supersedes the automatic pairing handoff" ); + let renamed = controller + .perform_request(MachineRequest::RenameClientMachine { + machine: local_key, + name: "Renamed mini".into(), + }) + .unwrap(); + assert!(renamed.restart_updates); + assert_eq!(renamed.session_label.as_deref(), Some("Renamed mini")); + assert_eq!( + renamed + .ui + .snapshot + .machines + .iter() + .find(|machine| machine.key == local_key) + .map(|machine| machine.name.as_str()), + Some("Renamed mini") + ); let failed = controller.perform_request(MachineRequest::Switch(offline_key)); assert!(failed.is_err()); assert_eq!( @@ -4771,11 +5072,7 @@ mod tests { }); let mut runtime = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("keep-open"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "keep-open", "machine-1", true); let result = runtime .perform_request(MachineRequest::SelectProviderScope("personal".into())) @@ -5033,11 +5330,7 @@ mod tests { }); let mut runtime = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("keep-first-open"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "keep-first-open", "machine-1", true); let second = key_for_id(&runtime.keys, &id("machine-2")).unwrap(); let Err(error) = runtime.perform_request(MachineRequest::Switch(second)) else { @@ -5112,11 +5405,7 @@ mod tests { }); let mut runtime = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("keep-first-open"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "keep-first-open", "machine-1", true); let rollback = ProviderSelectionRollback { selected_machine_id: runtime.snapshot.selected_machine_id.clone(), workspace_snapshot: runtime.workspace_snapshot.clone(), @@ -5126,16 +5415,9 @@ mod tests { default_mode: protocol::WorkspaceCreateMode::Isolated, modes: vec![protocol::WorkspaceCreateMode::Isolated], }; - runtime - .stage_connection( - Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("reject-second"), - machine_id: id("machine-2"), - }), - Some(rollback), - ) - .unwrap(); + let candidate_open = + cache_test_connection(&mut runtime, "reject-second", "machine-2", true); + runtime.stage_connection(Some(candidate_open), Some(rollback)).unwrap(); let candidate = crate::session::test_remote_session_without_provider_authority(); let candidate_ui = runtime.ui_state(true); @@ -5949,11 +6231,7 @@ mod tests { }); let mut runtime = ProviderMachineRuntime::connect(&socket.path, token()).unwrap(); - runtime.open = Some(OpenConnection { - client: runtime.client.clone(), - connection_id: id("current-connection"), - machine_id: id("machine-1"), - }); + install_test_connection(&mut runtime, "current-connection", "machine-1", false); let updates = runtime.subscribe_ui_updates().unwrap(); let (receiver, stop, worker) = updates.into_parts(); trigger.send(()).unwrap(); diff --git a/cmux-tui/crates/cmux-tui/src/machine_runtime.rs b/cmux-tui/crates/cmux-tui/src/machine_runtime.rs index 62f9ef4c49ea..73a4c7e466c7 100644 --- a/cmux-tui/crates/cmux-tui/src/machine_runtime.rs +++ b/cmux-tui/crates/cmux-tui/src/machine_runtime.rs @@ -1,38 +1,21 @@ //! Config-backed machine catalog and transport connectors. -use std::collections::HashSet; -use std::ffi::OsString; -use std::io::{self, BufReader, Write}; -#[cfg(test)] -use std::io::{BufRead, Read}; -#[cfg(unix)] -use std::os::unix::net::UnixStream; -#[cfg(unix)] -use std::os::unix::process::CommandExt; -use std::path::PathBuf; -use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; -use std::thread::{self, JoinHandle}; -#[cfg(unix)] -use std::time::{Duration, Instant}; +use std::sync::{Arc, Condvar, Mutex}; -use crate::config::{MachineConfig, MachineTargetConfig}; +use crate::config::{MachineConfig, MachineCreationSourceConfig, MachineTargetConfig}; use crate::machine::{ - MachineCapabilities, MachineDescriptor, MachineKey, MachineSnapshot, MachineStatus, -}; -use crate::process_diagnostics::BoundedDiagnosticBuffer; -use crate::session::{ - REMOTE_CONTROL_MESSAGE_MAX_BYTES, RemoteMessageReader, RemoteMessageWriter, RemoteSession, - RemoteTransport, RemoteTransportAbort, Session, read_bounded_json_line, - read_json_line_with_progress, + MachineCapabilities, MachineConnectionPhase, MachineConnectionTarget, MachineCreationSource, + MachineDescriptor, MachineKey, MachineSnapshot, MachineStatus, MachineUiState, }; +use crate::session::{RemoteSession, Session}; -const SSH_DIAGNOSTIC_BYTES: usize = 4096; -#[cfg(unix)] -const SSH_TERMINATION_GRACE: Duration = Duration::from_millis(250); -#[cfg(unix)] -const SSH_DIAGNOSTIC_DRAIN_GRACE: Duration = Duration::from_millis(50); +const SSH_CONFIG_MAX_DEPTH: usize = 16; +const SSH_CONFIG_MAX_FILES: usize = 256; +const SSH_CONFIG_MAX_HOSTS: usize = 4096; /// Provider-backed machine keys grow upward from one. Client-local overlay /// keys live in the upper half so the two process-local catalogs cannot /// collide without changing the provider protocol. @@ -50,11 +33,25 @@ pub struct MachineRuntime { entries: Vec, next_key: u64, connect_enabled: bool, + connection_targets: Vec, + creation_sources: Vec, + creation_counts: HashMap, + prototype_target: Option, } impl MachineRuntime { + #[cfg(test)] pub fn new(current_socket: PathBuf, configured: Vec) -> Self { + Self::with_creation_sources(current_socket, configured, Vec::new()) + } + + pub fn with_creation_sources( + current_socket: PathBuf, + configured: Vec, + creation_sources: Vec, + ) -> Self { let current_name = local_hostname().unwrap_or_else(|| "this machine".to_string()); + let prototype_target = MachineTargetConfig::Unix { socket: current_socket.clone() }; let mut runtime = Self { entries: vec![Entry { descriptor: MachineDescriptor { @@ -68,6 +65,10 @@ impl MachineRuntime { }], next_key: 2, connect_enabled: true, + connection_targets: discover_ssh_config_hosts(), + creation_sources, + creation_counts: HashMap::new(), + prototype_target: Some(prototype_target), }; let mut seen_ids = HashSet::from(["current".to_string()]); for machine in configured { @@ -84,8 +85,19 @@ impl MachineRuntime { /// session. Ephemeral SSH targets are enabled only for trusted local /// launch modes such as `--cloud`. pub fn external(configured: Vec, connect_enabled: bool) -> Self { - let mut runtime = - Self { entries: Vec::new(), next_key: CLIENT_MACHINE_KEY_START, connect_enabled }; + let mut runtime = Self { + entries: Vec::new(), + next_key: CLIENT_MACHINE_KEY_START, + connect_enabled, + connection_targets: if connect_enabled { + discover_ssh_config_hosts() + } else { + Vec::new() + }, + creation_sources: Vec::new(), + creation_counts: HashMap::new(), + prototype_target: None, + }; let mut seen_ids = HashSet::new(); for machine in configured { if !seen_ids.insert(machine.id.clone()) { @@ -116,6 +128,7 @@ impl MachineRuntime { self.entries[0].descriptor.key } + #[cfg(test)] pub fn snapshot(&self, active: MachineKey) -> MachineSnapshot { self.snapshot_with_active(Some(active)) } @@ -124,10 +137,60 @@ impl MachineRuntime { MachineSnapshot { machines: self.entries.iter().map(|entry| entry.descriptor.clone()).collect(), active, - capabilities: MachineCapabilities { create: false, connect: self.connect_enabled }, + capabilities: MachineCapabilities { + create: !self.creation_sources.is_empty(), + connect: self.connect_enabled, + }, } } + pub fn ui_state(&self, active: MachineKey) -> MachineUiState { + self.ui_state_with_active(Some(active)) + } + + pub fn ui_state_with_active(&self, active: Option) -> MachineUiState { + let mut ui = MachineUiState::new(self.snapshot_with_active(active)); + ui.creation_sources = self + .creation_sources + .iter() + .map(|source| MachineCreationSource { + id: source.id.clone(), + name: source.name.clone(), + subtitle: source.subtitle.clone(), + }) + .collect(); + ui.connection_targets.clone_from(&self.connection_targets); + ui.set_client_renamable_machines(self.entries.iter().map(|entry| entry.descriptor.key)); + ui + } + + /// Add a session-local catalog entry using the current mux transport. + /// This intentionally proves the provider picker and column behavior + /// without invoking Docker or a billable VM API. + pub fn create_from(&mut self, source_id: &str) -> anyhow::Result<(MachineKey, String)> { + let source = self + .creation_sources + .iter() + .find(|source| source.id == source_id) + .cloned() + .ok_or_else(|| anyhow::anyhow!("unknown machine creation source {source_id:?}"))?; + let target = self + .prototype_target + .clone() + .ok_or_else(|| anyhow::anyhow!("machine creation is unavailable in this client"))?; + let ordinal = self.creation_counts.entry(source.id.clone()).or_default(); + *ordinal = ordinal.saturating_add(1); + let ordinal = *ordinal; + let name = format!("{} {ordinal}", source.name); + let key = self.push(MachineConfig { + id: format!("prototype:{}:{ordinal}", source.id), + name: name.clone(), + subtitle: source.subtitle, + target, + }); + Ok((key, name)) + } + pub fn contains(&self, key: MachineKey) -> bool { self.entry(key).is_some() } @@ -136,19 +199,35 @@ impl MachineRuntime { self.entry(key).map(|entry| entry.descriptor.name.as_str()) } - pub fn connect(&mut self, key: MachineKey) -> anyhow::Result { - let entry = - self.entry(key).cloned().ok_or_else(|| anyhow::anyhow!("unknown machine {}", key.0))?; - match connect_target(&entry.target) { - Ok(session) => { - self.set_status(key, MachineStatus::Running); - Ok(session) - } - Err(error) => { - self.set_status(key, MachineStatus::Unavailable); - Err(error) - } + /// Rename a client-owned catalog row for this process. Persistent source + /// configuration remains untouched. + pub fn rename_machine(&mut self, key: MachineKey, name: &str) -> anyhow::Result { + let name = name.trim(); + if name.is_empty() { + anyhow::bail!(crate::localization::catalog().sidebar.machine_name_required); } + let entry = + self.entries.iter_mut().find(|entry| entry.descriptor.key == key).ok_or_else(|| { + anyhow::anyhow!(crate::localization::catalog().sidebar.client_machine_unavailable) + })?; + entry.descriptor.name = name.to_string(); + Ok(entry.descriptor.name.clone()) + } + + pub(crate) fn connection_connectors(&self) -> Vec<(MachineKey, MachineConnectFn)> { + self.entries + .iter() + .map(|entry| { + let target = entry.target.clone(); + let connector: MachineConnectFn = Arc::new(move || connect_target(&target)); + (entry.descriptor.key, connector) + }) + .collect() + } + + pub(crate) fn connection_connector(&self, key: MachineKey) -> Option { + let target = self.entry(key)?.target.clone(); + Some(Arc::new(move || connect_target(&target))) } pub fn connect_machine(&mut self, target: &str) -> anyhow::Result { @@ -156,6 +235,7 @@ impl MachineRuntime { anyhow::bail!("this client cannot connect external machines"); } let target = target.trim(); + let target = target.strip_prefix("ssh ").map(str::trim).unwrap_or(target); if target.is_empty() || target.starts_with('-') || target.chars().any(char::is_whitespace) { anyhow::bail!("machine address must be a host or user@host without whitespace"); } @@ -174,7 +254,7 @@ impl MachineRuntime { port: None, identity_file: None, session: "main".to_string(), - binary: "cmux-tui".to_string(), + binary: "~/.local/bin/cmux-tui".to_string(), }, })) } @@ -182,329 +262,479 @@ impl MachineRuntime { fn entry(&self, key: MachineKey) -> Option<&Entry> { self.entries.iter().find(|entry| entry.descriptor.key == key) } +} - fn set_status(&mut self, key: MachineKey, status: MachineStatus) { - if let Some(entry) = self.entries.iter_mut().find(|entry| entry.descriptor.key == key) { - entry.descriptor.status = status; - } - } +fn discover_ssh_config_hosts() -> Vec { + let Some(home) = std::env::var_os("HOME").filter(|home| !home.is_empty()) else { + return Vec::new(); + }; + let home = PathBuf::from(home); + let ssh_root = home.join(".ssh"); + ssh_config_hosts_from_path(&ssh_root.join("config"), &ssh_root, &home) + .into_iter() + .map(|host| MachineConnectionTarget { name: host.clone(), target: host }) + .collect() } -fn connect_target(target: &MachineTargetConfig) -> anyhow::Result { - let remote = match target { - MachineTargetConfig::Unix { socket } => RemoteSession::connect(socket)?, - MachineTargetConfig::Ssh { host, user, port, identity_file, session, binary } => { - let transport = ssh_transport( - host, - user.as_deref(), - *port, - identity_file.as_deref(), - session, - binary, - )?; - RemoteSession::connect_transport(transport)? - } +fn ssh_config_hosts_from_path(config: &Path, ssh_root: &Path, home: &Path) -> Vec { + let mut discovery = SshConfigDiscovery { + ssh_root, + home, + visited: HashSet::new(), + seen_hosts: HashSet::new(), + hosts: Vec::new(), }; - Ok(Session::Remote(remote)) + discovery.visit(config, 0); + discovery.hosts } -fn ssh_transport( - host: &str, - user: Option<&str>, - port: Option, - identity_file: Option<&std::path::Path>, - session: &str, - binary: &str, -) -> anyhow::Result { - let mut command = Command::new("ssh"); - command - .args(ssh_arguments(host, user, port, identity_file, session, binary)) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - let (stdin, stdout, process) = spawn_transport_process(&mut command)?; - Ok(RemoteTransport::new( - Box::new(ProcessReader { inner: BufReader::new(stdout), process: process.clone() }), - Box::new(ProcessWriter { inner: stdin, process: process.clone() }), - Arc::new(ProcessAbort { process }), - )) +struct SshConfigDiscovery<'a> { + ssh_root: &'a Path, + home: &'a Path, + visited: HashSet, + seen_hosts: HashSet, + hosts: Vec, } -fn ssh_arguments( - host: &str, - user: Option<&str>, - port: Option, - identity_file: Option<&std::path::Path>, - session: &str, - binary: &str, -) -> Vec { - let destination = user.map_or_else(|| host.to_string(), |user| format!("{user}@{host}")); - let remote_command = - format!("{} relay --session {}", shell_quote(binary), shell_quote(session)); - let mut arguments = vec![ - OsString::from("-T"), - OsString::from("-o"), - OsString::from("BatchMode=yes"), - OsString::from("-o"), - OsString::from("StrictHostKeyChecking=yes"), - OsString::from("-o"), - OsString::from("ForwardAgent=no"), - OsString::from("-o"), - OsString::from("ForwardX11=no"), - OsString::from("-o"), - OsString::from("ClearAllForwardings=yes"), - ]; - if let Some(port) = port { - arguments.push(OsString::from("-p")); - arguments.push(OsString::from(port.to_string())); +impl SshConfigDiscovery<'_> { + fn visit(&mut self, path: &Path, depth: usize) { + if depth > SSH_CONFIG_MAX_DEPTH + || self.visited.len() >= SSH_CONFIG_MAX_FILES + || self.hosts.len() >= SSH_CONFIG_MAX_HOSTS + { + return; + } + let identity = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + if !self.visited.insert(identity) { + return; + } + let Ok(contents) = fs::read_to_string(path) else { return }; + let mut includes = Vec::new(); + for line in contents.lines() { + let mut words = ssh_config_words(line); + let Some(first) = words.first_mut() else { continue }; + let mut inline_value = None; + if let Some((keyword, value)) = first.split_once('=') { + inline_value = (!value.is_empty()).then(|| value.to_string()); + *first = keyword.to_string(); + } + let keyword = first.to_ascii_lowercase(); + let mut values = inline_value.into_iter().chain(words.into_iter().skip(1)); + match keyword.as_str() { + "host" => { + for host in values.by_ref() { + if self.hosts.len() >= SSH_CONFIG_MAX_HOSTS { + return; + } + if is_concrete_ssh_host(&host) + && self.seen_hosts.insert(host.to_ascii_lowercase()) + { + self.hosts.push(host); + } + } + } + "include" => { + includes.extend(values); + } + _ => {} + } + } + // The root file is the user's curated catalog. Included files are + // often generated inventories, so list direct aliases first while + // still following every include for discovery and de-duplication. + for pattern in includes { + for included in self.expand_include(&pattern) { + self.visit(&included, depth.saturating_add(1)); + } + } + } + + fn expand_include(&self, pattern: &str) -> Vec { + let path = if pattern == "~" { + self.home.to_path_buf() + } else if let Some(relative) = pattern.strip_prefix("~/") { + self.home.join(relative) + } else { + let path = PathBuf::from(pattern); + if path.is_absolute() { path } else { self.ssh_root.join(path) } + }; + let Some(pattern) = path.to_str() else { return Vec::new() }; + let Ok(paths) = glob::glob(pattern) else { return Vec::new() }; + paths.filter_map(Result::ok).take(SSH_CONFIG_MAX_FILES).collect() } - if let Some(identity_file) = identity_file { - arguments.push(OsString::from("-i")); - arguments.push(identity_file.as_os_str().to_owned()); - } - arguments.extend([ - OsString::from("--"), - OsString::from(destination), - OsString::from(remote_command), - ]); - arguments } -fn spawn_transport_process( - command: &mut Command, -) -> anyhow::Result<(ChildStdin, ChildStdout, Arc)> { - #[cfg(unix)] - let (stderr_cancel, stderr_cancel_worker) = UnixStream::pair() - .map_err(|error| anyhow::anyhow!("cannot create ssh diagnostics cancellation: {error}"))?; - #[cfg(unix)] - command.process_group(0); - let mut child = - command.spawn().map_err(|error| anyhow::anyhow!("cannot start ssh: {error}"))?; - #[cfg(unix)] - let process_group = match libc::pid_t::try_from(child.id()) { - Ok(process_group) => process_group, - Err(_) => { - let _ = child.kill(); - let _ = child.wait(); - return Err(anyhow::anyhow!("ssh process ID is invalid")); +fn is_concrete_ssh_host(host: &str) -> bool { + !host.is_empty() + && !host.starts_with('-') + && !host.chars().any(|character| matches!(character, '*' | '?' | '!' | '[' | ']')) +} + +/// OpenSSH's config grammar only needs shell-like quoting for the directives +/// read here. Comments start outside quotes; backslashes quote one character. +fn ssh_config_words(line: &str) -> Vec { + let mut words = Vec::new(); + let mut current = String::new(); + let mut quote = None; + let mut escaped = false; + for character in line.chars() { + if escaped { + current.push(character); + escaped = false; + continue; } - }; - let stdin = child.stdin.take().ok_or_else(|| anyhow::anyhow!("ssh stdin unavailable"))?; - let stdout = child.stdout.take().ok_or_else(|| anyhow::anyhow!("ssh stdout unavailable"))?; - let stderr = child.stderr.take().ok_or_else(|| anyhow::anyhow!("ssh stderr unavailable"))?; - let diagnostics = Arc::new(BoundedDiagnosticBuffer::new(SSH_DIAGNOSTIC_BYTES)); - let worker_diagnostics = Arc::clone(&diagnostics); - let worker = thread::Builder::new().name("machine-ssh-stderr".to_string()).spawn(move || { - #[cfg(unix)] - worker_diagnostics.drain_cancellable(stderr, stderr_cancel_worker); - #[cfg(not(unix))] - worker_diagnostics.drain(stderr); - }); - let worker = match worker { - Ok(worker) => worker, - Err(error) => { - #[cfg(unix)] - unsafe { - libc::kill(-process_group, libc::SIGKILL); + if character == '\\' { + escaped = true; + continue; + } + if let Some(delimiter) = quote { + if character == delimiter { + quote = None; + } else { + current.push(character); } - let _ = child.kill(); - let _ = child.wait(); - return Err(anyhow::anyhow!("cannot monitor ssh diagnostics: {error}")); + continue; } - }; - let process = Arc::new(Process { - child: Mutex::new(Some(child)), - diagnostics, - #[cfg(unix)] - process_group, - #[cfg(unix)] - stderr_cancel, - stderr_worker: Mutex::new(Some(worker)), - closed: AtomicBool::new(false), - }); - Ok((stdin, stdout, process)) + match character { + '\'' | '"' => quote = Some(character), + '#' => break, + character if character.is_whitespace() => { + if !current.is_empty() { + words.push(std::mem::take(&mut current)); + } + } + _ => current.push(character), + } + } + if escaped { + current.push('\\'); + } + if !current.is_empty() { + words.push(current); + } + words +} + +pub(crate) trait MachineConnectionLease: Send {} + +impl MachineConnectionLease for T {} + +pub(crate) struct MachineConnection { + pub session: Session, + pub _lease: Option>, } -fn shell_quote(value: &str) -> String { - format!("'{}'", value.replace('\'', "'\"'\"'")) +pub(crate) type MachineConnectFn = Arc anyhow::Result + Send + Sync>; + +#[derive(Clone)] +pub(crate) struct MachineConnectionHub { + inner: Arc, } -struct Process { - child: Mutex>, - diagnostics: Arc, - #[cfg(unix)] - process_group: libc::pid_t, - #[cfg(unix)] - stderr_cancel: UnixStream, - stderr_worker: Mutex>>, +struct MachineConnectionHubInner { + slots: Mutex>, + changed: Condvar, closed: AtomicBool, } -impl Process { - fn diagnostic_after_stdout_eof(&self) -> Option { - let exited = self - .child - .lock() - .ok() - .and_then(|mut child| child.as_mut()?.try_wait().ok().flatten()) - .is_some(); - if exited { - let _ = self.terminate_and_reap(); +struct MachineConnectionSlot { + connector: MachineConnectFn, + state: MachineConnectionState, +} + +enum MachineConnectionState { + Disconnected, + Connecting, + Ready(MachineConnection), + Failed(String), +} + +impl MachineConnectionHub { + pub(crate) fn new( + connectors: impl IntoIterator, + ) -> Self { + let slots = connectors + .into_iter() + .map(|(key, connector)| { + ( + key, + MachineConnectionSlot { + connector, + state: MachineConnectionState::Disconnected, + }, + ) + }) + .collect(); + Self { + inner: Arc::new(MachineConnectionHubInner { + slots: Mutex::new(slots), + changed: Condvar::new(), + closed: AtomicBool::new(false), + }), } - self.diagnostic() } - fn diagnostic(&self) -> Option { - self.diagnostics.sanitized() + pub(crate) fn register(&self, key: MachineKey, connector: MachineConnectFn) { + let Ok(mut slots) = self.inner.slots.lock() else { return }; + match slots.get_mut(&key) { + Some(slot) => slot.connector = connector, + None => { + slots.insert( + key, + MachineConnectionSlot { + connector, + state: MachineConnectionState::Disconnected, + }, + ); + } + } } - #[cfg(unix)] - fn signal_group(&self, signal: libc::c_int) { - let _ = unsafe { libc::kill(-self.process_group, signal) }; + pub(crate) fn insert_ready(&self, key: MachineKey, connection: MachineConnection) { + let Ok(mut slots) = self.inner.slots.lock() else { return }; + let Some(slot) = slots.get_mut(&key) else { return }; + slot.state = MachineConnectionState::Ready(connection); + self.inner.changed.notify_all(); } - #[cfg(unix)] - fn group_is_alive(&self) -> bool { - let result = unsafe { libc::kill(-self.process_group, 0) }; - result == 0 || io::Error::last_os_error().kind() == io::ErrorKind::PermissionDenied + pub(crate) fn connect(&self, key: MachineKey) -> anyhow::Result { + self.connect_with_retry(key, true) } - fn finish_stderr(&self) { - if let Ok(mut worker) = self.stderr_worker.lock() - && let Some(worker) = worker.take() - { - #[cfg(unix)] - { - let deadline = Instant::now() + SSH_DIAGNOSTIC_DRAIN_GRACE; - while !worker.is_finished() && Instant::now() < deadline { - thread::sleep(Duration::from_millis(1)); + fn connect_with_retry(&self, key: MachineKey, retry_failed: bool) -> anyhow::Result { + loop { + if self.inner.closed.load(Ordering::Acquire) { + anyhow::bail!(crate::localization::catalog().sidebar.no_active_session); + } + let mut slots = self.inner.slots.lock().map_err(|_| { + anyhow::anyhow!( + crate::localization::catalog().sidebar.machine_catalog_updates_failed + ) + })?; + let slot = slots.get_mut(&key).ok_or_else(|| { + anyhow::anyhow!(crate::localization::catalog().sidebar.client_machine_unavailable) + })?; + match &slot.state { + MachineConnectionState::Ready(connection) => { + return Ok(connection.session.clone()); } - if !worker.is_finished() { - let _ = self.stderr_cancel.shutdown(std::net::Shutdown::Both); + MachineConnectionState::Connecting => { + drop(self.inner.changed.wait(slots).map_err(|_| { + anyhow::anyhow!( + crate::localization::catalog().sidebar.machine_catalog_updates_failed + ) + })?); } - } - let _ = worker.join(); - } - } - - fn terminate_and_reap(&self) -> io::Result<()> { - let mut result = Ok(()); - if !self.closed.swap(true, Ordering::AcqRel) { - match self.child.lock() { - Ok(mut child) => { - if let Some(mut child) = child.take() { - #[cfg(unix)] - { - self.signal_group(libc::SIGTERM); - let deadline = Instant::now() + SSH_TERMINATION_GRACE; - while self.group_is_alive() && Instant::now() < deadline { - let _ = child.try_wait(); - thread::sleep(Duration::from_millis(10)); - } - if self.group_is_alive() { - self.signal_group(libc::SIGKILL); - } - } - #[cfg(not(unix))] - { - let running = match child.try_wait() { - Ok(status) => status.is_none(), - Err(error) => { - result = Err(error); - true - } - }; - if running - && let Err(error) = child.kill() - && result.is_ok() - { - result = Err(error); - } + MachineConnectionState::Failed(error) if !retry_failed => { + return Err(anyhow::anyhow!(error.clone())); + } + MachineConnectionState::Disconnected | MachineConnectionState::Failed(_) => { + let connector = Arc::clone(&slot.connector); + slot.state = MachineConnectionState::Connecting; + drop(slots); + let result = connector(); + let mut slots = self.inner.slots.lock().map_err(|_| { + anyhow::anyhow!( + crate::localization::catalog().sidebar.machine_catalog_updates_failed + ) + })?; + let Some(slot) = slots.get_mut(&key) else { + return Err(anyhow::anyhow!( + crate::localization::catalog().sidebar.client_machine_unavailable + )); + }; + if self.inner.closed.load(Ordering::Acquire) { + slot.state = MachineConnectionState::Disconnected; + self.inner.changed.notify_all(); + anyhow::bail!(crate::localization::catalog().sidebar.no_active_session); + } + match result { + Ok(connection) => { + let session = connection.session.clone(); + slot.state = MachineConnectionState::Ready(connection); + self.inner.changed.notify_all(); + return Ok(session); } - if let Err(error) = child.wait() - && result.is_ok() - { - result = Err(error); + Err(error) => { + let message = error.to_string(); + slot.state = MachineConnectionState::Failed(message); + self.inner.changed.notify_all(); + return Err(error); } } } - Err(_) => result = Err(io::Error::other("ssh lock poisoned")), } } - self.finish_stderr(); - result } -} -impl Drop for Process { - fn drop(&mut self) { - let _ = self.terminate_and_reap(); + pub(crate) fn phases(&self) -> Vec<(MachineKey, MachineConnectionPhase)> { + let Ok(slots) = self.inner.slots.lock() else { return Vec::new() }; + slots + .iter() + .map(|(key, slot)| { + let phase = match &slot.state { + MachineConnectionState::Disconnected => MachineConnectionPhase::Disconnected, + MachineConnectionState::Connecting => MachineConnectionPhase::Connecting, + MachineConnectionState::Ready(_) => MachineConnectionPhase::Ready, + MachineConnectionState::Failed(_) => MachineConnectionPhase::Failed, + }; + (*key, phase) + }) + .collect() + } + + pub(crate) fn is_ready(&self, key: MachineKey) -> bool { + self.inner.slots.lock().ok().and_then(|slots| { + slots.get(&key).map(|slot| matches!(slot.state, MachineConnectionState::Ready(_))) + }) == Some(true) + } + + pub(crate) fn remove(&self, key: MachineKey) { + let connection = self.inner.slots.lock().ok().and_then(|mut slots| { + slots.remove(&key).and_then(|slot| match slot.state { + MachineConnectionState::Ready(connection) => Some(connection), + MachineConnectionState::Disconnected + | MachineConnectionState::Connecting + | MachineConnectionState::Failed(_) => None, + }) + }); + if let Some(connection) = connection { + connection.session.begin_shutdown(); + } + self.inner.changed.notify_all(); + } + + pub(crate) fn retain(&self, keep: &HashSet) { + let removed = self.inner.slots.lock().ok().map(|mut slots| { + let removed = + slots.keys().copied().filter(|key| !keep.contains(key)).collect::>(); + removed + .into_iter() + .filter_map(|key| slots.remove(&key)) + .filter_map(|slot| match slot.state { + MachineConnectionState::Ready(connection) => Some(connection), + MachineConnectionState::Disconnected + | MachineConnectionState::Connecting + | MachineConnectionState::Failed(_) => None, + }) + .collect::>() + }); + for connection in removed.into_iter().flatten() { + connection.session.begin_shutdown(); + } + self.inner.changed.notify_all(); } -} - -struct ProcessReader { - inner: BufReader, - process: Arc, -} -impl ProcessReader { - fn receive_inner(&mut self, on_progress: &mut dyn FnMut(&[u8])) -> io::Result> { - let _keep_alive = &self.process; - let message = read_json_line_with_progress(&mut self.inner, on_progress)?; - if message.is_none() - && let Some(diagnostic) = self.process.diagnostic_after_stdout_eof() - { - return Err(io::Error::other(format!("ssh transport closed: {diagnostic}"))); + pub(crate) fn close(&self) { + if self.inner.closed.swap(true, Ordering::AcqRel) { + return; + } + let connections = self.inner.slots.lock().ok().map(|mut slots| { + slots + .values_mut() + .filter_map(|slot| { + match std::mem::replace(&mut slot.state, MachineConnectionState::Disconnected) { + MachineConnectionState::Ready(connection) => Some(connection), + MachineConnectionState::Disconnected + | MachineConnectionState::Connecting + | MachineConnectionState::Failed(_) => None, + } + }) + .collect::>() + }); + for connection in connections.into_iter().flatten() { + connection.session.begin_shutdown(); } - Ok(message) + self.inner.changed.notify_all(); } } -impl RemoteMessageReader for ProcessReader { - fn receive(&mut self) -> io::Result> { - let _keep_alive = &self.process; - let message = read_bounded_json_line(&mut self.inner, REMOTE_CONTROL_MESSAGE_MAX_BYTES)?; - if message.is_none() - && let Some(diagnostic) = self.process.diagnostic_after_stdout_eof() - { - return Err(io::Error::other(format!("ssh transport closed: {diagnostic}"))); +fn connect_target(target: &MachineTargetConfig) -> anyhow::Result { + match target { + MachineTargetConfig::Unix { socket } => Ok(MachineConnection { + session: Session::Remote(RemoteSession::connect(socket)?), + _lease: None, + }), + MachineTargetConfig::Ssh { host, user, port, identity_file, session, binary } => { + #[cfg(unix)] + { + let connected = crate::remote_cli::connect_managed_ssh(managed_ssh_options( + host, + user.as_deref(), + *port, + identity_file.as_deref(), + session, + binary, + )?)?; + Ok(MachineConnection { + session: connected.session, + _lease: Some(Box::new(connected.lease)), + }) + } + #[cfg(not(unix))] + { + let _ = (host, user, port, identity_file, session, binary); + anyhow::bail!(crate::localization::catalog().sidebar.managed_ssh_requires_unix) + } } - Ok(message) } - - fn receive_with_progress( - &mut self, - on_progress: &mut dyn FnMut(&[u8]), - ) -> io::Result> { - self.receive_inner(on_progress) - } -} - -struct ProcessWriter { - inner: ChildStdin, - process: Arc, -} - -struct ProcessAbort { - process: Arc, } -impl RemoteTransportAbort for ProcessAbort { - fn abort(&self) -> io::Result<()> { - self.process.terminate_and_reap() - } -} +#[cfg(unix)] +fn managed_ssh_options( + host: &str, + user: Option<&str>, + port: Option, + identity_file: Option<&Path>, + session: &str, + binary: &str, +) -> anyhow::Result { + let host = host.trim(); + let user = user.map(str::trim).filter(|user| !user.is_empty()); + if host.is_empty() + || host.starts_with('-') + || host.chars().any(char::is_whitespace) + || user.is_some_and(|user| user.starts_with('-') || user.chars().any(char::is_whitespace)) + { + anyhow::bail!("machine address must be a host or user@host without whitespace"); + } + let host = if port.is_some() && host.contains(':') && !host.starts_with('[') { + format!("[{host}]") + } else { + host.to_string() + }; + let destination = match (user, port) { + (Some(user), Some(port)) => format!("{user}@{host}:{port}"), + (Some(user), None) => format!("{user}@{host}"), + (None, Some(port)) => format!("{host}:{port}"), + (None, None) => host, + }; -impl RemoteMessageWriter for ProcessWriter { - fn send(&mut self, message: &str) -> io::Result<()> { - self.inner.write_all(message.as_bytes())?; - self.inner.write_all(b"\n")?; - self.inner.flush() + let mut ssh_args = vec![ + "-o".into(), + "BatchMode=yes".into(), + "-o".into(), + "StrictHostKeyChecking=yes".into(), + "-o".into(), + "ForwardAgent=no".into(), + "-o".into(), + "ForwardX11=no".into(), + "-o".into(), + "ClearAllForwardings=yes".into(), + ]; + if let Some(identity_file) = identity_file { + ssh_args.push("-i".into()); + ssh_args.push(identity_file.to_string_lossy().into_owned()); } - fn close(&mut self) -> io::Result<()> { - self.process.terminate_and_reap() - } + let options = crate::remote_cli::ManagedSshOptions { + destination, + session: session.to_string(), + remote_binary: binary.to_string(), + ssh_args, + }; + crate::remote_cli::validate_managed_ssh_options(&options)?; + Ok(options) } fn local_hostname() -> Option { @@ -516,86 +746,75 @@ mod tests { use super::*; #[test] - fn shell_quote_preserves_remote_arguments() { - assert_eq!(shell_quote("main"), "'main'"); - assert_eq!(shell_quote("a'b"), "'a'\"'\"'b'"); + fn connected_target_is_deduplicated() { + let mut runtime = MachineRuntime::new(PathBuf::from("/tmp/current.sock"), Vec::new()); + let first = runtime.connect_machine("lawrence@mini.local").unwrap(); + let second = runtime.connect_machine("lawrence@mini.local").unwrap(); + assert_eq!(first, second); + assert_eq!(runtime.snapshot(runtime.initial_key()).machines.len(), 2); } - #[cfg(unix)] #[test] - fn transport_stderr_is_captured_instead_of_inheriting_the_tui() { - let mut command = Command::new("sh"); - command - .args(["-c", "printf 'permission denied\\nretry later' >&2"]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - let (stdin, mut stdout, process) = spawn_transport_process(&mut command).unwrap(); - drop(stdin); - let mut output = Vec::new(); - stdout.read_to_end(&mut output).unwrap(); - - assert!(output.is_empty()); - assert_eq!( - process.diagnostic_after_stdout_eof().as_deref(), - Some("permission denied retry later") - ); + fn typed_ssh_command_prefix_adds_the_same_host_alias() { + let mut runtime = MachineRuntime::new(PathBuf::from("/tmp/current.sock"), Vec::new()); + let command = runtime.connect_machine("ssh cmux-lawrence").unwrap(); + let alias = runtime.connect_machine("cmux-lawrence").unwrap(); + + assert_eq!(command, alias); + assert_eq!(runtime.name(command), Some("cmux-lawrence")); } - #[cfg(unix)] #[test] - fn transport_cleanup_does_not_wait_for_descendant_inheriting_stderr() { - let mut command = Command::new("sh"); - command - .args([ - "-c", - "sleep 30 >&2 & helper=$!; printf '%s\\n' \"$helper\"; printf 'permission denied\\n' >&2", - ]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - let (stdin, stdout, process) = spawn_transport_process(&mut command).unwrap(); - drop(stdin); - - let mut stdout = BufReader::new(stdout); - let mut helper_pid = String::new(); - stdout.read_line(&mut helper_pid).unwrap(); - let helper_pid = helper_pid.trim().parse::().unwrap(); - let mut remaining = Vec::new(); - stdout.read_to_end(&mut remaining).unwrap(); - assert!(remaining.is_empty()); - - let (result_sender, result_receiver) = std::sync::mpsc::sync_channel(1); - let diagnostic_process = Arc::clone(&process); - let waiter = thread::spawn(move || { - let _ = result_sender.send(diagnostic_process.diagnostic_after_stdout_eof()); - }); - let prompt_result = result_receiver.recv_timeout(Duration::from_millis(500)); - let completed_promptly = prompt_result.is_ok(); - let diagnostic = match prompt_result { - Ok(diagnostic) => diagnostic, - Err(_) => { - unsafe { - libc::kill(helper_pid, libc::SIGKILL); - } - result_receiver - .recv_timeout(Duration::from_secs(5)) - .expect("diagnostic reader should stop once the inherited descriptor closes") - } + fn client_catalog_machine_rename_is_session_local() { + let machine = MachineConfig { + id: "mini".into(), + name: "Mini".into(), + subtitle: "ssh".into(), + target: MachineTargetConfig::Unix { socket: PathBuf::from("/tmp/mini.sock") }, }; - waiter.join().unwrap(); + let mut runtime = MachineRuntime::new(PathBuf::from("/tmp/current.sock"), vec![machine]); + let key = runtime.snapshot(runtime.initial_key()).machines[1].key; - assert!(completed_promptly, "transport cleanup waited for an inherited stderr handle"); - assert_eq!(diagnostic.as_deref(), Some("permission denied")); + assert_eq!(runtime.rename_machine(key, " Build box ").unwrap(), "Build box"); + assert_eq!(runtime.name(key), Some("Build box")); + assert!(runtime.ui_state(runtime.initial_key()).is_client_machine_renamable(key)); } #[test] - fn connected_target_is_deduplicated() { - let mut runtime = MachineRuntime::new(PathBuf::from("/tmp/current.sock"), Vec::new()); - let first = runtime.connect_machine("lawrence@mini.local").unwrap(); - let second = runtime.connect_machine("lawrence@mini.local").unwrap(); - assert_eq!(first, second); - assert_eq!(runtime.snapshot(runtime.initial_key()).machines.len(), 2); + fn ssh_config_discovery_follows_includes_and_skips_patterns() { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path(); + let ssh_root = home.join(".ssh"); + let include_root = ssh_root.join("hosts"); + fs::create_dir_all(&include_root).unwrap(); + fs::write( + ssh_root.join("config"), + "Include hosts/*.conf\nHost buildbox *.internal !blocked duplicate\n", + ) + .unwrap(); + fs::write(include_root.join("a.conf"), "Host mini duplicate\n HostName 192.0.2.10\n") + .unwrap(); + fs::write(include_root.join("b.conf"), "Host=quoted-host # note\n").unwrap(); + + assert_eq!( + ssh_config_hosts_from_path(&ssh_root.join("config"), &ssh_root, home), + vec!["buildbox", "duplicate", "mini", "quoted-host"] + ); + } + + #[test] + fn ssh_config_discovery_breaks_include_cycles() { + let temp = tempfile::tempdir().unwrap(); + let home = temp.path(); + let ssh_root = home.join(".ssh"); + fs::create_dir_all(&ssh_root).unwrap(); + fs::write(ssh_root.join("config"), "Include loop\nHost root\n").unwrap(); + fs::write(ssh_root.join("loop"), "Include config\nHost nested\n").unwrap(); + + assert_eq!( + ssh_config_hosts_from_path(&ssh_root.join("config"), &ssh_root, home), + vec!["root", "nested"] + ); } #[test] @@ -612,6 +831,37 @@ mod tests { assert_eq!(runtime.snapshot(runtime.initial_key()).machines.len(), 2); } + #[test] + fn prototype_creation_sources_add_local_catalog_entries_without_provisioning() { + let mut runtime = MachineRuntime::with_creation_sources( + PathBuf::from("/tmp/current.sock"), + Vec::new(), + vec![MachineCreationSourceConfig { + id: "docker".into(), + name: "Docker".into(), + subtitle: "container prototype".into(), + }], + ); + let active = runtime.initial_key(); + + let ui = runtime.ui_state(active); + assert!(ui.snapshot.capabilities.create); + assert_eq!(ui.creation_sources[0].id, "docker"); + + let (first, first_name) = runtime.create_from("docker").unwrap(); + let (second, second_name) = runtime.create_from("docker").unwrap(); + assert_ne!(first, second); + assert_eq!(first_name, "Docker 1"); + assert_eq!(second_name, "Docker 2"); + let snapshot = runtime.snapshot(active); + assert_eq!(snapshot.machines.len(), 3); + assert_eq!(snapshot.machines[1].id, "prototype:docker:1"); + assert!(matches!( + runtime.entry(first).map(|entry| &entry.target), + Some(MachineTargetConfig::Unix { socket }) if socket == &PathBuf::from("/tmp/current.sock") + )); + } + #[test] fn external_catalog_has_no_implicit_machine_and_uses_disjoint_keys() { let machine = MachineConfig { @@ -636,20 +886,22 @@ mod tests { assert!(error.contains("cannot connect external machines"), "{error}"); } + #[cfg(unix)] #[test] - fn ssh_transport_is_noninteractive_and_fail_closed() { - let arguments = ssh_arguments( + fn ssh_machine_connection_uses_managed_bootstrap_and_fail_closed_policy() { + let options = managed_ssh_options( "mini.local", Some("lawrence"), Some(2200), - Some(std::path::Path::new("/tmp/cloud key")), - "agent's work", - "/opt/cmux tui", + Some(Path::new("/tmp/cloud key")), + "agents", + "/opt/cmux-tui", ) - .into_iter() - .map(|argument| argument.to_string_lossy().into_owned()) - .collect::>(); + .unwrap(); + assert_eq!(options.destination, "lawrence@mini.local:2200"); + assert_eq!(options.session, "agents"); + assert_eq!(options.remote_binary, "/opt/cmux-tui"); for option in [ "BatchMode=yes", "StrictHostKeyChecking=yes", @@ -657,15 +909,11 @@ mod tests { "ForwardX11=no", "ClearAllForwardings=yes", ] { - assert!(arguments.windows(2).any(|pair| pair == ["-o", option]), "{arguments:?}"); + assert!(options.ssh_args.windows(2).any(|pair| pair == ["-o", option])); } - assert!(arguments.windows(2).any(|pair| pair == ["-p", "2200"])); - assert!(arguments.windows(2).any(|pair| pair == ["-i", "/tmp/cloud key"])); - let separator = arguments.iter().position(|argument| argument == "--").unwrap(); - assert_eq!(arguments[separator + 1], "lawrence@mini.local"); - assert_eq!( - arguments[separator + 2], - "'/opt/cmux tui' relay --session 'agent'\"'\"'s work'" + assert!(options.ssh_args.windows(2).any(|pair| pair == ["-i", "/tmp/cloud key"])); + assert!( + managed_ssh_options("mini.local", None, None, None, "agents", "/opt/cmux tui").is_err() ); } } diff --git a/cmux-tui/crates/cmux-tui/src/main.rs b/cmux-tui/crates/cmux-tui/src/main.rs index ae205fde433b..de75d97d188e 100644 --- a/cmux-tui/crates/cmux-tui/src/main.rs +++ b/cmux-tui/crates/cmux-tui/src/main.rs @@ -62,6 +62,7 @@ mod remote_cli { mod remote_runtime; mod session; mod sidebar_files; +mod sidebar_projection; mod ui; #[cfg(target_os = "linux")] @@ -87,7 +88,9 @@ use machine_provider_client::{ }; #[cfg(unix)] use machine_provider_runtime::ProviderMachineController; -use machine_runtime::MachineRuntime; +use machine_runtime::{ + MachineConnection, MachineConnectionHub, MachineConnectionLease, MachineRuntime, +}; use session::{RemoteSession, Session}; use zeroize::Zeroize; @@ -1581,8 +1584,16 @@ fn run_server( None }; - let machine_runtime = (config.machine_sidebar.enabled || !config.machines.is_empty()) - .then(|| MachineRuntime::new(socket_path.clone(), config.machines.clone())); + let machine_runtime = (config.machine_sidebar.enabled + || !config.machine_sidebar.create_sources.is_empty() + || !config.machines.is_empty()) + .then(|| { + MachineRuntime::with_creation_sources( + socket_path.clone(), + config.machines.clone(), + config.machine_sidebar.create_sources.clone(), + ) + }); let result = if args.headless { #[cfg(unix)] { @@ -1659,7 +1670,10 @@ enum SessionClientMode { } fn session_client_mode(config: &config::Config) -> SessionClientMode { - if config.machine_sidebar.enabled || !config.machines.is_empty() { + if config.machine_sidebar.enabled + || !config.machine_sidebar.create_sources.is_empty() + || !config.machines.is_empty() + { SessionClientMode::Machines } else { SessionClientMode::Plain @@ -1679,27 +1693,46 @@ fn run_connected_session_client( match session_client_mode(&config) { SessionClientMode::Plain => run_tui(session, session_label, None), SessionClientMode::Machines => { - let runtime = MachineRuntime::new(socket_path, config.machines); - run_machine_client_with_initial(runtime, session) + let runtime = MachineRuntime::with_creation_sources( + socket_path, + config.machines, + config.machine_sidebar.create_sources, + ); + run_machine_client_with_initial(runtime, session, None) } } } -fn run_machine_client(mut runtime: MachineRuntime) -> anyhow::Result<()> { +fn run_machine_client(runtime: MachineRuntime) -> anyhow::Result<()> { let active = runtime.initial_key(); - let session = runtime.connect(active)?; - run_machine_client_with_initial(runtime, session) + let connections = MachineConnectionHub::new(runtime.connection_connectors()); + let session = connections.connect(active)?; + run_machine_client_with_hub(runtime, session, connections) } fn run_machine_client_with_initial( runtime: MachineRuntime, session: Session, + active_lease: Option>, +) -> anyhow::Result<()> { + let active = runtime.initial_key(); + let connections = MachineConnectionHub::new(runtime.connection_connectors()); + connections + .insert_ready(active, MachineConnection { session: session.clone(), _lease: active_lease }); + run_machine_client_with_hub(runtime, session, connections) +} + +fn run_machine_client_with_hub( + runtime: MachineRuntime, + session: Session, + connections: MachineConnectionHub, ) -> anyhow::Result<()> { let active = runtime.initial_key(); let label = runtime.name(active).unwrap_or("machine").to_string(); - let machine_ui = MachineUiState::new(runtime.snapshot(active)); + let mut machine_ui = runtime.ui_state(active); + machine_ui.set_connection_phases(connections.phases()); let controller: Box = - Box::new(StaticMachineController { runtime, active, pending_active: None }); + Box::new(StaticMachineController { runtime, active, connections, pending: None }); match run_tui_once(session, label, None, Some(machine_ui), Some(controller))? { app::RunOutcome::Quit => Ok(()), app::RunOutcome::Machine(_) => { @@ -1711,7 +1744,8 @@ fn run_machine_client_with_initial( struct StaticMachineController { runtime: MachineRuntime, active: machine::MachineKey, - pending_active: Option, + connections: MachineConnectionHub, + pending: Option, } impl MachineController for StaticMachineController { @@ -1720,6 +1754,7 @@ impl MachineController for StaticMachineController { MachineRequest::Switch(machine) => self.switch(machine), MachineRequest::Connect { target, route: MachineConnectRoute::Local } => { let machine = self.runtime.connect_machine(&target)?; + self.register(machine)?; self.switch(machine) } MachineRequest::Connect { route: MachineConnectRoute::Provider, .. } => Ok(self @@ -1729,6 +1764,18 @@ impl MachineController for StaticMachineController { MachineRequest::Create => { Ok(self.notice(localization::catalog().sidebar.machine_catalog_create_unsupported)) } + MachineRequest::CreateFrom { source_id } => { + let (machine, name) = self.runtime.create_from(&source_id)?; + self.register(machine)?; + let message = + format!("{}: {name}", localization::catalog().sidebar.prototype_machine_added); + Ok(self.notice(message)) + } + MachineRequest::RenameClientMachine { machine, name } => { + let name = self.runtime.rename_machine(machine, &name)?; + let result = MachineActionResult::ui(self.ui_state(self.active)); + Ok(if machine == self.active { result.with_session_label(name) } else { result }) + } MachineRequest::SelectProviderScope(_) | MachineRequest::InvokeProviderAction { .. } | MachineRequest::ReconnectProvider => Ok(self.notice( @@ -1749,32 +1796,59 @@ impl MachineController for StaticMachineController { } } - fn commit_replacement(&mut self) -> anyhow::Result<()> { - self.active = self.pending_active.take().ok_or_else(|| { + fn commit_replacement(&mut self, present: bool) -> anyhow::Result<()> { + let machine = self.pending.take().ok_or_else(|| { anyhow::anyhow!(localization::catalog().sidebar.machine_replacement_target_missing) })?; + if present { + self.active = machine; + } Ok(()) } fn abort_replacement(&mut self) { - self.pending_active = None; + if let Some(machine) = self.pending.take() + && machine != self.active + { + self.connections.remove(machine); + } + } + + fn close(&mut self) { + self.pending = None; + self.connections.close(); } } impl StaticMachineController { fn switch(&mut self, machine: machine::MachineKey) -> anyhow::Result { - let session = self.runtime.connect(machine)?; + self.register(machine)?; + let session = self.connections.connect(machine)?; let label = self.runtime.name(machine).unwrap_or("machine").to_string(); - self.pending_active = Some(machine); - let ui = MachineUiState::new(self.runtime.snapshot(machine)); + self.pending = Some(machine); + let ui = self.ui_state(machine); Ok(MachineActionResult::replace(ui, session, label)) } fn notice(&self, notice: impl Into) -> MachineActionResult { - let mut ui = MachineUiState::new(self.runtime.snapshot(self.active)); + let mut ui = self.ui_state(self.active); ui.notice = Some(notice.into()); MachineActionResult::ui(ui) } + + fn register(&self, machine: machine::MachineKey) -> anyhow::Result<()> { + let connector = self.runtime.connection_connector(machine).ok_or_else(|| { + anyhow::anyhow!(localization::catalog().sidebar.client_machine_unavailable) + })?; + self.connections.register(machine, connector); + Ok(()) + } + + fn ui_state(&self, active: machine::MachineKey) -> MachineUiState { + let mut ui = self.runtime.ui_state(active); + ui.set_connection_phases(self.connections.phases()); + ui + } } #[cfg(unix)] @@ -1798,6 +1872,7 @@ fn run_provider_machine_client( &error, )), }; + runtime.sync_connections(); let controller: Box = Box::new(runtime); match run_tui_once(session, label, None, Some(machine_ui), Some(controller))? { app::RunOutcome::Quit => Ok(()), @@ -2125,7 +2200,9 @@ mod tests { let runtime = MachineRuntime::new(PathBuf::from("/tmp/static-machine-notice.sock"), vec![]); let active = runtime.initial_key(); - let mut controller = StaticMachineController { runtime, active, pending_active: None }; + let connections = MachineConnectionHub::new(runtime.connection_connectors()); + let mut controller = + StaticMachineController { runtime, active, connections, pending: None }; assert_eq!( controller.perform(MachineRequest::Create).unwrap().ui.notice.as_deref(), @@ -2142,6 +2219,92 @@ mod tests { ); } + #[test] + fn static_machine_creation_does_not_connect_until_selected() { + let suffix = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let socket = std::env::temp_dir() + .join(format!("cmux-unselected-machine-{}-{suffix}.sock", std::process::id())); + let runtime = MachineRuntime::with_creation_sources( + socket, + vec![], + vec![config::MachineCreationSourceConfig { + id: "docker".into(), + name: "Docker".into(), + subtitle: "container prototype".into(), + }], + ); + let active = runtime.initial_key(); + let connections = MachineConnectionHub::new(runtime.connection_connectors()); + let mut controller = + StaticMachineController { runtime, active, connections, pending: None }; + + let action = + controller.perform(MachineRequest::CreateFrom { source_id: "docker".into() }).unwrap(); + let created = action + .ui + .snapshot + .machines + .iter() + .find(|machine| machine.id == "prototype:docker:1") + .unwrap() + .key; + + assert_eq!( + action.ui.connection_phase(created), + machine::MachineConnectionPhase::Disconnected, + "created machine transport must not open until the row is selected" + ); + assert!(action.replacement.is_none(), "creation must not replace the active session"); + } + + #[test] + fn static_machine_controller_retains_committed_connection_leases() { + use std::sync::atomic::AtomicUsize; + + struct CountedLease(Arc); + + impl Drop for CountedLease { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + + let dropped = Arc::new(AtomicUsize::new(0)); + let connects = Arc::new(AtomicUsize::new(0)); + let connector = |key: machine::MachineKey| { + let dropped = Arc::clone(&dropped); + let connects = Arc::clone(&connects); + let connector: machine_runtime::MachineConnectFn = Arc::new(move || { + connects.fetch_add(1, Ordering::SeqCst); + Ok(MachineConnection { + session: Session::Local(Mux::new( + format!("machine-hub-{}", key.0), + SurfaceOptions::default(), + )), + _lease: Some(Box::new(CountedLease(Arc::clone(&dropped)))), + }) + }); + (key, connector) + }; + let first = machine::MachineKey(1); + let second = machine::MachineKey(2); + let connections = MachineConnectionHub::new([connector(first), connector(second)]); + + connections.connect(first).unwrap(); + connections.connect(second).unwrap(); + connections.connect(first).unwrap(); + assert_eq!( + dropped.load(Ordering::SeqCst), + 0, + "switching must keep every connected machine lease warm" + ); + assert_eq!(connects.load(Ordering::SeqCst), 2, "returning to a machine reuses its session"); + + connections.close(); + assert_eq!(dropped.load(Ordering::SeqCst), 2, "all leases close with the connection hub"); + } + #[cfg(unix)] #[test] fn unix_provider_uses_the_edge_supplied_bearer() { diff --git a/cmux-tui/crates/cmux-tui/src/process_diagnostics.rs b/cmux-tui/crates/cmux-tui/src/process_diagnostics.rs index 1a356ec9764d..3d58fe663f5b 100644 --- a/cmux-tui/crates/cmux-tui/src/process_diagnostics.rs +++ b/cmux-tui/crates/cmux-tui/src/process_diagnostics.rs @@ -23,6 +23,7 @@ struct DiagnosticState { } impl BoundedDiagnosticBuffer { + #[cfg(test)] pub(crate) fn new(max_bytes: usize) -> Self { Self::with_redactions(max_bytes, &[]) } diff --git a/cmux-tui/crates/cmux-tui/src/remote_cli.rs b/cmux-tui/crates/cmux-tui/src/remote_cli.rs index c58da738b6fb..343a2b55aed2 100644 --- a/cmux-tui/crates/cmux-tui/src/remote_cli.rs +++ b/cmux-tui/crates/cmux-tui/src/remote_cli.rs @@ -28,7 +28,8 @@ use cmux_remote::identity::{ }; use cmux_remote::provider::{ IrohPathMode, ProviderError, ROUTING_DIRECT_ADDRS, ROUTING_NODE_ID, ROUTING_RELAY_URL, - RelayCredentialSource, SshProviderConfig, SupportedClientAuthModes, sanitized_route, + RelayCredentialSource, SshProvider, SshProviderConfig, SupportedClientAuthModes, + sanitized_route, }; use cmux_remote::ssh_bootstrap::{BUILD_IDENTITY, DISTRIBUTION_VERSION, NPM_BOOTSTRAP_VERSION}; use cmux_remote_protocol::{ @@ -1094,6 +1095,10 @@ fn run_rpc(args: &[String]) -> anyhow::Result<()> { } fn run_ssh(args: &[String]) -> anyhow::Result<()> { + connect_with_flags(direct_ssh_flags(args)?) +} + +fn direct_ssh_flags(args: &[String]) -> anyhow::Result { let destination = args .first() .filter(|argument| !argument.starts_with('-')) @@ -1108,7 +1113,81 @@ fn run_ssh(args: &[String]) -> anyhow::Result<()> { flags.lanes = LanePolicy::Single; } - connect_with_flags(flags) + Ok(flags) +} + +/// Programmatic equivalent of `cmux-tui ssh`, used by the native machine +/// rail so both entrypoints share compatibility checks, daemon startup, and +/// reconnect behavior. +pub(crate) struct ManagedSshOptions { + pub destination: String, + pub session: String, + pub remote_binary: String, + pub ssh_args: Vec, +} + +pub(crate) struct ManagedSshConnection { + pub session: Session, + pub lease: ManagedSshLease, +} + +/// Keeps the local bridge and its reconnecting SSH client alive for as long +/// as the selected machine session owns it. +pub(crate) struct ManagedSshLease { + runtime: Option, +} + +impl Drop for ManagedSshLease { + fn drop(&mut self) { + if let Some(runtime) = self.runtime.take() { + let _ = runtime.shutdown(); + } + } +} + +pub(crate) fn validate_managed_ssh_options(options: &ManagedSshOptions) -> anyhow::Result<()> { + ssh_url(&options.destination)?; + SshProvider::new(SshProviderConfig { + ssh_binary: "ssh".into(), + remote_binary: options.remote_binary.clone(), + remote_session: options.session.clone(), + remote_state_dir: None, + extra_args: options.ssh_args.clone(), + maximum_frame_bytes: crate::remote_runtime::MAX_CARRIER_FRAME_BYTES, + })?; + Ok(()) +} + +pub(crate) fn connect_managed_ssh( + options: ManagedSshOptions, +) -> anyhow::Result { + let mut arguments = vec![ + options.destination, + "--session".into(), + options.session, + "--remote-binary".into(), + options.remote_binary, + ]; + for argument in options.ssh_args { + arguments.push("--ssh-arg".into()); + arguments.push(argument); + } + + let connected = start_connected(direct_ssh_flags(&arguments)?)?; + let local_socket = connected.runtime.info().local_socket.clone(); + match RemoteSession::connect(&local_socket) { + Ok(remote) => Ok(ManagedSshConnection { + session: Session::Remote(remote), + lease: ManagedSshLease { runtime: Some(connected.runtime) }, + }), + Err(connect_error) => { + let cleanup_error = connected.runtime.shutdown().err(); + match cleanup_error { + Some(cleanup_error) => Err(connect_error.context(cleanup_error)), + None => Err(connect_error), + } + } + } } fn ssh_url(destination: &str) -> anyhow::Result { diff --git a/cmux-tui/crates/cmux-tui/src/session/mod.rs b/cmux-tui/crates/cmux-tui/src/session/mod.rs index ce1775835c7c..218cc1b16f23 100644 --- a/cmux-tui/crates/cmux-tui/src/session/mod.rs +++ b/cmux-tui/crates/cmux-tui/src/session/mod.rs @@ -32,9 +32,6 @@ use ghostty_vt::{ use serde::Deserialize; use serde_json::{Map, json}; -pub(crate) use remote::{ - REMOTE_CONTROL_MESSAGE_MAX_BYTES, read_bounded_json_line, read_json_line_with_progress, -}; pub use remote::{ RemoteMessageReader, RemoteMessageWriter, RemoteSession, RemoteSurface, RemoteTransport, RemoteTransportAbort, @@ -262,6 +259,17 @@ pub struct ClientSizeInfo { pub size_participating: bool, } +/// Canonical agent presence projected into sidebar views. Keeping this +/// transport-neutral lets local and remote sessions render identically. +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct AgentInfo { + pub surface: SurfaceId, + pub state: String, + pub source: String, + pub session: Option, + pub updated_at_ms: u64, +} + #[derive(Debug, Clone, Deserialize, PartialEq, Eq)] pub struct ClientInfo { pub client: u64, @@ -627,6 +635,23 @@ impl Session { } } + pub fn agents(&self) -> Vec { + match self { + Session::Local(mux) => mux + .list_agents(None, None) + .into_iter() + .map(|agent| AgentInfo { + surface: agent.surface, + state: agent.state.as_str().to_string(), + source: agent.source.as_str().to_string(), + session: agent.session, + updated_at_ms: agent.updated_at_ms, + }) + .collect(), + Session::Remote(remote) => remote.cached_agents(), + } + } + pub fn cached_surface(&self, id: SurfaceId) -> Option { match self { Session::Local(mux) => { diff --git a/cmux-tui/crates/cmux-tui/src/session/remote.rs b/cmux-tui/crates/cmux-tui/src/session/remote.rs index a97e5814bbbd..8d6e4e3b0a8e 100644 --- a/cmux-tui/crates/cmux-tui/src/session/remote.rs +++ b/cmux-tui/crates/cmux-tui/src/session/remote.rs @@ -35,10 +35,10 @@ use ghostty_vt::{ use serde_json::{Value, json}; use zeroize::{Zeroize, Zeroizing}; -use super::CLEAR_HISTORY_UNSUPPORTED_ERROR; #[cfg(test)] use super::tree::parse_tree; use super::tree::{TreeCapabilities, TreeView, parse_tree_with_capabilities}; +use super::{AgentInfo, CLEAR_HISTORY_UNSUPPORTED_ERROR}; const SUPPORTED_PROTOCOL_VERSION: u64 = 11; const SURFACE_OVERFLOW_RETRY_DELAYS: [Duration; 3] = @@ -280,9 +280,12 @@ impl Default for RemoteBrowserState { #[derive(Default)] struct RemoteTreeCache { view: TreeView, + agents: Vec, surface_tabs: HashMap, title_generation: u64, title_updates: HashMap, + agent_generation: u64, + agent_updates: HashMap, } #[derive(Clone, Copy)] @@ -298,6 +301,11 @@ struct TitleUpdate { title: String, } +struct AgentUpdate { + generation: u64, + agent: AgentInfo, +} + impl RemoteTreeCache { fn replace(&mut self, view: TreeView, refresh_generation: u64) { self.surface_tabs.clear(); @@ -364,6 +372,39 @@ impl RemoteTreeCache { fn title_generation(&self) -> u64 { self.title_generation } + + fn replace_agents(&mut self, agents: Vec, refresh_generation: u64) { + self.agents = agents; + let updates = std::mem::take(&mut self.agent_updates); + for update in updates.into_values() { + if update.generation > refresh_generation + && self.surface_tabs.contains_key(&update.agent.surface) + { + self.replace_agent(update.agent); + } + } + } + + fn update_agent(&mut self, agent: AgentInfo) { + self.agent_generation = self.agent_generation.saturating_add(1); + self.agent_updates.insert( + agent.surface, + AgentUpdate { generation: self.agent_generation, agent: agent.clone() }, + ); + self.replace_agent(agent); + } + + fn replace_agent(&mut self, agent: AgentInfo) { + if let Some(existing) = self.agents.iter_mut().find(|item| item.surface == agent.surface) { + *existing = agent; + } else { + self.agents.push(agent); + } + } + + fn agent_generation(&self) -> u64 { + self.agent_generation + } } #[cfg(test)] @@ -1598,6 +1639,7 @@ impl RemoteMessageReader for JsonLineReader { } } +#[cfg(test)] pub(crate) fn read_bounded_json_line( reader: &mut impl BufRead, limit: usize, @@ -1949,6 +1991,7 @@ impl RemoteSession { | "frame" | "detached" | "surface-exited" + | "agent-changed" | "title-changed" | "bell" | "scroll-changed" => surface == Some(target), @@ -2203,6 +2246,31 @@ impl RemoteSession { self.tree_stale.store(true, Ordering::Release); self.emit(MuxEvent::TreeChanged); } + Some("agent-changed") => { + let Some(surface) = surface_id() else { return }; + let Some(state) = value.get("state").and_then(Value::as_str) else { return }; + let Some(source) = value.get("source").and_then(Value::as_str) else { return }; + let Some(updated_at_ms) = value.get("updated_at_ms").and_then(Value::as_u64) else { + return; + }; + let session = value.get("session").and_then(Value::as_str).map(str::to_string); + let agent = AgentInfo { + surface, + state: state.to_string(), + source: source.to_string(), + session, + updated_at_ms, + }; + let event = MuxEvent::AgentChanged { + surface, + state: Arc::from(agent.state.as_str()), + source: Arc::from(agent.source.as_str()), + session: agent.session.as_deref().map(Arc::from), + updated_at_ms, + }; + self.tree.lock().unwrap().update_agent(agent); + self.emit(event); + } Some("layout-changed") => { self.tree_stale.store(true, Ordering::Release); if let Some(screen) = value.get("screen").and_then(|v| v.as_u64()) { @@ -3207,6 +3275,10 @@ impl RemoteSession { self.tree.lock().unwrap().view.clone() } + pub fn cached_agents(&self) -> Vec { + self.tree.lock().unwrap().agents.clone() + } + pub fn refresh_tree(&self) -> anyhow::Result { self.refresh_tree_inner(true) } @@ -3220,7 +3292,10 @@ impl RemoteSession { if identity_refresh { self.tree_stale.store(false, Ordering::Release); } - let refresh_generation = self.tree.lock().unwrap().title_generation(); + let (title_refresh_generation, agent_refresh_generation) = { + let cache = self.tree.lock().unwrap(); + (cache.title_generation(), cache.agent_generation()) + }; let data = match self.request(json!({"cmd": "list-workspaces"})) { Ok(data) => data, Err(e) => { @@ -3231,6 +3306,15 @@ impl RemoteSession { return Err(e); } }; + let agents = self + .request(json!({"cmd": "list-agents"})) + .ok() + .and_then(|data| { + data.get("agents") + .cloned() + .and_then(|agents| serde_json::from_value::>(agents).ok()) + }) + .unwrap_or_default(); let capabilities = self.capabilities.lock().unwrap(); let tree = parse_tree_with_capabilities( &data, @@ -3259,7 +3343,8 @@ impl RemoteSession { .retain(|surface_id, _| live_surface_ids.contains(surface_id)); let tree = { let mut cache = self.tree.lock().unwrap(); - cache.replace(tree, refresh_generation); + cache.replace(tree, title_refresh_generation); + cache.replace_agents(agents, agent_refresh_generation); cache.view.clone() }; let surfaces = self.surfaces.lock().unwrap().clone(); @@ -4105,7 +4190,7 @@ mod tests { #[test] fn per_surface_client_sizing_requires_protocol_10() { - assert!(SUPPORTED_PROTOCOL_VERSION >= 10); + const { assert!(SUPPORTED_PROTOCOL_VERSION >= 10) }; } #[test] @@ -5203,6 +5288,90 @@ mod tests { list_requests: usize, } + struct AgentRefreshWriter { + session: Arc>>>, + agent_requests: usize, + } + + impl RemoteMessageWriter for AgentRefreshWriter { + fn send(&mut self, message: &str) -> io::Result<()> { + let request: Value = serde_json::from_str(message).map_err(io::Error::other)?; + let id = request + .get("id") + .and_then(Value::as_u64) + .ok_or_else(|| io::Error::other("remote request omitted its id"))?; + let response = match request.get("cmd").and_then(Value::as_str) { + Some("list-workspaces") => json!({ + "id": id, + "ok": true, + "data": { + "workspaces": [{ + "id": 1, + "active": true, + "screens": [{ + "id": 2, + "active": true, + "active_pane": 3, + "layout": {"type": "leaf", "pane": 3}, + "panes": [{ + "id": 3, + "active_tab": 0, + "tabs": [{"surface": 4, "kind": "pty"}], + }], + }], + }], + }, + }), + Some("list-agents") => { + self.agent_requests += 1; + if self.agent_requests == 1 { + json!({ + "id": id, + "ok": true, + "data": { + "agents": [{ + "surface": 4, + "state": "working", + "source": "hook", + "session": "agent-session", + "updated_at_ms": 1, + }], + }, + }) + } else { + json!({"id": id, "ok": false, "error": "agent snapshot unavailable"}) + } + } + command => { + return Err(io::Error::other(format!( + "unexpected agent refresh command {command:?}" + ))); + } + }; + let session = self + .session + .lock() + .unwrap() + .as_ref() + .and_then(Weak::upgrade) + .ok_or_else(|| io::Error::other("test remote session was dropped"))?; + let pending = session + .pending + .lock() + .unwrap() + .remove(&id) + .ok_or_else(|| io::Error::other("remote request was not pending"))?; + pending + .response + .send(response) + .map_err(|_| io::Error::other("remote response receiver was dropped")) + } + + fn close(&mut self) -> io::Result<()> { + Ok(()) + } + } + impl RemoteMessageWriter for EnsureInitialTreeWriter { fn send(&mut self, message: &str) -> io::Result<()> { let request: Value = serde_json::from_str(message).map_err(io::Error::other)?; @@ -5235,6 +5404,7 @@ mod tests { }) } } + Some("list-agents") => json!({"agents": []}), Some("new-workspace") => json!({"surface": 4}), command => { return Err(io::Error::other(format!( @@ -5285,6 +5455,23 @@ mod tests { ); } + #[test] + fn failed_agent_refresh_clears_last_known_agent_rows() { + let session_slot = Arc::new(Mutex::new(None)); + let remote = test_session(Box::new(AgentRefreshWriter { + session: session_slot.clone(), + agent_requests: 0, + })); + *session_slot.lock().unwrap() = Some(Arc::downgrade(&remote)); + + remote.refresh_tree().unwrap(); + assert_eq!(remote.cached_agents().len(), 1); + + remote.refresh_tree().unwrap(); + + assert!(remote.cached_agents().is_empty()); + } + #[test] fn provider_guard_fails_before_writing_to_an_older_remote_server() { let session = @@ -6411,6 +6598,48 @@ mod tests { )); } + #[cfg(unix)] + #[test] + fn agent_events_update_the_remote_cache_without_invalidating_the_tree() { + let (client, _server) = UnixStream::pair().unwrap(); + let session = socket_test_session(client); + let events = session.subscribe(); + session.tree_stale.store(false, Ordering::Release); + + for (state, updated_at_ms) in [("working", 40), ("blocked", 41)] { + session.handle_line(json!({ + "event": "agent-changed", + "surface": 7, + "state": state, + "source": "hook", + "session": "review", + "updated_at_ms": updated_at_ms, + })); + } + + assert!(!session.tree_is_stale()); + assert_eq!( + session.cached_agents(), + vec![AgentInfo { + surface: 7, + state: "blocked".into(), + source: "hook".into(), + session: Some("review".into()), + updated_at_ms: 41, + }] + ); + assert!(matches!( + events.recv_timeout(Duration::from_secs(1)), + Ok(MuxEvent::AgentChanged { + surface: 7, + state, + updated_at_ms: 41, + .. + }) if state.as_ref() == "blocked" + )); + assert!(events.try_iter().next().is_none()); + } + #[test] fn surface_event_scope_filters_before_remote_cache_invalidation() { let (session, _requests) = recording_acknowledging_session(); @@ -6441,6 +6670,14 @@ mod tests { for event in [ json!({"event": "title-changed", "surface": 8, "title": "changed"}), + json!({ + "event": "agent-changed", + "surface": 8, + "state": "working", + "source": "hook", + "session": null, + "updated_at_ms": 1, + }), json!({"event": "surface-output", "surface": 8}), json!({"event": "surface-exited", "surface": 8}), json!({"event": "client-list-invalidated"}), @@ -6452,6 +6689,7 @@ mod tests { assert!(!session.tree_is_stale()); assert!(events.try_iter().next().is_none()); + assert!(session.cached_agents().is_empty()); assert_eq!(session.tree.lock().unwrap().view.surface(8).unwrap().title, "unrelated"); session.handle_line(json!({"event": "tree-changed"})); @@ -6478,6 +6716,21 @@ mod tests { Ok(MuxEvent::TitleChanged { surface: 7, .. }) )); + session.handle_line(json!({ + "event": "agent-changed", + "surface": 7, + "state": "working", + "source": "hook", + "session": null, + "updated_at_ms": 2, + })); + assert!(!session.tree_is_stale()); + assert_eq!(session.cached_agents()[0].surface, 7); + assert!(matches!( + events.recv_timeout(Duration::from_secs(1)), + Ok(MuxEvent::AgentChanged { surface: 7, .. }) + )); + session.handle_line(json!({"event": "surface-exited", "surface": 7})); assert!(session.tree_is_stale()); assert!(matches!( @@ -6618,6 +6871,39 @@ mod tests { assert_eq!(cache.view.workspaces[0].screens[0].panes[0].tabs[0].title, "fresh snapshot"); } + #[test] + fn agent_refresh_does_not_restore_an_update_for_a_removed_surface() { + let tree = parse_tree(&json!({ + "workspaces": [{ + "id": 1, + "screens": [{ + "id": 2, + "layout": {"type": "leaf", "pane": 3}, + "panes": [{ + "id": 3, + "tabs": [{"surface": 4, "title": "agent terminal"}], + }], + }], + }], + })); + let mut cache = RemoteTreeCache::default(); + cache.replace(tree, 0); + let refresh_generation = cache.agent_generation(); + cache.update_agent(AgentInfo { + surface: 4, + state: "working".into(), + source: "hook".into(), + session: Some("review".into()), + updated_at_ms: 41, + }); + + let title_generation = cache.title_generation(); + cache.replace(TreeView::default(), title_generation); + cache.replace_agents(Vec::new(), refresh_generation); + + assert!(cache.agents.is_empty()); + } + #[test] fn browser_state_without_frame_keeps_cached_frame() { let surface = RemoteSurface { diff --git a/cmux-tui/crates/cmux-tui/src/sidebar_projection.rs b/cmux-tui/crates/cmux-tui/src/sidebar_projection.rs new file mode 100644 index 000000000000..ce449b986947 --- /dev/null +++ b/cmux-tui/crates/cmux-tui/src/sidebar_projection.rs @@ -0,0 +1,427 @@ +//! Pure projection of mux resources into configurable native sidebar trees. + +use std::collections::{HashMap, HashSet}; + +use cmux_tui_core::{PaneId, SurfaceId, WorkspaceId}; + +use crate::config::{SidebarResourceKind, SidebarViewSpec}; +use crate::session::{AgentInfo, TreeView}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) enum ProjectionBranch { + Workspace(WorkspaceId), + Pane { workspace: WorkspaceId, pane: PaneId }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProjectionTarget { + Workspace { + index: usize, + id: WorkspaceId, + }, + Pane { + workspace: usize, + screen: usize, + pane: PaneId, + }, + Surface { + workspace: usize, + screen: usize, + pane: PaneId, + index: usize, + surface: SurfaceId, + agent: bool, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ProjectionRow { + pub resource: SidebarResourceKind, + pub depth: u16, + pub name: String, + pub subtitle: String, + pub agent_state: Option, + pub active: bool, + pub branch: Option, + pub expanded: bool, + pub target: ProjectionTarget, +} + +#[derive(Debug, Clone)] +pub(crate) struct ProjectionRailState { + /// Selected resource-row index. Action selection is tracked separately so + /// live resource insertions cannot retarget a pinned action. + pub selected: usize, + pub selected_action: Option, + pub scroll: usize, + pub footer_scroll: usize, + pub follow_selection: bool, + pub collapsed: HashSet, +} + +impl Default for ProjectionRailState { + fn default() -> Self { + Self { + selected: 0, + selected_action: None, + scroll: 0, + footer_scroll: 0, + follow_selection: true, + collapsed: HashSet::new(), + } + } +} + +#[derive(Clone, Copy)] +struct ProjectionContext { + workspace: usize, + screen: Option, + pane: Option, +} + +pub(crate) fn rows( + spec: &SidebarViewSpec, + tree: &TreeView, + agents: &[AgentInfo], + selected_workspace: usize, + collapsed: &HashSet, +) -> Vec { + let mut rows = Vec::new(); + let agents_by_surface: HashMap = + agents.iter().map(|agent| (agent.surface, agent)).collect(); + append_level( + &mut rows, + &spec.levels, + 0, + None, + tree, + &agents_by_surface, + selected_workspace.min(tree.workspaces.len().saturating_sub(1)), + collapsed, + ); + rows +} + +#[allow(clippy::too_many_arguments)] +fn append_level( + output: &mut Vec, + levels: &[SidebarResourceKind], + depth: usize, + context: Option, + tree: &TreeView, + agents: &HashMap, + selected_workspace: usize, + collapsed: &HashSet, +) { + let Some(resource) = levels.get(depth).copied() else { return }; + let has_children = depth + 1 < levels.len(); + match resource { + SidebarResourceKind::Machines => {} + SidebarResourceKind::Workspaces => { + for (workspace_index, workspace) in tree.workspaces.iter().enumerate() { + let branch = has_children.then_some(ProjectionBranch::Workspace(workspace.id)); + let expanded = branch.is_none_or(|branch| !collapsed.contains(&branch)); + output.push(ProjectionRow { + resource, + depth: depth as u16, + name: workspace.name.clone(), + subtitle: workspace.short_id.clone(), + agent_state: None, + active: workspace_index == tree.active_workspace, + branch, + expanded, + target: ProjectionTarget::Workspace { + index: workspace_index, + id: workspace.id, + }, + }); + if has_children && expanded { + append_level( + output, + levels, + depth + 1, + Some(ProjectionContext { + workspace: workspace_index, + screen: None, + pane: None, + }), + tree, + agents, + selected_workspace, + collapsed, + ); + } + } + } + SidebarResourceKind::Panes => { + let workspace_index = context.map_or(selected_workspace, |context| context.workspace); + let Some(workspace) = tree.workspaces.get(workspace_index) else { return }; + for (screen_index, screen) in workspace.screens.iter().enumerate() { + for pane in &screen.panes { + if context.is_some_and(|context| { + context.screen.is_some_and(|candidate| candidate != screen_index) + || context.pane.is_some_and(|candidate| candidate != pane.id) + }) { + continue; + } + let branch = has_children.then_some(ProjectionBranch::Pane { + workspace: workspace.id, + pane: pane.id, + }); + let expanded = branch.is_none_or(|branch| !collapsed.contains(&branch)); + output.push(ProjectionRow { + resource, + depth: depth as u16, + name: pane.display_name().to_string(), + subtitle: pane.short_id.clone(), + agent_state: None, + active: workspace_index == tree.active_workspace + && screen_index == workspace.active_screen + && pane.id == screen.active_pane, + branch, + expanded, + target: ProjectionTarget::Pane { + workspace: workspace_index, + screen: screen_index, + pane: pane.id, + }, + }); + if has_children && expanded { + append_level( + output, + levels, + depth + 1, + Some(ProjectionContext { + workspace: workspace_index, + screen: Some(screen_index), + pane: Some(pane.id), + }), + tree, + agents, + selected_workspace, + collapsed, + ); + } + } + } + } + SidebarResourceKind::Tabs | SidebarResourceKind::Agents => { + let agent_only = resource == SidebarResourceKind::Agents; + let workspace_index = context.map_or(selected_workspace, |context| context.workspace); + let Some(workspace) = tree.workspaces.get(workspace_index) else { return }; + for (screen_index, screen) in workspace.screens.iter().enumerate() { + if context.is_some_and(|context| { + context.screen.is_some_and(|candidate| candidate != screen_index) + }) { + continue; + } + for pane in &screen.panes { + if context.is_some_and(|context| { + context.pane.is_some_and(|candidate| candidate != pane.id) + }) { + continue; + } + for (tab_index, tab) in pane.tabs.iter().enumerate() { + let agent = agents.get(&tab.surface).copied(); + if agent_only && agent.is_none() { + continue; + } + let name = tab + .name + .as_deref() + .filter(|name| !name.is_empty()) + .or_else(|| (!tab.title.is_empty()).then_some(tab.title.as_str())) + .unwrap_or(tab.short_id.as_str()) + .to_string(); + let subtitle = if let Some(agent) = agent.filter(|_| agent_only) { + agent + .session + .as_deref() + .filter(|session| !session.is_empty()) + .unwrap_or(pane.short_id.as_str()) + .to_string() + } else { + pane.short_id.clone() + }; + output.push(ProjectionRow { + resource, + depth: depth as u16, + name, + subtitle, + agent_state: agent + .filter(|_| agent_only) + .map(|agent| agent.state.clone()), + active: workspace_index == tree.active_workspace + && screen_index == workspace.active_screen + && pane.id == screen.active_pane + && pane.active_tab == tab_index, + branch: None, + expanded: false, + target: ProjectionTarget::Surface { + workspace: workspace_index, + screen: screen_index, + pane: pane.id, + index: tab_index, + surface: tab.surface, + agent: agent_only, + }, + }); + } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cmux_tui_core::{Node, SurfaceKind}; + + use crate::session::tree::{PaneView, ScreenView, TabView, WorkspaceView}; + + fn tree() -> TreeView { + TreeView { + workspaces: vec![WorkspaceView { + id: 1, + resource_id: None, + key: "workspace-1".into(), + short_id: "w1".into(), + name: "project".into(), + screens: vec![ScreenView { + id: 2, + resource_id: None, + short_id: "s2".into(), + name: None, + layout: Node::Leaf(3), + active_pane: 3, + zoomed_pane: None, + viewport_base_width: None, + viewport_splits: Default::default(), + panes: vec![PaneView { + id: 3, + resource_id: None, + short_id: "p3".into(), + name: Some("editor".into()), + tabs: vec![tab(4, "shell"), tab(5, "codex")], + active_tab: 1, + focused_at: 0, + }], + }], + active_screen: 0, + }], + workspace_revision: 1, + pane_revision: Some(1), + active_workspace: 0, + } + } + + fn tab(surface: SurfaceId, title: &str) -> TabView { + TabView { + surface, + terminal_id: None, + short_id: format!("t{surface}"), + name: None, + title: title.into(), + kind: SurfaceKind::Pty, + browser_source: None, + browser_frames_stalled: false, + supports_clear_history_key_fallback: false, + notification: None, + } + } + + fn spec(levels: Vec) -> SidebarViewSpec { + SidebarViewSpec { + id: "test".into(), + levels, + actions: Vec::new(), + width: 22, + max_width: 0, + collapse_priority: 20, + } + } + + #[test] + fn workspace_agent_tree_uses_canonical_agent_records() { + let tree = tree(); + let agents = vec![AgentInfo { + surface: 5, + state: "working".into(), + source: "detected".into(), + session: Some("fix sidebar".into()), + updated_at_ms: 1, + }]; + let rows = rows( + &spec(vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Agents]), + &tree, + &agents, + 0, + &HashSet::new(), + ); + + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].resource, SidebarResourceKind::Workspaces); + assert_eq!(rows[1].name, "codex"); + assert_eq!(rows[1].subtitle, "fix sidebar"); + assert_eq!(rows[1].agent_state.as_deref(), Some("working")); + assert_eq!(rows[1].depth, 1); + assert!(matches!( + rows[1].target, + ProjectionTarget::Surface { surface: 5, agent: true, .. } + )); + } + + #[test] + fn collapsed_workspace_hides_its_projected_children() { + let tree = tree(); + let mut collapsed = HashSet::new(); + collapsed.insert(ProjectionBranch::Workspace(1)); + let rows = rows( + &spec(vec![SidebarResourceKind::Workspaces, SidebarResourceKind::Panes]), + &tree, + &[], + 0, + &collapsed, + ); + + assert_eq!(rows.len(), 1); + assert!(!rows[0].expanded); + } + + #[test] + fn three_level_tree_preserves_exact_tab_locations() { + let tree = tree(); + let rows = rows( + &spec(vec![ + SidebarResourceKind::Workspaces, + SidebarResourceKind::Panes, + SidebarResourceKind::Tabs, + ]), + &tree, + &[], + 0, + &HashSet::new(), + ); + + assert_eq!(rows.len(), 4); + assert_eq!(rows[3].depth, 2); + assert!(matches!( + rows[3].target, + ProjectionTarget::Surface { + workspace: 0, + screen: 0, + pane: 3, + index: 1, + surface: 5, + agent: false, + } + )); + } + + #[test] + fn flat_agent_view_is_empty_when_no_agents_are_running() { + let rows = rows(&spec(vec![SidebarResourceKind::Agents]), &tree(), &[], 0, &HashSet::new()); + assert!(rows.is_empty()); + } +} diff --git a/cmux-tui/crates/cmux-tui/src/ui/mod.rs b/cmux-tui/crates/cmux-tui/src/ui/mod.rs index 29e2a1c2ab16..8690cab00af6 100644 --- a/cmux-tui/crates/cmux-tui/src/ui/mod.rs +++ b/cmux-tui/crates/cmux-tui/src/ui/mod.rs @@ -22,10 +22,10 @@ use ratatui::style::{Color, Modifier, Style}; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; -use crate::app::{App, Hit}; +use crate::app::{App, Hit, RailKind}; use crate::config::Action; use crate::localization::catalog; -use crate::machine::DurableNoticeLevel; +use crate::machine::{DurableNoticeLevel, MachineConnectionPhase}; pub(crate) use overlay::toast_rect; pub(crate) use scrollbar::{ @@ -100,6 +100,7 @@ pub(crate) fn copy_buffer_row_cropped( pub fn draw(app: &mut App, frame: &mut Frame) { app.reset_frame_cursor_spec(); + app.reset_rendered_status_message(); let area = frame.area(); if area.height == 0 { return; @@ -109,12 +110,36 @@ pub fn draw(app: &mut App, frame: &mut Frame) { } app.hits.clear(); - if app.machine_sidebar_width > 0 { - sidebar::draw_machines(app, frame); + let mut sidebar_input_cursor = None; + if app.sidebar_layout.ordered.is_empty() { + // Preserve the pre-layout fallback used during startup, recovery, and + // isolated renderer tests. Each renderer resolves its area from the + // legacy live widths when no committed ordered layout exists yet. + if app.machine_sidebar_width > 0 { + sidebar::draw_machines(app, frame); + } + if app.sidebar_width > 0 { + sidebar_input_cursor = sidebar::draw(app, frame); + } + if app.tabs_sidebar_width > 0 { + sidebar::draw_tabs(app, frame); + } + } else { + for placement in app.sidebar_layout.ordered.clone() { + match placement.kind { + RailKind::Machine => sidebar::draw_machines(app, frame), + RailKind::Workspace => sidebar_input_cursor = sidebar::draw(app, frame), + RailKind::Tabs => sidebar::draw_tabs(app, frame), + RailKind::Projection(index) => sidebar::draw_projection(app, frame, index), + } + } } - let sidebar_input_cursor = (app.sidebar_width > 0).then(|| sidebar::draw(app, frame)).flatten(); - let pane_cursors = pane::draw_all(app, frame); + let pane_cursors = if draw_machine_transition(app, frame) { + pane::DrawCursors::default() + } else { + pane::draw_all(app, frame) + }; if app.is_surface_only() { draw_surface_status(app, frame); } else { @@ -139,6 +164,48 @@ pub fn draw(app: &mut App, frame: &mut Frame) { sanitize_render_buffer(frame.buffer_mut()); } +fn draw_machine_transition(app: &mut App, frame: &mut Frame) -> bool { + let Some((name, phase)) = + app.machine_transition().map(|(name, phase)| (name.to_string(), phase)) + else { + return false; + }; + let area = app.content_area; + app.pane_areas.clear(); + if area.width == 0 || area.height == 0 { + return true; + } + app.hits.retain(|(rect, _)| { + rect.x >= area.x.saturating_add(area.width) + || area.x >= rect.x.saturating_add(rect.width) + || rect.y >= area.y.saturating_add(area.height) + || area.y >= rect.y.saturating_add(rect.height) + }); + let status = match phase { + MachineConnectionPhase::Failed => catalog().sidebar.unavailable, + MachineConnectionPhase::Disconnected + | MachineConnectionPhase::Connecting + | MachineConnectionPhase::Ready => catalog().sidebar.connecting, + }; + let style = Style::default().fg(app.chrome.sidebar_dim_fg); + let title_style = + Style::default().fg(app.chrome.sidebar_selected_fg).add_modifier(Modifier::BOLD); + let buffer = frame.buffer_mut(); + for y in area.y..area.y.saturating_add(area.height) { + for x in area.x..area.x.saturating_add(area.width) { + buffer[(x, y)].set_symbol(" ").set_style(Style::default()); + } + } + let center_y = area.y.saturating_add(area.height / 2); + let title_width = name.width().min(area.width as usize); + let title_x = area.x.saturating_add(area.width.saturating_sub(title_width as u16) / 2); + buffer.set_stringn(title_x, center_y.saturating_sub(1), &name, title_width, title_style); + let status_width = status.width().min(area.width as usize); + let status_x = area.x.saturating_add(area.width.saturating_sub(status_width as u16) / 2); + buffer.set_stringn(status_x, center_y, status, status_width, style); + true +} + fn draw_durable_notice_banner(app: &mut App, frame: &mut Frame) { let area = frame.area(); if area.width == 0 || area.height == 0 { @@ -147,6 +214,8 @@ fn draw_durable_notice_banner(app: &mut App, frame: &mut Frame) { let Some(notice) = app.durable_notice().cloned() else { return; }; + app.hide_status_message(); + app.hits.retain(|(_, hit)| !matches!(hit, Hit::StatusMessage | Hit::CopyStatusMessage)); let (marker, color) = match notice.level { DurableNoticeLevel::Info => ("i ", app.config.theme.notification_info), DurableNoticeLevel::Warning => ("! ", app.config.theme.notification_warning), @@ -169,19 +238,102 @@ fn draw_durable_notice_banner(app: &mut App, frame: &mut Frame) { /// Single-surface clients keep the full terminal grid and overlay transient /// notices on its last row using foreground styling only. -fn draw_surface_status(app: &App, frame: &mut Frame) { - let Some(message) = app.status_message.as_deref() else { return }; +fn draw_surface_status(app: &mut App, frame: &mut Frame) { + let Some(message) = app.status_message.as_deref() else { + app.hide_status_message(); + return; + }; let area = frame.area(); if area.width == 0 { + app.hide_status_message(); return; } - frame.buffer_mut().set_stringn( - 0, - area.height - 1, - message, - area.width as usize, - Style::default().fg(Color::Red).add_modifier(Modifier::BOLD), + let copy_label = status_copy_label(); + let copy_width = copy_label.width().min(area.width as usize) as u16; + let show_copy = area.width > copy_width.saturating_add(2); + let message_width = if show_copy { + area.width.saturating_sub(copy_width.saturating_add(1)) + } else { + area.width + }; + let text = status_display_text(message, message_width as usize); + let text_width = text.width() as u16; + let style = Style::default().fg(Color::Red).add_modifier(Modifier::BOLD); + draw_interactive_status_message( + app, + frame, + Rect { x: 0, y: area.height - 1, width: text_width, height: 1 }, + text, + style, ); + if show_copy { + draw_status_copy_control( + app, + frame, + Rect { + x: text_width.saturating_add(1), + y: area.height - 1, + width: copy_width, + height: 1, + }, + ©_label, + style, + ); + } +} + +fn status_display_text(message: &str, max_width: usize) -> String { + let sanitized = message + .chars() + .map(|character| if character.is_control() { ' ' } else { character }) + .collect::(); + truncate(&sanitized, max_width) +} + +fn draw_interactive_status_message( + app: &mut App, + frame: &mut Frame, + rect: Rect, + text: String, + style: Style, +) { + if rect.width == 0 || text.is_empty() { + app.hide_status_message(); + return; + } + app.present_status_message(rect, text.clone()); + app.hits.push((rect, Hit::StatusMessage)); + frame.buffer_mut().set_stringn(rect.x, rect.y, &text, rect.width as usize, style); + + let mut selected_style = style.bg(app.config.theme.selection_bg); + if let Some(foreground) = app.config.theme.selection_fg { + selected_style = selected_style.fg(foreground); + } + for cell in 0..rect.width { + if app.status_message_cell_selected(&text, cell) { + frame.buffer_mut()[(rect.x + cell, rect.y)].set_style(selected_style); + } + } +} + +fn status_copy_label() -> String { + format!("[{}]", catalog().menu.copy_message) +} + +fn draw_status_copy_control( + app: &mut App, + frame: &mut Frame, + rect: Rect, + label: &str, + style: Style, +) { + if rect.width == 0 { + return; + } + let hovered = app.hover.is_some_and(|(x, y)| rect.contains(x, y)); + let style = if hovered { style.add_modifier(Modifier::REVERSED) } else { style }; + frame.buffer_mut().set_stringn(rect.x, rect.y, label, rect.width as usize, style); + app.hits.push((rect, Hit::CopyStatusMessage)); } fn sanitize_render_buffer(buffer: &mut Buffer) { @@ -224,35 +376,46 @@ fn draw_status_bar(app: &mut App, frame: &mut Frame) { (start, width) }; - let Some(ws) = app.tree.active_workspace().cloned() else { - if app.prefix_armed { - draw_prefix_help_bar(app, frame, bar_x, status_y.saturating_sub(1)); + if let Some(ws) = app.tree.active_workspace().cloned() { + put(frame, &mut x, " screens ", base.fg(chrome.status_dim_fg)); + for (i, screen) in ws.screens.iter().enumerate() { + let active = i == ws.active_screen; + let label = format!(" {} ", truncate(&screen.display_name(i), 20)); + let (start, width) = + put(frame, &mut x, &label, if active { active_style } else { base }); + if width > 0 { + hits.push(( + Rect { x: start, y: status_y, width, height: 1 }, + Hit::ScreenEntry { index: i, id: screen.id }, + )); + } } - return; - }; - put(frame, &mut x, " screens ", base.fg(chrome.status_dim_fg)); - for (i, screen) in ws.screens.iter().enumerate() { - let active = i == ws.active_screen; - let label = format!(" {} ", truncate(&screen.display_name(i), 20)); - let (start, width) = put(frame, &mut x, &label, if active { active_style } else { base }); + let (start, width) = put(frame, &mut x, " + ", base.fg(chrome.status_dim_fg)); if width > 0 { - hits.push(( - Rect { x: start, y: status_y, width, height: 1 }, - Hit::ScreenEntry { index: i, id: screen.id }, - )); + hits.push((Rect { x: start, y: status_y, width, height: 1 }, Hit::NewScreen)); } } - let (start, width) = put(frame, &mut x, " + ", base.fg(chrome.status_dim_fg)); - if width > 0 { - hits.push((Rect { x: start, y: status_y, width, height: 1 }, Hit::NewScreen)); - } // Session label / status message, right-aligned. Prefix help renders // over the pane border above this row. let available_label_width = area.width.saturating_sub(x) as usize; - let label = app - .status_message + let copy_label = status_copy_label(); + let copy_width = copy_label.width(); + let show_copy = + app.status_message.is_some() && available_label_width > copy_width.saturating_add(3); + let status_text = app.status_message.as_deref().map(|message| { + let reserved = if show_copy { copy_width.saturating_add(3) } else { 2 }; + status_display_text(message, available_label_width.saturating_sub(reserved)) + }); + if status_text.is_none() { + app.hide_status_message(); + } + let label = status_text .as_ref() - .map(|msg| format!(" {} ", truncate(msg, available_label_width.saturating_sub(2)))) + .map( + |message| { + if show_copy { format!(" {message} {copy_label} ") } else { format!(" {message} ") } + }, + ) .unwrap_or_else(|| { format!("[{}] ", truncate(&app.session_label, available_label_width.saturating_sub(3))) }); @@ -279,8 +442,9 @@ fn draw_status_bar(app: &mut App, frame: &mut Frame) { app.hits.extend(hits); if x.saturating_add(label_w) <= area.width { + let label_x = area.width - label_w; frame.buffer_mut().set_stringn( - area.width - label_w, + label_x, status_y, &label, label_w as usize, @@ -290,6 +454,32 @@ fn draw_status_bar(app: &mut App, frame: &mut Frame) { base.fg(chrome.status_dim_fg) }, ); + if let Some(status_text) = status_text { + let status_width = status_text.width() as u16; + draw_interactive_status_message( + app, + frame, + Rect { x: label_x.saturating_add(1), y: status_y, width: status_width, height: 1 }, + status_text, + base.fg(Color::Red).add_modifier(Modifier::BOLD), + ); + if show_copy { + draw_status_copy_control( + app, + frame, + Rect { + x: label_x.saturating_add(status_width).saturating_add(2), + y: status_y, + width: copy_width as u16, + height: 1, + }, + ©_label, + base.fg(Color::Red).add_modifier(Modifier::BOLD), + ); + } + } + } else { + app.hide_status_message(); } if app.prefix_armed { draw_prefix_help_bar(app, frame, bar_x, status_y.saturating_sub(1)); diff --git a/cmux-tui/crates/cmux-tui/src/ui/overlay.rs b/cmux-tui/crates/cmux-tui/src/ui/overlay.rs index f5a8f1203cf2..54e6541bc382 100644 --- a/cmux-tui/crates/cmux-tui/src/ui/overlay.rs +++ b/cmux-tui/crates/cmux-tui/src/ui/overlay.rs @@ -15,6 +15,15 @@ use crate::localization::catalog; use super::{ScrollbarState, ScrollbarStyle}; +#[derive(Clone, Copy)] +struct ConnectionPromptStyles { + base: Style, + title: Style, + input: Style, + button_accent: ratatui::style::Color, + button_hover: ratatui::style::Color, +} + /// Trusted approval dialog for a browser pairing request. pub fn draw_pairing_dialog(app: &mut App, frame: &mut Frame) { let screen = frame.area(); @@ -88,12 +97,20 @@ pub fn draw_prompt(app: &mut App, frame: &mut Frame) { let screen = frame.area(); let hover = app.hover; let shake = app.shake_frames; + let connection = app.connection_transaction.clone(); if app.shake_frames > 0 { app.shake_frames -= 1; } - let width: u16 = 42.min(screen.width.saturating_sub(2)).max(20); - let height: u16 = 9; + let width: u16 = + if connection.is_some() { 64 } else { 42 }.min(screen.width.saturating_sub(2)).max(20); + let height: u16 = if connection.as_ref().is_some_and(|transaction| { + matches!(transaction.phase, crate::app::ConnectionDialogPhase::Failed(_)) + }) { + 13 + } else { + 9 + }; if screen.width < width || screen.height < height { return; } @@ -121,6 +138,24 @@ pub fn draw_prompt(app: &mut App, frame: &mut Frame) { } } draw_border(buf, prompt.rect, border); + if let Some(transaction) = connection + && !matches!(transaction.phase, crate::app::ConnectionDialogPhase::Editing) + { + draw_connection_prompt( + frame, + prompt, + &transaction, + hover, + ConnectionPromptStyles { + base, + title: title_style, + input: input_style, + button_accent: chrome.prompt_button_accent_fg, + button_hover: chrome.prompt_button_hover_bg, + }, + ); + return; + } buf.set_stringn(x + 2, y + 2, prompt.label.as_str(), (width - 4) as usize, title_style); // Input row: visible slice around the cursor. @@ -181,9 +216,159 @@ pub fn draw_prompt(app: &mut App, frame: &mut Frame) { buf.set_stringn(ok_x, button_y, ok_label, ok_w as usize, button_style(prompt.ok, true)); } +fn draw_connection_prompt( + frame: &mut Frame, + prompt: &mut crate::app::Prompt, + transaction: &crate::app::ConnectionTransaction, + hover: Option<(u16, u16)>, + styles: ConnectionPromptStyles, +) { + use crate::app::ConnectionDialogPhase; + + let Rect { x, y, width, height } = prompt.rect; + let copy = &catalog().sidebar; + let (title, error) = match &transaction.phase { + ConnectionDialogPhase::Editing => return, + ConnectionDialogPhase::Connecting => { + (copy.connecting_to_message(&transaction.target), None) + } + ConnectionDialogPhase::Starting => (copy.starting_on_message(&transaction.target), None), + ConnectionDialogPhase::Failed(error) => { + (copy.failed_to_connect_message(&transaction.target), Some(error.as_str())) + } + }; + frame.buffer_mut().set_stringn(x + 2, y + 2, &title, (width - 4) as usize, styles.title); + + let input_w = width.saturating_sub(4); + prompt.input_rect = Rect::default(); + for dx in 0..input_w { + set_cell(frame.buffer_mut(), x + 2 + dx, y + 4, " ", styles.input); + } + frame.buffer_mut().set_stringn( + x + 2, + y + 4, + &transaction.target, + input_w as usize, + styles.input, + ); + + if let Some(error) = error { + for (index, line) in + wrapped_message_lines(error, (width - 4) as usize, 3).into_iter().enumerate() + { + frame.buffer_mut().set_stringn( + x + 2, + y + 6 + index as u16, + &line, + (width - 4) as usize, + styles.base, + ); + } + } + + let close_label = format!("[ {} esc ]", copy.close_dialog); + let retry_label = format!("[ {} ⏎ ]", copy.retry_connection); + let copy_label = format!("[ {} ^C ]", catalog().menu.copy_message); + let close_w = label_width(&close_label); + let retry_w = label_width(&retry_label); + let copy_w = label_width(©_label); + let button_y = y + height.saturating_sub(3); + let retry_x = x + width - 2 - retry_w; + let close_x = retry_x.saturating_sub(close_w + 2); + let copy_x = close_x.saturating_sub(copy_w + 2); + let failed = error.is_some(); + prompt.ok = if failed { + Rect { x: retry_x, y: button_y, width: retry_w, height: 1 } + } else { + Rect::default() + }; + prompt.clear = if failed && copy_x >= x + 2 { + Rect { x: copy_x, y: button_y, width: copy_w, height: 1 } + } else { + Rect::default() + }; + prompt.cancel = Rect { + x: if failed { close_x } else { x + width - 2 - close_w }, + y: button_y, + width: close_w, + height: 1, + }; + let button_style = |rect: Rect, accent: bool| { + let hovered = hover.is_some_and(|(hx, hy)| rect.contains(hx, hy)); + let mut style = if accent { styles.base.fg(styles.button_accent) } else { styles.base }; + if hovered { + style = style.add_modifier(Modifier::BOLD).bg(styles.button_hover); + } + style + }; + if prompt.clear.width > 0 { + frame.buffer_mut().set_stringn( + prompt.clear.x, + button_y, + ©_label, + copy_w as usize, + button_style(prompt.clear, false), + ); + } + frame.buffer_mut().set_stringn( + prompt.cancel.x, + button_y, + &close_label, + close_w as usize, + button_style(prompt.cancel, false), + ); + if prompt.ok.width > 0 { + frame.buffer_mut().set_stringn( + prompt.ok.x, + button_y, + &retry_label, + retry_w as usize, + button_style(prompt.ok, true), + ); + } +} + +fn wrapped_message_lines(message: &str, width: usize, limit: usize) -> Vec { + if width == 0 || limit == 0 { + return Vec::new(); + } + let sanitized = message + .chars() + .map(|character| if character.is_control() { ' ' } else { character }) + .collect::(); + let mut lines = Vec::new(); + let mut remaining = sanitized.as_str(); + while !remaining.is_empty() && lines.len() < limit { + let mut end = remaining.len(); + while end > 0 && remaining[..end].width() > width { + end = remaining[..end].char_indices().next_back().map_or(0, |(index, _)| index); + } + if end == 0 { + break; + } + let split = if end < remaining.len() { + remaining[..end].rfind(char::is_whitespace).filter(|index| *index > 0).unwrap_or(end) + } else { + end + }; + lines.push(remaining[..split].trim().to_string()); + remaining = remaining[split..].trim_start(); + } + if !remaining.is_empty() + && let Some(last) = lines.last_mut() + { + while format!("{last}…").width() > width && !last.is_empty() { + last.pop(); + } + last.push('…'); + } + lines +} + pub fn draw_menu(app: &mut App, frame: &mut Frame) { let screen = frame.area(); let chrome = app.chrome; + let hover = app.hover; let Some(menu) = app.menu.as_mut() else { return }; let base = Style::default().bg(chrome.menu_bg).fg(chrome.menu_fg); let border = base.fg(chrome.menu_border); @@ -221,7 +406,10 @@ pub fn draw_menu(app: &mut App, frame: &mut Frame) { continue; } + let scrollbar_dragging = menu.scrollbar_dragging(depth); let level = &menu.levels[depth]; + let scrollbar = level.scrollbar(); + let scrollbar_track = scrollbar.map(|(track, _)| track); let buf = frame.buffer_mut(); for dy in 0..height { for dx in 0..width { @@ -230,18 +418,48 @@ pub fn draw_menu(app: &mut App, frame: &mut Frame) { } draw_border(buf, level.rect, border); + if depth == 0 + && let Some(search) = menu.search.as_mut() + { + let title_x = x + 2; + let title_w = width.saturating_sub(4) as usize; + let prefix = format!(" {} · ", search.label); + let prefix_w = prefix.width().min(title_w); + let search_style = base.add_modifier(Modifier::BOLD); + buf.set_stringn(title_x, y, &prefix, title_w, search_style); + let value_x = title_x + prefix_w as u16; + let value_w = title_w.saturating_sub(prefix_w); + if search.input.as_str().is_empty() { + let placeholder = format!("{} ", search.placeholder); + buf.set_stringn( + value_x, + y, + &placeholder, + value_w, + base.add_modifier(Modifier::DIM), + ); + } else if value_w > 0 { + let (shown, _) = search.input.visible_text_and_cursor(value_w.saturating_sub(1)); + buf.set_stringn(value_x, y, &shown, value_w, search_style); + let cursor_x = value_x + shown.width().min(value_w.saturating_sub(1)) as u16; + buf.set_stringn(cursor_x, y, "▏", 1, search_style); + } + } + let pad = ContextMenu::PAD; let inner_x = x + 1; let inner_y = y + 1; let inner_w = width.saturating_sub(2); let inner_h = height.saturating_sub(2); + let scrollbar_width = u16::from(scrollbar_track.is_some()); + let row_content_w = inner_w.saturating_sub(scrollbar_width); for (i, item) in level.items.iter().enumerate().skip(level.scroll_offset).take(inner_h as usize) { let row_y = inner_y + (i - level.scroll_offset) as u16; if *item == MenuItem::Separator { set_cell(buf, x, row_y, "├", border); - for dx in 0..inner_w { + for dx in 0..row_content_w { set_cell(buf, inner_x + dx, row_y, "─", border); } set_cell(buf, x + width - 1, row_y, "┤", border); @@ -249,7 +467,7 @@ pub fn draw_menu(app: &mut App, frame: &mut Frame) { } if let Some(label) = item.label() { let style = if i == level.selected { selected } else { base }; - for dx in 0..inner_w { + for dx in 0..row_content_w { set_cell(buf, inner_x + dx, row_y, " ", style); } let shortcut_width = @@ -259,15 +477,17 @@ pub fn draw_menu(app: &mut App, frame: &mut Frame) { inner_x + pad + 1, row_y, label, - inner_w.saturating_sub(pad * 2 + arrow_width + shortcut_width) as usize, + row_content_w.saturating_sub(pad * 2 + arrow_width + shortcut_width) as usize, style, ); if let Some(shortcut) = item.shortcut() { let shortcut_width = - (shortcut.width() as u16).min(inner_w.saturating_sub(pad * 2)); + (shortcut.width() as u16).min(row_content_w.saturating_sub(pad * 2)); if shortcut_width > 0 { - let shortcut_x = - x + level.rect.width.saturating_sub(pad + 1 + shortcut_width); + let shortcut_x = x + level + .rect + .width + .saturating_sub(pad + 1 + shortcut_width + scrollbar_width); buf.set_stringn( shortcut_x, row_y, @@ -277,11 +497,21 @@ pub fn draw_menu(app: &mut App, frame: &mut Frame) { ); } } - if matches!(item, MenuItem::Submenu { .. }) && inner_w > 2 { - buf.set_stringn(x + width - pad - 3, row_y, " ›", 2, style); + if matches!(item, MenuItem::Submenu { .. }) && row_content_w > 2 { + buf.set_stringn(x + width - pad - 3 - scrollbar_width, row_y, " ›", 2, style); } } } + if let Some((track, thumb)) = scrollbar { + let state = if scrollbar_dragging { + ScrollbarState::Expanded + } else if hover.is_some_and(|(hx, hy)| track.contains(hx, hy)) { + ScrollbarState::Highlighted + } else { + ScrollbarState::Idle + }; + ScrollbarStyle::from_chrome(chrome).draw_thumb(buf, track, thumb, base, state); + } } } diff --git a/cmux-tui/crates/cmux-tui/src/ui/rail.rs b/cmux-tui/crates/cmux-tui/src/ui/rail.rs index 042e9bda5a6a..660b595e60c1 100644 --- a/cmux-tui/crates/cmux-tui/src/ui/rail.rs +++ b/cmux-tui/crates/cmux-tui/src/ui/rail.rs @@ -151,16 +151,23 @@ pub fn prepare(frame: &mut Frame, area: Rect, palette: RailPalette) { } } -pub fn header(frame: &mut Frame, area: Rect, label: &str, palette: RailPalette) { - let width = area.width.saturating_sub(1) as usize; - if width == 0 || area.height == 0 { - return; +pub fn header(frame: &mut Frame, area: Rect, label: &str, palette: RailPalette) -> Rect { + let rect = Rect { + x: area.x, + y: area.y, + width: area.width.saturating_sub(1), + height: area.height.min(1), + }; + let width = rect.width as usize; + if width == 0 || rect.height == 0 { + return rect; } let buf = frame.buffer_mut(); - for x in area.x..area.x + area.width.saturating_sub(1) { + for x in rect.x..rect.x + rect.width { buf[(x, area.y)].set_symbol(" ").set_style(palette.header); } buf.set_stringn(area.x, area.y, format!(" {label}"), width, palette.header); + rect } pub struct Entry<'a> { @@ -271,6 +278,55 @@ pub fn button( ); } +/// Dense one-line row used by configurable resource trees. The returned +/// rectangle is the disclosure target when the row has children. +#[allow(clippy::too_many_arguments)] +pub fn tree_row( + frame: &mut Frame, + area: Rect, + y: u16, + depth: u16, + name: &str, + detail: &str, + branch: Option, + highlighted: bool, + active: bool, + palette: RailPalette, +) -> Option { + if y >= area.y.saturating_add(area.height) || area.width < 3 { + return None; + } + let content_width = area.width.saturating_sub(1); + let style = if highlighted { palette.active } else { palette.base }; + let detail_style = + if highlighted { palette.active.add_modifier(Modifier::DIM) } else { palette.dim }; + let buf = frame.buffer_mut(); + if highlighted { + for x in area.x..area.x.saturating_add(content_width) { + buf[(x, y)].set_symbol(" ").set_style(style); + } + } + if active { + buf[(area.x, y)].set_symbol("▎").set_style(style.fg(palette.rail)); + } + let disclosure_x = area + .x + .saturating_add(1) + .saturating_add(depth.saturating_mul(2)) + .min(area.x.saturating_add(content_width.saturating_sub(1))); + let disclosure = branch.map(|expanded| { + buf[(disclosure_x, y)].set_symbol(if expanded { "▾" } else { "▸" }).set_style(detail_style); + Rect { x: disclosure_x, y, width: 1, height: 1 } + }); + let name_x = disclosure_x.saturating_add(2); + let available = area.x.saturating_add(content_width).saturating_sub(name_x) as usize; + if available > 0 { + let label = if detail.is_empty() { name.to_string() } else { format!("{name} {detail}") }; + buf.set_stringn(name_x, y, truncate(&label, available), available, style); + } + disclosure +} + pub fn row(area: Rect, y: u16) -> Rect { Rect { x: area.x, y, width: area.width.saturating_sub(1), height: 1 } } diff --git a/cmux-tui/crates/cmux-tui/src/ui/sidebar.rs b/cmux-tui/crates/cmux-tui/src/ui/sidebar.rs index e6dcda4d4548..939456452b21 100644 --- a/cmux-tui/crates/cmux-tui/src/ui/sidebar.rs +++ b/cmux-tui/crates/cmux-tui/src/ui/sidebar.rs @@ -11,11 +11,44 @@ use super::{ ScrollbarState, ScrollbarStyle, middle_truncate, rail, truncate, viewport_thumb_geometry, }; use crate::app::{App, Hit, RailKind, WorkspaceRailSelection}; -use crate::config::SidebarView; +use crate::config::{SidebarResourceKind, SidebarView}; use crate::localization; -use crate::machine::{ - MachineRailSelection, MachineStatus, ProviderScopeKind, WorkspaceCreationMode, -}; +use crate::machine::{MachineRailSelection, MachineStatus, ProviderScopeKind}; + +fn projection_resource_label(resource: SidebarResourceKind) -> &'static str { + let messages = &localization::catalog().sidebar; + match resource { + SidebarResourceKind::Machines => messages.machines, + SidebarResourceKind::Workspaces => messages.workspaces, + SidebarResourceKind::Panes => messages.panes, + SidebarResourceKind::Tabs => messages.tabs, + SidebarResourceKind::Agents => messages.agents, + } +} + +fn projection_empty_label(resource: SidebarResourceKind) -> &'static str { + let messages = &localization::catalog().sidebar; + match resource { + SidebarResourceKind::Machines => messages.no_machines, + SidebarResourceKind::Workspaces => messages.no_workspaces, + SidebarResourceKind::Panes => messages.no_panes, + SidebarResourceKind::Tabs => messages.no_tabs, + SidebarResourceKind::Agents => messages.no_agents, + } +} + +fn projection_detail(row: &crate::sidebar_projection::ProjectionRow) -> String { + let Some(state) = row.agent_state.as_deref() else { return row.subtitle.clone() }; + let messages = &localization::catalog().sidebar; + let state = match state { + "working" => messages.working, + "blocked" => messages.blocked, + "idle" => messages.idle, + "done" => messages.done, + _ => messages.unknown, + }; + if row.subtitle.is_empty() { state.to_string() } else { format!("{state} · {}", row.subtitle) } +} /// The color of a workspace's unread indicator, or `None` when nothing is /// unread. Mirrors the tab-bar severity cue (`error` > `warning` > `info`) @@ -57,7 +90,7 @@ pub fn draw_machines(app: &mut App, frame: &mut Frame) { let Some(area) = app.machine_sidebar_area(frame.area().height) else { return }; let Some(machine_ui) = app.machine_ui.as_ref() else { return }; let machines = machine_ui.snapshot.machines.clone(); - let active = machine_ui.snapshot.active; + let active = app.selected_machine(); let capabilities = machine_ui.snapshot.capabilities; let selection = machine_ui.selection; let managed_machines = machine_ui.managed_machines().to_vec(); @@ -66,7 +99,7 @@ pub fn draw_machines(app: &mut App, frame: &mut Frame) { let palette = rail::RailPalette::for_app(app, app.machine_sidebar_focused()); let messages = &localization::catalog().sidebar; rail::prepare(frame, area, palette); - rail::header(frame, area, messages.machines, palette); + let header = rail::header(frame, area, messages.machines, palette); let mut body_rows = 0; let scope_row = provider.as_ref().filter(|provider| !provider.scopes.is_empty()).map(|_| { @@ -187,12 +220,18 @@ pub fn draw_machines(app: &mut App, frame: &mut Frame) { let recoverable = managed.is_some_and(|managed| { managed.status == crate::machine::ManagedMachineStatus::Recoverable }); - let status = match machine.status { - MachineStatus::Running => messages.running, - MachineStatus::Connecting => messages.connecting, - MachineStatus::Sleeping => messages.sleeping, - MachineStatus::Stopped => messages.stopped, - MachineStatus::Unavailable => messages.unavailable, + let connection_phase = machine_ui.connection_phase(machine.key); + let status = match connection_phase { + crate::machine::MachineConnectionPhase::Connecting => messages.connecting, + crate::machine::MachineConnectionPhase::Failed => messages.unavailable, + crate::machine::MachineConnectionPhase::Disconnected + | crate::machine::MachineConnectionPhase::Ready => match machine.status { + MachineStatus::Running => messages.running, + MachineStatus::Connecting => messages.connecting, + MachineStatus::Sleeping => messages.sleeping, + MachineStatus::Stopped => messages.stopped, + MachineStatus::Unavailable => messages.unavailable, + }, }; let recoverable_subtitle = recoverable.then(|| { managed.and_then(|managed| managed.recoverable_until.as_ref()).map_or_else( @@ -206,13 +245,22 @@ pub fn draw_machines(app: &mut App, frame: &mut Frame) { let indicator = if recoverable { Some(app.config.theme.notification_warning) } else { - match machine.status { - MachineStatus::Running => Some(app.config.theme.notification_info), - MachineStatus::Connecting | MachineStatus::Sleeping => { + match connection_phase { + crate::machine::MachineConnectionPhase::Connecting => { Some(app.config.theme.notification_warning) } - MachineStatus::Stopped => None, - MachineStatus::Unavailable => Some(app.config.theme.notification_error), + crate::machine::MachineConnectionPhase::Failed => { + Some(app.config.theme.notification_error) + } + crate::machine::MachineConnectionPhase::Ready + | crate::machine::MachineConnectionPhase::Disconnected => match machine.status { + MachineStatus::Running => Some(app.config.theme.notification_info), + MachineStatus::Connecting | MachineStatus::Sleeping => { + Some(app.config.theme.notification_warning) + } + MachineStatus::Stopped => None, + MachineStatus::Unavailable => Some(app.config.theme.notification_error), + }, } }; rail::entry( @@ -255,10 +303,177 @@ pub fn draw_machines(app: &mut App, frame: &mut Frame) { ); hits.push((rail::row(area, y), Hit::ConnectMachine)); } + hits.push((header, Hit::RailHeader(RailKind::Machine))); hits.push((rail::divider(area), Hit::RailResize(RailKind::Machine))); app.hits.extend(hits); } +/// Native third-level column for tabs in the highlighted workspace. +pub fn draw_tabs(app: &mut App, frame: &mut Frame) { + let Some(area) = app.tabs_sidebar_area(frame.area().height) else { return }; + let targets = app.sidebar_tab_targets(); + app.tabs_rail_selection = app.tabs_rail_selection.min(targets.len().saturating_sub(1)); + let palette = rail::RailPalette::for_app(app, app.tabs_sidebar_focused()); + let messages = &localization::catalog().sidebar; + rail::prepare(frame, area, palette); + let header = rail::header(frame, area, messages.tabs, palette); + + let body_rows = if targets.is_empty() { 1 } else { targets.len() * rail::ENTRY_STRIDE }; + let selected = + (!targets.is_empty() && app.tabs_sidebar_focused() && app.tabs_rail_follow_selection) + .then_some(rail::RowSpan::new( + app.tabs_rail_selection * rail::ENTRY_STRIDE, + rail::ENTRY_HEIGHT, + )); + let viewport = rail::viewport( + area, + body_rows, + 0, + &mut app.tabs_rail_scroll, + &mut app.tabs_footer_scroll, + selected, + None, + ); + + if targets.is_empty() { + if let Some(y) = viewport.body_y(rail::RowSpan::new(0, 1)) { + rail::button(frame, area, y, messages.no_tabs, false, palette); + } + } else { + for (target_index, target) in targets.iter().enumerate() { + let span = rail::RowSpan::new(target_index * rail::ENTRY_STRIDE, rail::ENTRY_HEIGHT); + let Some(y) = viewport.body_y(span) else { continue }; + let selected = app.tabs_sidebar_focused() + && app.tabs_rail_selection == target_index + && app.tabs_rail_follow_selection; + rail::entry( + frame, + area, + y, + rail::Entry { + name: &target.name, + subtitle: &target.subtitle, + highlighted: target.active || selected, + active: target.active, + indicator: None, + dimmed: false, + }, + palette, + ); + let hit = Hit::SidebarTab { + workspace: target.workspace, + screen: target.screen, + pane: target.pane, + index: target.index, + surface: target.surface, + }; + app.hits.push((rail::row(area, y), hit)); + app.hits.push((rail::row(area, y + 1), hit)); + } + } + app.hits.push((header, Hit::RailHeader(RailKind::Tabs))); + app.hits.push((rail::divider(area), Hit::RailResize(RailKind::Tabs))); +} + +/// Render one configurable resource path as a dense native tree column. +pub fn draw_projection(app: &mut App, frame: &mut Frame, view_index: usize) { + let Some(area) = app.projection_sidebar_area(view_index) else { return }; + let Some(spec) = app.config.sidebar.views.get(view_index).cloned() else { return }; + let rows = app.projection_rows(view_index); + let actions = app.sidebar_action_rows(view_index); + let focused = app.projection_sidebar_focused(view_index); + let palette = rail::RailPalette::for_app(app, focused); + rail::prepare(frame, area, palette); + let header = spec + .levels + .iter() + .copied() + .map(projection_resource_label) + .collect::>() + .join(localization::catalog().sidebar.projection_path_separator); + let header = rail::header(frame, area, &header, palette); + + let selectable_rows = rows.len().saturating_add(actions.len()); + let (selected, viewport) = { + let state = app.projection_rail_state_mut(view_index); + state.selected = state.selected.min(rows.len().saturating_sub(1)); + state.selected_action = state + .selected_action + .map(|index| index.min(actions.len().saturating_sub(1))) + .filter(|_| !actions.is_empty()); + let selected = state + .selected_action + .map(|index| rows.len().saturating_add(index)) + .unwrap_or_else(|| state.selected.min(selectable_rows.saturating_sub(1))); + let selected_body = (focused + && state.follow_selection + && state.selected_action.is_none() + && !rows.is_empty()) + .then(|| rail::RowSpan::new(state.selected, 1)); + let selected_footer = (focused && state.follow_selection) + .then_some(state.selected_action) + .flatten() + .map(|index| rail::RowSpan::new(index, 1)); + let viewport = rail::viewport( + area, + rows.len().max(usize::from(rows.is_empty())), + actions.len(), + &mut state.scroll, + &mut state.footer_scroll, + selected_body, + selected_footer, + ); + (selected, viewport) + }; + if rows.is_empty() + && let Some(y) = viewport.body_y(rail::RowSpan::new(0, 1)) + { + let resource = spec.levels.last().copied().unwrap_or(SidebarResourceKind::Workspaces); + rail::button(frame, area, y, projection_empty_label(resource), false, palette); + } + for (row_index, row) in rows.iter().enumerate() { + let Some(y) = viewport.body_y(rail::RowSpan::new(row_index, 1)) else { continue }; + let highlighted = row.active || (focused && selected == row_index); + let detail = projection_detail(row); + let disclosure = rail::tree_row( + frame, + area, + y, + row.depth, + &row.name, + &detail, + row.branch.map(|_| row.expanded), + highlighted, + row.active, + palette, + ); + if let (Some(rect), Some(branch)) = (disclosure, row.branch) { + app.hits.push((rect, Hit::ProjectionToggle { view: view_index, branch })); + } + app.hits.push(( + rail::row(area, y), + Hit::ProjectionRow { view: view_index, row: row_index, target: row.target }, + )); + } + for (action_index, action) in actions.iter().enumerate() { + let Some(y) = viewport.footer_y(rail::RowSpan::new(action_index, 1)) else { continue }; + rail::action( + frame, + area, + y, + &action.label, + focused && selected == rows.len().saturating_add(action_index), + palette, + ); + app.hits.push(( + rail::row(area, y), + Hit::SidebarAction { view: view_index, action: action.target }, + )); + } + app.hits.push((header, Hit::RailHeader(RailKind::Projection(view_index)))); + app.hits.push((rail::divider(area), Hit::RailResize(RailKind::Projection(view_index)))); +} + fn draw_plugin(app: &mut App, frame: &mut Frame) { let Some(area) = app.workspace_sidebar_area(frame.area().height) else { return }; let width = area.width; @@ -332,9 +547,10 @@ fn draw_workspaces(app: &mut App, frame: &mut Frame) { let workspace_drag = app.workspace_drag(); let messages = &localization::catalog().sidebar; rail::prepare(frame, area, palette); - rail::header(frame, area, messages.workspaces, palette); + let header = rail::header(frame, area, messages.workspaces, palette); - let creation_modes = app.workspace_creation_modes(); + let actions = app.workspace_sidebar_action_rows(); + let view_index = app.view_index_for_rail(RailKind::Workspace); let recoverable = app .machine_ui .as_ref() @@ -365,9 +581,9 @@ fn draw_workspaces(app: &mut App, frame: &mut Frame) { .flatten(); let selected_footer = if app.workspace_sidebar_focused() && app.workspace_rail_follow_selection { - creation_modes + actions .iter() - .position(|mode| app.workspace_rail_selection.matches_mode(*mode)) + .position(|action| app.workspace_rail_selection.matches_action(action.target)) .map(|row| rail::RowSpan::new(row, 1)) } else { None @@ -375,7 +591,7 @@ fn draw_workspaces(app: &mut App, frame: &mut Frame) { let viewport = rail::viewport( area, body_rows, - creation_modes.len(), + actions.len(), &mut app.workspace_rail_scroll, &mut app.workspace_footer_scroll, selected_body, @@ -478,22 +694,30 @@ fn draw_workspaces(app: &mut App, frame: &mut Frame) { } } - for (row, mode) in creation_modes.iter().copied().enumerate() { + for (row, action) in actions.iter().enumerate() { let Some(y) = viewport.footer_y(rail::RowSpan::new(row, 1)) else { continue }; - let label = match mode { - None => messages.new_workspace, - Some(WorkspaceCreationMode::Isolated) => messages.new_isolated_workspace, - Some(WorkspaceCreationMode::Host) => messages.new_shared_workspace, - }; rail::action( frame, area, y, - label, - app.workspace_sidebar_focused() && app.workspace_rail_selection.matches_mode(mode), + &action.label, + app.workspace_sidebar_focused() + && app.workspace_rail_selection.matches_action(action.target), palette, ); - hits.push((rail::row(area, y), Hit::CreateWorkspace { mode })); + match action.target { + crate::app::SidebarActionTarget::CreateWorkspace(mode) => { + hits.push((rail::row(area, y), Hit::CreateWorkspace { mode })); + } + crate::app::SidebarActionTarget::Run(_) => { + if let Some(view) = view_index { + hits.push(( + rail::row(area, y), + Hit::SidebarAction { view, action: action.target }, + )); + } + } + } } if scrollbar_track.height > 0 { let (thumb_y, thumb_height) = viewport_thumb_geometry( @@ -519,6 +743,7 @@ fn draw_workspaces(app: &mut App, frame: &mut Frame) { state, ); } + hits.push((header, Hit::RailHeader(RailKind::Workspace))); hits.push((rail::divider(area), Hit::RailResize(RailKind::Workspace))); app.hits.extend(hits); } diff --git a/cmux-tui/crates/cmux-tui/tests/cli.rs b/cmux-tui/crates/cmux-tui/tests/cli.rs index 62c3d2362698..ccfb6c1c5d9d 100644 --- a/cmux-tui/crates/cmux-tui/tests/cli.rs +++ b/cmux-tui/crates/cmux-tui/tests/cli.rs @@ -664,7 +664,7 @@ fn session_reset_state_rejects_global_routing_options() { .output() .unwrap(); assert!(!output.status.success(), "{option} unexpectedly reached reset execution"); - let error: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + let error = json_error(&output); assert_eq!(error["code"], "session.reset_state.routing_options_unsupported"); assert_eq!(error["details"]["options"], serde_json::json!([option])); assert!(error["message"].as_str().unwrap().contains(option)); @@ -1977,7 +1977,10 @@ fn noun_first_cli_covers_resources_output_errors_and_private_raw_escape() { let identify = raw_cli(&server, serde_json::json!({"id":"identify-human","cmd":"identify"})); assert_success(&identify); - assert!(String::from_utf8_lossy(&identify.stdout).contains("\"protocol\":10")); + assert!( + String::from_utf8_lossy(&identify.stdout) + .contains(&format!("\"protocol\":{}", cmux_tui_core::server::PROTOCOL_VERSION)) + ); let identify_json = raw_cli(&server, serde_json::json!({"id":"identify-json","cmd":"identify"})); @@ -2335,11 +2338,37 @@ fn noun_first_cli_covers_resources_output_errors_and_private_raw_escape() { let select_bare = cli(&server, &["tab"]); assert_eq!(select_bare.status.code(), Some(2)); - let close = cli(&server, &["--quiet", "terminal", &terminal, "close"]); - assert_success(&close); - let closed_read = json_cli(&server, &["terminal", &terminal, "screen", "read"]); - assert_eq!(closed_read.status.code(), Some(1)); - assert_eq!(json_error(&closed_read)["code"], "selector.not_found"); + // Keep terminal.close focused on its CLI contract; multiview close semantics have dedicated + // core coverage. + let close_projection = json_cli(&server, &["tab", projected_tab, "close"]); + assert_success(&close_projection); + let remaining_terminal = json_cli(&server, &["terminal", &terminal, "screen", "read"]); + assert_success(&remaining_terminal); + + let mut terminal_closed = false; + for attempt in 0..3 { + let key = format!("matrix-terminal-close-{attempt}"); + let close = json_cli(&server, &["terminal", &terminal, "close", "--idempotency-key", &key]); + if !close.status.success() { + assert_eq!(close.status.code(), Some(1)); + let error = json_error(&close); + assert_eq!(error["code"], "mutation.indeterminate"); + assert_eq!(error["details"]["idempotency_key"], key); + assert_eq!(error["details"]["operation"], "terminal.close"); + assert_eq!(error["details"]["recovery"], "inspect_state_then_retry_with_new_key"); + } + + let read = json_cli(&server, &["terminal", &terminal, "screen", "read"]); + if !read.status.success() { + assert_eq!(read.status.code(), Some(1)); + assert_eq!(json_error(&read)["code"], "selector.not_found"); + terminal_closed = true; + break; + } + assert_success(&read); + assert!(!close.status.success(), "successful close left the terminal addressable"); + } + assert!(terminal_closed, "terminal remained addressable after three inspected close attempts"); let bogus = Command::new(bin()) .args(["--json", "--socket"]) @@ -2830,6 +2859,7 @@ fn create_live_terminal_host_record(root: &std::path::Path) -> fs::File { workspace_key: String::new(), supports_set_defaults: true, supports_clear_history: true, + supports_terminate_ack: false, }; let record_path = record.record_path(root); let live_path = record_path.with_extension(format!("{incarnation}-{host_start_nonce}.live")); diff --git a/cmux-tui/crates/cmux-tui/tests/terminal_host_recovery.rs b/cmux-tui/crates/cmux-tui/tests/terminal_host_recovery.rs index ee0a94a865b0..dcef5b4eecd7 100644 --- a/cmux-tui/crates/cmux-tui/tests/terminal_host_recovery.rs +++ b/cmux-tui/crates/cmux-tui/tests/terminal_host_recovery.rs @@ -3048,6 +3048,39 @@ fn request_response(path: &Path, value: serde_json::Value) -> serde_json::Value serde_json::from_str(&line).unwrap() } +#[test] +fn terminal_launch_rejection_preserves_the_host_error() { + let mut harness = RecoveryHarness::start_unstarted("launch-rejection-detail"); + let child = harness.daemon_command().spawn().unwrap(); + harness.child = Some(child); + wait_for_socket(&harness.socket); + + let missing = format!("/tmp/cmux-terminal-host-missing-{}", std::process::id()); + let response = request_response( + &harness.socket, + serde_json::json!({ + "id": 1, + "cmd": "run", + "argv": [missing], + "new_workspace": true, + "name": "must-fail", + "cols": 80, + "rows": 24, + }), + ); + + assert_eq!(response["ok"], false, "missing command unexpectedly launched: {response}"); + let error = response["error"].as_str().expect("rejection includes an error string"); + assert!( + error.contains("No such file") || error.contains("not found"), + "terminal host discarded its launch error: {error}" + ); + assert!( + !error.contains("closed before launch ready"), + "launcher exposed transport fallout instead of the host error: {error}" + ); +} + fn resource_request( path: &Path, id: &str, diff --git a/cmux-tui/docs/configuration.md b/cmux-tui/docs/configuration.md index f7f9005e0fa5..4e0a6fd3d096 100644 --- a/cmux-tui/docs/configuration.md +++ b/cmux-tui/docs/configuration.md @@ -38,12 +38,33 @@ Tabs are numbered by default. A recognized agent program can appear after the nu The built-in sidebar defaults to the workspace list. Set `"sidebar": {"view": "files"}` for the yazi-style file browser. `Tab` toggles the built-in view while the sidebar is focused, and the configurable `toggle-sidebar-view` action toggles it from anywhere. A configured `sidebar.plugin` still replaces either built-in view. +`sidebar.views` is an ordered list of native resource projections, with no fixed column count. Each view has a stable `id`, a `levels` path, and optional native `actions`. A one-level path renders a list. Multi-level paths such as `workspaces → agents` and `workspaces → panes → tabs` render collapsible trees in one column. Nesting is optional. Valid resources are `machines`, `workspaces`, `panes`, `tabs`, and `agents`. Flat pane, tab, and agent views follow the highlighted workspace. Omit a resource to hide it. + +`sidebar.profiles` names multiple view lists, and `sidebar.profile` selects the startup layout. Right-click anywhere and open **Sidebar → Layouts** to switch profiles without reconnecting machines. The same menu can hide or restore an individual view for the current session. Runtime visibility changes are keyed by profile and view ID, so switching away and back restores that profile's session-local choices. + +Actions use the same stable IDs and execution path as keyboard commands, including `new-workspace`, `new-tab`, and `new-pane-smart`. A view rooted at `workspaces` inherits `new-workspace`, including provider-specific isolated and shared choices. Set `"actions": []` to hide every pinned action, or provide an ordered list to replace the preset. Machine creation and connection actions remain capability-driven by the selected provider. + +Every view has an independent width and drag handle. Lower `collapse_priority` values hide first when the terminal must preserve 40 pane columns. A hidden view needs four additional columns before it returns, which prevents resize-boundary flicker. `sidebar.columns` remains a compatibility alias for one-level machine, workspace, and tab views; `sidebar.views` wins when both are present. + | Key | Type | Default | Effect | | --- | --- | --- | --- | | `sidebar.view` | `"files"` or `"workspaces"` | `"workspaces"` | Built-in sidebar view when `sidebar.plugin` is unset | | `sidebar.width` | integer | `22` | Sidebar width, clamped to 10 through 60 on load | | `sidebar.compact_width` | integer | `10` | Width used by compact mode, clamped to 10 through 60 and capped at `sidebar.width` | | `sidebar.max_width` | integer | `0` | Maximum live drag width; `0` means no configured maximum | +| `sidebar.profile` | string | first configured profile | Startup profile ID; ignored without `sidebar.profiles` | +| `sidebar.profiles` | array of profile objects | unset | Named layouts available from every context menu; overrides top-level `sidebar.views` and `sidebar.columns` | +| `sidebar.profiles[].id` | string | required | Stable unique profile identity | +| `sidebar.profiles[].name` | string | profile ID | Display name in the layout picker | +| `sidebar.profiles[].views` | array of view objects | required | Ordered projections using the same schema as `sidebar.views` | +| `sidebar.views` | array of view objects | unset | Ordered native lists and trees; omission preserves the machine-plus-workspace default | +| `sidebar.views[].id` | string | required | Stable unique identity for focus, collapse, scroll, and width state | +| `sidebar.views[].levels` | array of strings | required | Resource path, such as `["agents"]`, `["workspaces", "agents"]`, or `["workspaces", "panes", "tabs"]` | +| `sidebar.views[].actions` | array of action IDs | resource preset | Ordered native actions pinned below the resource rows; `[]` hides them | +| `sidebar.views[].width` | integer | resource default | Initial width, clamped to 10 through 60 | +| `sidebar.views[].max_width` | integer | `0` | Maximum live drag width; `0` means no configured maximum | +| `sidebar.views[].collapse_priority` | integer | resource default | Lower priorities hide first on narrow terminals | +| `sidebar.columns` | array of column objects | unset | Compatibility form for one-level `machines`, `workspaces`, and `tabs` views | | `sidebar.plugin.command` | array of strings | unset | External sidebar plugin argv; when set, the sidebar hosts this program in a PTY instead of the built-in list | | `sidebar.plugin.cwd` | string | unset | Working directory for the sidebar plugin process | @@ -74,17 +95,31 @@ cmux sidebar plugin use --builtin ## Machines -The machine rail is an optional first rail to the left of the existing sidebar. It is inactive when `machine_sidebar.enabled` is false and `machines` is empty. Setting `enabled` to true shows the current local session and the static connector actions even when no extra targets are configured. Any valid `machines` entry also activates the rail. +The machine rail is optional. Its position comes from a `sidebar.views` entry whose level is `machines`, or it stays first under the default layout. It activates when `machine_sidebar.enabled` is true, `machines` has a valid entry, or `machine_sidebar.create_sources` is nonempty. | Key | Type | Default | Effect | | --- | --- | --- | --- | | `machine_sidebar.enabled` | boolean | `false` | Enables the machine rail without requiring a configured target | | `machine_sidebar.width` | integer | `22` | Initial machine-rail width, clamped to 10 through 60 on load | | `machine_sidebar.max_width` | integer | `0` | Maximum live drag width for the machine rail; `0` means no configured maximum | +| `machine_sidebar.create_sources` | array | `[]` | Prototype-only native creation choices; no provider command is executed | | `machines` | array | `[]` | Static Unix-socket and SSH connection targets | +Each prototype creation source has a unique `id`, a `name`, and an optional `subtitle`. Selecting `+ new machine` opens the native source picker. The current prototype adds a session-local catalog entry backed by the current mux socket, so Docker, E2B, Firecracker, and other labels exercise the full UI without provisioning or billing. Production providers remain responsible for real lifecycle and transport operations. + +Try the tracked prototype configuration with: + +```bash +cd cmux-tui +CMUX_TUI_CONFIG=examples/resource-columns.prototype.json cargo run -p cmux-tui -- --session columns +``` + +`resource-columns.prototype.json` starts with a two-column focused layout that omits tabs, then exposes three-column and tree profiles from the right-click Sidebar menu. `resource-tree.prototype.json` combines machines with a workspace/agent tree. `resource-tree-no-agents.prototype.json` combines machines with a workspace/pane/tab tree and contains no agent representation. + Every machine has a unique nonempty `id`, a nonempty display `name`, an optional `subtitle`, and one transport. The id `current` is reserved for the automatically inserted local session. +SSH machine targets currently require macOS or Linux because the remote daemon uses Unix PTYs and sockets. A native Windows OpenSSH target reports the WSL 2 prerequisite instead of attempting a Unix command in `cmd.exe`. Install a Linux distribution under WSL 2 and expose that Linux environment through its own SSH alias before attaching it as a machine. + | Machine key | Applies to | Type | Default | Effect | | --- | --- | --- | --- | --- | | `id` | all | string | required | Stable config identity; duplicate and empty ids are ignored | @@ -96,8 +131,8 @@ Every machine has a unique nonempty `id`, a nonempty display `name`, an optional | `user` | SSH | string | unset | SSH user, passed as `user@host` | | `port` | SSH | integer | unset | SSH port, passed with `-p` | | `identity_file` | SSH | string | unset | Local SSH identity path, passed with `-i` | -| `session` | SSH | string | `"main"` | Remote cmux session passed to `relay --session` | -| `binary` | SSH | string | `"cmux-tui"` | Remote executable path used for `binary relay`; this is one executable, not a shell command | +| `session` | SSH | string | `"main"` | Remote cmux session started or reused by the managed connection | +| `binary` | SSH | string | `"~/.local/bin/cmux-tui"` | Shell-safe remote executable path used for compatibility checks and the managed daemon | ```json { @@ -130,7 +165,7 @@ Every machine has a unique nonempty `id`, a nonempty display `name`, an optional } ``` -The SSH target invokes noninteractive `ssh -T` with strict host-key checking, disabled agent forwarding, and disabled port forwarding, then runs `binary relay --session session` remotely. It connects to an existing remote server and does not start one. See [Machines](machines.md) for rail behavior and a complete `npx cmux` remote setup. +The SSH target uses the same managed connection as `cmux-tui ssh`. It probes `binary`, starts or reuses the named remote mux and sidecar, and retains a reconnecting local bridge while that machine is selected. Packaged releases can install their pinned binary when the probe reports it missing or incompatible. Source builds require the exact matching binary to be preinstalled. SSH is noninteractive with strict host-key checking, disabled agent and X11 forwarding, and disabled port forwarding. See [Machines](machines.md) for rail behavior and setup details. ### Dynamic machine provider @@ -246,8 +281,8 @@ WebSocket clients pair through a six-digit browser/TUI comparison by default. We | `keys.new-pane-right` | chord string or array or `"none"` | `"g"` | Insert a two-thirds-width terminal after the focused horizontal column | | `keys.undo-layout` | chord string or array or `"none"` | `"U"` | Undo the latest structural layout action on the focused screen | | `keys.focus-next-pane` | chord string or array or `"none"` | `"o"` | Cycle to the next pane in the current screen | -| `keys.focus-left` | chord string or array or `"none"` | `["h","left","alt+h","alt+left"]` | Focus left | -| `keys.focus-right` | chord string or array or `"none"` | `["l","right","alt+l","alt+right"]` | Focus right | +| `keys.focus-left` | chord string or array or `"none"` | `["h","left","alt+h","alt+left"]` | Focus left, entering the rightmost sidebar view at the pane boundary | +| `keys.focus-right` | chord string or array or `"none"` | `["l","right","alt+l","alt+right"]` | Focus right, returning to the pane after the final sidebar view | | `keys.focus-up` | chord string or array or `"none"` | `["k","up","alt+k","alt+up"]` | Focus up | | `keys.focus-down` | chord string or array or `"none"` | `["j","down","alt+j","alt+down"]` | Focus down | | `keys.swap-pane-prev` | chord string or array or `"none"` | `"{"` | Swap active pane with the previous pane in split-tree order | diff --git a/cmux-tui/docs/getting-started.md b/cmux-tui/docs/getting-started.md index 626752251864..62be1237cd3d 100644 --- a/cmux-tui/docs/getting-started.md +++ b/cmux-tui/docs/getting-started.md @@ -63,7 +63,7 @@ Resource selectors accept a typed opaque ID, `current`, or an exact name. Names ## Remote machines -The optional machine rail keeps rendering local while it connects individual session transports through Unix sockets or SSH. It is disabled for the default local run and activates when `machine_sidebar.enabled` is true or `machines` contains a valid entry in `cmux-tui.json`. Start a headless cmux session on each remote machine, and make the remote `cmux-tui` or `cmux` executable available to noninteractive SSH. The SSH connector runs its `relay` mode and does not nest a second TUI. +The optional machine rail keeps rendering local while it connects individual sessions through Unix sockets or SSH. It is disabled for the default local run and activates when `machine_sidebar.enabled` is true or `machines` contains a valid entry in `cmux-tui.json`. The SSH connector shares the managed lifecycle used by `cmux-tui ssh`: it checks the remote binary, starts the named headless mux and sidecar on demand, and reconnects without nesting a second TUI. Packaged releases can install their pinned remote binary. Source builds require the exact matching binary to be installed remotely. Packaged clients use the same configuration and can start with: diff --git a/cmux-tui/docs/keyboard.md b/cmux-tui/docs/keyboard.md index 3b939bccdb05..0d0c106fc5b7 100644 --- a/cmux-tui/docs/keyboard.md +++ b/cmux-tui/docs/keyboard.md @@ -89,9 +89,9 @@ Workspace navigation follows tmux's outer session lane: `(` and `)` move backwar When the built-in sidebar is focused, its header gains an accent background and its divider becomes a bold accent rail. `Tab` toggles files/workspaces without leaving sidebar focus. In the files view, Up/Down and Ctrl-J/Ctrl-K move the selection, Right descends into a directory, Enter descends or opens a file in a new `$EDITOR` tab, and Left or `h` goes to the parent when the machine rail is absent. `c` sends a safely quoted `cd` to the focused pane, `o` opens `.html` and `.md` files in a browser tab, `.` toggles dotfiles, `/` enters filter mode, and `~` follows the focused pane cwd again. Esc clears a nonempty filter before leaving filter mode. -In the workspaces view, Up/Down move the selection and Enter activates it. Any normal prefixed command leaves sidebar focus and runs through the usual action table; `prefix S` only returns focus to the pane. A configured sidebar plugin keeps its existing PTY forwarding behavior. +In the workspaces view, Up/Down move the selection and Enter activates it. A one-level `tabs` view follows the highlighted workspace. Multi-level views such as `workspaces → agents` are collapsible trees: Left collapses, Right expands, Space toggles, and Enter activates the exact workspace, pane, tab, or agent surface. Alt/Option with arrows or `hjkl` always navigates, so Alt-Left and Alt-Right traverse views instead of changing tree expansion. Right from the final view or Esc returns to the pane. Any normal prefixed command leaves sidebar focus and runs through the usual action table. A configured sidebar plugin keeps its existing PTY forwarding behavior. -When the optional machine rail is visible, `Ctrl-b S` still enters through the workspace rail. From the built-in workspace or files rail, Left or `h` moves focus to the machine rail. From the machine rail, Right or `l` returns to the workspace rail. Up/Down or `k`/`j` changes the selected machine, Enter connects to it, and Esc returns to the active pane. A mouse click can focus either rail directly. The machine rail swallows other unprefixed keys instead of forwarding them to a remote terminal. +When the optional machine rail is visible, `Ctrl-b S` enters through the first view containing workspaces. Alt/Option-Left or Alt/Option-`h` at the left pane boundary enters the rightmost visible view. Left or `h` and Right or `l` traverse the ordered native views. Up/Down or `k`/`j` changes the selected machine, Enter connects to it, and Esc returns to the active pane. Clicking a view header focuses that view. Clicking a machine, workspace, pane, tab, or agent activates it and returns keyboard input to the latest terminal. Sidebar views swallow other unprefixed keys instead of forwarding them to a remote terminal. ## Modeless Alt Layer diff --git a/cmux-tui/docs/machines.md b/cmux-tui/docs/machines.md index 5f1c6e565059..3db9834c06e8 100644 --- a/cmux-tui/docs/machines.md +++ b/cmux-tui/docs/machines.md @@ -1,28 +1,36 @@ # Machines -The optional machine rail adds a connection layer to the left of the existing workspace rail. Selecting a machine replaces the attached cmux session while the client, rail layout, mouse handling, and workspace rendering stay local. +The optional machine rail adds a connection layer to the native column stack. Selecting a machine replaces the attached cmux session while the client, rail layout, mouse handling, and workspace rendering stay local. -The feature is disabled by default. It activates when `machine_sidebar.enabled` is `true` or the `machines` array contains at least one valid entry. An active static catalog always starts with the current local session, labeled with the local hostname and `local`, followed by configured Unix-socket and SSH targets. A configured machine with id `current` is skipped because that id belongs to the local entry. +The feature is disabled by default. It activates when `machine_sidebar.enabled` is `true`, `machine_sidebar.create_sources` is nonempty, or the `machines` array contains at least one valid entry. An active static catalog always starts with the current local session, labeled with the local hostname and `local`, followed by configured Unix-socket and SSH targets. A configured machine with id `current` is skipped because that id belongs to the local entry. + +There is no master or slave role. The rail follows capabilities available to this client. A laptop can expose SSH and VM targets, while a headless Linux session can expose Docker devboxes through the same source contract. A client with no machine targets, creation sources, or enabled machine sidebar keeps the rail hidden. Host location does not change the model. ## Layout and input -The machine list and built-in workspace list use the same rail renderer, selection treatment, two-line entries, and divider. Each right divider has an independent drag width. `machine_sidebar.width` and `sidebar.width` provide their separate starting widths; their `max_width` settings provide separate drag limits. Both rails preserve at least 40 columns for pane content. When the terminal cannot fit two 10-column rails and the content minimum, cmux hides the machine rail first. +`sidebar.views` controls the order, resource path, width, and collapse priority of native rails. One-level machine, workspace, pane, tab, and agent views render as lists. Multi-level paths render collapsible trees, including workspace/agent and workspace/pane/tab representations. Every divider remains independently draggable, and all views preserve at least 40 pane columns. + +`Ctrl-b S` prefers the first view containing workspaces. Left or `h` and Right or `l` traverse adjacent configured views. In a tree, Left collapses an expanded branch and Right expands a collapsed branch before changing columns. Up/Down or `k`/`j` changes the current selection. Enter activates it, Space toggles a branch, and Esc returns to the active pane. Mouse clicks focus a column directly. Every divider resizes only its column. -`Ctrl-b S` focuses the workspace rail. Left or `h` moves to the machine rail, and Right or `l` returns to the workspace rail. Up/Down or `k`/`j` changes the selected machine. Home, End, PageUp, and PageDown move through long catalogs. Enter connects to the selected machine or invokes the selected footer action. Esc returns focus to the active pane. Mouse clicks focus either rail; a machine switch occurs on release over the same machine row. Drag either divider to resize only that rail. Wheel input scrolls the rail body, or the footer when a very short terminal clips its actions. +Right-click a client-owned machine or any tab in the tabs column to rename that exact row. Provider-owned machine renames remain capability-gated and versioned by the provider. Client-owned machine names last for the current process only; tab names remain session state. -The static catalog shows `+ Connect machine`. It accepts one `host` or `user@host` without whitespace, adds an SSH target for the current process, and connects to its `main` session. This temporary target is not written to configuration. `+ new machine` is capability-gated and does not appear for the static catalog. +The static catalog shows `+ Connect machine`. It discovers concrete aliases from `Host` directives in `~/.ssh/config` and recursively follows `Include` directives. Wildcard and negated patterns are omitted. Type while the native picker is open to filter large host catalogs, then use Up/Down and Enter. Large pickers have the same wheel, track-click, and thumb-drag scrollbar as other native overlays. `Add SSH host…` accepts `cmux-lawrence`, `user@host`, or the familiar `ssh cmux-lawrence` spelling. Either path adds an SSH target for the current process and connects to its `main` session. SSH performs final config resolution, so aliases retain their configured hostname, user, port, proxy, and identity settings. Temporary targets and renamed machine labels are not written to configuration. To keep `cmux-lawrence` across launches, add a concrete `Host cmux-lawrence` entry to `~/.ssh/config`; the picker discovers it on the next launch. + +`+ new machine` remains capability-gated. Configured `machine_sidebar.create_sources` enable a prototype native source picker whose new rows point back to the current mux. This validates Docker and microVM provider UX without running a provider or provisioning infrastructure. ## Static targets Unix targets connect directly to another local cmux control socket. Use an absolute socket path because configuration paths do not pass through a shell. -SSH targets start this process: +SSH targets use the same managed lifecycle as `cmux-tui ssh`. The client resolves the destination through OpenSSH, probes the configured remote binary, and then opens the remote link. The link starts the named headless mux and its sidecar when they do not exist, so the session does not need a separate supervisor just to connect. ```text -ssh -T -o BatchMode=yes -o StrictHostKeyChecking=yes -o ForwardAgent=no -o ClearAllForwardings=yes [-p PORT] [-i IDENTITY_FILE] -- [USER@]HOST 'BINARY' relay --session SESSION +ssh -T [-p PORT] -o BatchMode=yes -o StrictHostKeyChecking=yes -o ForwardAgent=no -o ForwardX11=no -o ClearAllForwardings=yes [-i IDENTITY_FILE] [USER@]HOST BINARY remote-probe --json ``` -The remote session must already be running. The remote `binary` must resolve in a noninteractive SSH login and defaults to `cmux-tui`. `relay` copies protocol bytes between stdio and that session's Unix socket. SSH owns host verification, authentication, encryption, and network transport; relay adds no authentication. The client never prompts for a password or new host key inside the TUI. The target must already be trusted in local `known_hosts`, and a key or SSH agent must authenticate it. Agent forwarding and all port forwarding are disabled. +The remote `binary` defaults to `~/.local/bin/cmux-tui` and must be a shell-safe path. Packaged releases can install their pinned npm build there when the probe reports a missing or recognized incompatible binary. A legacy binary that cannot answer `remote-probe` requires an explicit `cmux-tui ssh HOST --upgrade`. Development and other source builds cannot replace the remote automatically; install the exact matching build at `binary` instead. + +The client never prompts for a password or new host key inside the TUI. The target must already be trusted in local `known_hosts`, and a key or SSH agent must authenticate it. Agent forwarding, X11 forwarding, and all port forwarding are disabled. Switching machines drops the old local connection lease after the replacement commits. The remote mux stays available for later attachment. `cmux-tui relay` remains a low-level direct protocol diagnostic and is not the rail connection path. See [Configuration](configuration.md#machines) for the full schema and examples. @@ -54,21 +62,20 @@ See [Configuration](configuration.md#dynamic-machine-provider) for persistent cl ## Run with npm -Install cmux on a remote Linux or macOS machine so SSH has a stable executable path, then start a named headless session there: +Install cmux on a remote Linux or macOS machine so SSH has a stable executable path: ```bash npm install --global cmux command -v cmux -cmux --headless --session agents ``` -Keep the headless process under your normal service supervisor when it must survive logout. Put the absolute path printed by `command -v cmux` in the target's `binary` field and set `session` to `agents`. After adding that target to the local config, start the client normally: +Put the absolute path printed by `command -v cmux` in the target's `binary` field and set `session` to `agents`. The first managed connection starts that session on demand. After adding the target to the local config, start the client normally: ```bash npx cmux ``` -The local `npx cmux` process renders both rails and opens `ssh -T` only when that machine is selected. The remote process serves workspaces and terminals through its protocol-v11 session. +The local `npx cmux` process renders both rails and opens `ssh -T` only when that machine is selected. It verifies that the remote package and protocol match, then starts or reuses the remote protocol-v11 session. Run `npx cmux ssh dev@buildbox --session agents --upgrade` once when a legacy remote executable is too old to answer the compatibility probe. For a direct transport check, the equivalent relay is: @@ -76,7 +83,7 @@ For a direct transport check, the equivalent relay is: ssh -T dev@buildbox /home/dev/.local/bin/cmux relay --session agents ``` -This command emits raw JSON-lines protocol traffic, not a second TUI. Normally the machine connector owns it. +This command emits raw JSON-lines protocol traffic, not a second TUI. It checks an already running mux and bypasses the managed probe, startup, identity pinning, and reconnect path. ## Share a local machine through Cloud diff --git a/cmux-tui/docs/mouse.md b/cmux-tui/docs/mouse.md index 097f00723a2e..b70b39a8970e 100644 --- a/cmux-tui/docs/mouse.md +++ b/cmux-tui/docs/mouse.md @@ -6,7 +6,9 @@ The files sidebar view (`sidebar.view = "files"`) shows the focused pane's cwd, The workspaces view shows a `workspaces` header, two rows per workspace, and `+ new workspace`. Click either row of a workspace to select it. Click `+ new workspace` to create one. Its terminal-style scrollbar appears one column inside the resize divider only when workspace rows overflow. Wheel over the rail, click the scrollbar's invisible track, or drag its thumb to scroll the workspace list. Drag the sidebar's right border in either built-in view to set a session-local width override. Configured `sidebar.max_width` limits the drag width when it is greater than zero, and the TUI still leaves at least 40 columns for panes. -When configured, the machine rail appears to the left of the workspace or files rail with the same header, two-line entry, active marker, and selected-row treatment as the built-in workspace list. Press and release on the same non-active machine entry to connect to it. Click `+ Connect machine` to open the shared text-input dialog for a host address or pairing code. A negotiated dynamic provider receives that value as opaque input; the static catalog accepts `host` or `user@host` and creates a temporary local SSH target. A provider that advertises create capability also shows `+ new machine`; the built-in static Unix/SSH catalog does not advertise that capability. Drag the machine rail's right divider to resize that rail, or the second rail's right divider to resize the workspace/files rail. The two session-local width overrides are independent. +When configured, the machine rail uses the same header, two-line entry, active marker, and selected-row treatment as the built-in workspace list. Press a non-active machine entry to connect to it. Click `+ Connect machine` to open the native SSH host picker, then filter a discovered alias or choose `Add SSH host…` for a process-local target. Provider-owned connection flows may use the same row for a host address or pairing code. Click `+ new machine` to run a provider create action or choose among configured prototype sources. The prototype picker adds only a local catalog row and never invokes Docker or a cloud API. + +An ordered `tabs` column shows every tab in the highlighted workspace. Clicking a row activates its workspace, screen, pane, and tab. Wheel input scrolls long tab lists. Drag any native column's right divider to set its independent session-local width. Each pane has a border box. Click inside a pane to focus it. The top border is the tab bar: click a tab chip to select it, click `+` to create a PTY tab, click `‹` or `›` to scroll overflowing tabs, or wheel over the bar to scroll tab chips while keeping the active tab visible. @@ -14,12 +16,12 @@ The status bar lists screens for the active workspace. Click a screen segment to When a screen overflows horizontally, the open space in the status bar becomes a continuous viewport track. Click it to animate to that position, or drag it for direct movement. Horizontal wheel events over the pane region pan by one sixth of the viewport. Screens without horizontal overflow continue forwarding those events to the active surface. -A workspace-row or tab-chip press arms the stable identity from the hit target -that was actually rendered. Its matching release completes that same action -even if another frontend changes selection and triggers a routing refresh -between the two events. A release without a corresponding armed press is a -no-op; it cannot select whichever workspace or tab happens to occupy that -coordinate later. +Every native sidebar row activates on left press. Workspace presses also arm +the rendered stable identity for reorder, while release only finishes that +gesture. Pane tab chips still arm their rendered stable identity on press and +activate or move it on release. A release without a corresponding armed press +is a no-op; it cannot select whichever workspace or tab later occupies that +coordinate. ## Drag Reorder @@ -41,17 +43,17 @@ Drag pane borders to resize the matching split. Dragging a corner adjusts both i On a horizontally scrollable screen, drag either side of a column divider to resize the column on its left. Drag the final column's right border to resize that column. Column widths are clamped from one tenth through one full viewport. Splits inside each column remain independently resizable. One continuous divider drag is coalesced into one `Ctrl-b U` layout-undo entry. -Drag a rail border to resize that rail for the current TUI session. Dragging the workspace rail leaves compact mode and sets its full-width override. The configured base widths come from `machine_sidebar.width`, `sidebar.width`, and `sidebar.compact_width`; each rail honors its own `max_width`. With both rails visible, resizing one preserves the other rail's width while leaving at least 40 columns for pane content. +Drag a rail border to resize that rail for the current TUI session. Dragging the workspace rail leaves compact mode and sets its full-width override. `sidebar.views` supplies base widths, maximum widths, and collapse priorities; legacy layouts still use `machine_sidebar.width`, `sidebar.width`, and `sidebar.compact_width`. Resizing one view preserves every other visible view while leaving at least 40 columns for panes. ## Context Menus -Right-click a pane for rename tab, close tab, new pane, new tab, new browser tab, browser actions when applicable, split right, split down, close pane, maximize/restore, and ID copying. New pane runs the same smart-layout action as `Alt-n`. Pane and status-bar menus do not contain sidebar actions. When an inner PTY app enables mouse tracking, right-click is forwarded to the app; hold Shift while right-clicking to open the cmux menu. +Right-click a pane for rename tab, close tab, new pane, new tab, new browser tab, browser actions when applicable, split right, split down, close pane, maximize/restore, and ID copying. New pane runs the same smart-layout action as `Alt-n`. Every right-click menu, including blank status-bar space, contains Show/Hide Sidebar. When an inner PTY app enables mouse tracking, right-click is forwarded to the app; hold Shift while right-clicking to open the cmux menu. -Right-click anywhere inside the sidebar, including its header, empty space, file rows, workspace rows, and divider, for show/hide, compact/full, and focus actions. Workspace rows also include their rename, close, and copy-ID actions. Switching between files and workspaces remains a keyboard action (`Ctrl-b e` by default) and is not in the context menu. Right-click a status-bar screen for only its screen actions. +Right-click anywhere inside the sidebar, including its header, empty space, file rows, projected tree rows, and divider, for show/hide, compact/full, and focus actions. Workspace rows also include rename, close, and copy-ID actions. Tab and agent rows rename the exact surface represented by that row. Switching between files and workspaces remains a keyboard action (`Ctrl-b e` by default) and is not in the context menu. Right-click a status-bar screen for its screen actions plus Show/Hide Sidebar. Each context menu includes Keyboard shortcuts, which opens the same modal as `Ctrl-b ?`. The modal has a visible `[Esc close]` button and a terminal-style scrollbar when its rows overflow, with wheel, track-click, and thumb-drag control. Every menu action with a configured key shows the resolved shortcut on the right. Remapped prefix and action keys appear immediately, and unbound actions omit the shortcut. -Menus draw bordered overlays. Divider rows collapse as needed to keep every action visible when the flat menu would fit. Up and Down move the selected row, Enter activates it, and Esc closes the menu. A right press, drag to a row, and release activates that row. A plain right-click opens the menu and leaves it open. +Menus draw bordered overlays. Divider rows collapse as needed to keep every action visible when the flat menu would fit. When rows overflow, the menu draws the shared native scrollbar and supports wheel, track click, and thumb drag. Up and Down move the selected row, Enter activates it, and Esc closes the menu. A right press, drag to a row, and release activates that row. A plain right-click opens the menu and leaves it open. ## Selection and Clipboard diff --git a/cmux-tui/examples/resource-columns.prototype.json b/cmux-tui/examples/resource-columns.prototype.json new file mode 100644 index 000000000000..95d5d983397a --- /dev/null +++ b/cmux-tui/examples/resource-columns.prototype.json @@ -0,0 +1,73 @@ +{ + "sidebar": { + "view": "workspaces", + "profile": "focused", + "profiles": [ + { + "id": "focused", + "name": "Workspaces + agents", + "views": [ + { "id": "machines", "levels": ["machines"], "width": 18 }, + { + "id": "workspace-agents", + "levels": ["workspaces", "agents"], + "actions": ["new-workspace"], + "width": 28 + } + ] + }, + { + "id": "columns", + "name": "Three columns", + "views": [ + { "id": "machines", "levels": ["machines"], "width": 18 }, + { + "id": "workspaces", + "levels": ["workspaces"], + "actions": ["new-workspace"], + "width": 22 + }, + { "id": "tabs", "levels": ["tabs"], "width": 24 } + ] + }, + { + "id": "tree", + "name": "Workspace tree", + "views": [ + { "id": "machines", "levels": ["machines"], "width": 18 }, + { + "id": "workspace-tree", + "levels": ["workspaces", "panes", "tabs"], + "actions": ["new-workspace", "new-tab"], + "width": 32 + } + ] + } + ] + }, + "machine_sidebar": { + "enabled": true, + "create_sources": [ + { + "id": "docker", + "name": "Docker", + "subtitle": "container prototype" + }, + { + "id": "e2b", + "name": "E2B", + "subtitle": "hosted microVM prototype" + }, + { + "id": "firecracker", + "name": "Firecracker", + "subtitle": "self-hosted microVM prototype" + }, + { + "id": "tart", + "name": "Tart", + "subtitle": "macOS VM prototype" + } + ] + } +} diff --git a/cmux-tui/examples/resource-tree-no-agents.prototype.json b/cmux-tui/examples/resource-tree-no-agents.prototype.json new file mode 100644 index 000000000000..98709bebdd2b --- /dev/null +++ b/cmux-tui/examples/resource-tree-no-agents.prototype.json @@ -0,0 +1,16 @@ +{ + "sidebar": { + "views": [ + { "id": "machines", "levels": ["machines"], "width": 18 }, + { + "id": "workspace-tabs", + "levels": ["workspaces", "panes", "tabs"], + "actions": ["new-workspace"], + "width": 32 + } + ] + }, + "machine_sidebar": { + "enabled": true + } +} diff --git a/cmux-tui/examples/resource-tree.prototype.json b/cmux-tui/examples/resource-tree.prototype.json new file mode 100644 index 000000000000..399d56d8b450 --- /dev/null +++ b/cmux-tui/examples/resource-tree.prototype.json @@ -0,0 +1,44 @@ +{ + "sidebar": { + "views": [ + { + "id": "machines", + "levels": ["machines"], + "width": 18, + "collapse_priority": 10 + }, + { + "id": "workspace-agents", + "levels": ["workspaces", "agents"], + "actions": ["new-workspace"], + "width": 30, + "collapse_priority": 30 + } + ] + }, + "machine_sidebar": { + "enabled": true, + "create_sources": [ + { + "id": "docker", + "name": "Docker", + "subtitle": "container prototype" + }, + { + "id": "e2b", + "name": "E2B", + "subtitle": "hosted microVM prototype" + }, + { + "id": "firecracker", + "name": "Firecracker", + "subtitle": "self-hosted microVM prototype" + }, + { + "id": "tart", + "name": "Tart", + "subtitle": "macOS VM prototype" + } + ] + } +} diff --git a/cmux-tui/scripts/check-spec-inventory.py b/cmux-tui/scripts/check-spec-inventory.py index ebbf49090cb4..d76c091bd02e 100644 --- a/cmux-tui/scripts/check-spec-inventory.py +++ b/cmux-tui/scripts/check-spec-inventory.py @@ -744,6 +744,10 @@ def menu_action_variants() -> set[str]: MENU_ONLY_METADATA: dict[str, dict[str, str]] = { + "RenameClientMachine": { + "classification": "composite", + "route": "frontend prompt + client-local machine catalog", + }, "RenameManagedMachine": { "classification": "external-protocol", "route": "machine-provider rename_machine", @@ -788,6 +792,10 @@ def menu_action_variants() -> set[str]: "classification": "direct", "route": "browser-activate", }, + "RenameSurface": { + "classification": "composite", + "route": "frontend prompt + rename-surface", + }, "CopyTabId": { "classification": "presentation-only", "route": "tree snapshot + frontend clipboard", @@ -796,6 +804,18 @@ def menu_action_variants() -> set[str]: "classification": "presentation-only", "route": "tree snapshot + frontend clipboard", }, + "CopyStatusMessage": { + "classification": "presentation-only", + "route": "status snapshot + frontend clipboard", + }, + "ActivateSidebarProfile": { + "classification": "presentation-only", + "route": "frontend sidebar profile composition", + }, + "SetSidebarViewVisible": { + "classification": "presentation-only", + "route": "frontend per-profile view visibility", + }, "SetClientSizing": { "classification": "direct", "route": "set-client-sizing", @@ -820,6 +840,18 @@ def menu_action_variants() -> set[str]: "classification": "external-protocol", "route": "machine-provider invoke_action", }, + "CreateMachineFrom": { + "classification": "composite", + "route": "native source picker + client-local machine catalog", + }, + "ConnectMachineTarget": { + "classification": "composite", + "route": "SSH config picker + client-local machine connector", + }, + "ConnectOtherMachine": { + "classification": "composite", + "route": "frontend prompt + client-local machine connector", + }, } diff --git a/cmux-tui/scripts/smoke-tui.py b/cmux-tui/scripts/smoke-tui.py index 4e36dc5d8022..25f7b354cd9e 100644 --- a/cmux-tui/scripts/smoke-tui.py +++ b/cmux-tui/scripts/smoke-tui.py @@ -3,10 +3,17 @@ BIN = os.path.abspath(os.environ.get("CMUX_TUI_BIN", "target/debug/cmux-tui")) SESSION = f"smoke-{os.getpid()}" SOCK = None +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +INVENTORY = os.path.join(ROOT, "spec", "inventory.json") CONTROL_SOCKET_RE = re.compile(r"control socket at (.+)$") SGR_RE = re.compile(rb"\x1b\[([0-9;]*)m") +def expected_protocol(): + with open(INVENTORY, "r", encoding="utf-8") as f: + return json.load(f)["mux_protocol"] + + def sgr_commands(parameters): values = tuple(int(part or b"0") for part in parameters.split(b";")) start = 0 @@ -540,7 +547,7 @@ def assert_snapshot_parser_controls(): ident = rpc({"id": 1, "cmd": "identify"}) assert ident["ok"] and ident["data"]["app"] == "cmux-tui", ident -assert ident["data"]["protocol"] == 10, ident +assert ident["data"]["protocol"] == expected_protocol(), ident print("identify ok:", ident["data"]) ws0 = initial_tree[0] diff --git a/cmux-tui/spec/inventory.json b/cmux-tui/spec/inventory.json index 310bc1377073..29508dcfaeaa 100644 --- a/cmux-tui/spec/inventory.json +++ b/cmux-tui/spec/inventory.json @@ -231,6 +231,7 @@ ] }, "events": [ + {"name": "agent-changed", "streams": ["subscribe"]}, {"name": "bell", "streams": ["subscribe"]}, {"name": "browser-state", "streams": ["attach-browser"]}, {"name": "client-attached", "streams": ["subscribe"]}, @@ -354,6 +355,7 @@ {"variant": "Detach", "key": "detach", "classification": "presentation-only", "route": "close frontend transport"} ], "menu_actions": [ + {"variant": "RenameClientMachine", "classification": "composite", "route": "frontend prompt + client-local machine catalog"}, {"variant": "RenameManagedMachine", "classification": "external-protocol", "route": "machine-provider rename_machine"}, {"variant": "DeleteManagedMachine", "classification": "external-protocol", "route": "machine-provider delete_machine"}, {"variant": "RestoreManagedMachine", "classification": "external-protocol", "route": "machine-provider restore_machine"}, @@ -374,8 +376,10 @@ {"variant": "BrowserCopyUrl", "classification": "presentation-only", "route": "browser state + frontend clipboard"}, {"variant": "BrowserActivate", "classification": "direct", "route": "browser-activate"}, {"variant": "RenameTab", "classification": "composite", "route": "frontend prompt + rename-surface"}, + {"variant": "RenameSurface", "classification": "composite", "route": "frontend prompt + rename-surface"}, {"variant": "CopyTabId", "classification": "presentation-only", "route": "tree snapshot + frontend clipboard"}, {"variant": "CopyPaneId", "classification": "presentation-only", "route": "tree snapshot + frontend clipboard"}, + {"variant": "CopyStatusMessage", "classification": "presentation-only", "route": "status snapshot + frontend clipboard"}, {"variant": "NewPaneSmart", "classification": "composite", "route": "list-workspaces + new-pane"}, {"variant": "NewTab", "classification": "direct", "route": "new-tab"}, {"variant": "NewBrowserTab", "classification": "composite", "route": "frontend omnibar + new-browser-tab"}, @@ -387,13 +391,18 @@ {"variant": "ToggleSidebar", "classification": "presentation-only", "route": "frontend action adapter"}, {"variant": "ToggleSidebarCompact", "classification": "presentation-only", "route": "frontend action adapter"}, {"variant": "FocusSidebar", "classification": "presentation-only", "route": "frontend action adapter"}, + {"variant": "ActivateSidebarProfile", "classification": "presentation-only", "route": "frontend sidebar profile composition"}, + {"variant": "SetSidebarViewVisible", "classification": "presentation-only", "route": "frontend per-profile view visibility"}, {"variant": "ShowShortcuts", "classification": "presentation-only", "route": "frontend shortcut overlay"}, {"variant": "SetClientSizing", "classification": "direct", "route": "set-client-sizing"}, {"variant": "UseClientSize", "classification": "direct", "route": "set-client-sizing exclusive:true"}, {"variant": "RestoreAllClientSizing", "classification": "direct", "route": "set-client-sizing enabled:true without client"}, {"variant": "DisconnectClient", "classification": "composite", "route": "self: close frontend transport; peer: detach-client"}, {"variant": "SelectProviderScope", "classification": "external-protocol", "route": "machine-provider select_scope"}, - {"variant": "InvokeProviderAction", "classification": "external-protocol", "route": "machine-provider invoke_action"} + {"variant": "InvokeProviderAction", "classification": "external-protocol", "route": "machine-provider invoke_action"}, + {"variant": "CreateMachineFrom", "classification": "composite", "route": "native source picker + client-local machine catalog"}, + {"variant": "ConnectMachineTarget", "classification": "composite", "route": "SSH config picker + client-local machine connector"}, + {"variant": "ConnectOtherMachine", "classification": "composite", "route": "frontend prompt + client-local machine connector"} ], "feature_families": [ {"id": "topology-layout-focus", "wire_status": "implemented", "programmability": "partial", "route": "control commands and tree snapshots/events; SDK and conformance parity remain incomplete"}, diff --git a/cmux-tui/spec/sdk-schema.json b/cmux-tui/spec/sdk-schema.json index 3c54006e4d54..fd77d110e992 100644 --- a/cmux-tui/spec/sdk-schema.json +++ b/cmux-tui/spec/sdk-schema.json @@ -8434,6 +8434,7 @@ "stream": { "kind": "subscribe", "event_names": [ + "agent-changed", "bell", "client-attached", "client-changed", @@ -8825,6 +8826,68 @@ } }, "events": { + "agent-changed": { + "since": 11, + "capability": null, + "streams": [ + "subscribe" + ], + "emission": "emitted", + "payload": { + "kind": "object", + "fields": { + "event": { + "type": { + "kind": "literal", + "value": "agent-changed" + }, + "presence": "required", + "nullable": false + }, + "surface": { + "type": { + "kind": "ref", + "name": "Id" + }, + "presence": "required", + "nullable": false + }, + "state": { + "type": { + "kind": "ref", + "name": "AgentState" + }, + "presence": "required", + "nullable": false + }, + "source": { + "type": { + "kind": "ref", + "name": "AgentSource" + }, + "presence": "required", + "nullable": false + }, + "session": { + "type": { + "kind": "scalar", + "name": "string" + }, + "presence": "required", + "nullable": true + }, + "updated_at_ms": { + "type": { + "kind": "scalar", + "name": "uint64" + }, + "presence": "required", + "nullable": false + } + }, + "additional_properties": false + } + }, "bell": { "since": 5, "capability": null,