Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(linux): align native clients with SwiftUI behavior (#21)

leepokai6824eed8daf0
diff --git a/.github/workflows/host.yml b/.github/workflows/host.yml
index 21161ebe..cda1e9f5 100644
--- a/.github/workflows/host.yml
+++ b/.github/workflows/host.yml
@@ -43,7 +43,7 @@ jobs:
working-directory: apps/linux
steps:
- uses: actions/checkout@v4
- - run: sudo apt-get update && sudo apt-get install -y libgtk-4-dev libadwaita-1-dev
+ - run: sudo apt-get update && sudo apt-get install -y libgtk-4-dev libadwaita-1-dev libvte-2.91-gtk4-dev xvfb dbus-x11 imagemagick
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
@@ -52,6 +52,16 @@ jobs:
workspaces: apps/linux
- run: cargo clippy -- -D warnings
- run: cargo test
+ - name: Verify native UI flows
+ env:
+ GTK_A11Y: none
+ CODYNC_UI_ARTIFACTS: ${{ github.workspace }}/build/ui-parity
+ run: xvfb-run -a dbus-run-session -- python3 tests/ui_fixture.py
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: native-ui-${{ matrix.name }}
+ path: build/ui-parity/
- name: Package
if: startsWith(github.ref, 'refs/tags/v')
run: |
diff --git a/AGENTS.md b/AGENTS.md
index ad14c52a..a5ffa64d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -17,7 +17,7 @@ Run from the repository root unless a command changes directories:
- `cd host && cargo build`: build the host; `cargo run -- serve` starts it in the foreground.
- `cd host && cargo fmt --check && cargo clippy --all-targets -- -D warnings && cargo test`: run host CI checks.
- `cd kit && swift test`: run shared Swift tests.
-- `cd apps/linux && cargo test`: test Linux code; requires GTK 4 and libadwaita development packages.
+- `cd apps/linux && cargo test`: test Linux code; requires GTK 4, libadwaita and VTE GTK 4 development packages.
- `cd cloud && npm ci && npm test && npm run typecheck`: validate the cloud service; see `docs/guides/cloudflare-testing.md` for integration checks.
- `cd relay && npm ci && npm test && npm run typecheck`: install dependencies and validate the relay.
@@ -36,6 +36,13 @@ Name Swift files after their main `UpperCamelCase` type; use `snake_case.rs` and
- UI controls default to the shared custom components. Explicit exception: iOS BotListView and ThreadView use native navigation/toolbar items and automatic back navigation for system Liquid Glass, as specified in `docs/design/ui-conventions.md`. The macOS menu bar also uses native `MenuBarExtra(.menu)`, menus, pickers and toggles. Keep system authentication and widget containers native. Outside these exceptions, avoid: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.
+## Cross-platform UI changes
+
+- Any UI change in any client must include the corresponding updates to all other native clients and the TUI in the same change: shared SwiftUI (`kit/Sources/CodyncUI/`), iOS (`apps/ios/`), macOS (`apps/macos/`), Linux GTK (`apps/linux/src/`), and terminal UI (`host/src/tui/`). This applies in every direction; Linux and TUI changes must also be reflected in SwiftUI.
+- Keep shared features, actions, terminology, displayed information, and loading, empty, error, and permission states consistent. Adapt layout, controls, and input to each platform, including terminal keyboard interaction, while preserving the same user-facing behavior.
+- Inspect every client's corresponding implementation before finishing a UI task. Implement applicable changes together; do not silently defer another client. For a platform-only change or an unsupported capability, document which clients are unaffected and the concrete reason in the change summary.
+- Validate each affected client with its relevant build/tests and UI checks. Report any checks that could not run and why.
+
## Testing Guidelines
Use Swift Testing (`@Test`, `#expect`), Rust unit tests, and the relay’s Node assertion tests. Name tests after observable behavior. Add regression coverage for changed logic; no numeric coverage threshold is configured.
diff --git a/CLAUDE.md b/CLAUDE.md
index 66b5134b..c1dedc65 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -35,6 +35,13 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.
- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).
+## Cross-platform UI changes
+
+- Any UI change in any client must include the corresponding updates to all other native clients and the TUI in the same change: shared SwiftUI (`kit/Sources/CodyncUI/`), iOS (`apps/ios/`), macOS (`apps/macos/`), Linux GTK (`apps/linux/src/`), and terminal UI (`host/src/tui/`). This applies in every direction; Linux and TUI changes must also be reflected in SwiftUI.
+- Keep shared features, actions, terminology, displayed information, and loading, empty, error, and permission states consistent. Adapt layout, controls, and input to each platform, including terminal keyboard interaction, while preserving the same user-facing behavior.
+- Inspect every client's corresponding implementation before finishing a UI task. Implement applicable changes together; do not silently defer another client. For a platform-only change or an unsupported capability, document which clients are unaffected and the concrete reason in the change summary.
+- Validate each affected client with its relevant build/tests and UI checks. Report any checks that could not run and why.
+
## Codync 1.x does not exist for us
- Ignore everything from Codync 1.x (the Claude Code hooks + CloudKit session monitor): no migration, no compatibility shims, no cleanup of its files or hooks, no keeping old workers or App Store copy alive for it. Don't mention 1.x in code, docs or release notes.
@@ -70,7 +77,7 @@ Whenever you build and install/run a new build, stop the old copies so nothing s
- `apps/screen-linux/` — `codync-screen` (Rust, GStreamer + xdg portals), the Linux Remote screen helper; build/test in the same container as `apps/linux`
- `Widgets` (`apps/ios/Widgets/`) — usage widget + bot Live Activity (bundle id `com.pokai.Codync.ios.LiveActivity`)
- `CodyncKit` (`kit/`) — shared Swift package: `CodyncKit` + `CodyncUI` libraries
-- `apps/linux/` — `codync` GTK app (build/test in a container with libgtk-4-dev + libadwaita-1-dev)
+- `apps/linux/` — `codync` GTK app (build/test in a container with libgtk-4-dev + libadwaita-1-dev + libvte-2.91-gtk4-dev)
## Layout & naming
diff --git a/apps/linux/Cargo.lock b/apps/linux/Cargo.lock
index 4b81d333..7d51fb19 100644
--- a/apps/linux/Cargo.lock
+++ b/apps/linux/Cargo.lock
@@ -164,6 +164,7 @@ dependencies = [
"serde_json",
"tokio",
"uuid",
+ "vte4",
]
[[package]]
@@ -905,6 +906,12 @@ dependencies = [
"hashbrown",
]
+[[package]]
+name = "io-lifetimes"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
+
[[package]]
name = "ipnet"
version = "2.12.2"
@@ -1912,6 +1919,40 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
+[[package]]
+name = "vte4"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61732974d4915c5112a82506cdc86e19a83d786497c2c8bcd80d065825c695d"
+dependencies = [
+ "cairo-rs",
+ "gdk4",
+ "gio",
+ "glib",
+ "gtk4",
+ "io-lifetimes",
+ "libc",
+ "pango",
+ "vte4-sys",
+]
+
+[[package]]
+name = "vte4-sys"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd99766524f740945b1b3fc516dc2ee76311be2efa8d7a1238f35f04330b9afd"
+dependencies = [
+ "cairo-sys-rs",
+ "gdk4-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "gtk4-sys",
+ "libc",
+ "pango-sys",
+ "system-deps 7.0.8",
+]
+
[[package]]
name = "walkdir"
version = "2.5.0"
diff --git a/apps/linux/Cargo.toml b/apps/linux/Cargo.toml
index fd0744a2..7de7b101 100644
--- a/apps/linux/Cargo.toml
+++ b/apps/linux/Cargo.toml
@@ -20,3 +20,4 @@ serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "time", "process"] }
uuid = { version = "1", features = ["v4"] }
dirs = "7"
+vte = { package = "vte4", version = "0.10", features = ["v0_70"] }
diff --git a/apps/linux/src/client.rs b/apps/linux/src/client.rs
index 28e6bdfb..8f28e501 100644
--- a/apps/linux/src/client.rs
+++ b/apps/linux/src/client.rs
@@ -55,7 +55,20 @@ async fn call_async(method: String, body: Value) -> Result<Value, String> {
.post(format!("{}/api/{method}", base()))
.bearer_auth(token)
.json(&body)
- .timeout(Duration::from_secs(120))
+ .timeout(Duration::from_secs(
+ if matches!(
+ method.as_str(),
+ "agentAuth"
+ | "agentAuthenticate"
+ | "setAgentEnv"
+ | "installSkill"
+ | "installConnector"
+ ) {
+ 660
+ } else {
+ 120
+ },
+ ))
.send()
.await
.map_err(|_| "Can't reach the Codync host.".to_owned())?;
@@ -217,3 +230,138 @@ pub fn install_host(done: impl FnOnce(Result<(), String>) + 'static) {
pub fn empty() -> Value {
json!({})
}
+
+/// Save an attachment without overwriting an existing download or trusting a remote path.
+pub fn save_file(
+ bot: String,
+ id: String,
+ name: String,
+ done: impl FnOnce(Result<PathBuf, String>) + 'static,
+) {
+ let (tx, rx) = async_channel::bounded(1);
+ runtime().spawn(async move {
+ let result = async {
+ use tokio::io::AsyncWriteExt as _;
+ let dir = dirs::download_dir()
+ .or_else(dirs::home_dir)
+ .ok_or("No Downloads folder")?;
+ tokio::fs::create_dir_all(&dir)
+ .await
+ .map_err(|e| e.to_string())?;
+ let name = std::path::Path::new(&name)
+ .file_name()
+ .and_then(|n| n.to_str())
+ .filter(|n| !n.is_empty() && *n != "." && *n != "..")
+ .unwrap_or("attachment");
+ let mut suffix = 0;
+ let (path, mut file) = loop {
+ let path = dir.join(if suffix == 0 {
+ name.to_owned()
+ } else {
+ format!("{suffix}-{name}")
+ });
+ match tokio::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&path)
+ .await
+ {
+ Ok(file) => break (path, file),
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
+ Err(e) => return Err(e.to_string()),
+ }
+ };
+ let download = async {
+ let mut offset = 0_u64;
+ loop {
+ let v = call_async(
+ "readUpload".into(),
+ json!({"botId":bot,"uploadId":id,"offset":offset}),
+ )
+ .await?;
+ let chunk =
+ gtk::glib::base64_decode(v["data"].as_str().ok_or("Missing file data")?);
+ let size = v["size"].as_u64().ok_or("Missing file size")?;
+ if size > 100 * 1024 * 1024 || offset + chunk.len() as u64 > size {
+ return Err("Invalid attachment size".to_owned());
+ }
+ if chunk.is_empty() && offset < size {
+ return Err("Incomplete attachment".to_owned());
+ }
+ file.write_all(&chunk).await.map_err(|e| e.to_string())?;
+ offset += chunk.len() as u64;
+ if offset == size {
+ return Ok(());
+ }
+ }
+ }
+ .await;
+ drop(file);
+ if let Err(e) = download {
+ let _ = tokio::fs::remove_file(&path).await;
+ return Err(e);
+ }
+ Ok(path)
+ }
+ .await;
+ let _ = tx.send(result).await;
+ });
+ gtk::glib::spawn_future_local(async move {
+ if let Ok(r) = rx.recv().await {
+ done(r);
+ }
+ });
+}
+
+/// One ordered input queue and cancellable output stream for a host setup terminal.
+pub fn terminal(
+ id: String,
+ events: async_channel::Sender<Result<Value, String>>,
+) -> (async_channel::Sender<Vec<u8>>, tokio::task::AbortHandle) {
+ let (keys, input) = async_channel::unbounded::<Vec<u8>>();
+ let term = id.clone();
+ let errors = events.clone();
+ runtime().spawn(async move {
+ while let Ok(bytes) = input.recv().await {
+ let data = gtk::glib::base64_encode(&bytes).to_string();
+ if let Err(e) = call_async("termInput".into(), json!({"term":term,"data":data})).await {
+ let _ = errors.send(Err(e)).await;
+ }
+ }
+ });
+ let output = runtime().spawn(async move {
+ let read = async {
+ let token = token().ok_or("Host token is missing")?;
+ let response = http()
+ .get(format!("{}/term/{id}", base()))
+ .bearer_auth(token)
+ .send()
+ .await
+ .and_then(reqwest::Response::error_for_status)
+ .map_err(|e| e.to_string())?;
+ let mut stream = response.bytes_stream();
+ let mut buffer = Vec::new();
+ while let Some(chunk) = stream.next().await {
+ buffer.extend_from_slice(&chunk.map_err(|e| e.to_string())?);
+ while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
+ let line: Vec<_> = buffer.drain(..=end).collect();
+ let line = String::from_utf8_lossy(&line);
+ if let Some(data) = line.trim_end().strip_prefix("data:") {
+ let event: Value =
+ serde_json::from_str(data.trim()).map_err(|e| e.to_string())?;
+ let exited = event["type"] == "exit";
+ if events.send(Ok(event)).await.is_err() || exited {
+ return Ok(());
+ }
+ }
+ }
+ }
+ Err("Terminal disconnected. Close it and retry setup.".to_owned())
+ }
+ .await;
+ if let Err(e) = read {
+ let _ = events.send(Err(e)).await;
+ }
+ });
+ (keys, output.abort_handle())
+}
diff --git a/apps/linux/src/compose.rs b/apps/linux/src/compose.rs
index 1cde6e35..bedc9c86 100644
--- a/apps/linux/src/compose.rs
+++ b/apps/linux/src/compose.rs
@@ -2,10 +2,10 @@
//! new one, with Ctrl+1…9 shortcuts, and the message box underneath. Picked bots become chips;
//! one opens its chat, several start a group chat with them (or open the one they share).
+use crate::avatar;
use crate::client;
use crate::rows::{hline, icon_button, label};
use crate::ui::{self, App, flat_header};
-use crate::avatar;
use adw::prelude::*;
use serde_json::{Value, json};
use std::cell::{Cell, RefCell};
diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rs
index 48730c8e..fef2d620 100644
--- a/apps/linux/src/dialogs.rs
+++ b/apps/linux/src/dialogs.rs
@@ -785,21 +785,24 @@ fn text_area(view: &gtk::TextView, placeholder: &str, min: i32, max: i32) -> gtk
b
}
-fn confirm(
+pub fn confirm(
ui: &App,
title: &str,
body: &str,
action: &str,
destructive: bool,
- f: impl Fn() + 'static,
+ f: impl FnOnce() + 'static,
) {
+ let callback = std::cell::RefCell::new(Some(f));
let alert = adw::AlertDialog::new(Some(title), Some(body));
alert.add_responses(&[("cancel", "Cancel"), ("ok", action)]);
if destructive {
alert.set_response_appearance("ok", adw::ResponseAppearance::Destructive);
}
alert.connect_response(None, move |_, r| {
- if r == "ok" {
+ if r == "ok"
+ && let Some(f) = callback.borrow_mut().take()
+ {
f();
}
});
@@ -1106,6 +1109,25 @@ pub fn bot_menu(ui: &App, parent: &gtk::Widget, point: Option<(f64, f64)>, id: &
.divider(),
);
}
+ if !group {
+ for (icon, title, memory) in [
+ ("document-properties-symbolic", "Memory", true),
+ ("alarm-symbolic", "Routines", false),
+ ] {
+ let (ui2, id2) = (ui.clone(), id.to_owned());
+ items.push(MenuItem::new(
+ icon,
+ title,
+ Box::new(move || {
+ if memory {
+ crate::manage::memory(&ui2, &id2);
+ } else {
+ crate::manage::routines(&ui2, &id2);
+ }
+ }),
+ ));
+ }
+ }
if !group {
let (ui2, id2) = (ui.clone(), id.to_owned());
items.push(MenuItem::new(
@@ -1478,9 +1500,9 @@ pub fn settings(ui: &App) {
let ui2 = ui.clone();
button.connect_clicked(move |_| crate::connections::credentials(&ui2));
credentials.add(&button);
- let marketplace = gtk::Button::with_label("Connectors");
+ let marketplace = gtk::Button::with_label("Marketplace");
let ui2 = ui.clone();
- marketplace.connect_clicked(move |_| crate::connections::marketplace(&ui2));
+ marketplace.connect_clicked(move |_| crate::market::open(&ui2));
credentials.add(&marketplace);
page.add(&credentials);
let pair = adw::PreferencesGroup::builder()
diff --git a/apps/linux/src/main.rs b/apps/linux/src/main.rs
index bfb93985..e852cdb4 100644
--- a/apps/linux/src/main.rs
+++ b/apps/linux/src/main.rs
@@ -5,6 +5,8 @@ mod client;
mod compose;
mod connections;
mod dialogs;
+mod manage;
+mod market;
mod markup;
mod orb;
mod rows;
diff --git a/apps/linux/src/manage.rs b/apps/linux/src/manage.rs
new file mode 100644
index 00000000..47e9b0ec
--- /dev/null
+++ b/apps/linux/src/manage.rs
@@ -0,0 +1,599 @@
+//! Memory and routines use the same host-owned state and schedule validation as SwiftUI.
+use crate::{
+ client,
+ rows::{icon_button, label},
+ ui::{self, App, toast},
+};
+use adw::prelude::*;
+use serde_json::{Value, json};
+
+pub fn dialog(ui: &App, title: &str) -> (adw::Dialog, gtk::Box) {
+ let body = gtk::Box::builder()
+ .orientation(gtk::Orientation::Vertical)
+ .spacing(14)
+ .margin_top(20)
+ .margin_bottom(20)
+ .margin_start(20)
+ .margin_end(20)
+ .build();
+ let scroll = gtk::ScrolledWindow::builder()
+ .child(&body)
+ .vexpand(true)
+ .build();
+ let view = adw::ToolbarView::new();
+ view.add_top_bar(&adw::HeaderBar::new());
+ view.set_content(Some(&scroll));
+ let dialog = adw::Dialog::builder()
+ .title(title)
+ .content_width(620)
+ .content_height(650)
+ .child(&view)
+ .build();
+ dialog.present(Some(&ui.window));
+ (dialog, body)
+}
+
+pub fn memory(ui: &App, bot: &str) {
+ let (_, body) = dialog(ui, "Memory");
+ let refresh = icon_button("view-refresh-symbolic", "Refresh memory");
+ body.append(&refresh);
+ let list = gtk::Box::new(gtk::Orientation::Vertical, 12);
+ body.append(&list);
+ let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());
+ refresh.connect_clicked(move |_| load_memory(&ui2, &bot2, &list2));
+ load_memory(ui, bot, &list);
+}
+
+fn load_memory(ui: &App, bot: &str, list: &gtk::Box) {
+ ui::clear(list);
+ list.append(&label("Loading…", &["secondary"]));
+ let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());
+ client::call("memory", json!({"botId":bot}), move |r| {
+ ui::clear(&list);
+ let v = match r {
+ Ok(v) => v,
+ Err(e) => {
+ list.append(&label(&e, &["danger-text"]));
+ return;
+ }
+ };
+ let facts = v["facts"].as_array().cloned().unwrap_or_default();
+ if facts.is_empty() {
+ list.append(&label(
+ "Nothing yet. The bot remembers as you chat.",
+ &["secondary"],
+ ));
+ }
+ for fact in &facts {
+ let row = gtk::Box::new(gtk::Orientation::Horizontal, 10);
+ let text = label(fact["content"].as_str().unwrap_or(""), &[]);
+ text.set_wrap(true);
+ text.set_hexpand(true);
+ text.set_selectable(true);
+ row.append(&text);
+ let remove = icon_button("edit-delete-symbolic", "Forget");
+ row.append(&remove);
+ list.append(&row);
+ let (ui, bot, list, id) = (ui.clone(), bot.clone(), list.clone(), fact["id"].clone());
+ remove.connect_clicked(move |button| {
+ button.set_sensitive(false);
+ let (ui, bot, list) = (ui.clone(), bot.clone(), list.clone());
+ client::call("forgetMemory", json!({"botId":bot,"id":id}), move |r| {
+ if let Err(e) = r {
+ toast(&ui, &e);
+ }
+ load_memory(&ui, &bot, &list);
+ });
+ });
+ }
+ if !facts.is_empty() {
+ let clear = gtk::Button::with_label("Forget everything");
+ list.append(&clear);
+ let (ui, bot, list) = (ui.clone(), bot.clone(), list.clone());
+ clear.connect_clicked(move |_| {
+ let (ui2, bot, list) = (ui.clone(), bot.clone(), list.clone());
+ crate::dialogs::confirm(
+ &ui,
+ "Forget everything?",
+ "All remembered facts will be removed. Your chat stays.",
+ "Forget everything",
+ true,
+ move || {
+ client::call("clearMemory", json!({"botId":bot}), move |r| {
+ if let Err(e) = r {
+ toast(&ui2, &e);
+ }
+ load_memory(&ui2, &bot, &list);
+ });
+ },
+ );
+ });
+ }
+ });
+}
+
+pub fn routines(ui: &App, bot: &str) {
+ let (_, body) = dialog(ui, "Routines");
+ let actions = gtk::Box::new(gtk::Orientation::Horizontal, 8);
+ let add = icon_button("list-add-symbolic", "Set up a routine");
+ let refresh = icon_button("view-refresh-symbolic", "Refresh routines");
+ actions.append(&add);
+ actions.append(&refresh);
+ body.append(&actions);
+ let list = gtk::Box::new(gtk::Orientation::Vertical, 14);
+ body.append(&list);
+ let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());
+ add.connect_clicked(move |_| routine_editor(&ui2, &bot2, Value::Null, &list2));
+ let (ui2, bot2, list2) = (ui.clone(), bot.to_owned(), list.clone());
+ refresh.connect_clicked(move |_| load_routines(&ui2, &bot2, &list2));
+ load_routines(ui, bot, &list);
+}
+
+fn load_routines(ui: &App, bot: &str, list: &gtk::Box) {
+ ui::clear(list);
+ list.append(&label("Loading…", &["secondary"]));
+ let (ui, bot, list) = (ui.clone(), bot.to_owned(), list.clone());
+ client::call("routines", json!({"botId":bot}), move |r| {
+ ui::clear(&list);
+ let v = match r {
+ Ok(v) => v,
+ Err(e) => {
+ list.append(&label(&e, &["danger-text"]));
+ return;
+ }
+ };
+ let items = v["routines"].as_array().cloned().unwrap_or_default();
+ if items.is_empty() {
+ list.append(&label("No routines yet", &["secondary"]));
+ }
+ for item in items {
+ let card = gtk::Box::builder()
+ .orientation(gtk::Orientation::Vertical)
+ .spacing(8)
+ .css_classes(["details-box"])
+ .build();
+ card.append(&label(
+ item["name"].as_str().unwrap_or("Routine"),
+ &["headline"],
+ ));
+ let desc = item["triggerDescriptions"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ .collect::<Vec<_>>()
+ .join(" · ");
+ let text = label(
+ &format!(
+ "{} · {desc}",
+ if item["enabled"] == true {
+ "Enabled"
+ } else {
+ "Paused"
+ }
+ ),
+ &["secondary"],
+ );
+ text.set_wrap(true);
+ card.append(&text);
+ let instruction = label(item["instruction"].as_str().unwrap_or(""), &[]);
+ instruction.set_wrap(true);
+ card.append(&instruction);
+ if let Some(error) = item["lastError"].as_str() {
+ card.append(&label(error, &["danger-text"]));
+ }
+ if let Some(at) = item["nextRunAt"].as_i64() {
+ card.append(&label(
+ &format!("Next: {}", schedule_time(at)),
+ &["secondary"],
+ ));
+ }
+ let actions = gtk::Box::new(gtk::Orientation::Horizontal, 6);
+ card.append(&actions);
+ let edit = icon_button("document-edit-symbolic", "Edit routine");
+ actions.append(&edit);
+ let (ui2, bot2, item2, list2) = (ui.clone(), bot.clone(), item.clone(), list.clone());
+ edit.connect_clicked(move |_| routine_editor(&ui2, &bot2, item2.clone(), &list2));
+ for (icon, title, method) in [
+ ("media-playback-start-symbolic", "Test run", "runRoutine"),
+ (
+ "media-playback-pause-symbolic",
+ if item["enabled"] == true {
+ "Pause"
+ } else {
+ "Resume"
+ },
+ "setRoutineEnabled",
+ ),
+ ("user-trash-symbolic", "Delete routine", "deleteRoutine"),
+ ] {
+ let button = icon_button(icon, title);
+ actions.append(&button);
+ let active = v["runs"].as_array().into_iter().flatten().any(|run| {
+ run["routineId"] == item["id"]
+ && matches!(
+ run["status"].as_str(),
+ Some("pending" | "starting" | "running" | "recovering")
+ )
+ });
+ button.set_sensitive(method != "runRoutine" || !active);
+ let (ui, bot, item, list) = (ui.clone(), bot.clone(), item.clone(), list.clone());
+ button.connect_clicked(move |button| {
+ let (ui2, bot, list, item, button2) = (
+ ui.clone(),
+ bot.clone(),
+ list.clone(),
+ item.clone(),
+ button.clone(),
+ );
+ let run = move || {
+ button2.set_sensitive(false);
+ client::call(
+ method,
+ json!({"botId":bot,"id":item["id"],"enabled":item["enabled"] != true}),
+ move |r| {
+ if let Err(e) = r {
+ toast(&ui2, &e);
+ }
+ load_routines(&ui2, &bot, &list);
+ },
+ );
+ };
+ if method == "deleteRoutine" {
+ crate::dialogs::confirm(
+ &ui,
+ "Delete routine?",
+ "This stops future runs. Past messages stay.",
+ "Delete",
+ true,
+ run,
+ );
+ } else {
+ run();
+ }
+ });
+ }
+ if item["triggers"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")))
+ {
+ let copy = icon_button("edit-copy-symbolic", "Copy webhook URL and key");
+ actions.append(&copy);
+ let (ui, bot, id) = (ui.clone(), bot.clone(), item["id"].clone());
+ copy.connect_clicked(move |button| {
+ let (ui, button) = (ui.clone(), button.clone());
+ client::call(
+ "routineWebhook",
+ json!({"botId":bot,"id":id}),
+ move |r| match r {
+ Ok(v) => {
+ button.clipboard().set_text(&format!(
+ "{}\nAuthorization: Bearer {}",
+ v["url"].as_str().unwrap_or(""),
+ v["key"].as_str().unwrap_or("")
+ ));
+ toast(&ui, "Copied webhook URL and key");
+ }
+ Err(e) => toast(&ui, &e),
+ },
+ );
+ });
+ }
+ for run in v["runs"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|r| r["routineId"] == item["id"])
+ .take(10)
+ {
+ let text = format!(
+ "{} · {}{}",
+ schedule_time(run["createdAt"].as_i64().unwrap_or(0)),
+ run["status"].as_str().unwrap_or(""),
+ run["error"]
+ .as_str()
+ .map(|e| format!(" · {e}"))
+ .unwrap_or_default()
+ );
+ let text = label(&text, &["small", "secondary"]);
+ text.set_wrap(true);
+ card.append(&text);
+ }
+ list.append(&card);
+ }
+ });
+}
+
+fn schedule_time(at: i64) -> String {
+ gtk::glib::DateTime::from_unix_local(at / 1000)
+ .ok()
+ .and_then(|date| date.format("%b %e, %Y · %H:%M %Z").ok())
+ .map(|s| s.to_string())
+ .unwrap_or_default()
+}
+
+fn entry(body: &gtk::Box, title: &str, value: &str) -> gtk::Entry {
+ let group = gtk::Box::new(gtk::Orientation::Vertical, 6);
+ group.append(&label(title, &["secondary"]));
+ let field = gtk::Entry::builder().text(value).build();
+ group.append(&field);
+ body.append(&group);
+ field
+}
+
+fn routine_editor(ui: &App, bot: &str, routine: Value, list: &gtk::Box) {
+ let (window, body) = dialog(
+ ui,
+ if routine.is_null() {
+ "Set up a routine"
+ } else {
+ "Edit routine"
+ },
+ );
+ let name = entry(&body, "Name", routine["name"].as_str().unwrap_or(""));
+ body.append(&label("Instruction", &["secondary"]));
+ let instruction = gtk::TextView::builder()
+ .wrap_mode(gtk::WrapMode::WordChar)
+ .height_request(100)
+ .build();
+ instruction
+ .buffer()
+ .set_text(routine["instruction"].as_str().unwrap_or(""));
+ let scroll = gtk::ScrolledWindow::builder()
+ .child(&instruction)
+ .hscrollbar_policy(gtk::PolicyType::Never)
+ .min_content_height(80)
+ .max_content_height(120)
+ .propagate_natural_height(true)
+ .vexpand(false)
+ .build();
+ body.append(&scroll);
+ let kinds = if routine.is_null() {
+ vec!["daily", "weekly", "monthly", "custom", "once", "webhook"]
+ } else {
+ vec![
+ "keep", "daily", "weekly", "monthly", "custom", "once", "webhook",
+ ]
+ };
+ body.append(&label("Schedule", &["secondary"]));
+ let labels: Vec<&str> = kinds
+ .iter()
+ .map(|k| match *k {
+ "keep" => "Keep existing triggers",
+ "daily" => "Daily",
+ "weekly" => "Weekly",
+ "monthly" => "Monthly",
+ "custom" => "Custom cron",
+ "once" => "Run once",
+ _ => "Webhook",
+ })
+ .collect();
+ let kind = gtk::DropDown::from_strings(&labels);
+ body.append(&kind);
+ let hour = entry(&body, "Hour (0–23)", "9");
+ let minute = entry(&body, "Minute (0–59)", "0");
+ let day = entry(
+ &body,
+ "Weekly: weekday (0 = Sunday); monthly: day (1–31)",
+ "1",
+ );
+ let zone_name = gtk::glib::TimeZone::local().identifier().to_string();
+ let zone = entry(&body, "Time zone", &zone_name);
+ let expression = entry(
+ &body,
+ "Custom cron (minute hour day month weekday)",
+ "0 9 * * *",
+ );
+ let once = entry(
+ &body,
+ "Run once: date and time (ISO 8601, include time zone)",
+ "",
+ );
+ let existing = label(
+ &routine["triggerDescriptions"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ .collect::<Vec<_>>()
+ .join(" · "),
+ &["secondary"],
+ );
+ existing.set_wrap(true);
+ body.append(&existing);
+ let update_fields = {
+ let (kinds, hour, minute, day, zone, expression, once, existing) = (
+ kinds.clone(),
+ hour.clone(),
+ minute.clone(),
+ day.clone(),
+ zone.clone(),
+ expression.clone(),
+ once.clone(),
+ existing.clone(),
+ );
+ move |kind: &gtk::DropDown| {
+ let style = kinds[kind.selected() as usize];
+ for (field, visible) in [
+ (&hour, matches!(style, "daily" | "weekly" | "monthly")),
+ (&minute, matches!(style, "daily" | "weekly" | "monthly")),
+ (&day, matches!(style, "weekly" | "monthly")),
+ (
+ &zone,
+ matches!(style, "daily" | "weekly" | "monthly" | "custom"),
+ ),
+ (&expression, style == "custom"),
+ (&once, style == "once"),
+ ] {
+ if let Some(group) = field.parent() {
+ group.set_visible(visible);
+ }
+ }
+ existing.set_visible(style == "keep");
+ }
+ };
+ update_fields(&kind);
+ kind.connect_selected_notify(update_fields);
+ let timeout = entry(
+ &body,
+ "Run timeout (seconds)",
+ &routine["timeoutSeconds"]
+ .as_i64()
+ .unwrap_or(3600)
+ .to_string(),
+ );
+ let status = label("", &["secondary"]);
+ status.set_wrap(true);
+ body.append(&status);
+ let actions = gtk::Box::builder()
+ .orientation(gtk::Orientation::Horizontal)
+ .spacing(8)
+ .margin_top(12)
+ .margin_bottom(12)
+ .margin_start(20)
+ .margin_end(20)
+ .build();
+ if let Some(view) = window
+ .child()
+ .and_then(|w| w.downcast::<adw::ToolbarView>().ok())
+ {
+ view.add_bottom_bar(&actions);
+ }
+ for (title, save) in [("Preview schedule", false), ("Save", true)] {
+ let button = gtk::Button::with_label(title);
+ actions.append(&button);
+ let (
+ ui,
+ bot,
+ routine,
+ list,
+ window,
+ name,
+ instruction,
+ kind,
+ kinds,
+ hour,
+ minute,
+ day,
+ zone,
+ expression,
+ once,
+ timeout,
+ status,
+ ) = (
+ ui.clone(),
+ bot.to_owned(),
+ routine.clone(),
+ list.clone(),
+ window.clone(),
+ name.clone(),
+ instruction.clone(),
+ kind.clone(),
+ kinds.clone(),
+ hour.clone(),
+ minute.clone(),
+ day.clone(),
+ zone.clone(),
+ expression.clone(),
+ once.clone(),
+ timeout.clone(),
+ status.clone(),
+ );
+ button.connect_clicked(move |button| {
+ let style = kinds[kind.selected() as usize];
+ let draft = schedule_draft(style, &hour.text(), &minute.text(), &day.text(), &zone.text(), &expression.text(), &once.text(), &routine["triggers"]);
+ let draft = match draft { Ok(d) => d, Err(e) => { status.set_label(&e); return; } };
+ let buffer = instruction.buffer();
+ let text = buffer.text(&buffer.start_iter(), &buffer.end_iter(), false).to_string();
+ let timeout = match timeout.text().parse::<u64>() { Ok(v) if (1..=86400).contains(&v) => v, _ => { status.set_label("Timeout must be between 1 and 86400 seconds."); return; } };
+ if save && (name.text().trim().is_empty() || text.trim().is_empty()) { status.set_label("Enter a name and instruction."); return; }
+ button.set_sensitive(false);
+ let mut args = json!({"draft":draft});
+ if save { args = json!({"botId":bot,"name":name.text().as_str(),"instruction":text,"schedule":draft,"timeoutSeconds":timeout}); if !routine.is_null() { args["id"] = routine["id"].clone(); } }
+ let (ui, bot, list, window, status, button) = (ui.clone(), bot.clone(), list.clone(), window.clone(), status.clone(), button.clone());
+ client::call(if save { "saveRoutine" } else { "routineSchedule" }, args, move |r| {
+ button.set_sensitive(true);
+ match r {
+ Ok(v) if save => { let _ = v; window.close(); load_routines(&ui, &bot, &list); }
+ Ok(v) => status.set_label(&format!("{}{}{}", v["summary"].as_str().unwrap_or(""),
+ v["nextRunAt"].as_i64().map(|at| format!("\nNext: {}", schedule_time(at))).unwrap_or_default(),
+ v["warning"].as_str().map(|w| format!("\n{w}")).unwrap_or_default())),
+ Err(e) => status.set_label(&e),
+ }
+ });
+ });
+ }
+}
+
+#[allow(clippy::too_many_arguments)]
+fn schedule_draft(
+ style: &str,
+ hour: &str,
+ minute: &str,
+ day: &str,
+ zone: &str,
+ expression: &str,
+ once: &str,
+ original: &Value,
+) -> Result<Value, String> {
+ let mut draft = json!({"kind": if matches!(style, "keep" | "once" | "webhook") { style } else { "cron" }, "zone":zone,"original":original.as_array().cloned().unwrap_or_default()});
+ if draft["kind"] == "cron" {
+ draft["calendarStyle"] = style.into();
+ draft["expression"] = expression.into();
+ if style != "custom" {
+ draft["hour"] = hour.parse::<u8>().map_err(|_| "Enter a valid hour")?.into();
+ draft["minute"] = minute
+ .parse::<u8>()
+ .map_err(|_| "Enter a valid minute")?
+ .into();
+ if style == "weekly" {
+ draft["weekday"] = day
+ .parse::<u8>()
+ .map_err(|_| "Enter a weekday from 0 to 6")?
+ .into();
+ }
+ if style == "monthly" {
+ draft["monthDay"] = day
+ .parse::<u8>()
+ .map_err(|_| "Enter a day from 1 to 31")?
+ .into();
+ }
+ }
+ } else if style == "once" {
+ let date = gtk::glib::DateTime::from_iso8601(once, None)
+ .map_err(|_| "Enter an ISO 8601 date with a time zone")?;
+ draft["at"] = (date.to_unix() * 1000).into();
+ }
+ Ok(draft)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ #[test]
+ fn edits_preserve_existing_event_triggers() {
+ let original = json!([{"type":"event","source":"github","event":"pull_request.opened","filters":{"repo":"a/b"}}]);
+ let draft = schedule_draft("keep", "", "", "", "Asia/Taipei", "", "", &original).unwrap();
+ assert_eq!(draft["original"], original);
+ assert_eq!(draft["kind"], "keep");
+ }
+ #[test]
+ fn once_requires_a_date_and_weekly_carries_the_selected_zone() {
+ assert!(schedule_draft("once", "", "", "", "UTC", "", "bad", &Value::Null).is_err());
+ let draft = schedule_draft(
+ "weekly",
+ "14",
+ "20",
+ "0",
+ "Asia/Taipei",
+ "",
+ "",
+ &Value::Null,
+ )
+ .unwrap();
+ assert_eq!(draft["weekday"], 0);
+ assert_eq!(draft["zone"], "Asia/Taipei");
+ }
+}
diff --git a/apps/linux/src/market.rs b/apps/linux/src/market.rs
new file mode 100644
index 00000000..a4f37d6b
--- /dev/null
+++ b/apps/linux/src/market.rs
@@ -0,0 +1,428 @@
+//! Agent setup and skill management alongside the connector registry.
+use crate::{
+ client,
+ manage::dialog,
+ rows::{icon_button, label},
+ ui::{self, App, toast},
+};
+use adw::prelude::*;
+use serde_json::{Value, json};
+use std::{cell::RefCell, rc::Rc};
+use vte::prelude::*;
+
+pub fn open(ui: &App) {
+ let (_, body) = dialog(ui, "Marketplace");
+ let connectors = gtk::Button::with_label("Connectors");
+ body.append(&connectors);
+ let ui2 = ui.clone();
+ connectors.connect_clicked(move |_| crate::connections::marketplace(&ui2));
+ let credentials = gtk::Button::with_label("Credentials");
+ body.append(&credentials);
+ let ui2 = ui.clone();
+ credentials.connect_clicked(move |_| crate::connections::credentials(&ui2));
+ body.append(&label("Agents", &["headline"]));
+ let agents = gtk::Box::new(gtk::Orientation::Vertical, 8);
+ body.append(&agents);
+ let ui2 = ui.clone();
+ client::call("refreshBackends", json!({}), move |r| match r {
+ Ok(v) => {
+ ui2.state.borrow_mut().hello["backends"] = v["backends"].clone();
+ for backend in v["backends"].as_array().into_iter().flatten().filter(|b| {
+ b["available"] == true || b["installed"] == true || b["curated"] == true
+ }) {
+ let button = gtk::Button::with_label(backend["name"].as_str().unwrap_or("Agent"));
+ agents.append(&button);
+ let (ui, backend) = (ui2.clone(), backend.clone());
+ button.connect_clicked(move |_| agent(&ui, &backend));
+ }
+ }
+ Err(e) => agents.append(&label(&e, &["danger-text"])),
+ });
+ body.append(&label("Skills", &["headline"]));
+ let search = gtk::SearchEntry::new();
+ body.append(&search);
+ let list = gtk::Box::new(gtk::Orientation::Vertical, 8);
+ body.append(&list);
+ let refresh = icon_button("view-refresh-symbolic", "Refresh skills");
+ body.append(&refresh);
+ let (ui2, list2, search2) = (ui.clone(), list.clone(), search.clone());
+ refresh.connect_clicked(move |_| skills(&ui2, &list2, &search2.text()));
+ let (ui2, list2) = (ui.clone(), list.clone());
+ search.connect_activate(move |s| skills(&ui2, &list2, &s.text()));
+ skills(ui, &list, "");
+}
+
+fn skills(ui: &App, list: &gtk::Box, query: &str) {
+ ui::clear(list);
+ list.append(&label("Loading…", &["secondary"]));
+ let (ui, list, query) = (ui.clone(), list.clone(), query.to_lowercase());
+ client::call("skills", json!({}), move |r| {
+ ui::clear(&list);
+ let installed = match r {
+ Ok(v) => v["items"].as_array().cloned().unwrap_or_default(),
+ Err(e) => {
+ list.append(&label(&e, &["danger-text"]));
+ return;
+ }
+ };
+ for item in &installed {
+ let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);
+ let text = label(item["name"].as_str().unwrap_or("Skill"), &[]);
+ text.set_hexpand(true);
+ row.append(&text);
+ let remove = icon_button("user-trash-symbolic", "Remove skill");
+ row.append(&remove);
+ list.append(&row);
+ let (ui, list, id, query) =
+ (ui.clone(), list.clone(), item["id"].clone(), query.clone());
+ remove.connect_clicked(move |_| {
+ let (ui2, list, id, query) = (ui.clone(), list.clone(), id.clone(), query.clone());
+ crate::dialogs::confirm(
+ &ui,
+ "Remove skill?",
+ "Bots will no longer have this skill.",
+ "Remove",
+ true,
+ move || {
+ client::call("removeSkill", json!({"id":id}), move |r| {
+ if let Err(e) = r {
+ toast(&ui2, &e);
+ }
+ skills(&ui2, &list, &query);
+ });
+ },
+ );
+ });
+ }
+ client::call("marketSkills", json!({}), move |r| match r {
+ Ok(v) => {
+ let items: Vec<_> = v["items"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|i| {
+ format!("{} {}", i["name"], i["description"])
+ .to_lowercase()
+ .contains(&query)
+ })
+ .collect();
+ if items.is_empty() {
+ list.append(&label("No matching skills", &["secondary"]));
+ }
+ for item in items {
+ let row = gtk::Box::new(gtk::Orientation::Horizontal, 8);
+ let text = label(
+ &format!(
+ "{}\n{}",
+ item["name"].as_str().unwrap_or("Skill"),
+ item["description"].as_str().unwrap_or("")
+ ),
+ &[],
+ );
+ text.set_wrap(true);
+ text.set_hexpand(true);
+ row.append(&text);
+ let added = item["installed"] == true
+ || installed
+ .iter()
+ .any(|s| s["source"] == item["source"] && s["source"].is_string());
+ let add = gtk::Button::with_label(if added { "Added" } else { "Add" });
+ add.set_sensitive(!added);
+ row.append(&add);
+ list.append(&row);
+ let (ui, list, source, query) = (
+ ui.clone(),
+ list.clone(),
+ item["source"].clone(),
+ query.clone(),
+ );
+ add.connect_clicked(move |button| {
+ button.set_sensitive(false);
+ let (ui, list, query) = (ui.clone(), list.clone(), query.clone());
+ client::call("installSkill", json!({"source":source}), move |r| {
+ if let Err(e) = r {
+ toast(&ui, &e);
+ }
+ skills(&ui, &list, &query);
+ });
+ });
+ }
+ }
+ Err(e) => list.append(&label(&e, &["danger-text"])),
+ });
+ });
+}
+
+pub fn agent(ui: &App, backend: &Value) {
+ let (_, body) = dialog(ui, backend["name"].as_str().unwrap_or("Agent"));
+ let id = backend["id"].as_str().unwrap_or("").to_owned();
+ if backend["installed"] != true && backend["canInstall"] == true {
+ let install = gtk::Button::with_label("Install");
+ body.append(&install);
+ let (ui, id) = (ui.clone(), id.clone());
+ install.connect_clicked(move |_| setup(&ui, &id, "install", None));
+ }
+ let check = gtk::Button::with_label("Check sign-in");
+ body.append(&check);
+ let auth = gtk::Box::new(gtk::Orientation::Vertical, 10);
+ body.append(&auth);
+ let (ui2, id2, auth2) = (ui.clone(), id.clone(), auth.clone());
+ check.connect_clicked(move |_| load_auth(&ui2, &id2, &auth2));
+ if backend["installed"] == true || backend["available"] == true {
+ load_auth(ui, &id, &auth);
+ }
+}
+
+fn load_auth(ui: &App, id: &str, body: &gtk::Box) {
+ ui::clear(body);
+ body.append(&label("Checking sign-in…", &["secondary"]));
+ let (ui, id, body) = (ui.clone(), id.to_owned(), body.clone());
+ client::call("agentAuth", json!({"backend":id}), move |r| {
+ ui::clear(&body);
+ let v = match r {
+ Ok(v) => v,
+ Err(e) => {
+ body.append(&label(&e, &["danger-text"]));
+ return;
+ }
+ };
+ let status = label(
+ if v["signedIn"] == true {
+ "Signed in"
+ } else {
+ "Sign-in required"
+ },
+ &["headline"],
+ );
+ body.append(&status);
+ if let Some(detail) = v["detail"].as_str() {
+ let text = label(detail, &[]);
+ text.set_wrap(true);
+ body.append(&text);
+ }
+ if v["login"] == true {
+ let login = gtk::Button::with_label("Sign in in terminal");
+ body.append(&login);
+ let (ui, id) = (ui.clone(), id.clone());
+ login.connect_clicked(move |_| setup(&ui, &id, "login", None));
+ }
+ for method in v["methods"].as_array().into_iter().flatten() {
+ let button = gtk::Button::with_label(method["name"].as_str().unwrap_or("Sign in"));
+ body.append(&button);
+ let (ui, id, method, body) = (ui.clone(), id.clone(), method.clone(), body.clone());
+ button.connect_clicked(move |button| match method["kind"].as_str() {
+ Some("terminal") => setup(&ui, &id, "login", method["id"].as_str()),
+ Some("envVar") => env_fields(&ui, &id, &method, &body),
+ _ => {
+ button.set_sensitive(false);
+ let (ui, id, body) = (ui.clone(), id.clone(), body.clone());
+ client::call(
+ "agentAuthenticate",
+ json!({"backend":id,"method":method["id"]}),
+ move |r| {
+ if let Err(e) = r {
+ toast(&ui, &e);
+ }
+ load_auth(&ui, &id, &body);
+ },
+ );
+ }
+ });
+ }
+ });
+}
+
+fn env_fields(ui: &App, id: &str, method: &Value, auth: &gtk::Box) {
+ let (window, body) = dialog(ui, "Sign in with credentials");
+ let mut fields = vec![];
+ for var in method["vars"].as_array().into_iter().flatten() {
+ body.append(&label(
+ var["label"].as_str().unwrap_or("Credential"),
+ &["secondary"],
+ ));
+ let entry = gtk::Entry::builder()
+ .visibility(var["secret"] == false)
+ .build();
+ body.append(&entry);
+ fields.push((
+ var["name"].as_str().unwrap_or("").to_owned(),
+ var["optional"] != true,
+ entry,
+ ));
+ }
+ let error = label("", &["danger-text"]);
+ body.append(&error);
+ let save = gtk::Button::with_label("Save and sign in");
+ body.append(&save);
+ let (ui, id, auth) = (ui.clone(), id.to_owned(), auth.clone());
+ save.connect_clicked(move |button| {
+ if fields
+ .iter()
+ .any(|(_, required, e)| *required && e.text().is_empty())
+ {
+ error.set_label("Fill in the required credentials.");
+ return;
+ }
+ let vars: serde_json::Map<String, Value> = fields
+ .iter()
+ .filter(|(_, _, e)| !e.text().is_empty())
+ .map(|(k, _, e)| (k.clone(), e.text().to_string().into()))
+ .collect();
+ button.set_sensitive(false);
+ let (ui, id, auth, window, fields, error, button) = (
+ ui.clone(),
+ id.clone(),
+ auth.clone(),
+ window.clone(),
+ fields.clone(),
+ error.clone(),
+ button.clone(),
+ );
+ client::call("setAgentEnv", json!({"backend":id,"vars":vars}), move |r| {
+ button.set_sensitive(true);
+ match r {
+ Ok(_) => {
+ for (_, _, e) in fields {
+ e.set_text("");
+ }
+ window.close();
+ load_auth(&ui, &id, &auth);
+ }
+ Err(e) => error.set_label(&e),
+ }
+ });
+ });
+}
+
+fn setup(ui: &App, backend: &str, step: &str, method: Option<&str>) {
+ let (window, body) = dialog(
+ ui,
+ if step == "install" {
+ "Install agent"
+ } else {
+ "Sign in"
+ },
+ );
+ window.set_content_width(900);
+ window.set_content_height(650);
+ let terminal = vte::Terminal::new();
+ terminal.set_vexpand(true);
+ terminal.set_hexpand(true);
+ terminal.set_size(90, 28);
+ terminal.set_input_enabled(false);
+ terminal.set_allow_hyperlink(true);
+ // Only a user gesture opens URLs printed by the agent.
+ const PCRE2_MULTILINE: u32 = 0x0000_0400;
+ if let Ok(regex) = vte::Regex::for_match(r#"https?://[^\s<>\"']+"#, PCRE2_MULTILINE) {
+ terminal.match_add_regex(&regex, 0);
+ }
+ let click = gtk::GestureClick::new();
+ let terminal_link = terminal.downgrade();
+ click.connect_pressed(move |gesture, _, x, y| {
+ if !gesture
+ .current_event_state()
+ .contains(gtk::gdk::ModifierType::CONTROL_MASK)
+ {
+ return;
+ }
+ if let Some(terminal) = terminal_link.upgrade()
+ && let Some(url) = terminal
+ .check_hyperlink_at(x, y)
+ .or_else(|| terminal.check_match_at(x, y).0)
+ && (url.starts_with("https://") || url.starts_with("http://"))
+ {
+ let _ = gtk::gio::AppInfo::launch_default_for_uri(
+ &url,
+ None::<&gtk::gio::AppLaunchContext>,
+ );
+ }
+ });
+ terminal.add_controller(click);
+ body.append(&terminal);
+ let status = label("Starting…", &["secondary"]);
+ body.append(&status);
+ let state = Rc::new(RefCell::new(
+ None::<(
+ String,
+ async_channel::Sender<Vec<u8>>,
+ tokio::task::AbortHandle,
+ )>,
+ ));
+ let closed = Rc::new(std::cell::Cell::new(false));
+ let state2 = state.clone();
+ let closed2 = closed.clone();
+ window.connect_closed(move |_| {
+ closed2.set(true);
+ if let Some((id, keys, output)) = state2.borrow_mut().take() {
+ keys.close();
+ output.abort();
+ client::call("termClose", json!({"term":id}), |_| {});
+ }
+ });
+ let state2 = state.clone();
+ terminal.connect_commit(move |_, text, _| {
+ if let Some((_, keys, _)) = &*state2.borrow() {
+ let _ = keys.try_send(text.as_bytes().to_vec());
+ }
+ });
+ let state2 = state.clone();
+ let last_size = RefCell::new((0, 0));
+ terminal.add_tick_callback(move |t, _| {
+ if let Some((id, _, _)) = &*state2.borrow() {
+ let size = (t.column_count(), t.row_count());
+ if *last_size.borrow() != size {
+ *last_size.borrow_mut() = size;
+ client::call(
+ "termResize",
+ json!({"term":id,"cols":size.0,"rows":size.1}),
+ |_| {},
+ );
+ }
+ }
+ gtk::glib::ControlFlow::Continue
+ });
+ let args = json!({"backend":backend,"step":step,"method":method,"cols":90,"rows":28});
+ client::call("agentSetup", args, move |r| {
+ let id = match r {
+ Ok(v) => v["term"].as_str().unwrap_or("").to_owned(),
+ Err(e) => {
+ status.set_label(&e);
+ return;
+ }
+ };
+ if closed.get() {
+ client::call("termClose", json!({"term":id}), |_| {});
+ return;
+ }
+ let (tx, rx) = async_channel::unbounded();
+ let (keys, output) = client::terminal(id.clone(), tx);
+ *state.borrow_mut() = Some((id, keys, output));
+ terminal.set_input_enabled(true);
+ terminal.grab_focus();
+ status.set_label("Running on your computer · Ctrl+click opens a link");
+ gtk::glib::spawn_future_local(async move {
+ while let Ok(event) = rx.recv().await {
+ match event {
+ Ok(v) if v["type"] == "output" => {
+ terminal.feed(&gtk::glib::base64_decode(v["data"].as_str().unwrap_or("")))
+ }
+ Ok(v) if v["type"] == "exit" => {
+ terminal.set_input_enabled(false);
+ status.set_label(if v["code"] == 0 {
+ "Finished"
+ } else {
+ "Ended with an error"
+ });
+ break;
+ }
+ Ok(_) => {}
+ Err(e) => {
+ terminal.set_input_enabled(false);
+ status.set_label(&e);
+ break;
+ }
+ }
+ }
+ });
+ });
+}
diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rs
index f41dcd97..54921cca 100644
--- a/apps/linux/src/rows.rs
+++ b/apps/linux/src/rows.rs
@@ -123,7 +123,7 @@ pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk:
.build();
let text = e["data"]["text"].as_str().unwrap_or("");
for a in e["data"]["attachments"].as_array().into_iter().flatten() {
- col.append(&file_card(a));
+ col.append(&file_card(r.ui, e, a));
}
if !text.is_empty() {
let b = bubble(text, false, "bubble-user");
@@ -142,6 +142,28 @@ pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk:
s.add_css_class("danger-text");
}
col.append(&s);
+ if e["data"]["status"] == "failed"
+ && let Some(nonce) = e["data"]["clientNonce"].as_str()
+ {
+ let actions = gtk::Box::new(gtk::Orientation::Horizontal, 6);
+ for (icon, title, retry) in [
+ ("view-refresh-symbolic", "Resend", true),
+ ("user-trash-symbolic", "Delete", false),
+ ] {
+ let button = icon_button(icon, title);
+ let (ui, nonce) = (r.ui.clone(), nonce.to_owned());
+ button.connect_clicked(move |_| {
+ if retry {
+ ui::retry(&ui, &nonce)
+ } else {
+ ui::discard(&ui, &nonce)
+ }
+ });
+ actions.append(&button);
+ }
+ col.append(&actions);
+ }
+ col.append(&reactions(r.ui, e));
col.upcast()
}
@@ -160,7 +182,7 @@ pub fn message_text(e: &Value) -> String {
}
/// A file sent with a message: its name and size.
-fn file_card(a: &Value) -> gtk::Widget {
+fn file_card(ui: &App, entry: &Value, a: &Value) -> gtk::Widget {
let card = gtk::Box::builder()
.spacing(8)
.halign(gtk::Align::End)
@@ -177,6 +199,27 @@ fn file_card(a: &Value) -> gtk::Widget {
size.set_xalign(0.0);
col.append(&size);
card.append(&col);
+ if let (Some(id), Some(bot)) = (a["id"].as_str(), entry["botId"].as_str()) {
+ let save = icon_button("document-save-symbolic", "Save attachment");
+ let (ui, id, bot, name) = (
+ ui.clone(),
+ id.to_owned(),
+ bot.to_owned(),
+ a["name"].as_str().unwrap_or("File").to_owned(),
+ );
+ save.connect_clicked(move |button| {
+ button.set_sensitive(false);
+ let (ui, button) = (ui.clone(), button.clone());
+ client::save_file(bot.clone(), id.clone(), name.clone(), move |result| {
+ button.set_sensitive(true);
+ match result {
+ Ok(path) => toast(&ui, &format!("Saved {}", path.display())),
+ Err(e) => toast(&ui, &e),
+ }
+ });
+ });
+ card.append(&save);
+ }
card.upcast()
}
@@ -209,9 +252,68 @@ pub fn agent_bubble(r: &Reply, st: &State, e: &Value, group: bool, start: bool)
let t = label(&clock(e["createdAt"].as_i64().unwrap_or(0)), &["time"]);
t.set_margin_start(12);
col.append(&t);
+ col.append(&reactions(r.ui, e));
col.upcast()
}
+fn reactions(ui: &App, entry: &Value) -> gtk::Box {
+ let row = gtk::Box::new(gtk::Orientation::Horizontal, 4);
+ if entry["id"]
+ .as_str()
+ .unwrap_or_default()
+ .starts_with("local-")
+ {
+ return row;
+ }
+ for emoji in entry["data"]["reactions"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ {
+ let button = gtk::Button::with_label(emoji);
+ button.set_tooltip_text(Some("Remove reaction"));
+ button.add_css_class("flat");
+ let (ui, id, emoji) = (ui.clone(), entry["id"].clone(), emoji.to_owned());
+ button.connect_clicked(move |button| {
+ button.set_sensitive(false);
+ let (ui, button) = (ui.clone(), button.clone());
+ client::call("react", json!({"entryId": id, "emoji": emoji}), move |r| {
+ button.set_sensitive(true);
+ if let Err(e) = r {
+ toast(&ui, &e);
+ }
+ });
+ });
+ row.append(&button);
+ }
+ let add = icon_button("face-smile-symbolic", "React");
+ let (ui, id) = (ui.clone(), entry["id"].clone());
+ add.connect_clicked(move |button| {
+ let items = ["👍", "❤️", "😂", "🎉", "👀", "✅"]
+ .into_iter()
+ .map(|emoji| {
+ let (ui, id) = (ui.clone(), id.clone());
+ ui::MenuItem::new(
+ "",
+ emoji,
+ Box::new(move || {
+ let ui = ui.clone();
+ client::call("react", json!({"entryId":id,"emoji":emoji}), move |r| {
+ if let Err(e) = r {
+ toast(&ui, &e);
+ }
+ });
+ }),
+ )
+ })
+ .collect();
+ ui::popup_menu(button, None, items);
+ });
+ row.append(&add);
+ row
+}
+
pub fn notice(e: &Value) -> gtk::Widget {
let mut text = e["data"]["text"].as_str().unwrap_or("").to_owned();
// A voice call from the phone: "Voice chat · 00:16".
diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rs
index d0413a7e..b50534f6 100644
--- a/apps/linux/src/ui.rs
+++ b/apps/linux/src/ui.rs
@@ -11,9 +11,17 @@ use crate::{avatar, compose, dialogs, orb};
use adw::prelude::*;
use serde_json::{Value, json};
use std::cell::{Cell, RefCell};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::rc::Rc;
+#[derive(Clone)]
+pub struct Outgoing {
+ pub bot: String,
+ pub text: String,
+ pub thread: Option<String>,
+ pub files: Vec<std::path::PathBuf>,
+}
+
#[derive(Default)]
pub struct State {
pub bots: HashMap<String, Value>,
@@ -31,6 +39,9 @@ pub struct State {
pub hide_details: bool,
pub search: String,
pub online: bool,
+ pub outbox: HashMap<String, Outgoing>,
+ history_busy: HashSet<String>,
+ history_done: HashSet<String>,
}
/// A message box: send, or stop while the chat (or thread) is working. In a group,
@@ -354,7 +365,7 @@ fn empty_page(ui_new: &gtk::Button) -> gtk::Box {
page
}
-pub fn build(app: &adw::Application) {
+pub fn build(app: &adw::Application) -> App {
let new_btn = icon_button("list-add-symbolic", "New chat (Ctrl+N)");
let search = gtk::SearchEntry::builder()
.placeholder_text("Search")
@@ -717,6 +728,7 @@ pub fn build(app: &adw::Application) {
ui.window.present();
connect(&ui);
+ ui
}
fn close_open_thread(ui: &App) {
@@ -1041,6 +1053,11 @@ fn notify(ui: &App, old: &Value, new: &Value) {
pub fn upsert(st: &mut State, e: Value) {
let bot = e["botId"].as_str().unwrap_or_default().to_owned();
+ if !e["id"].as_str().unwrap_or_default().starts_with("local-")
+ && let Some(nonce) = e["data"]["clientNonce"].as_str()
+ {
+ st.outbox.remove(nonce);
+ }
let list = st.entries.entry(bot).or_default();
let id = e["id"].as_str().unwrap_or_default();
if let Some(i) = list.iter().position(|x| x["id"] == id) {
@@ -1057,9 +1074,6 @@ pub fn upsert(st: &mut State, e: Value) {
}
list.push(e);
list.sort_by_key(|x| x["seq"].as_i64().unwrap_or(i64::MAX));
- if list.len() > 400 {
- list.drain(..list.len() - 400);
- }
}
/// Coalesces bursts of events into one render per frame.
@@ -1302,6 +1316,76 @@ fn is_chat(e: &Value) -> bool {
}
}
+fn visible_entries<'a>(entries: &[&'a Value], streaming: bool) -> Vec<&'a Value> {
+ let live = entries.last().filter(|e| {
+ streaming
+ && e["kind"] == "agent"
+ && e["data"]["final"] == false
+ && e["data"]["text"]
+ .as_str()
+ .is_some_and(|t| !t.is_empty() && t != "(pass)")
+ });
+ entries
+ .iter()
+ .copied()
+ .filter(|e| is_chat(e) || live.is_some_and(|l| l["id"] == e["id"]))
+ .collect()
+}
+
+fn load_older(ui: &App, bot: &str) {
+ let before = {
+ let mut st = ui.state.borrow_mut();
+ if !st.history_busy.insert(bot.to_owned()) {
+ return;
+ }
+ st.entries
+ .get(bot)
+ .into_iter()
+ .flatten()
+ .filter(|e| {
+ e["threadId"].is_null()
+ && !e["id"].as_str().unwrap_or_default().starts_with("local-")
+ })
+ .filter_map(|e| e["seq"].as_i64())
+ .min()
+ .unwrap_or(i64::MAX)
+ };
+ schedule(ui);
+ let (ui, bot) = (ui.clone(), bot.to_owned());
+ client::call(
+ "history",
+ json!({"botId": bot, "beforeSeq": before, "limit": 200}),
+ move |result| {
+ let adjust = ui.scroller.vadjustment();
+ let (height, position) = (adjust.upper(), adjust.value());
+ let mut st = ui.state.borrow_mut();
+ st.history_busy.remove(&bot);
+ match result {
+ Ok(v) => {
+ let entries = v["entries"].as_array().cloned().unwrap_or_default();
+ if entries.len() < 200 {
+ st.history_done.insert(bot.clone());
+ }
+ for entry in entries {
+ upsert(&mut st, entry);
+ }
+ }
+ Err(error) => toast(&ui, &error),
+ }
+ let selected = st.current.as_deref() == Some(bot.as_str());
+ drop(st);
+ render(&ui);
+ if selected {
+ gtk::glib::idle_add_local_once(move || {
+ if ui.state.borrow().current.as_deref() == Some(bot.as_str()) {
+ adjust.set_value(position + (adjust.upper() - height).max(0.0));
+ }
+ });
+ }
+ },
+ );
+}
+
pub fn clear(b: &gtk::Box) {
while let Some(c) = b.first_child() {
b.remove(&c);
@@ -1404,6 +1488,21 @@ fn render_chat(ui: &App) {
.get(id)
.map(|l| l.iter().filter(|e| e["threadId"].is_null()).collect())
.unwrap_or_default();
+ if !st.history_done.contains(id)
+ && entries
+ .iter()
+ .any(|e| e["seq"].as_i64().is_some_and(|n| n > 1 && n < i64::MAX))
+ {
+ let earlier = gtk::Button::with_label(if st.history_busy.contains(id) {
+ "Loading…"
+ } else {
+ "Load earlier messages"
+ });
+ earlier.set_sensitive(!st.history_busy.contains(id));
+ let (ui2, id) = (ui.clone(), id.to_owned());
+ earlier.connect_clicked(move |_| load_older(&ui2, &id));
+ ui.chat_list.append(&earlier);
+ }
if !entries.iter().any(|e| is_chat(e)) {
ui.chat_list.append(&intro(&st, bot));
}
@@ -1636,7 +1735,13 @@ fn append_entries(
let group = is_group(chat);
let mut last_author = String::new();
let mut last_time: Option<i64> = None;
- for e in entries.iter().filter(|e| is_chat(e)) {
+ let thread = if main {
+ None
+ } else {
+ st.open_thread.as_deref()
+ };
+ let streaming = st.online && working_in(chat, chat["id"].as_str().unwrap_or_default(), thread);
+ for e in visible_entries(entries, streaming) {
let at = e["createdAt"].as_i64().unwrap_or(0);
if main && last_time.is_none_or(|t| at - t > 3_600_000) {
let sep = label(&rows::separator(at), &["footnote", "tertiary"]);
@@ -1814,7 +1919,48 @@ pub fn send_text(
thread: Option<String>,
files: Vec<std::path::PathBuf>,
) {
- let nonce = uuid::Uuid::new_v4().to_string();
+ send_outgoing(
+ ui,
+ Outgoing {
+ bot: bot.to_owned(),
+ text: text.to_owned(),
+ thread,
+ files,
+ },
+ uuid::Uuid::new_v4().to_string(),
+ );
+}
+
+pub fn retry(ui: &App, nonce: &str) {
+ let outgoing = ui.state.borrow().outbox.get(nonce).cloned();
+ if let Some(outgoing) = outgoing {
+ send_outgoing(ui, outgoing, nonce.to_owned());
+ }
+}
+
+pub fn discard(ui: &App, nonce: &str) {
+ let mut st = ui.state.borrow_mut();
+ if let Some(outgoing) = st.outbox.remove(nonce)
+ && let Some(entries) = st.entries.get_mut(&outgoing.bot)
+ {
+ entries.retain(|e| e["id"] != format!("local-{nonce}"));
+ }
+ drop(st);
+ schedule(ui);
+}
+
+fn send_outgoing(ui: &App, outgoing: Outgoing, nonce: String) {
+ ui.state
+ .borrow_mut()
+ .outbox
+ .insert(nonce.clone(), outgoing.clone());
+ let Outgoing {
+ bot,
+ text,
+ thread,
+ files,
+ } = outgoing;
+
let attachments: Vec<Value> = files
.iter()
.map(|p| {
@@ -1993,6 +2139,70 @@ pub fn popup_menu(parent: &impl IsA<gtk::Widget>, point: Option<(f64, f64)>, ite
mod tests {
use super::mention_query;
+ #[test]
+ fn streaming_shows_only_the_active_last_segment() {
+ use super::*;
+ let old = json!({"id":"old","kind":"agent","data":{"text":"thinking","final":false}});
+ let final_reply = json!({"id":"final","kind":"agent","data":{"text":"done","final":true}});
+ let live = json!({"id":"live","kind":"agent","data":{"text":"new reply","final":false}});
+ let tool = json!({"id":"tool","kind":"tool"});
+ assert_eq!(
+ visible_entries(&[&old, &final_reply, &live], true),
+ [&final_reply, &live]
+ );
+ assert_eq!(
+ visible_entries(&[&old, &final_reply, &live], false),
+ [&final_reply]
+ );
+ assert_eq!(
+ visible_entries(&[&old, &final_reply, &live, &tool], true),
+ [&final_reply]
+ );
+ let pass = json!({"id":"pass","kind":"agent","data":{"text":"(pass)","final":false}});
+ assert!(visible_entries(&[&pass], true).is_empty());
+ }
+
+ #[test]
+ fn loading_history_retains_old_pages_and_newer_revisions() {
+ use super::*;
+ let mut state = State::default();
+ for seq in (1..=600).rev() {
+ upsert(
+ &mut state,
+ json!({"botId":"b","id":format!("e{seq}"),"seq":seq,"rev":10}),
+ );
+ }
+ upsert(&mut state, json!({"botId":"b","id":"e1","seq":1,"rev":1}));
+ assert_eq!(state.entries["b"].len(), 600);
+ assert_eq!(state.entries["b"][0]["rev"], 10);
+ }
+
+ #[test]
+ fn host_acknowledgement_replaces_failed_echo_and_releases_outbox() {
+ use super::*;
+ let mut state = State::default();
+ state.outbox.insert(
+ "nonce".into(),
+ Outgoing {
+ bot: "b".into(),
+ text: "hi".into(),
+ thread: None,
+ files: vec![],
+ },
+ );
+ upsert(
+ &mut state,
+ json!({"botId":"b","id":"local-nonce","seq":i64::MAX,"kind":"user","data":{"clientNonce":"nonce","status":"failed"}}),
+ );
+ upsert(
+ &mut state,
+ json!({"botId":"b","id":"server","seq":1,"kind":"user","data":{"clientNonce":"nonce"}}),
+ );
+ assert_eq!(state.entries["b"].len(), 1);
+ assert_eq!(state.entries["b"][0]["id"], "server");
+ assert!(state.outbox.is_empty());
+ }
+
#[test]
fn mentions() {
assert_eq!(mention_query("hi @al"), Some("al"));
@@ -2002,3 +2212,7 @@ mod tests {
assert_eq!(mention_query("@al\nnext"), None);
}
}
+
+#[cfg(test)]
+#[path = "ui_tests.rs"]
+mod ui_tests;
diff --git a/apps/linux/src/ui_tests.rs b/apps/linux/src/ui_tests.rs
new file mode 100644
index 00000000..6024dcc4
--- /dev/null
+++ b/apps/linux/src/ui_tests.rs
@@ -0,0 +1,273 @@
+//! Native widget integration tests, run under Xvfb with tests/ui_fixture.py.
+use super::*;
+use std::time::{Duration, Instant};
+
+#[track_caller]
+fn wait(mut ready: impl FnMut() -> bool) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ while gtk::glib::MainContext::default().pending() {
+ gtk::glib::MainContext::default().iteration(false);
+ }
+ if ready() {
+ return;
+ }
+ if Instant::now() >= deadline {
+ if let Ok(dir) = std::env::var("CODYNC_UI_ARTIFACTS") {
+ let _ = std::fs::create_dir_all(&dir);
+ let _ = std::process::Command::new("import")
+ .args(["-window", "root", &format!("{dir}/failure.png")])
+ .status();
+ }
+ panic!("native UI did not reach the expected state");
+ }
+ std::thread::sleep(Duration::from_millis(10));
+ }
+}
+fn widgets(root: &impl IsA<gtk::Widget>) -> Vec<gtk::Widget> {
+ let root = root.as_ref();
+ let mut result = vec![root.clone()];
+ let mut child = root.first_child();
+ while let Some(widget) = child {
+ result.extend(widgets(&widget));
+ child = widget.next_sibling();
+ }
+ result
+}
+fn button(root: &impl IsA<gtk::Widget>, name: &str) -> Option<gtk::Button> {
+ widgets(root)
+ .into_iter()
+ .filter_map(|w| w.downcast::<gtk::Button>().ok())
+ .find(|b| b.label().as_deref() == Some(name) || b.tooltip_text().as_deref() == Some(name))
+}
+fn text(root: &impl IsA<gtk::Widget>, value: &str) -> bool {
+ widgets(root)
+ .into_iter()
+ .filter_map(|w| w.downcast::<gtk::Label>().ok())
+ .any(|l| l.text().contains(value))
+}
+#[track_caller]
+fn click(root: &impl IsA<gtk::Widget>, name: &str) {
+ wait(|| button(root, name).is_some_and(|b| b.is_sensitive()));
+ let button = button(root, name).unwrap();
+ wait(|| button.is_mapped());
+ // libadwaita 1.5 opens a newly mapped dialog on its second frame.
+ // Emitting clicks before that can save and close a dialog before it opens.
+ let frames = Rc::new(std::cell::Cell::new(0));
+ let frames2 = frames.clone();
+ button.add_tick_callback(move |_, _| {
+ frames2.set(frames2.get() + 1);
+ if frames2.get() >= 3 {
+ gtk::glib::ControlFlow::Break
+ } else {
+ gtk::glib::ControlFlow::Continue
+ }
+ });
+ wait(|| frames.get() >= 3);
+ button.emit_clicked();
+}
+fn close(ui: &App) {
+ if let Some(dialog) = ui.window.visible_dialog() {
+ dialog.force_close();
+ wait(|| ui.window.visible_dialog().as_ref() != Some(&dialog));
+ }
+}
+fn screenshot(name: &str) {
+ if let Ok(dir) = std::env::var("CODYNC_UI_ARTIFACTS") {
+ let deadline = Instant::now() + Duration::from_millis(400);
+ wait(|| Instant::now() > deadline);
+ std::fs::create_dir_all(&dir).unwrap();
+ assert!(
+ std::process::Command::new("import")
+ .args(["-window", "root", &format!("{dir}/{name}.png")])
+ .status()
+ .unwrap()
+ .success()
+ );
+ }
+}
+fn requests() -> Value {
+ let result = Rc::new(RefCell::new(None));
+ let result2 = result.clone();
+ client::call("_testState", json!({}), move |r| {
+ *result2.borrow_mut() = Some(r.unwrap());
+ });
+ wait(|| result.borrow().is_some());
+ result.borrow_mut().take().unwrap()
+}
+
+#[test]
+#[ignore = "run under Xvfb using tests/ui_fixture.py"]
+fn native_ui_flows() {
+ assert_eq!(std::env::var("CODYNC_UI_TEST").as_deref(), Ok("1"));
+ adw::init().unwrap();
+ // Exercise actions after their dialog is ready, without racing presentation animations.
+ gtk::Settings::default()
+ .unwrap()
+ .set_gtk_enable_animations(false);
+ let app = adw::Application::builder()
+ .application_id("com.pokai.Codync.ParityTest")
+ .build();
+ app.register(None::<&gtk::gio::Cancellable>).unwrap();
+ let display = gtk::gdk::Display::default().unwrap();
+ let css = gtk::CssProvider::new();
+ css.load_from_string(&format!("{}\n{}", crate::colors(&crate::DARK), crate::CSS));
+ gtk::style_context_add_provider_for_display(
+ &display,
+ &css,
+ gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,
+ );
+ adw::StyleManager::default().set_color_scheme(adw::ColorScheme::ForceDark);
+ let ui = build(&app);
+ wait(|| {
+ ui.state
+ .borrow()
+ .entries
+ .get("bot")
+ .is_some_and(|e| e.len() == 2)
+ });
+ select(&ui, "bot");
+ wait(|| text(&ui.chat_list, "Streaming fixture answer"));
+ click(&ui.chat_list, "Load earlier messages");
+ wait(|| text(&ui.chat_list, "Older fixture message"));
+ assert!(text(&ui.chat_list, "Streaming fixture answer"));
+ screenshot("linux-chat-streaming");
+
+ send_text(&ui, "bot", "Retry this message", None, vec![]);
+ wait(|| text(&ui.chat_list, "Failed to send"));
+ click(&ui.chat_list, "Resend");
+ wait(|| ui.state.borrow().outbox.is_empty());
+ assert_eq!(
+ ui.state.borrow().entries["bot"]
+ .iter()
+ .filter(|e| e["data"]["text"] == "Retry this message")
+ .count(),
+ 1
+ );
+ let sent: Vec<_> = requests()["requests"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|r| r[0] == "send")
+ .cloned()
+ .collect();
+ assert_eq!(sent.len(), 2);
+ assert_eq!(sent[0][1]["clientNonce"], sent[1][1]["clientNonce"]);
+
+ click(&ui.chat_list, "Remove reaction");
+ wait(|| {
+ requests()["requests"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|r| r[0] == "react")
+ });
+ click(&ui.chat_list, "Save attachment");
+ wait(|| {
+ requests()["requests"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|r| r[0] == "readUpload")
+ });
+
+ let downloads = std::path::PathBuf::from(std::env::var("CODYNC_UI_DOWNLOADS").unwrap());
+ wait(|| std::fs::read(downloads.join("parity.txt")).ok().as_deref() == Some(b"fixture"));
+ click(&ui.chat_list, "Save attachment");
+ wait(|| {
+ std::fs::read(downloads.join("1-parity.txt"))
+ .ok()
+ .as_deref()
+ == Some(b"fixture")
+ });
+ assert_eq!(
+ std::fs::read(downloads.join("parity.txt")).unwrap(),
+ b"fixture"
+ );
+ send_text(&ui, "bot", "Discard this message", None, vec![]);
+ wait(|| text(&ui.chat_list, "Failed to send"));
+ click(&ui.chat_list, "Delete");
+ wait(|| !text(&ui.chat_list, "Discard this message"));
+
+ crate::manage::memory(&ui, "bot");
+ let memory = ui.window.visible_dialog().unwrap();
+ wait(|| text(&memory, "Prefers native interfaces"));
+ screenshot("linux-memory");
+ click(&memory, "Forget");
+ wait(|| text(&memory, "Nothing yet"));
+ close(&ui);
+
+ crate::manage::routines(&ui, "bot");
+ let routines = ui.window.visible_dialog().unwrap();
+ wait(|| text(&routines, "No routines yet"));
+ click(&routines, "Set up a routine");
+ let editor = ui.window.visible_dialog().unwrap();
+ let entries: Vec<_> = widgets(&editor)
+ .into_iter()
+ .filter_map(|w| w.downcast::<gtk::Entry>().ok())
+ .collect();
+ entries[0].set_text("Morning review");
+ let instruction = widgets(&editor)
+ .into_iter()
+ .find_map(|w| w.downcast::<gtk::TextView>().ok())
+ .unwrap();
+ instruction.buffer().set_text("Review the latest changes");
+ click(&editor, "Preview schedule");
+ wait(|| text(&editor, "Daily at 09:00 UTC"));
+ screenshot("linux-routine-editor");
+ click(&editor, "Save");
+ wait(|| text(&routines, "Morning review"));
+ click(&routines, "Pause");
+ wait(|| text(&routines, "Paused"));
+ screenshot("linux-routines");
+ close(&ui);
+
+ crate::market::open(&ui);
+ let market = ui.window.visible_dialog().unwrap();
+ wait(|| button(&market, "Add").is_some());
+ screenshot("linux-marketplace");
+ click(&market, "Add");
+ wait(|| button(&market, "Remove skill").is_some());
+ click(&market, "Fixture Agent");
+ let agent = ui.window.visible_dialog().unwrap();
+ click(&agent, "API key");
+ let credentials = ui.window.visible_dialog().unwrap();
+ let entry = widgets(&credentials)
+ .into_iter()
+ .find_map(|w| w.downcast::<gtk::Entry>().ok())
+ .unwrap();
+ assert!(!gtk::prelude::EntryExt::is_visible(&entry)); // GtkEditable visibility masks the credential.
+ entry.set_text("fixture-key");
+ click(&credentials, "Save and sign in");
+ wait(|| ui.window.visible_dialog().as_ref() == Some(&agent));
+ click(&agent, "Sign in in terminal");
+ let terminal = ui.window.visible_dialog().unwrap();
+ wait(|| text(&terminal, "Running on your computer"));
+ screenshot("linux-agent-terminal");
+ close(&ui);
+ close(&ui);
+ close(&ui);
+ let log = requests();
+ for method in [
+ "history",
+ "react",
+ "readUpload",
+ "forgetMemory",
+ "saveRoutine",
+ "setRoutineEnabled",
+ "installSkill",
+ "setAgentEnv",
+ "agentSetup",
+ "termClose",
+ ] {
+ assert!(
+ log["requests"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|r| r[0] == method),
+ "missing {method}"
+ );
+ }
+ ui.window.close();
+}
diff --git a/apps/linux/tests/ui_fixture.py b/apps/linux/tests/ui_fixture.py
new file mode 100644
index 00000000..c78d880f
--- /dev/null
+++ b/apps/linux/tests/ui_fixture.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+"""Run the native GTK regression test against a deterministic, isolated host API."""
+import base64
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+BOT = dict(id="bot", name="Parity bot", backend="fixture", description="UI regression fixture", cwd="/tmp/project", status="working", workingChat=None, workingThread=None, avatarColor="blue", avatarShape="blob", permission="ask", notify=True, unread=0, lastAt=1, lastMessage="Fixture", kind="bot", computer=True)
+BACKEND = dict(id="fixture", name="Fixture Agent", installed=True, available=True, curated=True, canInstall=True)
+ENTRIES = [dict(id="user", botId="bot", seq=201, rev=201, turn=1, kind="user", createdAt=1720000000000, threadId=None, data=dict(text="Read this attachment", attachments=[dict(id="file", name="parity.txt", size=7)], reactions=["👍"])), dict(id="live", botId="bot", seq=202, rev=202, turn=1, kind="agent", createdAt=1720000000001, threadId=None, data=dict(text="Streaming fixture answer", final=False))]
+
+class Host(BaseHTTPRequestHandler):
+ requests = []
+ facts = [dict(id="fact", content="Prefers native interfaces", kind="profile")]
+ routines = []
+ skills = []
+ attempts = {}
+ lock = threading.Lock()
+
+ def log_message(self, *_):
+ pass
+
+ def send_json(self, value, status=200):
+ body = json.dumps(value).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}")
+ method = self.path.rsplit("/", 1)[-1]
+ cls = type(self)
+ with cls.lock:
+ cls.requests.append([method, body])
+ if method == "_testState":
+ return self.send_json(dict(requests=cls.requests))
+ if method == "hello":
+ return self.send_json(dict(name="Fixture computer", home="/tmp", version="test", backends=[BACKEND]))
+ if method == "refreshBackends":
+ return self.send_json(dict(backends=[BACKEND]))
+ if method == "screenStatus":
+ return self.send_json(dict(enabled=True, connected=True))
+ if method == "history":
+ return self.send_json(dict(entries=[dict(id="older", botId="bot", seq=1, rev=1, turn=0, kind="user", createdAt=1710000000000, data=dict(text="Older fixture message"))]))
+ if method == "send":
+ nonce = body["clientNonce"]
+ cls.attempts[nonce] = cls.attempts.get(nonce, 0) + 1
+ if cls.attempts[nonce] == 1:
+ return self.send_json(dict(error="Fixture connection interrupted"), 503)
+ return self.send_json(dict(entry=dict(id="sent", botId=body["botId"], threadId=body.get("threadId"), seq=300, rev=300, turn=2, kind="user", createdAt=1720000000002, data=dict(text=body["text"], clientNonce=nonce, status="queued"))))
+ if method == "readUpload":
+ return self.send_json(dict(data=base64.b64encode(b"fixture").decode(), size=7))
+ if method == "memory":
+ return self.send_json(dict(facts=cls.facts, location="fixture"))
+ if method in ("forgetMemory", "clearMemory"):
+ cls.facts = []
+ if method == "routines":
+ return self.send_json(dict(routines=cls.routines, runs=[]))
+ if method == "saveRoutine":
+ assert body["schedule"]["kind"] == "cron"
+ assert body["timeoutSeconds"] == 3600
+ routine = dict(id="routine", name=body["name"], instruction=body["instruction"], enabled=True, triggers=[dict(type="cron", expression="0 9 * * *", timeZone="UTC")], triggerDescriptions=["Daily at 09:00 UTC"], nextRunAt=1820000000000)
+ cls.routines = [routine]
+ return self.send_json(routine)
+ if method == "routineSchedule":
+ return self.send_json(dict(summary="Daily at 09:00 UTC", nextRunAt=1820000000000))
+ if method == "setRoutineEnabled":
+ cls.routines[0]["enabled"] = body["enabled"]
+ cls.routines[0]["nextRunAt"] = 1820000000000 if body["enabled"] else None
+ if method == "deleteRoutine":
+ cls.routines = []
+ if method == "skills":
+ return self.send_json(dict(items=cls.skills))
+ if method == "marketSkills":
+ return self.send_json(dict(items=[dict(name="Review code", source="fixture/review", description="Review native UI changes")]))
+ if method == "installSkill":
+ cls.skills = [dict(id="skill", name="Review code", source=body["source"])]
+ if method == "removeSkill":
+ cls.skills = []
+ if method == "agentAuth":
+ return self.send_json(dict(signedIn=False, login=True, methods=[dict(id="env", name="API key", kind="envVar", vars=[dict(name="FIXTURE_KEY", label="API key", secret=True, optional=False)])]))
+ if method == "agentSetup":
+ return self.send_json(dict(term="fixture-terminal"))
+ if method == "setAgentEnv":
+ return self.send_json(dict(signedIn=True))
+ if method in ("connectors", "marketConnectors"):
+ return self.send_json(dict(items=[]))
+ self.send_json({})
+
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.end_headers()
+ try:
+ if self.path.startswith("/term/"):
+ events = [dict(type="output", data=base64.b64encode(b"\x1b[32mFixture terminal ready\x1b[0m\r\n").decode())]
+ else:
+ events = [dict(type="bot", rev=1, bot=BOT), dict(type="bot", rev=2, bot={**BOT, "id":"other", "name":"Other bot", "status":"idle"})] + [dict(type="entry", rev=e["rev"], entry=e) for e in ENTRIES]
+ for event in events:
+ self.wfile.write(("data: " + json.dumps(event) + "\n\n").encode())
+ self.wfile.flush()
+ while True:
+ time.sleep(0.5)
+ self.wfile.write(b": keepalive\n\n")
+ self.wfile.flush()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+if __name__ == "__main__":
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Host)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ with tempfile.TemporaryDirectory(prefix="codync-ui-fixture-") as directory:
+ pathlib.Path(directory, "token").write_text("fixture-token")
+ downloads = pathlib.Path(directory, "downloads")
+ downloads.mkdir()
+ config = pathlib.Path(directory, "config")
+ config.mkdir()
+ (config / "user-dirs.dirs").write_text(f'XDG_DOWNLOAD_DIR="{downloads}"\n')
+ env = {**os.environ, "XDG_CONFIG_HOME":str(config), "CODYNC_UI_DOWNLOADS":str(downloads), "CODYNC_HOME":directory, "CODYNC_URL":f"http://127.0.0.1:{server.server_port}", "CODYNC_UI_TEST":"1", "CODYNC_UI_ARTIFACTS":os.environ.get("CODYNC_UI_ARTIFACTS", directory)}
+ try:
+ result = subprocess.run(sys.argv[1:] or ["cargo", "test", "native_ui_flows", "--", "--ignored", "--test-threads=1", "--nocapture"], env=env)
+ finally:
+ server.shutdown()
+ sys.exit(result.returncode)
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index 634fa1e2..bf40df5d 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -17,7 +17,7 @@ Codync/
│ │ ├── chat/ # Groups, bot-to-bot requests, prompt snapshots, memory
│ │ ├── remote/ # Identity, wire crypto, E2E channel, cloud, relay socket, push
│ │ ├── market/ # Marketplace, Composio, MCP OAuth
-│ │ └── tui/ # Terminal client (manage.rs + sheets.rs: memory, routines, marketplace, sign-in)
+│ │ └── tui/ # Terminal client (manage.rs + sheets.rs: settings; connections.rs: secure connection requests)
│ └── tests/ # Host integration tests and scripted ACP agents
├── kit/ # Shared Swift package
│ ├── Sources/
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index a90e90fc..875dbcd9 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -71,3 +71,57 @@ Shared `.codyncMenu` lists scroll vertically when their content exceeds 420 poin
A visible conversation registers its own read scope while its scene is active. New chat-visible entries (including final updates to an existing message ID) and later roster unread updates acknowledge that scope through the host. Opening the view, returning to the foreground, and reconnecting also acknowledge it. Never gate a receipt on the cached unread count: entry and roster events can arrive separately. Replies acknowledge only their own thread; leaving a view or backgrounding the scene unregisters it. The host remains authoritative and broadcasts the resulting unread state to all clients.
The iPhone conversation navigation title includes a compact second line with the connection label and the current connection route icon: cloud for Cloudflare, Wi-Fi for direct Wi-Fi/Tailscale. It follows the live route, not the preferred route setting; offline and reconnecting states replace the route icon. VoiceOver also reads the connection description.
+
+
+## Native client parity
+
+UI changes apply to SwiftUI (iOS/macOS), Linux GTK and the terminal client together.
+Use each platform's controls while preserving the same actions, information and states.
+The October 2026 parity changes bring GTK and TUI up to the existing SwiftUI behavior;
+SwiftUI already supplies these actions and needs no duplicate implementation.
+
+- Chat and threads show the latest non-final agent segment only while that lane is
+ working and connected. Earlier narration, tools, empty text and `(pass)` stay out
+ of chat. Completed replies remain visible.
+- GTK's **Load earlier messages** requests older history without evicting loaded pages.
+ Failed messages retain their attachments and nonce for **Resend**, and can be deleted.
+ Reactions work in chats and threads. Attachments save to Downloads without replacing
+ an existing file.
+- TUI keeps text and attachments in the composer until sending succeeds. A failed
+ send can be retried with Enter; it reuses the nonce. A late response must not erase
+ a draft edited while the request was running.
+- GTK bot menus include **Memory** and **Routines**. Memory supports forgetting one or
+ all facts. Routines support creation, editing, schedule previews, pause/resume, test
+ runs, deletion, history and webhook credentials. The host validates schedules;
+ editing can preserve existing event, interval and multiple triggers.
+- GTK **Marketplace** includes agents, connectors and skills. Agent setup supports
+ install/login terminals, browser authentication and masked credential fields.
+ VTE's terminal sends ordered input, receives output, resizes with its view and closes
+ the host terminal when dismissed. Ctrl+click opens HTTP(S) links.
+- TUI **C** opens a pending connection request in the current lane; selecting a request
+ and pressing Enter opens that request. Credentials, connector installation/sign-in
+ and hosted apps use the secure setup APIs. Ctrl+X cancels the request; Escape closes
+ the editor without cancelling. Secrets are masked and never sent as chat text.
+- TUI bot settings include **Use computer**, matching SwiftUI and GTK. The separate
+ remote-screen viewer and voice-call UI remain phone-specific capabilities.
+
+### Verification
+
+Run Rust format, Clippy and tests for `host/` and `apps/linux/`. Linux needs
+`libgtk-4-dev`, `libadwaita-1-dev` and `libvte-2.91-gtk4-dev` (VTE 0.70+).
+
+The native GTK test runs real widgets and HTTP/SSE calls against an isolated fixture:
+
+```sh
+cd apps/linux
+GTK_A11Y=none CODYNC_UI_ARTIFACTS=/tmp/codync-ui \
+ xvfb-run -a dbus-run-session -- python3 tests/ui_fixture.py
+```
+
+Install `xvfb`, `dbus-x11` and `imagemagick` for that command. It exercises history,
+streaming, retry/discard, reactions, attachment downloads, memory, routines, skill
+installation, masked agent credentials and terminal cleanup. Downloads and tokens stay
+inside its temporary directory. CI runs it on both Linux architectures and uploads
+screenshots as `native-ui-linux-*` artifacts. Host tests cover TUI draft recovery,
+lane-specific streaming, computer settings and complete connection-request API flows.
+These fixtures do not authenticate real third-party accounts.
diff --git a/host/src/tui/app.rs b/host/src/tui/app.rs
index ec696525..1704135f 100644
--- a/host/src/tui/app.rs
+++ b/host/src/tui/app.rs
@@ -25,6 +25,8 @@ pub enum Msg {
#[derive(Clone)]
pub enum After {
Nothing,
+ Sent(String),
+ Connection(String, super::connections::Step),
Hello,
History(String),
Thread,
@@ -85,6 +87,7 @@ pub struct Bot {
pub pinned: bool,
pub hidden: bool,
pub notify: bool,
+ pub computer: bool,
pub connectors: Vec<String>,
pub skills: Vec<String>,
pub status: Status,
@@ -127,6 +130,7 @@ impl Bot {
pinned: v["pinned"].as_bool().unwrap_or(false),
hidden: v["hidden"].as_bool().unwrap_or(false),
notify: v["notify"].as_bool().unwrap_or(true),
+ computer: v["computer"].as_bool().unwrap_or(false),
connectors: strs(&v["connectors"]),
skills: strs(&v["skills"]),
status: match v["status"].as_str() {
@@ -246,7 +250,7 @@ impl Entry {
/// What the chat shows as a message: the user's, and each turn's final reply.
pub fn is_message(&self) -> bool {
- self.kind == Kind::User || self.is_final()
+ self.kind == Kind::User || self.is_final() || self.data["connectionRequest"].is_object()
}
pub fn pending(&self) -> bool {
@@ -501,13 +505,14 @@ pub enum Field {
Folder,
Approvals,
Notify,
+ Computer,
Color,
Shape,
Connectors,
Skills,
}
-pub const FIELDS: [Field; 11] = [
+pub const FIELDS: [Field; 12] = [
Field::Name,
Field::Instructions,
Field::Agent,
@@ -515,6 +520,7 @@ pub const FIELDS: [Field; 11] = [
Field::Folder,
Field::Approvals,
Field::Notify,
+ Field::Computer,
Field::Color,
Field::Shape,
Field::Connectors,
@@ -527,6 +533,7 @@ pub struct Toggle {
pub on: bool,
}
+#[allow(clippy::struct_excessive_bools, reason = "independent bot settings and save state")]
pub struct Form {
pub bot_id: Option<String>,
pub name: Editor,
@@ -536,6 +543,7 @@ pub struct Form {
pub cwd: String,
pub auto: bool,
pub notify: bool,
+ pub computer: bool,
pub color: usize,
pub shape: usize,
pub connectors: Vec<Toggle>,
@@ -634,6 +642,14 @@ pub struct Hits {
pub clicks: Vec<(Rect, Click)>,
}
+#[derive(Clone)]
+struct PendingSend {
+ text: String,
+ files: Vec<std::path::PathBuf>,
+ nonce: String,
+ busy: bool,
+}
+
#[allow(clippy::struct_excessive_bools, reason = "independent UI flags, not a state machine")]
pub struct App {
pub client: Client,
@@ -655,6 +671,7 @@ pub struct App {
pub drafts: HashMap<String, Editor>,
/// Files dropped on the composer (pasted paths), per draft like the text.
pub files: HashMap<String, Vec<std::path::PathBuf>>,
+ sends: HashMap<String, PendingSend>,
/// Lines scrolled up from the bottom of the chat (0 = follow new messages).
pub chat_scroll: usize,
pub trace_scroll: usize,
@@ -709,6 +726,7 @@ impl App {
chat_page: false,
drafts: HashMap::new(),
files: HashMap::new(),
+ sends: HashMap::new(),
chat_scroll: 0,
trace_scroll: 0,
trace: TraceMode::Off,
@@ -1027,6 +1045,14 @@ impl App {
}
fn on_reply(&mut self, after: After, r: Result<Value, String>) {
+ if let After::Connection(id, step) = after {
+ self.connection_reply(&id, step, r);
+ return;
+ }
+ if let After::Sent(key) = after {
+ self.sent(&key, r);
+ return;
+ }
if let After::Sheet(s) = after {
self.on_sheet_reply(s, r);
return;
@@ -1061,7 +1087,7 @@ impl App {
}
};
match after {
- After::Nothing | After::Sheet(_) => {}
+ After::Nothing | After::Sheet(_) | After::Sent(_) | After::Connection(_, _) => {}
After::Installed => {
self.error = None;
self.flash("Host installed; connecting…");
@@ -1252,23 +1278,35 @@ impl App {
KeyCode::Char('j') if ctrl => draft.insert("\n"),
KeyCode::Enter => {
let text = draft.text.trim().to_owned();
- let files = self.files.remove(&key).unwrap_or_default();
+ let files = self.files.get(&key).cloned().unwrap_or_default();
if text.is_empty() && files.is_empty() {
return;
}
- draft.clear();
+ if self.sends.get(&key).is_some_and(|s| s.busy) {
+ self.flash("Sending…");
+ return;
+ }
+ let nonce = self
+ .sends
+ .get(&key)
+ .filter(|s| s.text == text && s.files == files)
+ .map_or_else(|| uuid::Uuid::new_v4().to_string(), |s| s.nonce.clone());
+ self.sends.insert(
+ key.clone(),
+ PendingSend { text: text.clone(), files: files.clone(), nonce: nonce.clone(), busy: true },
+ );
self.chat_scroll = 0;
- let nonce = uuid::Uuid::new_v4().to_string();
let mut body = json!({"botId": id, "text": text, "clientNonce": nonce});
if let Some(root) = thread {
body["threadId"] = root.into();
}
+ let after = After::Sent(key);
if files.is_empty() {
- self.call("send", body, After::Nothing);
+ self.call("send", body, after);
} else {
- self.flash(&format!("uploading {} file{}…", files.len(), if files.len() == 1 { "" } else { "s" }));
- self.client.spawn_send_files(body, files, self.tx.clone());
+ self.client.spawn_send_files(body, files, after, self.tx.clone());
}
+ self.flash("Sending… Your draft stays here until delivered.");
}
KeyCode::Backspace if draft.text.is_empty() => {
if let Some(files) = self.files.get_mut(&key) {
@@ -1294,6 +1332,25 @@ impl App {
}
}
+ fn sent(&mut self, key: &str, result: Result<Value, String>) {
+ let Some(sent) = self.sends.get_mut(key) else { return };
+ sent.busy = false;
+ match result {
+ Ok(value) => {
+ if self.drafts.get(key).is_some_and(|d| d.text.trim() == sent.text)
+ && self.files.get(key).map_or(&[][..], Vec::as_slice) == sent.files
+ {
+ self.drafts.remove(key);
+ self.files.remove(key);
+ }
+ self.sends.remove(key);
+ self.on_event(&json!({"type": "entry", "entry": value["entry"]}));
+ self.flash("Sent");
+ }
+ Err(error) => self.flash(&format!("{error} Draft kept; Enter retries, Ctrl+C clears text.")),
+ }
+ }
+
fn scroll_chat(&mut self, delta: isize) {
self.chat_scroll = self.chat_scroll.saturating_add_signed(delta);
}
@@ -1315,6 +1372,7 @@ impl App {
KeyCode::Char('d') if ctrl => self.scroll_focused(-half),
KeyCode::Char('u') if ctrl => self.scroll_focused(half),
KeyCode::Char('q') => self.quit = true,
+ KeyCode::Char('C') => self.open_connection(),
KeyCode::Char('I') if self.error.is_some() && self.bots.is_empty() => self.install_host(),
KeyCode::Char('?') => self.overlays.push(Overlay::Help(Editor::default())),
KeyCode::Char('!') => self.jump(Mark::Need),
@@ -1634,6 +1692,10 @@ impl App {
match k.code {
KeyCode::Char('j') | KeyCode::Down => self.step_pick(1),
KeyCode::Char('k') | KeyCode::Up => self.step_pick(-1),
+ KeyCode::Char('C') => self.open_connection(),
+ KeyCode::Enter if picked.as_ref().is_some_and(|e| e.data["connectionRequest"]["status"] == "pending") => {
+ self.open_connection();
+ }
KeyCode::Enter | KeyCode::Char('r') if self.thread.is_some() => {
self.pick = None;
self.start_typing();
@@ -1812,6 +1874,7 @@ impl App {
cwd: if b.managed_workspace { String::new() } else { b.cwd.clone() },
auto: b.auto,
notify: b.notify,
+ computer: b.computer,
color: COLORS.iter().position(|c| *c == b.color).unwrap_or(7),
shape: SHAPES.iter().position(|s| *s == b.shape).unwrap_or(0),
connectors: b.connectors.iter().map(|id| Toggle { id: id.clone(), name: id.clone(), on: true }).collect(),
@@ -2087,6 +2150,7 @@ impl App {
cwd: String::new(),
auto: false,
notify: true,
+ computer: false,
color: (n * 7) % COLORS.len(),
shape: n % SHAPES.len(),
connectors: self
@@ -2161,6 +2225,7 @@ impl App {
Field::Agent
| Field::Approvals
| Field::Notify
+ | Field::Computer
| Field::Color
| Field::Shape
| Field::Connectors
@@ -2183,6 +2248,7 @@ impl App {
}
Field::Approvals => f.auto = !f.auto,
Field::Notify => f.notify = !f.notify,
+ Field::Computer => f.computer = !f.computer,
Field::Color if !space => f.color = cycle(f.color, d, COLORS.len()),
Field::Shape if !space => f.shape = cycle(f.shape, d, SHAPES.len()),
Field::Connectors | Field::Skills => {
@@ -2230,6 +2296,7 @@ impl App {
"permission": if f.auto { "auto" } else { "ask" },
"model": if model.is_empty() { Value::Null } else { model.into() },
"notify": f.notify,
+ "computer": f.computer,
"avatarColor": COLORS[f.color],
"avatarShape": SHAPES[f.shape],
"connectors": f.connectors.iter().filter(|t| t.on).map(|t| t.id.clone()).collect::<Vec<_>>(),
@@ -2397,6 +2464,52 @@ pub fn tilde(path: &str, home: &str) -> String {
mod tests {
use super::*;
+ fn test_app() -> App {
+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();
+ App::new(Client::new("http://127.0.0.1:1", None), tx, String::new())
+ }
+
+ #[test]
+ fn send_failure_keeps_text_files_and_nonce_for_retry() {
+ let mut app = test_app();
+ let key = "bot/thread";
+ let files = vec![std::path::PathBuf::from("/tmp/report.txt")];
+ app.drafts.insert(key.into(), Editor::with("draft"));
+ app.files.insert(key.into(), files.clone());
+ app.sends.insert(
+ key.into(),
+ PendingSend { text: "draft".into(), files: files.clone(), nonce: "same-nonce".into(), busy: true },
+ );
+ app.on_reply(After::Sent(key.into()), Err("Disconnected".into()));
+ assert_eq!(app.drafts[key].text, "draft");
+ assert_eq!(app.files[key], files);
+ assert_eq!(app.sends[key].nonce, "same-nonce");
+ assert!(!app.sends[key].busy);
+ app.on_reply(After::Sent(key.into()), Ok(json!({})));
+ assert!(!app.drafts.contains_key(key));
+ assert!(!app.files.contains_key(key));
+ }
+
+ #[test]
+ fn late_send_success_does_not_erase_a_new_draft() {
+ let mut app = test_app();
+ app.drafts.insert("bot".into(), Editor::with("new draft"));
+ app.sends.insert(
+ "bot".into(),
+ PendingSend { text: "old draft".into(), files: vec![], nonce: "n".into(), busy: true },
+ );
+ app.on_reply(After::Sent("bot".into()), Ok(json!({})));
+ assert_eq!(app.drafts["bot"].text, "new draft");
+ }
+
+ #[test]
+ fn computer_permission_survives_loading_the_editor() {
+ let mut app = test_app();
+ app.upsert_bot(&json!({"id":"b", "computer":true}));
+ assert!(app.bots["b"].computer);
+ assert!(FIELDS.contains(&Field::Computer));
+ }
+
#[test]
fn dropped_paths_are_files_only() {
let dir = std::env::temp_dir().join(format!("codync-drop-{}", std::process::id()));
diff --git a/host/src/tui/connections.rs b/host/src/tui/connections.rs
new file mode 100644
index 00000000..ec2c7f21
--- /dev/null
+++ b/host/src/tui/connections.rs
@@ -0,0 +1,413 @@
+//! Connection requests remain actionable in a terminal. Secrets stay in masked setup fields.
+use super::app::{After, App, Editor, Entry, Overlay};
+use super::manage::{Fields, Input, Submit};
+use serde_json::{Value, json};
+
+#[derive(Clone, Copy)]
+pub enum Step {
+ Credentials,
+ Catalog,
+ Install,
+ Installed,
+ Authorize,
+ SignIn,
+ AppStart,
+ AppCheck,
+ Finish,
+}
+
+pub struct Connection {
+ pub entry: String,
+ pub request: Value,
+ pub step: Step,
+ pub metadata: Value,
+}
+
+fn input(name: &str, label: &str, secret: bool, required: bool) -> Input {
+ Input {
+ name: name.into(),
+ label: label.into(),
+ secret,
+ required,
+ multiline: false,
+ placeholder: String::new(),
+ ed: Editor::default(),
+ }
+}
+
+pub fn fields(entry: &Entry) -> Fields {
+ let request = &entry.data["connectionRequest"];
+ let (step, inputs) = match request["kind"].as_str() {
+ Some("login") => (
+ Step::Credentials,
+ vec![input("username", "Username / email", false, true), input("value", "Password / op://", true, true)],
+ ),
+ Some("secret") => (
+ Step::Credentials,
+ vec![input("value", request["field"].as_str().unwrap_or("Credential / op://"), true, true)],
+ ),
+ Some("app") => (Step::AppStart, vec![]),
+ _ if request["connectorId"].is_string() => (Step::Installed, vec![]),
+ _ => (Step::Catalog, vec![]),
+ };
+ Fields {
+ title: request["title"].as_str().unwrap_or("Connect service").into(),
+ note: "Saved securely; never added to chat. Ctrl+X cancels the request; Esc closes.".into(),
+ choices: vec![],
+ choice: 0,
+ inputs,
+ cursor: 0,
+ error: None,
+ saving: false,
+ submit: Submit::Connection(Box::new(Connection {
+ entry: entry.id.clone(),
+ request: request.clone(),
+ step,
+ metadata: Value::Null,
+ })),
+ }
+}
+
+pub fn option_fields(f: &mut Fields) {
+ let Submit::Connection(c) = &f.submit else { return };
+ if !matches!(c.step, Step::Install) {
+ return;
+ }
+ f.inputs = c.metadata["options"][f.choice]["inputs"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|v| {
+ let name = v["name"].as_str().unwrap_or("");
+ let mut i = input(name, name, v["secret"] == true, v["required"] == true);
+ i.ed = Editor::with(v["default"].as_str().unwrap_or(""));
+ i.placeholder = v["description"].as_str().unwrap_or("").into();
+ i
+ })
+ .collect();
+ f.cursor = 0;
+}
+
+impl App {
+ pub(super) fn open_connection(&mut self) {
+ let Some(bot) = &self.selected else { return };
+ let entry = self
+ .lane(bot)
+ .into_iter()
+ .find(|e| {
+ e.data["connectionRequest"]["status"] == "pending" && self.pick.as_ref().is_none_or(|id| *id == e.id)
+ })
+ .cloned();
+ if let Some(entry) = entry {
+ self.overlays.push(Overlay::Fields(Box::new(fields(&entry))));
+ } else {
+ self.flash("No pending connection request here");
+ }
+ }
+
+ pub(super) fn submit_connection(&self, f: &Fields, values: &serde_json::Map<String, Value>) {
+ let Submit::Connection(c) = &f.submit else { return };
+ let (method, args, reply) = match c.step {
+ Step::Credentials => (
+ "connectorRequestFinish",
+ json!({"entryId":c.entry,"value":values.get("value"),"username":values.get("username")}),
+ Step::Finish,
+ ),
+ Step::Catalog => ("connectorInfo", json!({"registryName":c.request["registryName"]}), Step::Catalog),
+ Step::Install => (
+ "installConnector",
+ json!({"registryName":c.metadata["name"],"option":c.metadata["options"][f.choice]["id"],"inputs":values}),
+ Step::Install,
+ ),
+ Step::Installed => ("connectors", json!({}), Step::Installed),
+ Step::Authorize if f.choice == 0 => {
+ ("connectorSignIn", json!({"id":c.request["connectorId"]}), Step::SignIn)
+ }
+ Step::AppStart => ("composioConnect", json!({"toolkit":c.request["toolkit"]}), Step::AppStart),
+ Step::AppCheck if c.metadata["status"] == "needsFields" => (
+ "composioConnectFields",
+ json!({"toolkit":c.request["toolkit"],"mode":c.metadata["mode"],"fields":values}),
+ Step::AppCheck,
+ ),
+ Step::AppCheck => ("composioConnection", json!({"id":c.metadata["connection"]}), Step::AppCheck),
+ _ => (
+ "connectorRequestFinish",
+ json!({"entryId":c.entry,"connectorId":c.request["connectorId"]}),
+ Step::Finish,
+ ),
+ };
+ self.call(method, args, After::Connection(c.entry.clone(), reply));
+ }
+
+ pub(super) fn connection_reply(&mut self, id: &str, step: Step, result: Result<Value, String>) {
+ let Some(index) = self.overlays.iter().position(
+ |o| matches!(o, Overlay::Fields(f) if matches!(&f.submit, Submit::Connection(c) if c.entry == id)),
+ ) else {
+ return;
+ };
+ let Overlay::Fields(f) = &mut self.overlays[index] else { return };
+ f.saving = false;
+ let value = match result {
+ Ok(v) => v,
+ Err(e) => {
+ f.error = Some(e);
+ return;
+ }
+ };
+ f.error = None;
+ let Submit::Connection(c) = &mut f.submit else { return };
+ let mut finish = false;
+ match step {
+ Step::Finish => {
+ self.overlays.remove(index);
+ self.flash("Connection request updated");
+ return;
+ }
+ Step::Catalog => {
+ f.choices = value["options"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|o| o["id"].as_str().unwrap_or("Setup").to_owned())
+ .collect();
+ if f.choices.is_empty() {
+ f.error = Some("No supported setup options".into());
+ return;
+ }
+ c.metadata = value;
+ c.step = Step::Install;
+ f.choice = 0;
+ option_fields(f);
+ }
+ Step::Install | Step::Installed => {
+ let connector = if matches!(step, Step::Install) {
+ value["connector"].clone()
+ } else {
+ value["items"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .find(|v| v["id"] == c.request["connectorId"])
+ .cloned()
+ .unwrap_or(Value::Null)
+ };
+ if connector.is_null() {
+ f.error = Some("Connector is no longer installed".into());
+ return;
+ }
+ c.request["connectorId"] = connector["id"].clone();
+ for i in &mut f.inputs {
+ i.ed.clear();
+ }
+ f.inputs.clear();
+ f.cursor = 0;
+ if connector["auth"] == "signedOut" {
+ c.step = Step::Authorize;
+ f.choices = vec!["Sign in".into(), "Check connection".into()];
+ f.choice = 0;
+ } else {
+ c.step = Step::Finish;
+ finish = true;
+ }
+ }
+ Step::SignIn => {
+ c.step = Step::Authorize;
+ f.choice = 1;
+ f.note = "Sign-in link copied. Finish in browser, then Enter checks. Ctrl+X cancels.".into();
+ if let Some(url) = value["url"].as_str() {
+ super::app::copy(url);
+ super::manage::open_browser(url, &self.url);
+ }
+ }
+ Step::AppStart | Step::AppCheck => {
+ if value["status"] == "active" {
+ c.request["connectorId"] =
+ format!("composio-{}", c.request["toolkit"].as_str().unwrap_or("")).into();
+ c.step = Step::Finish;
+ f.inputs.clear();
+ finish = true;
+ } else {
+ if matches!(step, Step::AppStart) || value["status"] == "needsFields" {
+ c.metadata = value.clone();
+ f.inputs = value["fields"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|v| {
+ input(
+ v["name"].as_str().unwrap_or(""),
+ v["label"].as_str().unwrap_or("Credential"),
+ v["secret"] != false,
+ v["required"] != false,
+ )
+ })
+ .collect();
+ }
+ c.step = Step::AppCheck;
+ f.note = "Complete sign-in, then Enter checks. Ctrl+X cancels.".into();
+ if let Some(url) = value["url"].as_str() {
+ super::app::copy(url);
+ super::manage::open_browser(url, &self.url);
+ }
+ if matches!(step, Step::AppCheck) {
+ f.error = Some(format!(
+ "Connection status: {}. Finish signing in and check again.",
+ value["status"].as_str().unwrap_or("pending")
+ ));
+ }
+ }
+ }
+ Step::Credentials | Step::Authorize => {}
+ }
+ if finish {
+ f.saving = true;
+ let Submit::Connection(c) = &f.submit else { return };
+ let args = json!({"entryId":c.entry,"connectorId":c.request["connectorId"]});
+ self.call("connectorRequestFinish", args, After::Connection(id.into(), Step::Finish));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::app::Kind;
+ use super::*;
+ async fn fixture() -> (
+ App,
+ tokio::sync::mpsc::UnboundedReceiver<super::super::app::Msg>,
+ std::sync::Arc<std::sync::Mutex<Vec<Value>>>,
+ tokio::task::JoinHandle<()>,
+ ) {
+ use axum::{Json, Router, extract::Path, routing::post};
+ let calls = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
+ let received = calls.clone();
+ let router = Router::new().route("/api/{method}", post(move |Path(method): Path<String>, Json(body): Json<Value>| {
+ let received = received.clone();
+ async move {
+ received.lock().unwrap().push(json!({"method":method,"body":body}));
+ Json(match method.as_str() {
+ "connectorInfo" => json!({"name":"fixture","options":[{"id":"local","inputs":[{"name":"key","secret":true,"required":true}]}]}),
+ "installConnector" => json!({"connector":{"id":"connector","auth":"signedOut"}}),
+ "composioConnect" => json!({"status":"needsFields","mode":"apiKey","fields":[{"name":"token","label":"Token","secret":true}]}),
+ "composioConnectFields" => json!({"status":"active"}),
+ _ => json!({}),
+ })
+ }
+ }));
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let task = tokio::spawn(async move {
+ axum::serve(listener, router).await.unwrap();
+ });
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ (App::new(super::super::net::Client::new(&url, Some("fixture")), tx, url), rx, calls, task)
+ }
+
+ fn open(app: &mut App, request: &Value) {
+ let e = Entry {
+ id: "request".into(),
+ seq: 1,
+ turn: 1,
+ kind: Kind::Notice,
+ data: json!({"connectionRequest":request}),
+ created_at: 0,
+ thread_id: None,
+ };
+ app.overlays.push(Overlay::Fields(Box::new(fields(&e))));
+ }
+
+ fn key(app: &mut App, code: crossterm::event::KeyCode, modifiers: crossterm::event::KeyModifiers) {
+ app.on_key(crossterm::event::KeyEvent::new(code, modifiers));
+ }
+
+ async fn reply(app: &mut App, rx: &mut tokio::sync::mpsc::UnboundedReceiver<super::super::app::Msg>) {
+ let msg = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv()).await.unwrap().unwrap();
+ app.on_msg(msg);
+ }
+
+ #[tokio::test]
+ async fn credentials_submit_exact_secret_and_cancel_is_explicit() {
+ use crossterm::event::{KeyCode, KeyModifiers};
+ let (mut app, mut rx, calls, server) = fixture().await;
+ open(&mut app, &json!({"kind":"login","status":"pending"}));
+ let Some(Overlay::Fields(f)) = app.overlays.last_mut() else { panic!("fields") };
+ f.inputs[0].ed = Editor::with("name");
+ f.inputs[1].ed = Editor::with(" secret with spaces ");
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ assert!(app.overlays.is_empty());
+ assert_eq!(
+ calls.lock().unwrap()[0]["body"],
+ json!({"entryId":"request","username":"name","value":" secret with spaces "})
+ );
+ open(&mut app, &json!({"kind":"secret","status":"pending"}));
+ key(&mut app, KeyCode::Esc, KeyModifiers::NONE);
+ assert_eq!(calls.lock().unwrap().len(), 1);
+ open(&mut app, &json!({"kind":"secret","status":"pending"}));
+ key(&mut app, KeyCode::Char('x'), KeyModifiers::CONTROL);
+ reply(&mut app, &mut rx).await;
+ assert_eq!(calls.lock().unwrap()[1]["body"], json!({"entryId":"request","cancel":true}));
+ server.abort();
+ }
+
+ #[tokio::test]
+ async fn registry_request_installs_signs_in_and_finishes() {
+ use crossterm::event::{KeyCode, KeyModifiers};
+ let (mut app, mut rx, calls, server) = fixture().await;
+ open(&mut app, &json!({"kind":"connector","status":"pending","registryName":"fixture"}));
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ let Some(Overlay::Fields(f)) = app.overlays.last_mut() else { panic!("fields") };
+ assert!(f.inputs[0].secret);
+ f.inputs[0].ed = Editor::with("fixture-key");
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ let calls = calls.lock().unwrap();
+ let methods: Vec<_> = calls.iter().map(|c| c["method"].as_str().unwrap()).collect();
+ assert_eq!(methods, ["connectorInfo", "installConnector", "connectorSignIn", "connectorRequestFinish"]);
+ assert_eq!(calls[1]["body"]["inputs"]["key"], "fixture-key");
+ assert_eq!(calls[3]["body"]["connectorId"], "connector");
+ assert!(app.overlays.is_empty());
+ server.abort();
+ }
+
+ #[tokio::test]
+ async fn hosted_app_fields_finish_only_after_active_status() {
+ use crossterm::event::{KeyCode, KeyModifiers};
+ let (mut app, mut rx, calls, server) = fixture().await;
+ open(&mut app, &json!({"kind":"app","status":"pending","toolkit":"fixture"}));
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ let Some(Overlay::Fields(f)) = app.overlays.last_mut() else { panic!("fields") };
+ assert!(f.inputs[0].secret);
+ f.inputs[0].ed = Editor::with("fixture-token");
+ key(&mut app, KeyCode::Enter, KeyModifiers::NONE);
+ reply(&mut app, &mut rx).await;
+ reply(&mut app, &mut rx).await;
+ assert!(app.overlays.is_empty());
+ assert_eq!(calls.lock().unwrap()[2]["body"]["connectorId"], "composio-fixture");
+ server.abort();
+ }
+
+ #[test]
+ fn login_fields_mask_the_password_and_keep_it_out_of_chat() {
+ let e = Entry {
+ id: "r".into(),
+ seq: 1,
+ turn: 1,
+ kind: Kind::Notice,
+ data: json!({"connectionRequest":{"kind":"login","status":"pending"}}),
+ created_at: 0,
+ thread_id: None,
+ };
+ let f = fields(&e);
+ assert!(!f.inputs[0].secret);
+ assert!(f.inputs[1].secret);
+ assert!(f.inputs.iter().all(|i| i.ed.text.is_empty()));
+ assert!(matches!(f.submit, Submit::Connection(c) if matches!(c.step, Step::Credentials)));
+ }
+}
diff --git a/host/src/tui/manage.rs b/host/src/tui/manage.rs
index 5520d986..5b1d65a8 100644
--- a/host/src/tui/manage.rs
+++ b/host/src/tui/manage.rs
@@ -134,6 +134,7 @@ pub struct Input {
pub enum Submit {
AgentEnv(String),
+ Connection(Box<super::connections::Connection>),
Connector(Value),
Import,
}
@@ -613,6 +614,7 @@ impl App {
submit: Submit::Connector(item),
};
connector_inputs(&mut f);
+ super::connections::option_fields(&mut f);
self.overlays.push(Overlay::Market(m));
self.overlays.push(Overlay::Fields(Box::new(f)));
return None;
@@ -795,11 +797,24 @@ impl App {
// ---------- fields ----------
pub(super) fn fields_key(&mut self, mut f: Box<Fields>, k: KeyEvent) -> Option<Overlay> {
+ if f.saving {
+ return if k.code == KeyCode::Esc { None } else { Some(Overlay::Fields(f)) };
+ }
let rows = f.offset() + f.inputs.len();
let on_choice = f.offset() == 1 && f.cursor == 0;
let multiline = f.current().is_some_and(|i| i.multiline);
match k.code {
KeyCode::Esc => return None,
+ KeyCode::Char('x') if ctrl(k) && matches!(f.submit, Submit::Connection(_)) => {
+ if let Submit::Connection(c) = &f.submit {
+ f.saving = true;
+ self.call(
+ "connectorRequestFinish",
+ json!({"entryId":c.entry,"cancel":true}),
+ After::Connection(c.entry.clone(), super::connections::Step::Finish),
+ );
+ }
+ }
_ if newline(k) && multiline => {
if let Some(i) = f.current() {
i.ed.insert("\n");
@@ -812,6 +827,7 @@ impl App {
KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') if on_choice => {
f.choice = (f.choice + 1) % f.choices.len();
connector_inputs(&mut f);
+ super::connections::option_fields(&mut f);
}
_ => {
if let Some(i) = f.current() {
@@ -834,11 +850,12 @@ impl App {
.inputs
.iter()
.filter(|i| !i.ed.text.trim().is_empty())
- .map(|i| (i.name.clone(), i.ed.text.trim().into()))
+ .map(|i| (i.name.clone(), if i.secret { i.ed.text.as_str() } else { i.ed.text.trim() }.into()))
.collect();
f.saving = true;
f.error = None;
match &f.submit {
+ Submit::Connection(_) => self.submit_connection(f, &values),
Submit::AgentEnv(backend) => {
if values.is_empty() {
f.saving = false;
@@ -1314,7 +1331,7 @@ pub fn when_text(triggers: &Value, zone: &str) -> Option<String> {
}
/// Opens `url` in this computer's browser, when the host is this computer.
-fn open_browser(url: &str, host: &str) -> bool {
+pub(super) fn open_browser(url: &str, host: &str) -> bool {
let local = ["//127.0.0.1", "//localhost", "//[::1]"].iter().any(|h| host.contains(h));
if !local || url.is_empty() {
return false;
diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rs
index 7cbb2d36..5d34e8cf 100644
--- a/host/src/tui/mod.rs
+++ b/host/src/tui/mod.rs
@@ -2,6 +2,7 @@
//! same HTTP + SSE API as the phone and desktop apps (locally: no pairing needed).
mod app;
+mod connections;
mod manage;
mod md;
mod net;
diff --git a/host/src/tui/net.rs b/host/src/tui/net.rs
index 8eb487f0..94e2968f 100644
--- a/host/src/tui/net.rs
+++ b/host/src/tui/net.rs
@@ -79,8 +79,8 @@ impl Client {
}
/// Uploads `files` in 384 KiB chunks (under the channel's message limit, like the apps), then sends
- /// `body` with them attached. The reply comes back as `Msg::Reply(After::Nothing, …)`.
- pub fn spawn_send_files(&self, mut body: Value, files: Vec<PathBuf>, tx: UnboundedSender<Msg>) {
+ /// `body` with them attached. The reply comes back as `Msg::Reply(after, …)`.
+ pub fn spawn_send_files(&self, mut body: Value, files: Vec<PathBuf>, after: After, tx: UnboundedSender<Msg>) {
use base64::Engine as _;
const CHUNK: usize = 384 * 1024;
const MAX: u64 = 100 * 1024 * 1024;
@@ -116,7 +116,7 @@ impl Client {
body["attachments"] = ids.into();
c.call("send", &body).await
};
- let _ = tx.send(Msg::Reply(After::Nothing, upload.await));
+ let _ = tx.send(Msg::Reply(after, upload.await));
});
}
diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rs
index 64938340..bc527eb0 100644
--- a/host/src/tui/sheets.rs
+++ b/host/src/tui/sheets.rs
@@ -10,7 +10,7 @@ use serde_json::Value;
use super::app::{App, Editor};
use super::manage::{
- AgentSetup, Fields, Market, MemorySheet, RoutineField, RoutineForm, RoutineList, Row, SetupRow, TABS, Tab,
+ AgentSetup, Fields, Market, MemorySheet, RoutineField, RoutineForm, RoutineList, Row, SetupRow, Submit, TABS, Tab,
};
use super::md::truncate;
use super::view::{
@@ -399,8 +399,27 @@ pub fn fields(buf: &mut Buffer, area: Rect, f: &Fields) {
put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));
}
hline(buf, inner.x, by - 2, inner.width, t.line.patch(t.panel));
- let x = put(buf, inner.x, by, 14, if f.saving { " … Saving " } else { " ↵ Save " }, t.btn_primary) + 1;
+ let x = put(
+ buf,
+ inner.x,
+ by,
+ 14,
+ if f.saving {
+ " … Saving "
+ } else if matches!(f.submit, Submit::Connection(_)) {
+ " ↵ Continue "
+ } else {
+ " ↵ Save "
+ },
+ t.btn_primary,
+ ) + 1;
put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));
- let hint = if tall { "⇧↵ new line · paste works" } else { "tab next field" };
+ let hint = if matches!(f.submit, Submit::Connection(_)) {
+ "^x cancel request · tab next · esc close"
+ } else if tall {
+ "⇧↵ new line · paste works"
+ } else {
+ "tab next field"
+ };
rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));
}
diff --git a/host/src/tui/view.rs b/host/src/tui/view.rs
index 06045927..259ba1c3 100644
--- a/host/src/tui/view.rs
+++ b/host/src/tui/view.rs
@@ -950,6 +950,16 @@ fn replies(n: i64) -> String {
if n == 1 { "1 reply".into() } else { format!("{n} replies") }
}
+fn live_entry<'a>(app: &App, bot: &Bot, entries: &[&'a Entry]) -> Option<&'a str> {
+ if !app.online || bot.status != Status::Working || !bot.works_in(app.thread.as_deref()) {
+ return None;
+ }
+ entries
+ .last()
+ .filter(|e| e.kind == Kind::Agent && e.data["final"] == false && !e.text().is_empty() && e.text() != "(pass)")
+ .map(|e| e.id.as_str())
+}
+
fn build_chat(app: &App, b: &Bot, width: usize) -> Built {
let t = theme();
let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };
@@ -978,7 +988,13 @@ fn build_chat(app: &App, b: &Bot, width: usize) -> Built {
let side = width.saturating_sub(w(&label) + 4);
out.lines.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));
}
+ let live = live_entry(app, b, &entries);
for e in &entries {
+ let mut visible = (*e).clone();
+ if live == Some(e.id.as_str()) {
+ visible.data["final"] = true.into();
+ }
+ let e = &visible;
entry_lines(&mut out, app, b, e, &info, thread.is_none(), width);
}
// A turn in flight: who's on it and what they're doing.
@@ -1145,7 +1161,17 @@ fn entry_lines(
}
}
Kind::Notice => {
- let text = e.notice_text();
+ let from = out.lines.len();
+ let text = if let Some(status) = e.data["connectionRequest"]["status"].as_str() {
+ format!(
+ "{} · {} · {}",
+ e.data["connectionRequest"]["title"].as_str().unwrap_or("Connect service"),
+ e.notice_text(),
+ if status == "pending" { "C connects / cancels" } else { status }
+ )
+ } else {
+ e.notice_text()
+ };
gap(out);
match e.data["style"].as_str() {
Some("divider") => {
@@ -1166,6 +1192,9 @@ fn entry_lines(
&[Span::raw(" ")],
)),
}
+ if e.data["connectionRequest"].is_object() {
+ out.messages.push((e.id.clone(), from, out.lines.len()));
+ }
}
_ => {}
}
@@ -1912,7 +1941,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, items
);
}
-const HELP: [(&str, &str, &str); 51] = [
+const HELP: [(&str, &str, &str); 52] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -1931,6 +1960,7 @@ const HELP: [(&str, &str, &str); 51] = [
("CHAT", "s", "stop the bot"),
("CHAT", "o", "last turn's steps"),
("CHAT", "c", "copy the last reply"),
+ ("CHAT", "C", "open connection / login request"),
("CHAT", "r", "reply in a thread"),
("CHAT", "v", "pick a message"),
("CHAT", "j k ↵", "picking: move / open"),
@@ -2051,6 +2081,7 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
Field::Folder => "Workspace",
Field::Approvals => "Approvals",
Field::Notify => "Notify",
+ Field::Computer => "Use computer",
Field::Color => "Color",
Field::Shape => "Shape",
Field::Connectors => "Connectors",
@@ -2126,6 +2157,10 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let s = if f.auto { "○ Ask ◉ Auto (approve every request)" } else { "◉ Ask ○ Auto" };
put(buf, vx, y, vw, s, t.text.patch(base));
}
+ Field::Computer => {
+ let s = if f.computer { "◉ On ○ Off" } else { "○ On ◉ Off" };
+ put(buf, vx, y, vw, s, t.text.patch(base));
+ }
Field::Notify => {
let s = if f.notify { "◉ Done and needs-you ○ Off" } else { "○ Done and needs-you ◉ Off" };
put(buf, vx, y, vw, s, t.text.patch(base));
@@ -2182,7 +2217,9 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
Field::Connectors | Field::Skills => "←→ move · space toggle · tab next",
Field::Agent => "←→ change · ↵ install / sign in · tab next",
Field::Model => "←→ pick a model · or type its id",
- Field::Color | Field::Shape | Field::Approvals | Field::Notify => "←→ change · tab next field",
+ Field::Color | Field::Shape | Field::Approvals | Field::Notify | Field::Computer => {
+ "←→ change · tab next field"
+ }
Field::Instructions => "⇧↵ new line · tab next field",
Field::Name => "tab next field · ^s save",
};
@@ -2399,6 +2436,33 @@ fn toasts(buf: &mut Buffer, area: Rect, app: &App) {
mod tests {
use super::*;
+ #[test]
+ fn live_text_stays_in_its_lane_and_disappears_after_a_tool() {
+ use serde_json::json;
+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());
+ app.on_msg(super::super::app::Msg::Event(json!({"type":"bot","bot":{"id":"b","status":"working"}})));
+ app.online = true;
+ let entry = Entry {
+ id: "live".into(),
+ seq: 1,
+ turn: 1,
+ kind: Kind::Agent,
+ data: json!({"text":"answer","final":false}),
+ created_at: 0,
+ thread_id: None,
+ };
+ let bot = &app.bots["b"];
+ assert_eq!(live_entry(&app, bot, &[&entry]), Some("live"));
+ let tool = Entry { kind: Kind::Tool, ..entry.clone() };
+ assert_eq!(live_entry(&app, bot, &[&entry, &tool]), None);
+ app.thread = Some("thread".into());
+ assert_eq!(live_entry(&app, &app.bots["b"], &[&entry]), None);
+ app.thread = None;
+ app.online = false;
+ assert_eq!(live_entry(&app, &app.bots["b"], &[&entry]), None);
+ }
+
#[test]
fn civil_dates() {
assert_eq!(month_day(0), (0, 1)); // 1970-01-01
diff --git a/packaging/install.sh b/packaging/install.sh
index 699f19ce..724af2ca 100755
--- a/packaging/install.sh
+++ b/packaging/install.sh
@@ -107,7 +107,7 @@ install_linux_app() {
mkdir -p "$data" && cp -R "$TMP/$name/share/." "$data/"
say "Installed the Codync desktop app to $BIN_DIR/codync"
if command -v ldd >/dev/null && missing=$(ldd "$BIN_DIR/codync" 2>&1 | grep 'not found'); then
- echo " It won't start yet: it needs GTK 4, libadwaita and glibc 2.39+ (Ubuntu 24.04 or newer). Missing:"
+ echo " It won't start yet: it needs GTK 4, libadwaita, VTE (GTK 4) and glibc 2.39+ (Ubuntu 24.04 or newer). Missing:"
echo "$missing" | sed 's/^[[:space:]]*/ /' | sort -u
fi
}