From 9ee48383f956a89c1373639fb3934500fcbeced2 Mon Sep 17 00:00:00 2001 From: Ignacio Martin Date: Mon, 16 Nov 2026 18:51:00 +0100 Subject: [PATCH] Mirror the SWARM panel run read-only over the remote protocol Adds protocol 1.10 with the swarm_activity capability and a request_swarm command. The desktop answers it with the run header, agent rows and a tail of one agent's output, using a token so unchanged output is not resent. The phone's agent choice never moves the desktop selection, and the phone cannot start or stop a run. --- crates/gaviero-remote/PROTOCOL.md | 59 +++- .../fixtures/client/request_swarm.json | 13 + crates/gaviero-remote/protocol.schema.json | 45 ++- crates/gaviero-remote/src/envelope.rs | 18 ++ crates/gaviero-remote/src/version.rs | 9 +- crates/gaviero-remote/tests/protocol.rs | 2 +- crates/gaviero-tui/CLAUDE.md | 2 +- crates/gaviero-tui/src/app/remote.rs | 265 ++++++++++++++++++ crates/gaviero-tui/src/app/remote_setup.rs | 1 + .../gaviero-tui/src/panels/swarm_dashboard.rs | 9 +- 10 files changed, 411 insertions(+), 12 deletions(-) create mode 100644 crates/gaviero-remote/fixtures/client/request_swarm.json diff --git a/crates/gaviero-remote/PROTOCOL.md b/crates/gaviero-remote/PROTOCOL.md index 19af145d..bdf3c876 100644 --- a/crates/gaviero-remote/PROTOCOL.md +++ b/crates/gaviero-remote/PROTOCOL.md @@ -1,4 +1,4 @@ -# Gaviero Remote Protocol — v1.9 (1.0 frozen; 1.1 through 1.9 additive) +# Gaviero Remote Protocol — v1.10 (1.0 frozen; 1.1 through 1.10 additive) Normative wire contract between the gaviero TUI sidecar (server) and the mobile client. 1.0 was frozen by Plan A V3 unit A0 on 2026-08-05; 1.1 was added by Plan C V1 unit C0 on @@ -8,7 +8,7 @@ truth); one example fixture per frame lives in [`fixtures/`](fixtures/). Where p schema disagree, the schema wins. ``` -PROTOCOL_VERSION = { major: 1, minor: 9 } +PROTOCOL_VERSION = { major: 1, minor: 10 } WebSocket path = /v1/ws Subprotocol = gaviero.v1 Instances path = /v1/instances (HTTPS GET, 1.1, on every instance) @@ -182,6 +182,7 @@ holds the current token. | `read_file` | `{ path }` — requires `file_browser`; reads one regular UTF-8 file, read-only. | | `turn_review_action` | `{ turn_id, action, path?, folder? }` — requires `turn_review` (1.2); see §1.2 additions; `folder` since 1.5 (§Turn review folders) | | `request_skill_completions` | `{ query, limit? }` — requires `skill_completions` (1.8); catalog skills for a `$skill` invocation | +| `request_swarm` | `{ agent_id?, output_token? }` — requires `swarm_activity` (1.10); the desktop SWARM panel's run and one agent's output, read-only | There is **no** `rotate_token` command. Rotation is desktop-only and reaches the client as close 4006. @@ -220,7 +221,7 @@ share a folder name, each gains the nearest parent folder that tells them apart `hello.capabilities` is an array of strings, **empty in 1.0**; the shape is frozen so minor versions can advertise features. 1.1 advertises `latest_page` and `instances`; 1.2 adds -`turn_review`; 1.3 adds `file_browser`; 1.4 adds `permission_turn_grant`; 1.6 adds `permission_grants`; 1.7 adds `shell_history`; 1.8 adds `skill_completions`. Clients +`turn_review`; 1.3 adds `file_browser`; 1.4 adds `permission_turn_grant`; 1.6 adds `permission_grants`; 1.7 adds `shell_history`; 1.8 adds `skill_completions`; 1.10 adds `swarm_activity`. Clients ignore unknown entries. ## DTOs @@ -485,6 +486,58 @@ and is not escaped, with at least two characters typed and no space between it and the caret — and on tap replaces the token with `insert` plus a space. Older servers receive no skill completion requests. +## Swarm activity (`swarm_activity` capability, 1.10) + +Servers advertising `swarm_activity` answer `request_swarm` with what the desktop SWARM panel +(`Alt+w`) shows for its run: the header, one row per agent, and one agent's output. The desktop +runs one script at a time, so there is at most one run; after it ends it stays readable until the +next one starts. The view is read-only — there is no start, stop or undo command. + +`request_swarm`: `{ "agent_id": "scout", "output_token": "3:17" }`, both optional. `agent_id` +picks whose output to return; absent, or not in the run, ⇒ the agent selected on the desktop +(which follows the agent that started last until the user picks one). The phone's choice never +moves the desktop selection. `output_token` is the `output.token` of the previous reply. + +The completed `command_result.result`: + +```json +{ "run": { "run_id": 3, "script": "deep_explore", "phase": "running", "running": true, + "tier_current": 1, "tier_total": 3, "cost_usd": 0.042, "message": "", + "counts": { "running": 1, "queued": 1, "done": 0, "failed": 0 }, + "agents": [ { "id": "scout", "status": "running", "error": null, + "detail": "[Read src/main.rs]", "tier": "cheap", + "backend": "claude:haiku", "elapsed_ms": 12000, + "branch": null, "modified_files": [] } ] }, + "selected_id": "scout", + "output": { "agent_id": "scout", "token": "3:17", "unchanged": false, + "lines": [ { "kind": "status", "text": "Running: reading" }, + { "kind": "text", "text": "Looking at the entry point…" }, + { "kind": "tool_call", "text": "[Read src/main.rs]" } ], + "truncated": false } } +``` + +No run since the desktop started ⇒ `{ "run": null, "selected_id": null, "output": null }`. + +- `phase` is the desktop's display string (`starting`, a pipeline phase, `completed`, + `completed with failures`, `failed`, `stopped`, `reverted`). `message` is the run-wide note the + desktop shows under the header (preparation notes, the failure, gate results); may be empty. +- `status ∈ queued | running | completed | failed`; `error` is the reason when `failed` + (`not run`, `stopped`, … for agents a run never finished). `tier ∈ cheap | expensive | null`; + `backend` is the `provider:model` it was dispatched to, once known. `elapsed_ms` is the run time + at reply time (frozen once the agent finished; null before it started) — clients may tick it + locally for running agents between polls. `branch` and `modified_files` come from the agent's + manifest when the run completes. +- `output.lines` are the agent's activity, oldest first: `text` (streamed answer, ANSI stripped; + may contain newlines), `tool_call`, `status` (state changes), `file_change` (`[wrote path +a -d]`). + At most the newest 64 KiB; `truncated: true` when older output was left out (the desktop itself + keeps 500 lines / 256 KiB per agent). +- `output.token` changes whenever that agent's output changes (and with every new run). When the + request's `output_token` equals it, `output` is `{ agent_id, token, unchanged: true }` with no + `lines` — keep what you have. The header and agents are always sent in full. + +The Flutter client polls it about once a second while its Swarm section is on screen. Older +servers receive no swarm requests. + ## File browser (`file_browser` capability) Servers advertising `hello.capabilities: ["file_browser", ...]` implement the read-only workspace diff --git a/crates/gaviero-remote/fixtures/client/request_swarm.json b/crates/gaviero-remote/fixtures/client/request_swarm.json new file mode 100644 index 00000000..0bba51ba --- /dev/null +++ b/crates/gaviero-remote/fixtures/client/request_swarm.json @@ -0,0 +1,13 @@ +{ + "version": { + "major": 1, + "minor": 10 + }, + "instance_id": "a3f9c2e14b7d8650", + "command_id": "cmd-request_swarm", + "type": "request_swarm", + "payload": { + "agent_id": "scout", + "output_token": "3:17" + } +} diff --git a/crates/gaviero-remote/protocol.schema.json b/crates/gaviero-remote/protocol.schema.json index 0eaaa052..32ba4850 100644 --- a/crates/gaviero-remote/protocol.schema.json +++ b/crates/gaviero-remote/protocol.schema.json @@ -124,7 +124,7 @@ ] }, "ProtocolVersion": { - "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.", + "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.\nMinor 10 is additive: the `swarm_activity` capability and the\n`request_swarm` client frame.", "properties": { "major": { "format": "uint16", @@ -260,6 +260,26 @@ ], "type": "object" }, + "RequestSwarm": { + "description": "Read the SWARM panel's run (1.10, `swarm_activity`). Polled; never moves\nthe desktop's selection.", + "properties": { + "agent_id": { + "description": "Agent whose output to return. Absent, or no longer in the run ⇒ the\nagent selected on the desktop.", + "type": [ + "string", + "null" + ] + }, + "output_token": { + "description": "`output.token` from the previous reply. When the chosen agent's output\nhas not changed since, the reply carries `output.unchanged: true` and\nno lines.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, "RequestTerminals": { "properties": { "history": { @@ -771,6 +791,23 @@ "payload" ], "type": "object" + }, + { + "description": "1.10 (`swarm_activity`): the SWARM panel's run and one agent's output.", + "properties": { + "payload": { + "$ref": "#/$defs/RequestSwarm" + }, + "type": { + "const": "request_swarm", + "type": "string" + } + }, + "required": [ + "type", + "payload" + ], + "type": "object" } ], "properties": { @@ -848,7 +885,7 @@ "type": "object" }, "ProtocolVersion": { - "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.", + "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.\nMinor 10 is additive: the `swarm_activity` capability and the\n`request_swarm` client frame.", "properties": { "major": { "format": "uint16", @@ -919,7 +956,7 @@ "instances_path": "/v1/instances", "protocol_version": { "major": 1, - "minor": 9 + "minor": 10 }, "server_envelope": { "$defs": { @@ -1865,7 +1902,7 @@ "type": "object" }, "ProtocolVersion": { - "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.", + "description": "Wire protocol version. Deliberately unrelated to any plan-document\nversion: this is the first protocol ever on the wire, so it starts at\nmajor 1 (Plan A V3 §0.1 item 1). Minor 1 (Plan C V1 §4) is additive:\n`hello.machine`, capability strings, optional\n`request_messages.before_seq`, and the `GET /v1/instances` resource.\nMinor 2 is additive: the turn-review frames, `snapshot.open_turn_reviews`,\nand two error codes. Minor 3 is additive: the `file_browser` capability\nwith the `list_directory` / `read_file` client frames. Minor 4 is\nadditive: the `permission_turn_grant` capability, optional\n`permission_request.mcp_server` and `permission_decision.grant`. Minor 5\nis additive: optional `TurnReviewFile.folder` and\n`turn_review_action.folder` (no capability — a client groups by `folder`\nwhen files carry it, and echoes it only then). Minor 6 is additive: the\n`permission_grants` capability, optional `permission_request.grants`, and\nthree more `PermissionGrant` values (`tool_session`,\n`mcp_server_session`, `turn_all`) — the desktop's `a` / `A` / `p` keys.\nMinor 7 is additive: the `shell_history` capability and optional\n`request_terminals.history`. Minor 8 is additive: the `skill_completions`\ncapability and the `request_skill_completions` client frame. Minor 9 is\nadditive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`.\nMinor 10 is additive: the `swarm_activity` capability and the\n`request_swarm` client frame.", "properties": { "major": { "format": "uint16", diff --git a/crates/gaviero-remote/src/envelope.rs b/crates/gaviero-remote/src/envelope.rs index f125a966..d10ec082 100644 --- a/crates/gaviero-remote/src/envelope.rs +++ b/crates/gaviero-remote/src/envelope.rs @@ -39,6 +39,8 @@ pub enum ClientFrame { TurnReviewAction(TurnReviewAction), /// 1.8 (`skill_completions`): catalog skills for a `$skill` invocation. RequestSkillCompletions(RequestSkillCompletions), + /// 1.10 (`swarm_activity`): the SWARM panel's run and one agent's output. + RequestSwarm(RequestSwarm), } impl ClientFrame { @@ -64,6 +66,7 @@ impl ClientFrame { "read_file", "turn_review_action", "request_skill_completions", + "request_swarm", ]; } @@ -206,6 +209,21 @@ pub struct RequestSkillCompletions { pub limit: Option, } +/// Read the SWARM panel's run (1.10, `swarm_activity`). Polled; never moves +/// the desktop's selection. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] +pub struct RequestSwarm { + /// Agent whose output to return. Absent, or no longer in the run ⇒ the + /// agent selected on the desktop. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent_id: Option, + /// `output.token` from the previous reply. When the chosen agent's output + /// has not changed since, the reply carries `output.unchanged: true` and + /// no lines. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_token: Option, +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)] pub struct ListDirectory { /// Explorer display path (`/`). Omitted or empty lists diff --git a/crates/gaviero-remote/src/version.rs b/crates/gaviero-remote/src/version.rs index c40f3c86..b2ef5a9c 100644 --- a/crates/gaviero-remote/src/version.rs +++ b/crates/gaviero-remote/src/version.rs @@ -21,13 +21,15 @@ use serde::{Deserialize, Serialize}; /// `request_terminals.history`. Minor 8 is additive: the `skill_completions` /// capability and the `request_skill_completions` client frame. Minor 9 is /// additive: optional `InstanceInfo.last_activity_at` in `GET /v1/instances`. +/// Minor 10 is additive: the `swarm_activity` capability and the +/// `request_swarm` client frame. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct ProtocolVersion { pub major: u16, pub minor: u16, } -pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion { major: 1, minor: 9 }; +pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion { major: 1, minor: 10 }; /// `hello.capabilities` entries this server version advertises (Plan C §4.1). pub mod capability { @@ -53,6 +55,9 @@ pub mod capability { /// 1.8: `request_skill_completions` lists catalog skills for a `$skill` /// invocation. pub const SKILL_COMPLETIONS: &str = "skill_completions"; + /// 1.10: `request_swarm` reads the SWARM panel's run — its agents, their + /// state, and one agent's output. Read-only. + pub const SWARM_ACTIVITY: &str = "swarm_activity"; } /// Why a peer's version is unacceptable. @@ -90,7 +95,7 @@ mod tests { .is_ok() ); assert!( - ours.check_compatible(&ProtocolVersion { major: 1, minor: 9 }) + ours.check_compatible(&ProtocolVersion { major: 1, minor: 10 }) .is_ok() ); } diff --git a/crates/gaviero-remote/tests/protocol.rs b/crates/gaviero-remote/tests/protocol.rs index 7a007fb1..eeba3c01 100644 --- a/crates/gaviero-remote/tests/protocol.rs +++ b/crates/gaviero-remote/tests/protocol.rs @@ -38,7 +38,7 @@ fn fixtures(side: &str) -> Vec<(String, String)> { #[test] fn client_fixtures_round_trip() { let fixtures = fixtures("client"); - assert_eq!(fixtures.len(), 20, "one fixture per client frame type"); + assert_eq!(fixtures.len(), 21, "one fixture per client frame type"); for (name, text) in fixtures { let parsed: Value = serde_json::from_str(&text).unwrap(); let env: ClientEnvelope = diff --git a/crates/gaviero-tui/CLAUDE.md b/crates/gaviero-tui/CLAUDE.md index 80e08fba..3f6c84c4 100644 --- a/crates/gaviero-tui/CLAUDE.md +++ b/crates/gaviero-tui/CLAUDE.md @@ -38,7 +38,7 @@ Workspace dispatch: directory → `Workspace::single_folder`; `*.gaviero-workspa **Observer bridge:** implements `WriteGateObserver` and `AcpObserver` from [`gaviero_core::observer`](../gaviero-core/src/observer.rs), plus the memory / manifest / MCP observers. Each holds an event-channel sender. **No background task mutates `App` directly.** -**SWARM panel** (`Alt+w`): [`panels/swarm_dashboard.rs`](src/panels/swarm_dashboard.rs) holds state and rendering, [`app/swarm_run.rs`](src/app/swarm_run.rs) launching and input. Three views: script picker (`ScriptCatalog`, plus a path typed in the filter), input form (`gaviero_dsl::inspect_file`, plus a Profile selector when any model profile exists; its Prompt field is the chat's box, [`widgets/prompt_input.rs`](src/widgets/prompt_input.rs), and `$skill` is expanded at launch; `file` and `dir` vars complete like `@`, and list params complete the tier after `id=` from the selected profile; below the vars, when the resolved profile reads, an **Agents** section (one `FieldRole::AgentTier` choice per agent the workflow runs — its tier, from the profile's tiers → `--tier`) and a **Tiers** section (per tier those agents now use, a `FieldRole::TierModel` choice — its client, from the profile's clients → `--tier-client` — and a `FieldRole::TierEffort` choice — the chosen model's levels from core `effort_completions` (`SwarmForm::effort_options`, stubbed in tests) plus the client's own effort or `(provider default)` → `--tier-effort`); on these rows Enter opens the options as a list in the form's popup (`AutocompleteMode::Choice`, `open_choice_list`), ↑/↓ move, Enter picks and moves to the next field, ←/→/Space still cycle; only changed rows are passed, the profile is re-read (`reload_profile_info`) when Folder or Profile changes, and choices survive where the new profile still offers them; the form opens on its first input, below the Folder / Workflow / Profile selectors; a list param is `FieldValue::List`, one input per item in `--param` entry syntax, split / rejoined by `split_list_value` / `join_list_items` — short form unless an item is a `{…}` literal, so free fields survive), and the run (one row per planned agent; the selected agent's output below). Starting a run moves the form into `SwarmDashboardState::last_forms` (keyed by script path, this session only): opening that script again — `r` on a finished or stopped run, or the picker — restores every value (`SwarmForm::restore_from`: selectors by option name, agent/tier/effort rows, typed inputs the script still has) with focus on Run. A run is `pipeline::execute` in-process, prepared by the same [`script_run`](../gaviero-core/src/swarm/script_run.rs) helpers as `gaviero-cli --script`; keep the two in step. It uses the pipeline's Write Gate, not TURN REVIEW. Every update carries a run id so a stopped run's stragglers are dropped. This panel is the only way the TUI runs a script: chat has no `/run`, and `/swarm`, `/cswarm` and `/undo-swarm` stay gone. Remote does not mirror the panel. +**SWARM panel** (`Alt+w`): [`panels/swarm_dashboard.rs`](src/panels/swarm_dashboard.rs) holds state and rendering, [`app/swarm_run.rs`](src/app/swarm_run.rs) launching and input. Three views: script picker (`ScriptCatalog`, plus a path typed in the filter), input form (`gaviero_dsl::inspect_file`, plus a Profile selector when any model profile exists; its Prompt field is the chat's box, [`widgets/prompt_input.rs`](src/widgets/prompt_input.rs), and `$skill` is expanded at launch; `file` and `dir` vars complete like `@`, and list params complete the tier after `id=` from the selected profile; below the vars, when the resolved profile reads, an **Agents** section (one `FieldRole::AgentTier` choice per agent the workflow runs — its tier, from the profile's tiers → `--tier`) and a **Tiers** section (per tier those agents now use, a `FieldRole::TierModel` choice — its client, from the profile's clients → `--tier-client` — and a `FieldRole::TierEffort` choice — the chosen model's levels from core `effort_completions` (`SwarmForm::effort_options`, stubbed in tests) plus the client's own effort or `(provider default)` → `--tier-effort`); on these rows Enter opens the options as a list in the form's popup (`AutocompleteMode::Choice`, `open_choice_list`), ↑/↓ move, Enter picks and moves to the next field, ←/→/Space still cycle; only changed rows are passed, the profile is re-read (`reload_profile_info`) when Folder or Profile changes, and choices survive where the new profile still offers them; the form opens on its first input, below the Folder / Workflow / Profile selectors; a list param is `FieldValue::List`, one input per item in `--param` entry syntax, split / rejoined by `split_list_value` / `join_list_items` — short form unless an item is a `{…}` literal, so free fields survive), and the run (one row per planned agent; the selected agent's output below). Starting a run moves the form into `SwarmDashboardState::last_forms` (keyed by script path, this session only): opening that script again — `r` on a finished or stopped run, or the picker — restores every value (`SwarmForm::restore_from`: selectors by option name, agent/tier/effort rows, typed inputs the script still has) with focus on Run. A run is `pipeline::execute` in-process, prepared by the same [`script_run`](../gaviero-core/src/swarm/script_run.rs) helpers as `gaviero-cli --script`; keep the two in step. It uses the pipeline's Write Gate, not TURN REVIEW. Every update carries a run id so a stopped run's stragglers are dropped. This panel is the only way the TUI runs a script: chat has no `/run`, and `/swarm`, `/cswarm` and `/undo-swarm` stay gone. Remote mirrors the run read-only: `request_swarm` (protocol 1.10 `swarm_activity`, `app/remote.rs` `swarm_snapshot`) returns the header, agent rows and one agent's output tail; the phone's agent choice never moves the desktop selection, and the phone can neither start nor stop a run. **Turn review (mandatory):** [`app/turn_review.rs`](src/app/turn_review.rs) + the dispatch task in [`app/side_panel.rs`](src/app/side_panel.rs). Each chat turn is bracketed by `app.turn_capture.begin/end` (core `turn_capture`); the session runs with `AgentOptions::host_capture` and the conversation's gate mode `AutoAccept`. A non-empty change set opens the TURN REVIEW left panel (non-modal) and blocks *that* conversation's next prompt (desktop keeps the typed prompt; remote gets `turn_review_pending`). Pending reviews and their decisions persist under `.gaviero/turns/pending/` and reopen on startup. Any host write made while a turn may be running — editor saves, review reverts, MCP config synthesis — must go through `turn_review::note_host_write` or it is attributed to the agent. diff --git a/crates/gaviero-tui/src/app/remote.rs b/crates/gaviero-tui/src/app/remote.rs index 17e20d91..9270de60 100644 --- a/crates/gaviero-tui/src/app/remote.rs +++ b/crates/gaviero-tui/src/app/remote.rs @@ -214,6 +214,138 @@ fn terminal_snapshot(app: &App, requested: Option, history: Option) -> result } +/// Most output bytes one `request_swarm` reply carries: the newest ones. +const SWARM_OUTPUT_BYTES: usize = 64 * 1024; + +/// The SWARM panel's run as the phone shows it (1.10 `swarm_activity`): the +/// header and agent table the desktop draws, plus one agent's output. The +/// phone picks its agent with `agent_id`; the desktop selection never moves. +/// `output_token` names output the phone already has, so a poll of an idle +/// agent sends no lines. +fn swarm_snapshot( + app: &App, + agent_id: Option<&str>, + output_token: Option<&str>, +) -> serde_json::Value { + use gaviero_core::swarm::models::AgentStatus; + use gaviero_core::types::ModelTier; + + let dash = &app.swarm_dashboard; + if !dash.has_run() { + return serde_json::json!({ "run": null, "selected_id": null, "output": null }); + } + let agents: Vec<_> = dash + .agents + .iter() + .map(|agent| { + let (status, error) = match &agent.status { + AgentStatus::Pending => ("queued", None), + AgentStatus::Running => ("running", None), + AgentStatus::Completed => ("completed", None), + AgentStatus::Failed(e) => ("failed", Some(e.clone())), + }; + serde_json::json!({ + "id": agent.id, + "status": status, + "error": error, + "detail": agent.detail.replace(['\n', '\r'], " "), + "tier": agent.model_tier.map(|t| match t { + ModelTier::Cheap => "cheap", + ModelTier::Expensive => "expensive", + }), + "backend": agent.backend, + "elapsed_ms": agent.elapsed().map(|d| d.as_millis() as u64), + "branch": agent.branch, + "modified_files": agent.modified_files, + }) + }) + .collect(); + let counts = dash.counts(); + let run = serde_json::json!({ + "run_id": dash.run_id, + "script": dash.script_label, + "phase": dash.phase, + "running": dash.running, + "tier_current": dash.tier_current, + "tier_total": dash.tier_total, + "cost_usd": dash.estimated_cost_usd, + "message": dash.status_message, + "counts": { + "running": counts.running, + "queued": counts.queued, + "done": counts.done, + "failed": counts.failed, + }, + "agents": agents, + }); + + let selected = agent_id + .and_then(|id| dash.agents.iter().find(|a| a.id == id)) + .or_else(|| dash.agents.get(dash.scroll.selected)) + .or_else(|| dash.agents.first()); + let output = selected.map(|agent| { + let token = format!("{}:{}", dash.run_id, agent.revision()); + if output_token == Some(token.as_str()) { + return serde_json::json!({ + "agent_id": agent.id, + "token": token, + "unchanged": true, + }); + } + let (lines, truncated) = output_tail(&agent.activity, SWARM_OUTPUT_BYTES); + serde_json::json!({ + "agent_id": agent.id, + "token": token, + "unchanged": false, + "lines": lines, + "truncated": truncated, + }) + }); + serde_json::json!({ + "run": run, + "selected_id": selected.map(|a| a.id.clone()), + "output": output, + }) +} + +/// The newest activity lines that fit in `budget` bytes, oldest first. The +/// oldest kept line loses its head when it does not fit whole. +fn output_tail( + activity: &[crate::panels::swarm_dashboard::ActivityLine], + budget: usize, +) -> (Vec, bool) { + use crate::panels::swarm_dashboard::ActivityKind; + let mut lines = Vec::new(); + let mut left = budget; + let mut truncated = false; + for line in activity.iter().rev() { + if left == 0 { + truncated = true; + break; + } + let text = if line.text.len() <= left { + line.text.as_str() + } else { + truncated = true; + let mut cut = line.text.len() - left; + while !line.text.is_char_boundary(cut) { + cut += 1; + } + &line.text[cut..] + }; + left -= text.len(); + let kind = match line.kind { + ActivityKind::Text => "text", + ActivityKind::ToolCall => "tool_call", + ActivityKind::Status => "status", + ActivityKind::FileChange => "file_change", + }; + lines.push(serde_json::json!({ "kind": kind, "text": text })); + } + lines.reverse(); + (lines, truncated) +} + /// `@` completion for the phone composer: the same file list and matcher /// as the desktop popup, so an accepted path resolves in `send_prompt`. fn file_completions( @@ -393,6 +525,15 @@ pub fn handle_remote_command(app: &mut App, envelope: ClientEnvelope, max_prompt .map(|result| (CommandStatus::Completed, Some(result))), ClientFrame::RequestSkillCompletions(r) => skill_completions(app, &r.query, r.limit) .map(|result| (CommandStatus::Completed, Some(result))), + // 1.10 (`swarm_activity`): read-only view of the SWARM panel. + ClientFrame::RequestSwarm(r) => Ok(( + CommandStatus::Completed, + Some(swarm_snapshot( + app, + r.agent_id.as_deref(), + r.output_token.as_deref(), + )), + )), // 1.3 (`file_browser`): read-only workspace browsing. ClientFrame::ListDirectory(r) => { crate::app::remote_files::list_directory(app, r.path.as_deref()) @@ -1044,6 +1185,130 @@ mod tests { assert_eq!(terminal_snapshot(&app, None, Some(50))["history"], serde_json::json!([])); } + #[test] + fn swarm_request_mirrors_the_run_without_moving_the_desktop_selection() { + use crate::panels::swarm_dashboard::{PlannedAgent, SwarmUpdate}; + use gaviero_core::swarm::models::AgentStatus; + use gaviero_core::types::ModelTier; + use gaviero_remote::envelope::RequestSwarm; + + let (dir, mut app) = two_tab_app(); + let mut request = |app: &mut App, agent_id: Option<&str>, token: Option<&str>| { + handle_remote_command( + app, + ClientEnvelope { + version: gaviero_remote::version::PROTOCOL_VERSION, + instance_id: Some("test".into()), + command_id: format!("swarm-{agent_id:?}-{token:?}"), + frame: ClientFrame::RequestSwarm(RequestSwarm { + agent_id: agent_id.map(str::to_string), + output_token: token.map(str::to_string), + }), + }, + 131072, + ); + match app.remote.pending_frames.pop() { + Some(ServerFrame::CommandResult(done)) => done.result.unwrap(), + other => panic!("expected command_result, got {other:?}"), + } + }; + + // Nothing has run yet. + let idle = request(&mut app, None, None); + assert!(idle["run"].is_null()); + assert!(idle["output"].is_null()); + + let run = app.swarm_dashboard.begin_run( + "deep_explore".into(), + dir.path().to_path_buf(), + vec![ + PlannedAgent { id: "scout".into(), tier: ModelTier::Cheap, model: Some("claude:haiku".into()) }, + PlannedAgent { id: "writer".into(), tier: ModelTier::Expensive, model: None }, + ], + vec!["prepared".into()], + ); + app.swarm_dashboard.apply(run, SwarmUpdate::Agent { + id: "scout".into(), + status: AgentStatus::Running, + detail: "reading".into(), + }); + app.swarm_dashboard.apply(run, SwarmUpdate::Text { id: "scout".into(), text: "hello\x1b[1m world".into() }); + app.swarm_dashboard.apply(run, SwarmUpdate::Tool { id: "scout".into(), summary: "Read src/main.rs".into() }); + + let first = request(&mut app, None, None); + let header = &first["run"]; + assert_eq!(header["script"], "deep_explore"); + assert_eq!(header["running"], true); + assert_eq!(header["message"], "prepared"); + assert_eq!(header["counts"]["running"], 1); + assert_eq!(header["counts"]["queued"], 1); + let agents = header["agents"].as_array().unwrap(); + assert_eq!(agents.len(), 2); + assert_eq!(agents[0]["status"], "running"); + assert_eq!(agents[0]["tier"], "cheap"); + assert_eq!(agents[0]["backend"], "claude:haiku"); + assert_eq!(agents[0]["detail"], "[Read src/main.rs]"); + assert_eq!(agents[1]["status"], "queued"); + assert_eq!(agents[1]["tier"], "expensive"); + // No agent asked for: the desktop's selection (it follows the + // running agent). + assert_eq!(first["selected_id"], "scout"); + let output = &first["output"]; + assert_eq!(output["unchanged"], false); + let kinds: Vec<_> = output["lines"].as_array().unwrap().iter().map(|l| l["kind"].as_str().unwrap()).collect(); + assert_eq!(kinds, ["status", "text", "tool_call"]); + assert_eq!(output["lines"][1]["text"], "hello world"); + let token = output["token"].as_str().unwrap().to_string(); + + // Same output again: no lines. + let same = request(&mut app, Some("scout"), Some(&token)); + assert_eq!(same["output"]["unchanged"], true); + assert!(same["output"].get("lines").is_none()); + + // The phone looks at another agent; the desktop keeps its own. + let desktop_selected = app.swarm_dashboard.scroll.selected; + let writer = request(&mut app, Some("writer"), Some(&token)); + assert_eq!(writer["selected_id"], "writer"); + assert_eq!(writer["output"]["unchanged"], false); + assert_eq!(writer["output"]["lines"], serde_json::json!([])); + assert_eq!(app.swarm_dashboard.scroll.selected, desktop_selected); + + // An agent that is gone falls back to the desktop's selection. + assert_eq!(request(&mut app, Some("gone"), None)["selected_id"], "scout"); + + // A failed run reports each unfinished agent's reason. + app.swarm_dashboard.apply(run, SwarmUpdate::Failed("boom".into())); + let failed = request(&mut app, None, None); + assert_eq!(failed["run"]["phase"], "failed"); + assert_eq!(failed["run"]["running"], false); + assert_eq!(failed["run"]["message"], "boom"); + assert_eq!(failed["run"]["agents"][1]["status"], "failed"); + assert_eq!(failed["run"]["agents"][1]["error"], "failed"); + } + + #[test] + fn swarm_output_tail_keeps_the_newest_bytes() { + use crate::panels::swarm_dashboard::{ActivityKind, ActivityLine}; + let activity = vec![ + ActivityLine { kind: ActivityKind::Status, text: "Running: x".into() }, + ActivityLine { kind: ActivityKind::Text, text: "ééé".into() }, + ActivityLine { kind: ActivityKind::ToolCall, text: "[Read]".into() }, + ]; + let (all, truncated) = output_tail(&activity, 1024); + assert!(!truncated); + assert_eq!(all.len(), 3); + // 6 bytes for the tool line, 2 left: the head of "ééé" (6 bytes) is + // cut on a char boundary, and the oldest line is dropped. + let (tail, truncated) = output_tail(&activity, 8); + assert!(truncated); + assert_eq!(tail.len(), 2); + assert_eq!(tail[0]["text"], "é"); + assert_eq!(tail[1]["text"], "[Read]"); + let (none, truncated) = output_tail(&activity, 6); + assert!(truncated); + assert_eq!(none.len(), 1); + } + #[test] fn remote_file_completions_match_workspace_paths_and_clamp() { use gaviero_remote::envelope::RequestFileCompletions; diff --git a/crates/gaviero-tui/src/app/remote_setup.rs b/crates/gaviero-tui/src/app/remote_setup.rs index f4a37d1a..af7b9a92 100644 --- a/crates/gaviero-tui/src/app/remote_setup.rs +++ b/crates/gaviero-tui/src/app/remote_setup.rs @@ -647,6 +647,7 @@ pub async fn start( gaviero_remote::version::capability::PERMISSION_GRANTS.to_string(), gaviero_remote::version::capability::SHELL_HISTORY.to_string(), gaviero_remote::version::capability::SKILL_COMPLETIONS.to_string(), + gaviero_remote::version::capability::SWARM_ACTIVITY.to_string(), ], machine: Some(gaviero_remote::dto::MachineInfo { host: config.machine_host.clone(), diff --git a/crates/gaviero-tui/src/panels/swarm_dashboard.rs b/crates/gaviero-tui/src/panels/swarm_dashboard.rs index 78722285..0b6d1f22 100644 --- a/crates/gaviero-tui/src/panels/swarm_dashboard.rs +++ b/crates/gaviero-tui/src/panels/swarm_dashboard.rs @@ -1399,11 +1399,18 @@ impl AgentEntry { } } - fn elapsed(&self) -> Option { + /// Run time so far, or the frozen time once finished. + pub fn elapsed(&self) -> Option { self.finished_after .or_else(|| self.started_at.map(|s| s.elapsed())) } + /// Bumped on every activity change, so a remote client can skip + /// output it already has. + pub fn revision(&self) -> u64 { + self.revision + } + fn is_finished(&self) -> bool { matches!(self.status, AgentStatus::Completed | AgentStatus::Failed(_)) }