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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
Linux app looks and works like the Mac window: sidebar, chats, groups, threads, compose and group editor
leepokai098e7a6aa80c
diff --git a/apps/linux/src/avatar.rs b/apps/linux/src/avatar.rsindex f06ad9a4..891e7eee 100644--- a/apps/linux/src/avatar.rs+++ b/apps/linux/src/avatar.rs@@ -1,4 +1,5 @@//! Grok-Bot-style characters (same silhouettes and palette as the Apple apps), drawn with cairo.+//! Mirrors CodyncKit/Design/CharacterAvatar.swift: `CharacterAvatar`, `GroupAvatar`, `AvatarWithStatus`.use gtk::cairo::Context;use gtk::prelude::*;@@ -25,9 +26,9 @@ pub const COLORS: &[(&str, u32)] = &[pub fn rgb(hex: u32) -> (f64, f64, f64) {(- ((hex >> 16) & 0xFF) as f64 / 255.0,- ((hex >> 8) & 0xFF) as f64 / 255.0,- (hex & 0xFF) as f64 / 255.0,+ f64::from((hex >> 16) & 0xFF) / 255.0,+ f64::from((hex >> 8) & 0xFF) / 255.0,+ f64::from(hex & 0xFF) / 255.0,)}@@ -35,8 +36,7 @@ pub fn color_of(name: &str) -> u32 {COLORS.iter().find(|(n, _)| *n == name)- .map(|c| c.1)- .unwrap_or(0x1084FE)+ .map_or(0x1084FE, |c| c.1)}fn rounded_rect(cr: &Context, x: f64, y: f64, w: f64, h: f64, r: f64) {@@ -48,42 +48,57 @@ fn rounded_rect(cr: &Context, x: f64, y: f64, w: f64, h: f64, r: f64) {cr.close_path();}-/// Draws the silhouette into a 100×100 unit box.+fn ellipse(cr: &Context, x: f64, y: f64, w: f64, h: f64) {+ cr.save().ok();+ cr.translate(x + w / 2.0, y + h / 2.0);+ cr.scale(w / 2.0, h / 2.0);+ cr.new_sub_path();+ cr.arc(0.0, 0.0, 1.0, 0.0, 2.0 * PI);+ cr.restore().ok();+}++/// A quadratic curve as the cubic cairo draws.+fn quad_to(cr: &Context, (cx, cy): (f64, f64), (x, y): (f64, f64)) {+ let (x0, y0) = cr.current_point().unwrap_or((x, y));+ cr.curve_to(+ x0 + 2.0 / 3.0 * (cx - x0),+ y0 + 2.0 / 3.0 * (cy - y0),+ x + 2.0 / 3.0 * (cx - x),+ y + 2.0 / 3.0 * (cy - y),+ x,+ y,+ );+}++/// Draws the silhouette into a 100×100 unit box (`CharacterShape`).fn silhouette(cr: &Context, shape: &str) {match shape {- "pebble" => {- cr.save().ok();- cr.translate(50.0, 50.0);- cr.scale(50.0, 40.0);- cr.arc(0.0, 0.0, 1.0, 0.0, 2.0 * PI);- cr.restore().ok();- }+ "pebble" => ellipse(cr, 0.0, 10.0, 100.0, 80.0),"squircle" => rounded_rect(cr, 4.0, 4.0, 92.0, 92.0, 30.0),"tablet" => rounded_rect(cr, 14.0, 0.0, 72.0, 100.0, 22.0),"wedge" => {cr.move_to(50.0, 4.0);- cr.curve_to(76.0, 30.0, 90.0, 55.0, 98.0, 86.0);- cr.curve_to(66.0, 100.0, 34.0, 100.0, 2.0, 86.0);- cr.curve_to(10.0, 55.0, 24.0, 30.0, 50.0, 4.0);+ quad_to(cr, (90.0, 40.0), (98.0, 86.0));+ quad_to(cr, (50.0, 104.0), (2.0, 86.0));+ quad_to(cr, (10.0, 40.0), (50.0, 4.0));cr.close_path();}"hex" => {for i in 0..6 {- let a = i as f64 * PI / 3.0 - PI / 2.0;+ let a = f64::from(i) * PI / 3.0 - PI / 2.0;let (x, y) = (50.0 + a.cos() * 49.0, 50.0 + a.sin() * 49.0);if i == 0 {- cr.move_to(x, y)+ cr.move_to(x, y);} else {- cr.line_to(x, y)+ cr.line_to(x, y);}}cr.close_path();}"cloud" => {- for (x, y, r) in [(27.0, 57.0, 27.0), (73.0, 57.0, 27.0), (50.0, 40.0, 32.0)] {- cr.new_sub_path();- cr.arc(x, y, r, 0.0, 2.0 * PI);- }+ ellipse(cr, 0.0, 30.0, 55.0, 55.0);+ ellipse(cr, 45.0, 30.0, 55.0, 55.0);+ ellipse(cr, 18.0, 8.0, 64.0, 64.0);rounded_rect(cr, 10.0, 50.0, 80.0, 35.0, 15.0);}"teardrop" => {@@ -95,13 +110,13 @@ fn silhouette(cr: &Context, shape: &str) {}_ => {for i in 0..=64 {- let a = i as f64 / 64.0 * 2.0 * PI;+ let a = f64::from(i) / 64.0 * 2.0 * PI;let r = 46.0 + 3.5 * (a * 3.0 + 0.6).sin();let (x, y) = (50.0 + a.cos() * r, 50.0 + a.sin() * r);if i == 0 {- cr.move_to(x, y)+ cr.move_to(x, y);} else {- cr.line_to(x, y)+ cr.line_to(x, y);}}cr.close_path();@@ -116,17 +131,28 @@ pub enum Mood {Needs,}-/// Same look as `CharacterAvatar` on Apple platforms: a halftone of dots shaded-/// as if the silhouette were a sphere (grey ink, the bot's color only on the-/// brightest dots) and two slit eyes. Working swings the light and drifts the-/// eyes; needing you sends a ripple out from the center. Below 24px the body-/// stays solid because the dots stop reading.-/// Same grid as the Apple apps (CharacterAvatar.swift): 13×13 square cells,-/// eyes are the *missing* dots in columns 4 and 8 of rows 4–6.-const CELLS: i32 = 13;-const EYE_COLUMNS: [i32; 2] = [4, 8];-const EYE_ROWS: [i32; 3] = [4, 5, 6];+pub fn mood(b: &Value) -> Mood {+ match b["status"].as_str() {+ Some("needsInput") => Mood::Needs,+ Some("working") => Mood::Working,+ _ => Mood::Idle,+ }+}+/// Small icons use fewer, larger dots so the gaps and hollow eyes survive.+fn grid(size: f64) -> (i32, &'static [i32], &'static [i32]) {+ if size < 18.0 {+ (7, &[2, 4], &[2, 3])+ } else if size < 28.0 {+ (9, &[3, 6], &[3, 4])+ } else {+ (13, &[4, 8], &[4, 5, 6])+ }+}++/// A halftone of dots shaded as if the silhouette were a ball (grey ink, the bot's color+/// only on the brightest dots), eyes left hollow. Working swings the light and glances;+/// needing you sends a ripple out from the center.pub fn draw(cr: &Context,size: f64,@@ -139,46 +165,34 @@ pub fn draw(cr.save().ok();cr.scale(size / 100.0, size / 100.0);let (r, g, b) = rgb(color_of(color));- let step = 100.0 / f64::from(CELLS);+ let (cells, eye_cols, all_eye_rows) = grid(size);+ let step = 100.0 / f64::from(cells);let animated = mood != Mood::Idle;- // Glance: whole-cell steps left / center / right, like a small display.let glance = if mood == Mood::Working {((t * 2.0 * PI / 3.2).sin() * 1.4).round() as i32} else {0};let blinking = animated && (t / 4.7).fract() < 0.035;- let eye_rows: &[i32] = if blinking { &EYE_ROWS[2..] } else { &EYE_ROWS };- let is_eye = |col: i32, row: i32| {- EYE_COLUMNS.iter().any(|c| c + glance == col) && eye_rows.contains(&row)+ let eye_rows = if blinking {+ &all_eye_rows[all_eye_rows.len() - 1..]+ } else {+ all_eye_rows};-silhouette(cr, shape);- if size < 24.0 {- // Too few dots to read: a solid body with the same hollow eyes.- cr.set_source_rgb(r, g, b);- cr.fill().ok();- cr.set_operator(gtk::cairo::Operator::Clear);- for c in EYE_COLUMNS {- for &row in eye_rows {- cr.rectangle(- f64::from(c + glance) * step,- f64::from(row) * step,- step,- step,- );- }- }- cr.fill().ok();- cr.set_operator(gtk::cairo::Operator::Over);- cr.restore().ok();- return;+ let hex = shape == "hex";+ if hex {+ cr.set_line_width(8.0);+ cr.set_line_join(gtk::cairo::LineJoin::Round);}let mut dots = Vec::new();- for row in 0..CELLS {- for col in 0..CELLS {+ for row in 0..cells {+ for col in 0..cells {let (x, y) = ((f64::from(col) + 0.5) * step, (f64::from(row) + 0.5) * step);- if cr.in_fill(x, y).unwrap_or(false) && !is_eye(col, row) {+ let inside =+ cr.in_fill(x, y).unwrap_or(false) || (hex && cr.in_stroke(x, y).unwrap_or(false));+ let eye = eye_cols.iter().any(|c| c + glance == col) && eye_rows.contains(&row);+ if inside && !eye {dots.push((x, y));}}@@ -196,7 +210,12 @@ pub fn draw(shade *= 0.6 + 0.4 * (0.5 + 0.5 * ((u * u + v * v).sqrt() * 9.0 - t * 5.0).sin());}cr.arc(x, y, step * 0.42 * (0.55 + 0.45 * shade), 0.0, 2.0 * PI);- cr.set_source_rgba(ink.0, ink.1, ink.2, 0.2 + 0.4 * (shade / 0.7).min(1.0));+ let alpha = if cells < 13 {+ 0.4 + 0.4 * shade+ } else {+ 0.2 + 0.4 * (shade / 0.7).min(1.0)+ };+ cr.set_source_rgba(ink.0, ink.1, ink.2, alpha);cr.fill_preserve().ok();if shade > 0.6 {cr.set_source_rgba(r, g, b, (shade - 0.6) / 0.4);@@ -207,99 +226,169 @@ pub fn draw(cr.restore().ok();}-pub fn widget(- shape: &str,- color: &str,- size: i32,- working: bool,- status: &str,-) -> gtk::DrawingArea {- many(- vec![(shape.to_owned(), color.to_owned())],- size,- working,- status,- )-}+type Part = (String, String, Mood);-fn look(b: &Value) -> (String, String) {+fn part(b: &Value, animated: bool) -> Part {(b["avatarShape"].as_str().unwrap_or("blob").to_owned(),b["avatarColor"].as_str().unwrap_or("blue").to_owned(),+ if animated { mood(b) } else { Mood::Idle },+ )+}++#[derive(Clone, Copy, PartialEq)]+enum Badge {+ None,+ Unread,+ Needs,+}++/// One character in a fixed look.+pub fn shape(shape: &str, color: &str, size: i32, mood: Mood) -> gtk::DrawingArea {+ area(+ vec![(shape.to_owned(), color.to_owned(), mood)],+ size,+ Badge::None,)}-/// A bot's character, or for a group its first two members overlapped.-pub fn of(+/// A bot's character, or for a group its first two members, one tucked behind the other.+pub fn of(bots: &HashMap<String, Value>, b: &Value, size: i32, animated: bool) -> gtk::DrawingArea {+ build(bots, b, size, animated, Badge::None)+}++/// The roster avatar: a dot when unread, an amber "!" when it needs you.+pub fn with_status(bots: &HashMap<String, Value>, b: &Value, size: i32) -> gtk::DrawingArea {+ let badge = if b["status"] == "needsInput" {+ Badge::Needs+ } else if b["unread"].as_i64().unwrap_or(0) > 0 {+ Badge::Unread+ } else {+ Badge::None+ };+ build(bots, b, size, true, badge)+}++fn build(bots: &HashMap<String, Value>,b: &Value,size: i32,- working: bool,- status: &str,+ animated: bool,+ badge: Badge,) -> gtk::DrawingArea {- let parts = if b["kind"] == "group" {- b["members"]+ if b["kind"] == "group" {+ let parts = b["members"].as_array().into_iter().flatten().filter_map(|m| bots.get(m.as_str()?)).take(2)- .map(look)- .collect()+ .map(|m| part(m, animated))+ .collect();+ area(parts, size, badge)} else {- vec![look(b)]- };- many(parts, size, working, status)+ area(vec![part(b, animated)], size, badge)+ }}-fn many(parts: Vec<(String, String)>, size: i32, working: bool, status: &str) -> gtk::DrawingArea {+/// Several characters drawn side by side, overlapping by `overlap` px (the empty state's trio).+pub fn row(looks: &[(&str, &str, Mood)], size: i32, overlap: i32) -> gtk::DrawingArea {+ let n = i32::try_from(looks.len()).unwrap_or(1);+ let looks: Vec<Part> = looks+ .iter()+ .map(|(s, c, m)| ((*s).to_owned(), (*c).to_owned(), *m))+ .collect();+ let moving = looks.iter().any(|p| p.2 != Mood::Idle);+ let area = gtk::DrawingArea::builder()+ .content_width(size * n - overlap * (n - 1))+ .content_height(size)+ .halign(gtk::Align::Center)+ .build();+ let start = std::time::Instant::now();+ area.set_draw_func(move |area, cr, _, _| {+ let fg = area.color();+ let ink = (+ f64::from(fg.red()),+ f64::from(fg.green()),+ f64::from(fg.blue()),+ );+ let t = start.elapsed().as_secs_f64();+ for (i, (s, c, m)) in looks.iter().enumerate() {+ cr.save().ok();+ cr.translate(f64::from(size - overlap) * i as f64, 0.0);+ draw(cr, f64::from(size), s, c, ink, *m, t);+ cr.restore().ok();+ }+ });+ if moving {+ area.add_tick_callback(|a, _| {+ a.queue_draw();+ gtk::glib::ControlFlow::Continue+ });+ }+ area+}++fn area(parts: Vec<Part>, size: i32, badge: Badge) -> gtk::DrawingArea {let area = gtk::DrawingArea::builder().content_width(size).content_height(size).valign(gtk::Align::Center)+ .halign(gtk::Align::Center).build();- let status = status.to_owned();- let mood = if status == "needs" {- Mood::Needs- } else if working {- Mood::Working- } else {- Mood::Idle- };+ let moving = parts.iter().any(|p| p.2 != Mood::Idle);let start = std::time::Instant::now();area.set_draw_func(move |area, cr, w, _| {- let s = w as f64;+ let s = f64::from(w);let fg = area.color();- let ink = (fg.red() as f64, fg.green() as f64, fg.blue() as f64);+ let ink = (+ f64::from(fg.red()),+ f64::from(fg.green()),+ f64::from(fg.blue()),+ );let t = start.elapsed().as_secs_f64();match parts.as_slice() {- [] => draw(cr, s, "blob", "gray", ink, mood, t),- [(shape, color)] => draw(cr, s, shape, color, ink, mood, t),- _ => {- let sub = s * 0.68;- for (i, (shape, color)) in parts.iter().enumerate() {- let o = if i == 0 { 0.0 } else { s - sub };+ [] => draw(cr, s, "blob", "gray", ink, Mood::Idle, t),+ [(shape, color, m)] => draw(cr, s, shape, color, ink, *m, t),+ [first, second, ..] => {+ let small = s * 0.66;+ // Second member top-right, behind; first bottom-left.+ for (p, (x, y)) in [(second, (s - small, 0.0)), (first, (0.0, s - small))] {cr.save().ok();- cr.translate(o, o);- draw(cr, sub, shape, color, ink, mood, t);+ cr.translate(x, y);+ draw(cr, small, &p.0, &p.1, ink, p.2, t);cr.restore().ok();}}}- if !status.is_empty() {- let d = s * if status == "needs" { 0.36 } else { 0.28 };+ if badge != Badge::None {+ let d = s * if badge == Badge::Needs { 0.36 } else { 0.28 };let (cx, cy) = (s - d / 2.0, s - d / 2.0);- let (r, g, b) = if status == "needs" {- rgb(0xF0A030)- } else {- ink- };- cr.arc(cx, cy, d / 2.0, 0.0, 2.0 * PI);- cr.set_source_rgb(r, g, b);+ let dark = adw::StyleManager::default().is_dark();+ let bg = if dark { 0.04 } else { 1.0 };+ cr.arc(cx, cy, d / 2.0 + 2.0, 0.0, 2.0 * PI);+ cr.set_source_rgb(bg, bg, bg);cr.fill().ok();+ cr.arc(cx, cy, d / 2.0, 0.0, 2.0 * PI);+ if badge == Badge::Needs {+ let (r, g, b) = rgb(0xF0A030);+ cr.set_source_rgb(r, g, b);+ cr.fill().ok();+ cr.set_source_rgb(1.0, 1.0, 1.0);+ cr.set_line_width(d * 0.16);+ cr.set_line_cap(gtk::cairo::LineCap::Round);+ cr.move_to(cx, cy - d * 0.22);+ cr.line_to(cx, cy + d * 0.06);+ cr.stroke().ok();+ cr.arc(cx, cy + d * 0.24, d * 0.08, 0.0, 2.0 * PI);+ cr.fill().ok();+ } else {+ cr.set_source_rgb(ink.0, ink.1, ink.2);+ cr.fill().ok();+ }}});- if working {+ if moving {area.add_tick_callback(|a, _| {a.queue_draw();gtk::glib::ControlFlow::Continuediff --git a/apps/linux/src/compose.rs b/apps/linux/src/compose.rsnew file mode 100644index 00000000..ae7ea7a6--- /dev/null+++ b/apps/linux/src/compose.rs@@ -0,0 +1,491 @@+//! The "new message" page (kit NewChatView): a To: field that searches your bots or creates a+//! 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::client;+use crate::rows::{hline, icon_button, label};+use crate::ui::{self, App, flat_header};+use crate::{avatar, dialogs};+use adw::prelude::*;+use serde_json::{Value, json};+use std::cell::{Cell, RefCell};++pub struct Page {+ pub root: gtk::Box,+ chips: gtk::Box,+ to: gtk::Entry,+ list: gtk::Box,+ draft: gtk::Entry,+ close_btn: gtk::Button,+ recipients: RefCell<Vec<String>>,+ creating: Cell<bool>,+ /// The chat that was open before, restored when the page closes empty-handed.+ previous: RefCell<Option<String>>,+}++pub fn build() -> Page {+ let chips = gtk::Box::builder().spacing(6).build();+ let to = gtk::Entry::builder()+ .css_classes(["plain", "title3"])+ .hexpand(true)+ .width_chars(20)+ .build();+ chips.append(&to);+ let to_row = gtk::Box::builder()+ .spacing(8)+ .hexpand(true)+ .margin_start(16)+ .margin_end(8)+ .build();+ to_row.append(&label("To:", &["title3", "secondary"]));+ to_row.append(+ >k::ScrolledWindow::builder()+ .child(&chips)+ .vscrollbar_policy(gtk::PolicyType::Never)+ .hscrollbar_policy(gtk::PolicyType::External)+ .hexpand(true)+ .build(),+ );+ let close = icon_button("window-close-symbolic", "Close (Esc)");+ to_row.append(&close);+ let list = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(2)+ .build();+ let card = gtk::Box::builder()+ .css_classes(["pick-card"])+ .halign(gtk::Align::Start)+ .valign(gtk::Align::Start)+ .margin_start(22)+ .margin_end(22)+ .margin_top(10)+ .build();+ card.append(+ >k::ScrolledWindow::builder()+ .child(&list)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .propagate_natural_height(true)+ .propagate_natural_width(true)+ .max_content_height(460)+ .hexpand(true)+ .build(),+ );+ let draft = gtk::Entry::builder()+ .css_classes(["plain"])+ .hexpand(true)+ .margin_top(11)+ .margin_bottom(11)+ .build();+ let pill = gtk::Box::builder()+ .css_classes(["composer"])+ .margin_start(16)+ .margin_end(16)+ .margin_bottom(16)+ .margin_top(16)+ .build();+ pill.append(&draft);+ let root = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .css_classes(["chat-bg"])+ .build();+ let header = flat_header(&to_row);+ root.append(&header);+ root.append(&hline());+ root.append(&card);+ root.append(>k::Box::builder().vexpand(true).build());+ root.append(&pill);+ Page {+ root,+ chips,+ to,+ list,+ draft,+ close_btn: close,+ recipients: RefCell::new(vec![]),+ creating: Cell::new(false),+ previous: RefCell::new(None),+ }+}++pub fn open(ui: &App) {+ {+ let mut st = ui.state.borrow_mut();+ if !st.composing {+ *ui.compose_page.previous.borrow_mut() = st.current.take();+ }+ st.composing = true;+ st.open_thread = None;+ }+ let p = &ui.compose_page;+ p.recipients.borrow_mut().clear();+ p.to.set_text("");+ p.draft.set_text("");+ ui.roster.unselect_all();+ ui.split.set_show_content(true);+ ui::render(ui);+ p.to.grab_focus();+}++fn close(ui: &App) {+ {+ let mut st = ui.state.borrow_mut();+ st.composing = false;+ if st.current.is_none() {+ st.current = ui.compose_page.previous.borrow_mut().take();+ }+ }+ ui::schedule(ui);+}++/// Bots not picked yet; a group can only be opened on its own, so groups go once someone's picked.+fn matches(ui: &App) -> Vec<Value> {+ let st = ui.state.borrow();+ let q = ui.compose_page.to.text().trim().to_lowercase();+ let picked = ui.compose_page.recipients.borrow();+ ui::roster(&st)+ .into_iter()+ .filter(|b| {+ let id = b["id"].as_str().unwrap_or_default();+ !picked.iter().any(|p| p == id)+ && (!ui::is_group(b) || picked.is_empty())+ && (q.is_empty()+ || b["name"]+ .as_str()+ .is_some_and(|n| n.to_lowercase().contains(&q)))+ })+ .cloned()+ .collect()+}++fn keycaps(n: usize) -> gtk::Box {+ let b = gtk::Box::builder().spacing(3).build();+ for k in ["Ctrl", &n.to_string()] {+ let l = gtk::Label::builder()+ .label(k)+ .css_classes(["keycap"])+ .build();+ b.append(&l);+ }+ b+}++fn pick_row(icon: &impl IsA<gtk::Widget>, text: &str, shortcut: Option<usize>) -> gtk::Button {+ let row = gtk::Box::builder().spacing(12).build();+ row.append(icon);+ let l = gtk::Label::builder()+ .label(text)+ .xalign(0.0)+ .hexpand(true)+ .ellipsize(gtk::pango::EllipsizeMode::End)+ // Wide enough to fill the Mac's 620 pt card when there's room.+ .width_chars(62)+ .max_width_chars(62)+ .build();+ row.append(&l);+ if let Some(n) = shortcut {+ row.append(&keycaps(n));+ }+ gtk::Button::builder()+ .child(&row)+ .css_classes(["pick-row"])+ .build()+}++pub fn render(ui: &App) {+ let p = &ui.compose_page;+ // Chips before the field.+ while let Some(c) = p.chips.first_child() {+ if c == p.to.clone().upcast::<gtk::Widget>() {+ break;+ }+ p.chips.remove(&c);+ }+ let st = ui.state.borrow();+ let picked: Vec<Value> = p+ .recipients+ .borrow()+ .iter()+ .filter_map(|id| st.bots.get(id).cloned())+ .collect();+ for b in &picked {+ let id = b["id"].as_str().unwrap_or_default().to_owned();+ let ui2 = ui.clone();+ let chip = bot_chip(&st.bots, b, move || remove(&ui2, &id));+ p.chips+ .insert_child_after(&chip, p.to.prev_sibling().as_ref());+ }+ p.to.set_placeholder_text(Some(if picked.is_empty() {+ "Search or create bots"+ } else {+ "Add another bot"+ }));+ p.draft.set_placeholder_text(Some(&match picked.len() {+ 0 => "Message Bot".to_owned(),+ _ => format!(+ "Message {}",+ picked+ .iter()+ .filter_map(|b| b["name"].as_str())+ .collect::<Vec<_>>()+ .join(", ")+ ),+ }));+ drop(st);++ ui::clear(&p.list);+ let q = p.to.text().trim().to_owned();+ let plus_box = gtk::Image::builder()+ .icon_name(if p.creating.get() {+ "content-loading-symbolic"+ } else {+ "list-add-symbolic"+ })+ .pixel_size(13)+ .width_request(26)+ .height_request(26)+ .css_classes(["plus-circle"])+ .build();+ let create_row = pick_row(+ &plus_box,+ &if q.is_empty() {+ "Create new Bot".to_owned()+ } else {+ format!("Create “{q}”")+ },+ Some(1),+ );+ {+ let ui2 = ui.clone();+ create_row.connect_clicked(move |_| create(&ui2));+ }+ p.list.append(&create_row);+ let st = ui.state.borrow();+ for (i, b) in matches(ui).iter().enumerate() {+ let n = i + 2;+ let row = pick_row(+ &avatar::of(&st.bots, b, 26, false),+ b["name"].as_str().unwrap_or(""),+ (n <= 9).then_some(n),+ );+ let (ui2, b2) = (ui.clone(), b.clone());+ row.connect_clicked(move |_| choose(&ui2, &b2));+ p.list.append(&row);+ }+}++/// A picked bot (To: field, group editor); its x takes it back out.+pub fn bot_chip(+ bots: &std::collections::HashMap<String, Value>,+ b: &Value,+ remove: impl Fn() + 'static,+) -> gtk::Box {+ let chip = gtk::Box::builder()+ .spacing(6)+ .css_classes(["chip"])+ .valign(gtk::Align::Center)+ .build();+ chip.append(&avatar::of(bots, b, 20, false));+ let name = b["name"].as_str().unwrap_or("");+ let l = label(name, &["body13"]);+ l.set_max_width_chars(24);+ l.set_ellipsize(gtk::pango::EllipsizeMode::End);+ chip.append(&l);+ let x = gtk::Button::builder()+ .icon_name("window-close-symbolic")+ .css_classes(["chip-x"])+ .tooltip_text(format!("Remove {name}"))+ .build();+ x.connect_clicked(move |_| remove());+ chip.append(&x);+ chip+}++/// A bot becomes a chip; a group (with nobody picked) opens right away.+fn choose(ui: &App, b: &Value) {+ let id = b["id"].as_str().unwrap_or_default().to_owned();+ if ui::is_group(b) {+ open_chat(ui, &id);+ return;+ }+ ui.compose_page.recipients.borrow_mut().push(id);+ ui.compose_page.to.set_text("");+ render(ui);+ ui.compose_page.to.grab_focus();+}++fn remove(ui: &App, id: &str) {+ ui.compose_page.recipients.borrow_mut().retain(|x| x != id);+ render(ui);+}++/// Return in To: picks the top match, or with the field empty, starts the chat.+fn submit_to(ui: &App) {+ if ui.compose_page.to.text().trim().is_empty() {+ start(ui);+ } else if let Some(first) = matches(ui).first() {+ choose(ui, first);+ } else {+ create(ui);+ }+}++/// One bot: its chat. Several: their group chat.+fn start(ui: &App) {+ let ids = ui.compose_page.recipients.borrow().clone();+ match ids.len() {+ 0 => {}+ 1 => open_chat(ui, &ids[0]),+ _ => {+ let names = {+ let st = ui.state.borrow();+ ids.iter()+ .filter_map(|id| st.bots.get(id)?["name"].as_str().map(str::to_owned))+ .collect::<Vec<_>>()+ .join(", ")+ };+ let ui2 = ui.clone();+ client::call(+ "createBot",+ json!({"id": "", "kind": "group", "name": names, "members": ids}),+ move |r| match r {+ Ok(v) => {+ let bot = v["bot"].clone();+ let id = bot["id"].as_str().unwrap_or_default().to_owned();+ ui2.state.borrow_mut().bots.insert(id.clone(), bot);+ open_chat(&ui2, &id);+ }+ Err(e) => ui::toast(&ui2, &e),+ },+ );+ }+ }+}++/// Opens the chat and sends whatever was typed.+fn open_chat(ui: &App, id: &str) {+ let text = ui.compose_page.draft.text().trim().to_owned();+ ui.compose_page.draft.set_text("");+ ui.compose_page.previous.borrow_mut().take();+ ui::select(ui, id);+ if !text.is_empty() {+ ui::send_text(ui, id, &text, None);+ }+}++/// "New Bot" (or the typed name) with sensible defaults: the first available agent, home folder.+fn create(ui: &App) {+ if ui.compose_page.creating.replace(true) {+ return;+ }+ render(ui);+ let typed = ui.compose_page.to.text().trim().to_owned();+ let name = if typed.is_empty() {+ "New Bot".to_owned()+ } else {+ typed+ };+ let body = {+ let st = ui.state.borrow();+ let backends = st.hello["backends"].as_array().cloned().unwrap_or_default();+ let n = uuid::Uuid::new_v4().as_u128() as usize;+ json!({+ "name": name, "description": "", "permission": "ask", "model": null, "command": null,+ "cwd": st.hello["home"].as_str().unwrap_or(""),+ "avatarShape": avatar::SHAPES[n % avatar::SHAPES.len()],+ "avatarColor": avatar::COLORS[(n / 8) % avatar::COLORS.len()].0,+ "backend": backends.iter().find(|b| b["available"] == true).and_then(|b| b["id"].as_str()).unwrap_or("claude"),+ })+ };+ let ui2 = ui.clone();+ client::call("createBot", body, move |r| {+ ui2.compose_page.creating.set(false);+ match r {+ Ok(v) => {+ let bot = v["bot"].clone();+ let id = bot["id"].as_str().unwrap_or_default().to_owned();+ ui2.state.borrow_mut().bots.insert(id.clone(), bot.clone());+ if ui2.compose_page.recipients.borrow().is_empty() {+ open_chat(&ui2, &id);+ // A fresh "New Bot" opens on its settings, like the Mac's details panel.+ if bot["name"] == "New Bot" {+ dialogs::editor(&ui2, Some(bot));+ }+ } else {+ choose(&ui2, &bot);+ }+ }+ Err(e) => {+ ui::toast(&ui2, &e);+ render(&ui2);+ }+ }+ });+}++pub fn wire(ui: &App) {+ let p = &ui.compose_page;+ {+ let ui2 = ui.clone();+ p.to.connect_changed(move |_| render(&ui2));+ }+ {+ let ui2 = ui.clone();+ p.to.connect_activate(move |_| submit_to(&ui2));+ }+ {+ let ui2 = ui.clone();+ p.draft.connect_activate(move |_| start(&ui2));+ }+ // Backspace in an empty To: takes the last chip back out.+ {+ let ui2 = ui.clone();+ let keys = gtk::EventControllerKey::builder()+ .propagation_phase(gtk::PropagationPhase::Capture)+ .build();+ keys.connect_key_pressed(move |_, key, _, _| {+ let p = &ui2.compose_page;+ if key == gtk::gdk::Key::BackSpace && p.to.text().is_empty() {+ let last = p.recipients.borrow().last().cloned();+ if let Some(id) = last {+ remove(&ui2, &id);+ return gtk::glib::Propagation::Stop;+ }+ }+ gtk::glib::Propagation::Proceed+ });+ p.to.add_controller(keys);+ }+ // Ctrl+1 creates, Ctrl+2…9 pick; Esc closes.+ {+ let ui2 = ui.clone();+ let keys = gtk::EventControllerKey::builder()+ .propagation_phase(gtk::PropagationPhase::Capture)+ .build();+ keys.connect_key_pressed(move |_, key, _, mods| {+ if key == gtk::gdk::Key::Escape {+ close(&ui2);+ return gtk::glib::Propagation::Stop;+ }+ if mods.contains(gtk::gdk::ModifierType::CONTROL_MASK)+ && let Some(d) = key.to_unicode().and_then(|c| c.to_digit(10))+ {+ match d {+ 1 => create(&ui2),+ 2..=9 => {+ if let Some(b) = matches(&ui2).get(d as usize - 2) {+ choose(&ui2, b);+ }+ }+ _ => return gtk::glib::Propagation::Proceed,+ }+ return gtk::glib::Propagation::Stop;+ }+ gtk::glib::Propagation::Proceed+ });+ p.root.add_controller(keys);+ }+ {+ let ui2 = ui.clone();+ p.close_btn.connect_clicked(move |_| close(&ui2));+ }+}diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rsindex 6537aaef..43c5f784 100644--- a/apps/linux/src/dialogs.rs+++ b/apps/linux/src/dialogs.rs@@ -1,7 +1,8 @@//! Bot and group editors, full-conversation trace, settings/pairing and the bot menu.use crate::client;-use crate::ui::{self, App};+use crate::rows::{icon_button, label};+use crate::ui::{self, App, MenuItem};use crate::{avatar, markup};use adw::prelude::*;use serde_json::{Value, json};@@ -65,12 +66,11 @@ pub fn editor(ui: &App, bot: Option<Value>) {preview.remove(&c);}let b = d.borrow();- preview.append(&avatar::widget(+ preview.append(&avatar::shape(b["avatarShape"].as_str().unwrap_or("blob"),b["avatarColor"].as_str().unwrap_or("blue"),84,- true,- "",+ avatar::Mood::Working,));}};@@ -89,12 +89,11 @@ pub fn editor(ui: &App, bot: Option<Value>) {.build();for s in avatar::SHAPES {let btn = gtk::Button::builder()- .child(&avatar::widget(+ .child(&avatar::shape(s,d.borrow()["avatarColor"].as_str().unwrap_or("blue"),30,- false,- "",+ avatar::Mood::Idle,)).css_classes(["flat"]).tooltip_text(*s)@@ -376,7 +375,8 @@ pub fn editor(ui: &App, bot: Option<Value>) {// MARK: group editor-/// Create a group chat, or rename one, describe it and change who's in it.+/// Create a group chat, or change its name, what it's for and who's in it (GroupEditorView).+/// Bots are picked like recipients: chips on top, a search, and the bots not in it yet.pub fn group_editor(ui: &App, group: Option<Value>) {let is_new = group.is_none();let group_id = group@@ -392,32 +392,49 @@ pub fn group_editor(ui: &App, group: Option<Value>) {.filter_map(|m| m.as_str().map(str::to_owned)).collect(),));- let (dialog, view, header) = header_dialog(+ let (dialog, body, save) = modal(if is_new {"New group chat"} else {"Group chat"},- 480,- 620,+ if is_new { "Create" } else { "Save" },+ 420,+ 560,);- let save = gtk::Button::builder()- .icon_name("object-select-symbolic")- .tooltip_text(if is_new { "Create" } else { "Save" })- .css_classes(["accent-fill", "circular"])- .build();- header.pack_end(&save);+ let preview = gtk::Box::builder().halign(gtk::Align::Center).build();+ body.append(&preview);- let page = adw::PreferencesPage::new();- let profile = adw::PreferencesGroup::new();- // The sidebar's avatar: the first two members overlapped.- let preview = gtk::Box::builder()- .halign(gtk::Align::Center)- .margin_bottom(8)+ let bots_label = field_label("Bots");+ let chips = gtk::Box::builder().spacing(6).build();+ let chips_scroll = gtk::ScrolledWindow::builder()+ .child(&chips)+ .vscrollbar_policy(gtk::PolicyType::Never)+ .hscrollbar_policy(gtk::PolicyType::External).build();- profile.add(&preview);- let name = adw::EntryRow::builder()- .title("Name")+ let search = gtk::Entry::builder().css_classes(["field-box"]).build();+ let candidates = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(2)+ .build();+ let bots_field = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(8)+ .build();+ bots_field.append(&bots_label);+ bots_field.append(&chips_scroll);+ bots_field.append(&search);+ bots_field.append(&candidates);+ let help = label(+ "Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools.",+ &["footnote", "tertiary"],+ );+ help.set_wrap(true);+ bots_field.append(&help);+ body.append(&bots_field);++ let name = gtk::Entry::builder()+ .css_classes(["field-box"]).text(group.as_ref()@@ -425,19 +442,9 @@ pub fn group_editor(ui: &App, group: Option<Value>) {.unwrap_or(""),).build();- profile.add(&name);- page.add(&profile);-- let about_group = adw::PreferencesGroup::builder()- .title("About this group")- .description("Optional. Every bot in the group sees it.")- .build();+ body.append(&field("Name", &name));let about = gtk::TextView::builder().wrap_mode(gtk::WrapMode::WordChar)- .top_margin(8)- .bottom_margin(8)- .left_margin(8)- .right_margin(8).build();about.buffer().set_text(group@@ -445,116 +452,16 @@ pub fn group_editor(ui: &App, group: Option<Value>) {.and_then(|g| g["description"].as_str()).unwrap_or(""),);- about_group.add(- >k::Frame::builder()- .child(- >k::ScrolledWindow::builder()- .min_content_height(70)- .child(&about)- .build(),- )- .build(),- );- page.add(&about_group);-- let bots_group = adw::PreferencesGroup::builder()- .description("Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools.")- .build();- let st = ui.state.borrow();- let mut candidates: Vec<&Value> = st- .bots- .values()- .filter(|b| {- b["kind"] != "group"- && (b["hidden"] != true- || b["id"]- .as_str()- .is_some_and(|id| members.borrow().iter().any(|m| m == id)))- })- .collect();- candidates.sort_by_key(|b| b["name"].as_str().unwrap_or("").to_lowercase());- let mut checks: Vec<(String, String, gtk::CheckButton)> = vec![];- for b in candidates {- let id = b["id"].as_str().unwrap_or_default().to_owned();- let bname = b["name"].as_str().unwrap_or("").to_owned();- let check = gtk::CheckButton::builder()- .active(members.borrow().contains(&id))- .valign(gtk::Align::Center)- .build();- let row = adw::ActionRow::builder()- .title(gtk::glib::markup_escape_text(&bname))- .subtitle(gtk::glib::markup_escape_text(&ui::folder(- b["cwd"].as_str().unwrap_or(""),- )))- .activatable_widget(&check)- .build();- row.add_prefix(&avatar::of(&st.bots, b, 30, false, ""));- row.add_suffix(&check);- bots_group.add(&row);- checks.push((id, bname, check));- }- drop(st);- page.add(&bots_group);- let checks = Rc::new(checks);- // "Alice, Bob" when no name is typed; nothing to save without a bot.- let sync = {- let (members, checks, bots_group, name, save, ui2) = (- members.clone(),- checks.clone(),- bots_group.clone(),- name.clone(),- save.clone(),- ui.clone(),- );- move || {- let m = members.borrow();- while let Some(c) = preview.first_child() {- preview.remove(&c);- }- preview.append(&avatar::of(- &ui2.state.borrow().bots,- &json!({"kind": "group", "members": *m}),- 84,- false,- "",- ));- bots_group.set_title(&format!("Bots · {}", m.len()));- let names: Vec<&str> = m- .iter()- .filter_map(|id| checks.iter().find(|c| c.0 == *id).map(|c| c.1.as_str()))- .collect();- name.set_title(- if names.is_empty() {- "Name".to_owned()- } else {- format!("Name · {}", names.join(", "))- }- .as_str(),- );- save.set_sensitive(!m.is_empty());- }- };- for (id, _, check) in checks.iter() {- let (members, sync, id) = (members.clone(), sync.clone(), id.clone());- check.connect_toggled(move |c| {- {- let mut m = members.borrow_mut();- m.retain(|x| *x != id);- if c.is_active() {- m.push(id.clone());- }- }- sync();- });- }- sync();-+ body.append(&field(+ "About",+ &text_area(&about, "What this group works on (optional)", 2, 5),+ ));if let Some(g) = group.as_ref() {- let danger = adw::PreferencesGroup::new();let del = gtk::Button::builder().label("Delete group chat")- .css_classes(["destructive-action"])- .halign(gtk::Align::Center)+ .css_classes(["secondary-pill", "danger-text"])+ .halign(gtk::Align::Start)+ .margin_top(8).build();let (ui2, dialog2, id, gname) = (ui.clone(),@@ -566,20 +473,168 @@ pub fn group_editor(ui: &App, group: Option<Value>) {dialog2.close();confirm_delete(&ui2, &id, &gname, true);});- danger.add(&del);- page.add(&danger);+ body.append(&del);}- view.set_content(Some(&page));++ let names_of = {+ let ui2 = ui.clone();+ move |ids: &[String]| -> Vec<String> {+ let st = ui2.state.borrow();+ ids.iter()+ .filter_map(|id| st.bots.get(id)?["name"].as_str().map(str::to_owned))+ .collect()+ }+ };+ // Redraws the avatar, chips, candidates and default name from `members` and the search.+ let sync: Rc<RefCell<Box<dyn Fn()>>> = Rc::new(RefCell::new(Box::new(|| {})));+ let toggle = {+ let (members, sync, search) = (members.clone(), Rc::downgrade(&sync), search.clone());+ move |id: &str| {+ {+ let mut m = members.borrow_mut();+ if m.iter().any(|x| x == id) {+ m.retain(|x| x != id);+ } else {+ m.push(id.to_owned());+ }+ }+ search.set_text("");+ if let Some(sync) = sync.upgrade() {+ (sync.borrow())();+ }+ }+ };+ let toggle = Rc::new(toggle);+ *sync.borrow_mut() = {+ let (ui2, members, chips, chips_scroll, candidates, search, name, save, toggle) = (+ ui.clone(),+ members.clone(),+ chips.clone(),+ chips_scroll.clone(),+ candidates.clone(),+ search.clone(),+ name.clone(),+ save.clone(),+ toggle.clone(),+ );+ let names_of = names_of.clone();+ let preview = preview.clone();+ Box::new(move || {+ let m = members.borrow().clone();+ let st = ui2.state.borrow();+ ui::clear(&preview);+ if m.is_empty() {+ let icon = gtk::Image::builder()+ .icon_name("system-users-symbolic")+ .pixel_size(29)+ .width_request(72)+ .height_request(72)+ .css_classes(["secondary"])+ .build();+ preview.append(&icon);+ } else {+ preview.append(&avatar::of(+ &st.bots,+ &json!({"kind": "group", "members": m}),+ 72,+ false,+ ));+ }+ bots_label.set_label(&format!("Bots · {}", m.len()));+ ui::clear(&chips);+ chips_scroll.set_visible(!m.is_empty());+ for id in &m {+ if let Some(b) = st.bots.get(id) {+ let (t, id) = (toggle.clone(), id.clone());+ chips.append(&crate::compose::bot_chip(&st.bots, b, move || t(&id)));+ }+ }+ search.set_placeholder_text(Some(if m.is_empty() {+ "Search bots"+ } else {+ "Add another bot"+ }));+ let q = search.text().trim().to_lowercase();+ ui::clear(&candidates);+ for b in ui::roster(&st).into_iter().filter(|b| {+ !ui::is_group(b)+ && !m.iter().any(|x| b["id"] == x.as_str())+ && (q.is_empty()+ || b["name"]+ .as_str()+ .is_some_and(|n| n.to_lowercase().contains(&q)))+ }) {+ let row = gtk::Box::builder().spacing(12).build();+ row.append(&avatar::of(&st.bots, b, 26, false));+ let text = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(1)+ .hexpand(true)+ .build();+ let bname = b["name"].as_str().unwrap_or("");+ text.append(&label(bname, &["body13"]));+ text.append(&label(+ &ui::folder(b["cwd"].as_str().unwrap_or("")),+ &["footnote", "tertiary"],+ ));+ row.append(&text);+ let plus = gtk::Image::from_icon_name("list-add-symbolic");+ plus.add_css_class("tertiary");+ row.append(&plus);+ let btn = gtk::Button::builder()+ .child(&row)+ .css_classes(["candidate"])+ .tooltip_text(format!("Add {bname}"))+ .build();+ let (t, id) = (toggle.clone(), b["id"].as_str().unwrap_or("").to_owned());+ btn.connect_clicked(move |_| t(&id));+ candidates.append(&btn);+ }+ drop(st);+ let names = names_of(&m);+ name.set_placeholder_text(Some(&if names.is_empty() {+ "Name".to_owned()+ } else {+ names.join(", ")+ }));+ save.set_sensitive(!m.is_empty());+ })+ };+ {+ let sync = sync.clone();+ search.connect_changed(move |_| (sync.borrow())());+ }+ {+ let (ui2, members, toggle) = (ui.clone(), members.clone(), toggle.clone());+ search.connect_activate(move |s| {+ let q = s.text().trim().to_lowercase();+ let first = {+ let st = ui2.state.borrow();+ let m = members.borrow();+ ui::roster(&st)+ .into_iter()+ .find(|b| {+ !ui::is_group(b)+ && !m.iter().any(|x| b["id"] == x.as_str())+ && b["name"]+ .as_str()+ .is_some_and(|n| n.to_lowercase().contains(&q))+ })+ .and_then(|b| b["id"].as_str().map(str::to_owned))+ };+ if let Some(id) = first {+ toggle(&id);+ }+ });+ }+ (sync.borrow())();let (ui2, dialog2) = (ui.clone(), dialog.clone());save.connect_clicked(move |btn| {let m = members.borrow().clone();let typed = name.text().trim().to_owned();let final_name = if typed.is_empty() {- m.iter()- .filter_map(|id| checks.iter().find(|c| c.0 == *id).map(|c| c.1.clone()))- .collect::<Vec<_>>()- .join(", ")+ names_of(&m).join(", ")} else {typed};@@ -604,17 +659,13 @@ pub fn group_editor(ui: &App, group: Option<Value>) {Ok(v) => {let bot = v["bot"].clone();let id = bot["id"].as_str().unwrap_or_default().to_owned();- {- let mut st = ui3.state.borrow_mut();- st.bots.insert(id.clone(), bot);- if is_new {- st.current = Some(id);- st.open_thread = None;- }- }+ ui3.state.borrow_mut().bots.insert(id.clone(), bot);dialog3.close();- ui3.split.set_show_content(true);- ui::schedule(&ui3);+ if is_new {+ ui::select(&ui3, &id);+ } else {+ ui::schedule(&ui3);+ }}Err(e) => {btn2.set_sensitive(true);@@ -625,26 +676,140 @@ pub fn group_editor(ui: &App, group: Option<Value>) {dialog.present(Some(&ui.window));}-fn confirm_delete(ui: &App, id: &str, name: &str, group: bool) {- let alert = adw::AlertDialog::new(- Some(&format!("Delete {name}?")),- Some(if group {- "The group chat is removed. Its bots stay."- } else {- "The conversation is removed. Files it changed stay as they are."- }),+/// A sheet with Codync's modal header (title, a check to save, close) over a scrolling body.+fn modal(+ title: &str,+ save_tip: &str,+ width: i32,+ height: i32,+) -> (adw::Dialog, gtk::Box, gtk::Button) {+ let save = icon_button("object-select-symbolic", save_tip);+ let close = icon_button("window-close-symbolic", "Close");+ let head = gtk::Box::builder()+ .spacing(8)+ .margin_start(16)+ .margin_end(10)+ .height_request(48)+ .build();+ let t = label(title, &["semibold"]);+ t.set_hexpand(true);+ head.append(&t);+ head.append(&save);+ head.append(&close);+ let body = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .margin_start(16)+ .margin_end(16)+ .margin_top(4)+ .margin_bottom(16)+ .build();+ let col = gtk::Box::new(gtk::Orientation::Vertical, 0);+ col.append(&head);+ col.append(+ >k::ScrolledWindow::builder()+ .child(&body)+ .vexpand(true)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .build(),);- alert.add_responses(&[("cancel", "Cancel"), ("delete", "Delete")]);- alert.set_response_appearance("delete", adw::ResponseAppearance::Destructive);- let id = id.to_owned();+ let dialog = adw::Dialog::builder()+ .title(title)+ .content_width(width)+ .content_height(height)+ .child(&col)+ .build();+ {+ let d = dialog.clone();+ close.connect_clicked(move |_| {+ d.close();+ });+ }+ (dialog, body, save)+}++fn field_label(text: &str) -> gtk::Label {+ label(text, &["field-label"])+}++/// A labelled field (the editors' `Field`).+fn field(title: &str, content: &impl IsA<gtk::Widget>) -> gtk::Box {+ let b = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(6)+ .build();+ b.append(&field_label(title));+ b.append(content);+ b+}++/// A multi-line field box with a placeholder, `min`…`max` lines tall.+fn text_area(view: >k::TextView, placeholder: &str, min: i32, max: i32) -> gtk::Box {+ let hint = label(placeholder, &["tertiary"]);+ hint.set_valign(gtk::Align::Start);+ hint.set_can_target(false);+ let buf = view.buffer();+ hint.set_visible(buf.char_count() == 0);+ {+ let hint = hint.clone();+ buf.connect_changed(move |b| hint.set_visible(b.char_count() == 0));+ }+ let scroll = gtk::ScrolledWindow::builder()+ .child(view)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .min_content_height(min * 16)+ .max_content_height(max * 16)+ .propagate_natural_height(true)+ .build();+ let overlay = gtk::Overlay::builder().child(&scroll).build();+ overlay.add_overlay(&hint);+ let b = gtk::Box::builder().css_classes(["field-box-area"]).build();+ overlay.set_hexpand(true);+ b.append(&overlay);+ b+}++fn confirm(+ ui: &App,+ title: &str,+ body: &str,+ action: &str,+ destructive: bool,+ f: impl Fn() + 'static,+) {+ 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 == "delete" {- client::call("deleteBot", json!({"botId": id}), |_| {});+ if r == "ok" {+ f();}});alert.present(Some(&ui.window));}+fn confirm_delete(ui: &App, id: &str, name: &str, group: bool) {+ let id = id.to_owned();+ confirm(+ ui,+ &format!("Delete {name}?"),+ if group {+ "The group chat is removed. Its bots stay."+ } else {+ "Files it changed on your computer stay as they are."+ },+ if group {+ "Delete group chat"+ } else {+ "Delete bot and its conversation"+ },+ true,+ move || client::call("deleteBot", json!({"botId": id}), |_| {}),+ );+}+fn client_seed() -> usize {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -849,88 +1014,224 @@ fn trace_lane(list: >k::Box, entries: &[&Value]) {}}-// MARK: bot menu+// MARK: menus-pub fn bot_menu(ui: &App) -> gtk::Popover {- let pop = gtk::Popover::new();- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .build();- let bot = {- let st = ui.state.borrow();- st.current.as_ref().and_then(|id| st.bots.get(id)).cloned()+/// A bot's actions: from the roster (right-click) like the Mac sidebar's menu, or from+/// the chat header's More button.+pub fn bot_menu(ui: &App, parent: >k::Widget, point: Option<(f64, f64)>, id: &str, roster: bool) {+ let Some(bot) = ui.state.borrow().bots.get(id).cloned() else {+ return;};- let Some(bot) = bot else { return pop };- let id = bot["id"].as_str().unwrap_or_default().to_owned();let group = bot["kind"] == "group";- let add = |label: &str, destructive: bool, f: Box<dyn Fn()>| {- let b = gtk::Button::builder()- .label(label)- .css_classes(["flat"])- .build();- if destructive {- b.add_css_class("error");- }- let pop2 = pop.clone();- b.connect_clicked(move |_| {- pop2.popdown();- f();- });- col.append(&b);- };- {- let (ui2, bot2) = (ui.clone(), bot.clone());- if group {- add(- "Edit group",- false,- Box::new(move || group_editor(&ui2, Some(bot2.clone()))),- );- } else {- add(- "Edit profile",- false,- Box::new(move || editor(&ui2, Some(bot2.clone()))),- );- }+ let pinned = bot["pinned"].as_bool().unwrap_or(false);+ let name = bot["name"].as_str().unwrap_or("").to_owned();+ let mut items = vec![];+ if !roster {+ let ui2 = ui.clone();+ items.push(MenuItem::new(+ "view-list-symbolic",+ "Full conversation",+ Box::new(move || trace(&ui2)),+ ));}{- let (id2, pinned) = (id.clone(), bot["pinned"].as_bool().unwrap_or(false));- add(+ let id2 = id.to_owned();+ items.push(MenuItem::new(+ "view-pin-symbolic",if pinned { "Unpin" } else { "Pin" },- false,Box::new(move || {- client::call("updateBot", json!({"id": id2, "pinned": !pinned}), |_| {})+ client::call("updateBot", json!({"id": id2, "pinned": !pinned}), |_| {});+ }),+ ));+ }+ if roster {+ let id2 = id.to_owned();+ items.push(MenuItem::new(+ "mail-unread-symbolic",+ "Mark as Read",+ Box::new(move || client::call("markRead", json!({"botId": id2}), |_| {})),+ ));+ }+ {+ let (ui2, bot2) = (ui.clone(), bot.clone());+ let item = MenuItem::new(+ if group {+ "system-users-symbolic"+ } else {+ "document-edit-symbolic"+ },+ if group {+ "Edit group…"+ } else {+ "Edit profile…"+ },+ Box::new(move || {+ if group {+ group_editor(&ui2, Some(bot2.clone()));+ } else {+ editor(&ui2, Some(bot2.clone()));+ }}),);+ items.push(if roster { item.divider() } else { item });+ }+ if roster {+ let id2 = id.to_owned();+ items.push(+ MenuItem::new(+ "edit-copy-symbolic",+ "Copy conversation ID",+ Box::new(move || {+ if let Some(d) = gtk::gdk::Display::default() {+ d.clipboard().set_text(&id2);+ }+ }),+ )+ .divider(),+ );}if !group {- let id2 = id.clone();- add(+ let (ui2, id2) = (ui.clone(), id.to_owned());+ items.push(MenuItem::new(+ "view-refresh-symbolic","New session",- false,- Box::new(move || client::call("newSession", json!({"botId": id2}), |_| {})),+ Box::new(move || {+ let id3 = id2.clone();+ confirm(+ &ui2,+ "Start a new session?",+ "The conversation stays here, but the agent starts with a fresh context.",+ "New session",+ false,+ move || client::call("newSession", json!({"botId": id3}), |_| {}),+ );+ }),+ ));+ }+ if roster {+ let id2 = id.to_owned();+ items.push(+ MenuItem::new(+ "view-conceal-symbolic",+ "Hide from sidebar",+ Box::new(move || {+ client::call("updateBot", json!({"id": id2, "hidden": true}), |_| {});+ }),+ )+ .divider(),);}{- let (ui2, id2, name) = (- ui.clone(),- id.clone(),- bot["name"].as_str().unwrap_or("").to_owned(),- );- add(- if group {- "Delete group…"- } else {- "Delete bot…"- },- true,+ let (ui2, id2) = (ui.clone(), id.to_owned());+ let item = MenuItem::new(+ "user-trash-symbolic",+ if group { "Delete group" } else { "Delete" },Box::new(move || confirm_delete(&ui2, &id2, &name, group)),- );+ )+ .destructive();+ items.push(if roster { item } else { item.divider() });+ }+ ui::popup_menu(parent, point, items);+}++/// The sidebar's Account panel: usage, this computer and its devices, the mobile app, help.+pub fn account_menu(ui: &App, anchor: >k::Button) {+ let usage = {+ let st = ui.state.borrow();+ st.usage["providers"]+ .as_array()+ .into_iter()+ .flatten()+ .flat_map(|p| p["windows"].as_array().into_iter().flatten())+ .filter_map(|w| w["percent"].as_f64())+ .fold(None, |m: Option<f64>, p| Some(m.map_or(p, |m| m.max(p))))+ };+ let open = |url: &'static str| -> Box<dyn Fn()> {+ Box::new(move || {+ gtk::UriLauncher::new(url).launch(+ None::<>k::Window>,+ gtk::gio::Cancellable::NONE,+ |_| {},+ );+ })+ };+ let (ui2, ui3) = (ui.clone(), ui.clone());+ let items = vec![+ MenuItem::new(+ "power-profile-balanced-symbolic",+ "Usage",+ Box::new(move || usage_sheet(&ui2)),+ )+ .detail(usage.map(|u| format!("{u:.0}%")))+ .chevron(),+ MenuItem::new(+ "computer-symbolic",+ "Computers & devices",+ Box::new(move || settings(&ui3)),+ )+ .chevron(),+ MenuItem::new(+ "phone-symbolic",+ "Get Codync for mobile",+ open("https://apps.apple.com/app/id6760984418"),+ ),+ MenuItem::new(+ "help-browser-symbolic",+ "Help & documentation",+ open("https://github.com/leepokai/codync#readme"),+ )+ .divider(),+ MenuItem::new(+ "dialog-warning-symbolic",+ "Report an issue",+ open("https://github.com/leepokai/codync/issues"),+ ),+ ];+ ui::popup_menu(anchor, None, items);+}++/// Usage limits per provider (UsageSheet).+fn usage_sheet(ui: &App) {+ let (dialog, view, _) = header_dialog("Usage", 520, 460);+ let page = adw::PreferencesPage::new();+ let usage = adw::PreferencesGroup::new();+ let st = ui.state.borrow();+ let mut any = false;+ for p in st.usage["providers"].as_array().into_iter().flatten() {+ for w in p["windows"].as_array().into_iter().flatten() {+ any = true;+ let reset = w["resetsText"]+ .as_str()+ .map(|s| format!("resets {s}"))+ .unwrap_or_default();+ let row = adw::ActionRow::builder()+ .title(format!(+ "{} {}",+ p["name"].as_str().unwrap_or(""),+ w["label"].as_str().unwrap_or("")+ ))+ .subtitle(gtk::glib::markup_escape_text(&reset))+ .build();+ let pct = w["percent"].as_f64().unwrap_or(0.0);+ row.add_suffix(+ >k::LevelBar::builder()+ .min_value(0.0)+ .max_value(100.0)+ .value(pct)+ .width_request(120)+ .valign(gtk::Align::Center)+ .build(),+ );+ row.add_suffix(>k::Label::new(Some(&format!("{pct:.0}%"))));+ usage.add(&row);+ }+ }+ if !any {+ usage.add(&label("No usage information yet.", &["secondary"]));}- pop.set_child(Some(&col));- pop+ page.add(&usage);+ view.set_content(Some(&page));+ dialog.present(Some(&ui.window));}// MARK: settings & pairing@@ -994,7 +1295,7 @@ fn remote_screen_group() -> adw::PreferencesGroup {}pub fn settings(ui: &App) {- let (dialog, view, _) = header_dialog("Settings", 520, 720);+ let (dialog, view, _) = header_dialog("Computers & devices", 520, 720);let page = adw::PreferencesPage::new();let pair = adw::PreferencesGroup::builder().title("Pair your iPhone")@@ -1092,39 +1393,6 @@ pub fn settings(ui: &App) {}page.add(&agents);- let usage = adw::PreferencesGroup::builder()- .title("Usage limits")- .build();- for p in st.usage["providers"].as_array().into_iter().flatten() {- for w in p["windows"].as_array().into_iter().flatten() {- let reset = w["resetsText"]- .as_str()- .map(|s| format!("resets {s}"))- .unwrap_or_default();- let row = adw::ActionRow::builder()- .title(format!(- "{} {}",- p["name"].as_str().unwrap_or(""),- w["label"].as_str().unwrap_or("")- ))- .subtitle(gtk::glib::markup_escape_text(&reset))- .build();- let bar = gtk::LevelBar::builder()- .min_value(0.0)- .max_value(100.0)- .value(w["percent"].as_f64().unwrap_or(0.0))- .width_request(120)- .valign(gtk::Align::Center)- .build();- row.add_suffix(&bar);- row.add_suffix(>k::Label::new(Some(&format!(- "{:.0}%",- w["percent"].as_f64().unwrap_or(0.0)- ))));- usage.add(&row);- }- }- page.add(&usage);let about = adw::PreferencesGroup::new();about.add(&adw::ActionRow::builder()diff --git a/apps/linux/src/main.rs b/apps/linux/src/main.rsindex 2def869d..f066d268 100644--- a/apps/linux/src/main.rs+++ b/apps/linux/src/main.rs@@ -2,36 +2,225 @@mod avatar;mod client;+mod compose;mod dialogs;mod markup;+mod orb;mod rows;mod ui;use adw::prelude::*;+/// The Apple apps' `Palette` (CodyncKit/Design/Theme.swift), light then dark.+struct Palette {+ background: &'static str,+ surface: &'static str,+ bubble_agent: &'static str,+ bubble_user: &'static str,+ border: &'static str,+ text: &'static str,+ secondary: &'static str,+ tertiary: &'static str,+ accent_fill: &'static str,+ on_accent: &'static str,+ accent_dim: &'static str,+ danger: &'static str,+ code: &'static str,+ panel: &'static str,+}++const LIGHT: Palette = Palette {+ background: "#FFFFFF",+ surface: "#F4F4F4",+ bubble_agent: "#F0F0F0",+ bubble_user: "#E2E2E2",+ border: "#E6E6E6",+ text: "#141414",+ secondary: "#6B6B6B",+ tertiary: "#9B9B9B",+ accent_fill: "#000000",+ on_accent: "#FFFFFF",+ accent_dim: "#D9D9D9",+ danger: "#C23A2B",+ code: "#F4F4F4",+ panel: "#FAFAFA",+};++const DARK: Palette = Palette {+ background: "#0A0A0A",+ surface: "#141414",+ bubble_agent: "#1C1C1C",+ bubble_user: "#3A3A3A",+ border: "#262626",+ text: "#F2F2F2",+ secondary: "#9A9A9A",+ tertiary: "#6E6E6E",+ accent_fill: "#FFFFFF",+ on_accent: "#000000",+ accent_dim: "#333333",+ danger: "#F0A7A7",+ code: "#111111",+ panel: "#1B1B1B",+};++fn colors(p: &Palette) -> String {+ format!(+ "@define-color cd_bg {};\n@define-color cd_surface {};\n@define-color cd_agent {};\n@define-color cd_user {};\n\+ @define-color cd_border {};\n@define-color cd_text {};\n@define-color cd_secondary {};\n@define-color cd_tertiary {};\n\+ @define-color cd_accent {};\n@define-color cd_on_accent {};\n@define-color cd_accent_dim {};\n@define-color cd_danger {};\n\+ @define-color cd_code {};\n@define-color cd_panel {};\n@define-color cd_warning #F0A030;\n",+ p.background,+ p.surface,+ p.bubble_agent,+ p.bubble_user,+ p.border,+ p.text,+ p.secondary,+ p.tertiary,+ p.accent_fill,+ p.on_accent,+ p.accent_dim,+ p.danger,+ p.code,+ p.panel+ )+}++/// Sizes follow the Mac app (SwiftUI points = GTK px): body 12, secondary 11,+/// footnote/caption 10, headline 13, title3 15, title2 17.const CSS: &str = r#"-.bubble { border-radius: 18px; padding: 8px 13px; }-.bubble-user { background: @window_fg_color; color: @window_bg_color; }-.bubble-agent { padding-left: 0; padding-right: 0; }-.card { border-radius: 16px; padding: 14px; border: 1px solid alpha(currentColor, 0.15); background: alpha(currentColor, 0.03); }-.card.pending { border-color: alpha(#ff9800, 0.7); }-.accent-fill { background: @window_fg_color; color: @window_bg_color; }-.accent-fill:hover { background: alpha(@window_fg_color, 0.85); }-.accent-text { color: @window_fg_color; }-.needs-text { color: #e08600; }-.muted { opacity: 0.6; }-.small { font-size: 0.85em; }-.badge { background: @window_fg_color; color: @window_bg_color; border-radius: 999px; padding: 0 6px; font-weight: bold; font-size: 0.8em; min-width: 12px; }-.chip { border-radius: 999px; padding: 3px 10px; border: 1px solid alpha(currentColor, 0.15); }-.codebox { font-family: monospace; font-size: 0.9em; background: alpha(currentColor, 0.06); border-radius: 8px; padding: 8px; }-.composer { border-radius: 20px; padding: 8px 12px; border: 1px solid alpha(currentColor, 0.18); }-.composer textview, .composer text { background: transparent; }-.notice-error { background: alpha(#e0443e, 0.12); border-radius: 12px; padding: 10px 12px; }-.round { border-radius: 999px; min-width: 38px; min-height: 38px; padding: 0; }-.reply-btn { opacity: 0; transition: opacity 150ms ease-out; min-width: 28px; min-height: 28px; padding: 0; }+@define-color window_bg_color @cd_bg;+@define-color window_fg_color @cd_text;+@define-color view_bg_color @cd_bg;+@define-color view_fg_color @cd_text;+@define-color headerbar_bg_color @cd_bg;+@define-color headerbar_fg_color @cd_text;+@define-color headerbar_border_color @cd_border;+@define-color headerbar_shade_color transparent;+@define-color sidebar_bg_color @cd_surface;+@define-color sidebar_fg_color @cd_text;+@define-color sidebar_border_color @cd_border;+@define-color dialog_bg_color @cd_bg;+@define-color dialog_fg_color @cd_text;+@define-color popover_bg_color @cd_panel;+@define-color popover_fg_color @cd_text;+@define-color card_bg_color @cd_agent;+@define-color accent_bg_color #0A84FF;+@define-color accent_color @cd_text;++window { font-size: 12px; }+.surface { background: @cd_surface; }+.chat-bg { background: @cd_bg; }+headerbar.flat-header { background: transparent; box-shadow: none; border: none; min-height: 44px; padding: 0; }+headerbar.flat-header windowhandle > box { padding: 0 6px; }+.hline { background: @cd_border; min-height: 1px; }+.vline { background: @cd_border; min-width: 1px; }++.name { font-weight: 600; font-size: 12px; color: @cd_text; }+.secondary { color: @cd_secondary; }+.tertiary { color: @cd_tertiary; }+.warning-text { color: @cd_warning; }+.danger-text { color: @cd_danger; }+.small { font-size: 11px; }+.footnote { font-size: 10px; }+.headline { font-size: 13px; font-weight: 700; }+.title3 { font-size: 15px; }+.title2 { font-size: 17px; font-weight: 600; }+.body13 { font-size: 13px; }+.semibold { font-weight: 600; }+.medium { font-weight: 500; }+.mono { font-family: monospace; }++/* Icon-only button (IconButtonStyle): no fill until hovered. */+button.icon-btn { min-width: 28px; min-height: 28px; padding: 0; border-radius: 8px; background: transparent;+ color: @cd_secondary; box-shadow: none; border: none; transition: background 120ms, color 120ms; }+button.icon-btn:hover { background: alpha(@cd_text, 0.08); color: @cd_text; }+button.icon-btn:active { background: alpha(@cd_text, 0.14); }+button.plain { background: transparent; box-shadow: none; border: none; padding: 0; min-height: 0; min-width: 0; }+button.plain:hover { background: transparent; }++button.primary-pill { background: @cd_accent; color: @cd_on_accent; border-radius: 999px; padding: 6px 14px;+ font-weight: 500; font-size: 13px; box-shadow: none; border: none; min-height: 0; }+button.primary-pill:hover { background: alpha(@cd_accent, 0.88); }+button.primary-pill:disabled { opacity: 0.4; }+button.secondary-pill { background: @cd_user; color: @cd_text; border-radius: 999px; padding: 6px 14px;+ font-weight: 500; box-shadow: none; border: none; min-height: 0; }+button.secondary-pill.danger-text { color: @cd_danger; }++/* Sidebar */+entry.search-field, searchbar entry, entry.search-field:focus-within { background: @cd_agent; border-radius: 8px; min-height: 28px;+ box-shadow: none; outline: none; border: none; font-size: 13px; padding: 0 9px; }+entry.search-field image { color: @cd_secondary; }+list.roster { background: transparent; }+list.roster > row { border-radius: 10px; padding: 6px 8px; margin-bottom: 2px; background: transparent;+ transition: background 120ms; outline: none; }+list.roster > row:hover { background: @cd_agent; }+list.roster > row:selected, list.roster > row:selected:hover { background: @cd_user; color: @cd_text; }+.badge { background: @cd_accent; color: @cd_on_accent; border-radius: 999px; padding: 0 6px; min-width: 6px;+ min-height: 18px; font-weight: bold; font-size: 10px; }+button.footer-row { border-radius: 10px; padding: 0 8px; min-height: 38px; background: transparent; box-shadow: none;+ border: none; font-size: 13px; font-weight: 500; color: @cd_text; transition: background 120ms; }+button.footer-row:hover, button.footer-row:checked { background: @cd_agent; }+.person-circle { background: @cd_user; border-radius: 999px; color: @cd_secondary; }++/* Menus: a floating panel of rows (DesktopActionMenu / SidebarAccountPanel). */+popover.panel > contents { background: @cd_panel; border-radius: 18px; padding: 7px; box-shadow: 0 8px 20px rgba(0,0,0,0.25); }+popover.panel > arrow { background: transparent; border: none; }+button.menu-row { min-height: 30px; padding: 0 10px; border-radius: 10px; background: transparent; box-shadow: none;+ border: none; font-size: 12px; font-weight: normal; color: @cd_text; }+button.menu-row:hover, button.menu-row:focus-visible { background: alpha(@cd_text, 0.08); }+button.menu-row.danger-text { color: @cd_danger; }+.menu-divider { background: alpha(@cd_text, 0.13); min-height: 1px; margin: 5px 10px; }++/* Conversation */+.bubble { border-radius: 22px; padding: 8px 12px; font-size: 12px; color: @cd_text; }+.bubble-user { background: @cd_user; }+.bubble-agent { background: @cd_agent; }+.time { font-size: 10px; color: @cd_tertiary; }+.author { font-size: 11px; font-weight: 500; }+button.thread-chip { border-radius: 999px; padding: 5px 10px; background: @cd_surface; box-shadow: none; border: none;+ min-height: 0; transition: background 120ms; }+button.thread-chip:hover { background: @cd_agent; }+button.mention-chip { border-radius: 999px; padding: 6px 10px; background: @cd_surface; box-shadow: none; border: none; min-height: 0; }+button.working { background: @cd_agent; border-radius: 22px; padding: 12px; box-shadow: none; border: none; min-height: 0; }+.perm-card { background: @cd_agent; border-radius: 22px; padding: 16px; }+.choices { background: @cd_bg; border-radius: 14px; }+button.choice { min-height: 46px; padding: 0 14px; border-radius: 0; background: transparent; box-shadow: none; border: none;+ font-size: 13px; }+button.choice:first-child { border-radius: 14px 14px 0 0; }+button.choice:last-child { border-radius: 0 0 14px 14px; }+button.choice:hover { background: alpha(@cd_text, 0.05); }+.codebox { font-family: monospace; font-size: 10px; background: @cd_code; border-radius: 8px; padding: 8px; }+.notice-error { background: alpha(@cd_danger, 0.12); border-radius: 12px; padding: 12px; }+.composer { background: @cd_user; border-radius: 24px; padding: 4px 6px 4px 14px; box-shadow: 0 2px 10px rgba(0,0,0,0.06); }+.composer textview, .composer textview text, .composer scrolledwindow { background: transparent; font-size: 12px; }+button.send { min-width: 28px; min-height: 28px; padding: 0; border-radius: 999px; background: @cd_accent;+ color: @cd_on_accent; box-shadow: none; border: none; }+button.send:disabled { background: @cd_accent_dim; color: @cd_tertiary; }+.reply-btn { opacity: 0; transition: opacity 150ms ease-out; }.reply-host:hover .reply-btn, .reply-btn:focus-visible { opacity: 1; }-.thread-chip { border-radius: 999px; padding: 3px 10px; background: alpha(currentColor, 0.06); }-.thread-chip:hover { background: alpha(currentColor, 0.1); }+.details-box { background: @cd_surface; border-radius: 8px; }++/* Compose page and editors */+floating-sheet > sheet, dialog.floating sheet, dialog sheet { outline: none; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.45); border-radius: 18px; }+entry.plain, entry.plain:focus-within { background: transparent; box-shadow: none; outline: none; border: none; padding: 0; min-height: 0; }+.chip { background: @cd_agent; border-radius: 999px; padding: 3px 4px 3px 8px; }+button.chip-x { min-width: 18px; min-height: 18px; padding: 0; background: transparent; box-shadow: none; border: none; color: @cd_secondary; }+.pick-card { background: @cd_surface; border-radius: 18px; padding: 8px; box-shadow: 0 6px 16px rgba(0,0,0,0.08); }+button.pick-row { padding: 8px 12px; border-radius: 12px; background: transparent; box-shadow: none; border: none;+ font-weight: normal; font-size: 13px; transition: background 120ms; }+button.pick-row:hover, button.pick-row.first { background: @cd_agent; }+.keycap { font-family: monospace; font-size: 10px; color: @cd_secondary; background: @cd_bg; border-radius: 4px;+ min-width: 18px; min-height: 18px; padding: 0 3px; }+.plus-circle { background: @cd_agent; border-radius: 999px; }+.field-label { font-size: 11px; color: @cd_secondary; margin-left: 4px; }+entry.field-box, entry.field-box:focus-within { background: @cd_surface; border-radius: 12px; padding: 0 10px; min-height: 32px;+ box-shadow: none; outline: none; border: none; }+.field-box-area { background: @cd_surface; border-radius: 12px; padding: 8px 10px; }+.field-box-area textview, .field-box-area textview text { background: transparent; }+button.candidate { padding: 8px 12px; border-radius: 12px; background: transparent; box-shadow: none; border: none;+ font-weight: normal; transition: background 120ms; }+button.candidate:hover { background: @cd_agent; }"#;fn main() -> gtk::glib::ExitCode {@@ -39,13 +228,32 @@ fn main() -> gtk::glib::ExitCode {.application_id("com.pokai.Codync").build();app.connect_startup(|_| {- let provider = gtk::CssProvider::new();- provider.load_from_string(CSS);+ let display = gtk::gdk::Display::default().expect("no display");+ let base = gtk::CssProvider::new();+ base.load_from_string(CSS);+ let palette = gtk::CssProvider::new();+ let style = adw::StyleManager::default();+ // Black and white like the Apple apps: follow the system, default dark.+ style.set_color_scheme(adw::ColorScheme::PreferDark);+ let apply = {+ let palette = palette.clone();+ move |s: &adw::StyleManager| {+ palette.load_from_string(&colors(if s.is_dark() { &DARK } else { &LIGHT }));+ }+ };+ apply(&style);+ style.connect_dark_notify(apply);+ // The palette's named colors must exist before the rules that use them.gtk::style_context_add_provider_for_display(- >k::gdk::Display::default().expect("no display"),- &provider,+ &display,+ &palette,gtk::STYLE_PROVIDER_PRIORITY_APPLICATION,);+ gtk::style_context_add_provider_for_display(+ &display,+ &base,+ gtk::STYLE_PROVIDER_PRIORITY_APPLICATION + 1,+ );});app.connect_activate(|app| {if let Some(win) = app.active_window() {diff --git a/apps/linux/src/orb.rs b/apps/linux/src/orb.rsnew file mode 100644index 00000000..19be9f56--- /dev/null+++ b/apps/linux/src/orb.rs@@ -0,0 +1,164 @@+//! `ThinkingOrb` from the Apple apps (CodyncKit/Design/ThinkingOrbGeometry.swift, a port of+//! thinking-orbs 0.3.1, MIT, Jakub Antalik): the *working* orbits and the *listening* lattice.+//! Drawn in the widget's CSS color, so a `warning-text` / `secondary` class tints it.++use gtk::prelude::*;+use std::f64::consts::PI;++struct Dot {+ x: f64,+ y: f64,+ z: f64,+ radius: f64,+ white: f64,+ alpha: f64,+}++fn hash(a: f64, b: f64) -> f64 {+ let h = (a * 12.9898 + b * 78.233).sin() * 43758.5453;+ h - h.floor()+}++type P = (f64, f64, f64);++fn projector(yaw: f64, tilt: f64, size: f64, scale: f64) -> impl Fn(P) -> P {+ let (sy, cy, st, ct) = (yaw.sin(), yaw.cos(), tilt.sin(), tilt.cos());+ move |(px, py, pz)| {+ let x = px * cy + pz * sy;+ let z = -px * sy + pz * cy;+ (+ size / 2.0 + x * scale,+ size / 2.0 - (py * ct - z * st) * scale,+ py * st + z * ct,+ )+ }+}++fn orbits(size: f64, t: f64) -> Vec<Dot> {+ let small = size < 40.0;+ let radius = size / 2.0 * 0.82;+ let project = projector(t * 0.12, 0.3, size, 1.0);+ let rs = (size / 300.0).powf(0.6);+ let multiplier = if small { 2.4 } else { 1.0 };+ let (orbit_count, ghost_count) = if small { (3, 10) } else { (12, 40) };+ let mut dots = vec![];+ for orb in 0..orbit_count {+ let o = f64::from(orb);+ let (h1, h2, h3) = (hash(o, 1.7), hash(o, 5.2), hash(o, 8.9));+ let ro = radius * (0.45 + 0.52 * h1);+ let (theta, phi) = (h1 * 2.0 * PI, (2.0 * h2 - 1.0).acos());+ let n = (phi.sin() * theta.cos(), phi.cos(), phi.sin() * theta.sin());+ let mut u = (-n.1, n.0, 0.0);+ let len = (u.0 * u.0 + u.1 * u.1).sqrt().max(1e-6);+ u = (u.0 / len, u.1 / len, 0.0);+ let v = (-n.2 * u.1, n.2 * u.0, n.0 * u.1 - n.1 * u.0);+ let speed = (0.25 + 0.55 * h3) * if h3 > 0.5 { 1.0 } else { -1.0 };+ let at = |angle: f64| {+ project((+ (u.0 * angle.cos() + v.0 * angle.sin()) * ro,+ (u.1 * angle.cos() + v.1 * angle.sin()) * ro,+ (u.2 * angle.cos() + v.2 * angle.sin()) * ro,+ ))+ };+ for k in 0..ghost_count {+ let p = at(f64::from(k) / f64::from(ghost_count) * 2.0 * PI);+ let depth = (p.2 / ro + 1.0) / 2.0;+ dots.push(Dot {+ x: p.0,+ y: p.1,+ z: p.2,+ radius: 0.9 * multiplier * rs,+ white: 0.72,+ alpha: 0.5 * (0.4 + 0.6 * depth),+ });+ }+ for m in 0..3 {+ let p = at(t * speed + f64::from(m) / 3.0 * 2.0 * PI + h2 * 6.0);+ let depth = (p.2 / ro + 1.0) / 2.0;+ dots.push(Dot {+ x: p.0,+ y: p.1,+ z: p.2,+ radius: (1.2 + 1.6 * depth) * multiplier * rs,+ white: 0.3 - 0.22 * depth,+ alpha: 1.0,+ });+ }+ }+ dots+}++fn listening(size: f64, t: f64) -> Vec<Dot> {+ let small = size < 40.0;+ let rs = (size / 300.0).powf(0.6);+ let rings = if small { 5 } else { 9 };+ let density = if small { 13.0 } else { 23.0 };+ let multiplier = if small { 1.6 } else { 1.0 };+ let radius = size / 2.0 * 0.874;+ let project = projector(t * 0.18, 0.38, size, 1.0);+ let mut dots = vec![];+ for ri in 0..=rings {+ let r = f64::from(ri);+ let lat = -PI / 2.0 + r / f64::from(rings) * PI;+ let wave = 0.62 * (t * 2.1 - r * 0.52).sin() + 0.38 * (t * 1.27 + r * 0.83).sin();+ let rr = radius * (0.88 + 0.105 * wave);+ let lon_count = ((lat.cos().abs() * density).round() as i32).max(1);+ for j in 0..lon_count {+ let lon = f64::from(j) / f64::from(lon_count) * 2.0 * PI;+ let p = project((+ lat.cos() * lon.cos() * rr,+ lat.sin() * rr,+ lat.cos() * lon.sin() * rr,+ ));+ let depth = (p.2 / radius + 1.0) / 2.0;+ let crest = wave.max(0.0);+ dots.push(Dot {+ x: p.0,+ y: p.1,+ z: p.2,+ radius: (0.6 + 1.7 * depth) * multiplier * (1.0 + 0.4 * crest) * rs,+ white: 0.66 - 0.56 * depth - 0.1 * crest,+ alpha: 1.0,+ });+ }+ }+ dots+}++/// A turning orb; `listening` is the "needs you" state.+pub fn widget(listening_state: bool, size: i32) -> gtk::DrawingArea {+ let area = gtk::DrawingArea::builder()+ .content_width(size)+ .content_height(size)+ .valign(gtk::Align::Center)+ .build();+ let start = std::time::Instant::now();+ area.set_draw_func(move |area, cr, w, _| {+ let s = f64::from(w);+ let c = area.color();+ let speed = if listening_state { 3.998 } else { 3.9 };+ let t = 0.6 + start.elapsed().as_secs_f64() * speed;+ let mut dots = if listening_state {+ listening(s, t)+ } else {+ orbits(s, t)+ };+ dots.sort_by(|a, b| a.z.total_cmp(&b.z));+ for d in dots.iter().filter(|d| d.alpha >= 0.02) {+ let ink = (1.0 - d.white.clamp(0.0, 1.0)) * d.alpha;+ cr.set_source_rgba(+ f64::from(c.red()),+ f64::from(c.green()),+ f64::from(c.blue()),+ ink,+ );+ cr.arc(d.x, d.y, d.radius.max(0.3), 0.0, 2.0 * PI);+ cr.fill().ok();+ }+ });+ area.add_tick_callback(|a, _| {+ a.queue_draw();+ gtk::glib::ControlFlow::Continue+ });+ area+}diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rsindex cdec9745..c79d4e60 100644--- a/apps/linux/src/rows.rs+++ b/apps/linux/src/rows.rs@@ -1,109 +1,238 @@-//! The rows a conversation is made of: bubbles, notices and approval cards.+//! The rows a conversation is made of (kit/Sources/CodyncUI/Thread/ChatRows.swift and+//! PermissionCard.swift): bubbles, author labels, thread chips, notices, approval cards and+//! the working indicator.use crate::client;-use crate::ui::{self, App, State, ago, folder, toast};-use crate::{avatar, markup};+use crate::ui::{self, App, State, folder, toast};+use crate::{avatar, markup, orb};use adw::prelude::*;+use gtk::glib::DateTime;use serde_json::{Value, json};-pub fn user_bubble(e: &Value, bot_working: bool, start: bool) -> gtk::Widget {+// MARK: time++fn local(ms: i64) -> Option<DateTime> {+ DateTime::from_unix_local(ms / 1000).ok()+}++fn fmt(d: &DateTime, f: &str) -> String {+ d.format(f)+ .map(|s| s.trim().replace(" ", " "))+ .unwrap_or_default()+}++/// Days between the date and today (0 = today).+fn days_ago(d: &DateTime) -> i32 {+ let Ok(now) = DateTime::now_local() else {+ return 0;+ };+ let day = |x: &DateTime| {+ DateTime::from_local(x.year(), x.month(), x.day_of_month(), 0, 0, 0.0)+ .map(|d| d.to_unix())+ .unwrap_or(0)+ };+ i32::try_from((day(&now) - day(d)) / 86_400).unwrap_or(i32::MAX)+}++/// 3:27 PM+pub fn clock(ms: i64) -> String {+ local(ms).map(|d| fmt(&d, "%l:%M %p")).unwrap_or_default()+}++/// Roster/thread stamp: 3:45 AM · Yesterday · Wednesday · Sep 16+pub fn day(ms: i64) -> String {+ let Some(d) = local(ms) else {+ return String::new();+ };+ match days_ago(&d) {+ ..=0 => fmt(&d, "%l:%M %p"),+ 1 => "Yesterday".into(),+ 2..6 => fmt(&d, "%A"),+ _ => fmt(&d, "%b %e"),+ }+}++/// Chat separator: Today 3:27 AM · Yesterday 5:20 PM · Sep 16 9:02 AM+pub fn separator(ms: i64) -> String {+ let Some(d) = local(ms) else {+ return String::new();+ };+ let when = match days_ago(&d) {+ ..=0 => "Today".to_owned(),+ 1 => "Yesterday".to_owned(),+ _ => fmt(&d, "%b %e"),+ };+ format!("{when} {}", fmt(&d, "%l:%M %p"))+}++// MARK: small pieces++pub fn label(text: &str, classes: &[&str]) -> gtk::Label {+ gtk::Label::builder()+ .label(text)+ .xalign(0.0)+ .css_classes(classes.iter().map(|c| (*c).to_owned()).collect::<Vec<_>>())+ .build()+}++/// An icon-only button with its tooltip (IconButton).+pub fn icon_button(icon: &str, tooltip: &str) -> gtk::Button {+ gtk::Button::builder()+ .icon_name(icon)+ .tooltip_text(tooltip)+ .css_classes(["icon-btn"])+ .valign(gtk::Align::Center)+ .build()+}++pub fn hline() -> gtk::Box {+ gtk::Box::builder().css_classes(["hline"]).build()+}++fn bubble(text: &str, markup: bool, class: &str) -> gtk::Label {+ let l = gtk::Label::builder()+ .wrap(true)+ .wrap_mode(gtk::pango::WrapMode::WordChar)+ .selectable(true)+ .xalign(0.0)+ .css_classes(["bubble", class])+ .build();+ if markup {+ l.set_markup(&markup::to_pango(text));+ } else {+ l.set_label(text);+ }+ l+}++// MARK: messages++/// Main-chat context for a message: the entry id it starts a thread on.+pub struct Reply<'a> {+ pub ui: &'a App,+ pub root: Option<&'a str>,+}++pub fn user_bubble(r: &Reply, e: &Value, bot_working: bool, start: bool) -> gtk::Widget {let col = gtk::Box::builder().orientation(gtk::Orientation::Vertical)+ .spacing(4).halign(gtk::Align::End)- .margin_start(60)- .margin_top(if start { 12 } else { 2 })+ .margin_start(56)+ .margin_top(if start { 12 } else { 4 }).build();- col.append(- >k::Label::builder()- .label(e["data"]["text"].as_str().unwrap_or(""))- .wrap(true)- .wrap_mode(gtk::pango::WrapMode::WordChar)- .selectable(true)- .xalign(0.0)- .css_classes(["bubble", "bubble-user"])- .build(),- );+ let text = e["data"]["text"].as_str().unwrap_or("");+ let b = bubble(text, false, "bubble-user");+ col.append(&with_menu(r, b.upcast_ref(), true, text, false));let status = match e["data"]["status"].as_str() {- Some("sending") => "Sending…",- Some("queued") if bot_working => "Waiting to send — it'll read this when it's done",- Some("failed") => "Failed to send",- Some("cancelled") => "Not sent — stopped",- _ => "",+ Some("sending") => "Sending…".to_owned(),+ Some("queued") if bot_working => "Waiting to send — it'll read this when it's done".into(),+ Some("failed") => "Failed to send".into(),+ Some("cancelled") => "Not sent — stopped".into(),+ _ => clock(e["createdAt"].as_i64().unwrap_or(0)),};- if !status.is_empty() {- col.append(- >k::Label::builder()- .label(status)- .css_classes(["small", "muted"])- .halign(gtk::Align::End)- .build(),- );+ let s = label(&status, &["time"]);+ s.set_halign(gtk::Align::End);+ if e["data"]["status"] == "failed" {+ s.add_css_class("danger-text");}+ col.append(&s);col.upcast()}-pub fn agent_bubble(e: &Value, bot: &Value, start: bool) -> gtk::Widget {- let row = gtk::Box::builder()- .spacing(8)- .margin_end(60)- .margin_top(if start { 12 } else { 2 })+pub fn agent_bubble(r: &Reply, st: &State, e: &Value, group: bool, start: bool) -> gtk::Widget {+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(4)+ .margin_end(64)+ .margin_top(if start { 12 } else { 4 }).build();- if start {- row.append(&avatar::widget(- bot["avatarShape"].as_str().unwrap_or("blob"),- bot["avatarColor"].as_str().unwrap_or("blue"),- 28,- false,- "",- ));- } else {- row.append(>k::Box::builder().width_request(28).build());+ if group && start {+ col.append(&author_label(st, e["data"]["author"].as_str()));}- let label = gtk::Label::builder()- .use_markup(true)- .label(markup::to_pango(e["data"]["text"].as_str().unwrap_or("")))- .wrap(true)- .wrap_mode(gtk::pango::WrapMode::WordChar)- .selectable(true)- .xalign(0.0)- .css_classes(["bubble", "bubble-agent"])- .valign(gtk::Align::End)- .build();- row.append(&label);- row.upcast()+ let text = e["data"]["text"].as_str().unwrap_or("");+ let b = bubble(text, true, "bubble-agent");+ b.set_halign(gtk::Align::Start);+ col.append(&with_menu(r, b.upcast_ref(), false, text, true));+ let t = label(&clock(e["createdAt"].as_i64().unwrap_or(0)), &["time"]);+ t.set_margin_start(12);+ col.append(&t);+ col.upcast()}pub fn notice(e: &Value) -> gtk::Widget {let text = e["data"]["text"].as_str().unwrap_or("");- let label = gtk::Label::builder()- .label(text)- .wrap(true)- .selectable(true)- .margin_top(10)- .build();match e["data"]["style"].as_str() {+ Some("divider") => {+ let row = gtk::Box::builder()+ .spacing(10)+ .margin_top(16)+ .margin_bottom(6)+ .build();+ let l = gtk::Label::builder()+ .label(text)+ .wrap(true)+ .justify(gtk::Justification::Center)+ .max_width_chars(40)+ .css_classes(["footnote", "tertiary"])+ .build();+ let (a, b) = (hline(), hline());+ for w in [&a, &b] {+ w.set_hexpand(true);+ w.set_valign(gtk::Align::Center);+ }+ row.append(&a);+ row.append(&l);+ row.append(&b);+ row.upcast()+ }Some("error") => {- label.add_css_class("notice-error");- label.set_xalign(0.0);+ let row = gtk::Box::builder()+ .spacing(8)+ .css_classes(["notice-error"])+ .margin_top(10)+ .build();+ let icon = gtk::Image::from_icon_name("dialog-warning-symbolic");+ icon.add_css_class("danger-text");+ icon.set_valign(gtk::Align::Start);+ row.append(&icon);+ let l = label(text, &["small"]);+ l.set_wrap(true);+ l.set_selectable(true);+ l.set_hexpand(true);+ row.append(&l);+ row.upcast()+ }+ _ => {+ let l = gtk::Label::builder()+ .label(text)+ .wrap(true)+ .justify(gtk::Justification::Center)+ .css_classes(["footnote", "secondary"])+ .margin_top(10)+ .build();+ l.upcast()}- _ => label.add_css_class("dim-label"),}- label.upcast()}-pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {+pub fn permission_card(ui: &App, st: &State, e: &Value, group: bool) -> gtk::Widget {+ let outer = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(4)+ .margin_top(12)+ .build();+ if group {+ outer.append(&author_label(st, e["data"]["author"].as_str()));+ }let d = &e["data"];let pending = d["status"] == "pending";let card = gtk::Box::builder().orientation(gtk::Orientation::Vertical)- .spacing(6)- .css_classes(["card"])- .margin_start(36)- .margin_top(12)+ .spacing(10)+ .css_classes(["perm-card"])+ .margin_end(40).build();- if pending {- card.add_css_class("pending");- }let headline = match d["toolKind"].as_str() {Some("execute") => "Wants to run a command",Some("edit" | "delete" | "move") => "Wants to change files",@@ -111,35 +240,55 @@ pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {Some("read" | "search") => "Wants to read files",_ => "Wants to use a tool",};- card.append(- >k::Label::builder()- .label(format!("✋ {headline}"))- .xalign(0.0)- .css_classes(["heading"])- .build(),- );- card.append(- >k::Label::builder()- .label(d["title"].as_str().unwrap_or(""))- .xalign(0.0)- .wrap(true)- .build(),+ let top = gtk::Box::builder().spacing(8).build();+ top.append(&label(headline, &["headline"]));+ if pending {+ let dot = gtk::DrawingArea::builder()+ .content_width(7)+ .content_height(7)+ .valign(gtk::Align::Center)+ .build();+ dot.set_draw_func(|_, cr, w, _| {+ let r = f64::from(w) / 2.0;+ cr.arc(r, r, r, 0.0, std::f64::consts::TAU);+ let (red, g, b) = avatar::rgb(0xF0A030);+ cr.set_source_rgb(red, g, b);+ cr.fill().ok();+ });+ top.append(&dot);+ }+ card.append(&top);+ let title = label(+ d["title"].as_str().unwrap_or(""),+ &["small", "mono", "secondary"],);+ title.set_wrap(true);+ title.set_wrap_mode(gtk::pango::WrapMode::WordChar);+ card.append(&title);let host = st.hello["name"].as_str().unwrap_or("this computer");- card.append(- >k::Label::builder()- .label(format!(- "Runs on {host} · {}",- folder(d["cwd"].as_str().unwrap_or(""))- ))- .xalign(0.0)- .css_classes(["small", "muted"])- .build(),- );+ let runs = gtk::Box::builder().spacing(5).build();+ let icon = gtk::Image::from_icon_name("computer-symbolic");+ icon.add_css_class("tertiary");+ icon.set_pixel_size(12);+ runs.append(&icon);+ let cwd = d["cwd"].as_str().map(folder);+ runs.append(&label(+ &format!(+ "Runs on {host}{}",+ cwd.map(|c| format!(" · {c}")).unwrap_or_default()+ ),+ &["footnote", "tertiary"],+ ));+ card.append(&runs);+let mut detail = String::new();if let Some(c) = d["command"].as_str() {detail.push_str(c);}+ if let Some(c) = d["detail"].as_str() {+ detail.push('\n');+ detail.push_str(&c.chars().take(2000).collect::<String>());+ }for diff in d["diffs"].as_array().into_iter().flatten() {detail.push_str(&format!("\n{} +{} −{}\n{}",@@ -150,49 +299,52 @@ pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {));}if !detail.trim().is_empty() {- let exp = gtk::Expander::new(Some("Details"));- exp.set_child(Some(- >k::Label::builder()- .label(detail.trim())- .xalign(0.0)- .selectable(true)- .wrap(true)- .css_classes(["codebox"])- .build(),- ));- card.append(&exp);+ card.append(&disclosure("Details", &{+ let l = label(detail.trim(), &["codebox"]);+ l.set_selectable(true);+ l.set_wrap(true);+ l.set_wrap_mode(gtk::pango::WrapMode::WordChar);+ l+ }));}if pending {- let buttons = gtk::FlowBox::builder()- .selection_mode(gtk::SelectionMode::None)- .max_children_per_line(4)- .column_spacing(8)- .row_spacing(8)- .homogeneous(true)+ let choices = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .css_classes(["choices"])+ .margin_top(4).build();let mut opts: Vec<&Value> = d["options"].as_array().into_iter().flatten().collect();let rank = |k: &str| match k {"allow_once" => 0,"allow_always" => 1,"reject_once" => 2,- _ => 3,+ "reject_always" => 3,+ _ => 9,};opts.sort_by_key(|o| rank(o["kind"].as_str().unwrap_or("")));- for o in opts {+ for (i, o) in opts.iter().enumerate() {let kind = o["kind"].as_str().unwrap_or("");- let label = match kind {+ let text = match kind {"allow_once" => "Allow once","allow_always" => "Always allow","reject_once" => "Deny","reject_always" => "Never",_ => o["name"].as_str().unwrap_or("OK"),};- let btn = gtk::Button::with_label(label);+ if i > 0 {+ choices.append(&hline());+ }+ let l = label(text, &[]);if kind == "allow_once" {- btn.add_css_class("accent-fill");- } else if kind.starts_with("reject") {- btn.add_css_class("destructive-action");+ l.add_css_class("semibold");}+ if !kind.starts_with("allow") {+ l.add_css_class("danger-text");+ }+ let btn = gtk::Button::builder()+ .child(&l)+ .css_classes(["choice"])+ .build();let (entry_id, opt) = (e["id"].as_str().unwrap_or("").to_owned(),o["optionId"].clone(),@@ -211,9 +363,9 @@ pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {},);});- buttons.insert(&btn, -1);+ choices.append(&btn);}- card.append(&buttons);+ card.append(&choices);} else {let chosen = d["options"].as_array()@@ -227,73 +379,147 @@ pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {(Some("answered"), Some("allow_once")) => "Allowed once",(Some("answered"), Some("allow_always")) => "Always allowed",(Some("answered"), Some("reject_once")) => "Denied",- (Some("answered"), _) => "Answered",+ (Some("answered"), Some("reject_always")) => "Never allowed",+ (Some("answered"), _) => chosen+ .and_then(|o| o["name"].as_str())+ .unwrap_or("Answered"),(Some("cancelled"), _) => "Cancelled",_ => "Expired — the agent moved on",};- card.append(- >k::Label::builder()- .label(outcome)- .xalign(0.0)- .css_classes(["small", "dim-label"])- .build(),- );+ card.append(&label(outcome, &["footnote", "medium", "secondary"]));+ }+ outer.append(&card);+ outer.upcast()+}++/// A "Details ›" line that slides its content open.+pub fn disclosure(title: &str, content: &impl IsA<gtk::Widget>) -> gtk::Box {+ let col = gtk::Box::new(gtk::Orientation::Vertical, 0);+ let head = gtk::Box::builder().spacing(4).build();+ head.append(&label(title, &["footnote", "medium", "secondary"]));+ let chevron = gtk::Image::from_icon_name("go-next-symbolic");+ chevron.set_pixel_size(10);+ chevron.add_css_class("secondary");+ head.append(&chevron);+ let btn = gtk::Button::builder()+ .child(&head)+ .css_classes(["plain"])+ .halign(gtk::Align::Start)+ .build();+ let rev = gtk::Revealer::builder()+ .child(content)+ .transition_type(gtk::RevealerTransitionType::SlideDown)+ .build();+ content.set_margin_top(6);+ {+ let rev = rev.clone();+ btn.connect_clicked(move |_| {+ let open = !rev.reveals_child();+ rev.set_reveal_child(open);+ chevron.set_icon_name(Some(if open {+ "go-down-symbolic"+ } else {+ "go-next-symbolic"+ }));+ });}- card.upcast()+ col.append(&btn);+ col.append(&rev);+ col}-/// Who wrote a message in a group: their name in their color.+/// Who wrote a message in a group: their avatar and name in their color.pub fn author_label(st: &State, id: Option<&str>) -> gtk::Widget {let bot = id.and_then(|id| st.bots.get(id));let name = bot.and_then(|b| b["name"].as_str()).unwrap_or("A deleted bot");- let hex = avatar::color_of(- bot.and_then(|b| b["avatarColor"].as_str())- .unwrap_or("gray"),- );- gtk::Label::builder()+ let row = gtk::Box::builder().spacing(8).build();+ if let Some(b) = bot {+ row.append(&avatar::of(&st.bots, b, 26, false));+ }+ let l = gtk::Label::builder().use_markup(true)- .label(format!(- "<span foreground=\"#{hex:06X}\">{}</span>",- gtk::glib::markup_escape_text(name)- ))- .xalign(0.0)- .css_classes(["small", "heading"])- .margin_start(36)- .margin_top(12)- .build()- .upcast()+ .label(match bot {+ Some(b) => format!(+ "<span foreground=\"#{:06X}\">{}</span>",+ avatar::color_of(b["avatarColor"].as_str().unwrap_or("gray")),+ gtk::glib::markup_escape_text(name)+ ),+ None => gtk::glib::markup_escape_text(name).to_string(),+ })+ .css_classes(["author"])+ .build();+ if bot.is_none() {+ l.add_css_class("secondary");+ }+ row.append(&l);+ row.upcast()}-/// A main-chat message with a "Reply in thread" button that shows on hover or focus,-/// and the same action (plus Copy) on right-click or long-press, so touchscreens reach it.-pub fn with_reply(ui: &App, w: >k::Widget, end: bool, root: &str, text: &str) -> gtk::Widget {+/// Copy / Reply in thread / Show what it did on right-click or long-press, and a+/// "Reply in thread" button that shows beside a main-chat message on hover.+fn with_menu(r: &Reply, w: >k::Widget, end: bool, text: &str, agent: bool) -> gtk::Widget {let host = gtk::Box::builder().spacing(4).css_classes(["reply-host"])+ .halign(if end {+ gtk::Align::End+ } else {+ gtk::Align::Start+ }).build();- if end {- host.set_halign(gtk::Align::End);+ let btn = r.root.map(|root| {+ let btn = icon_button("mail-reply-sender-symbolic", "Reply in thread");+ btn.add_css_class("reply-btn");+ let (ui2, root2) = (r.ui.clone(), root.to_owned());+ btn.connect_clicked(move |_| ui::open_thread(&ui2, &root2));+ btn+ });+ if end && let Some(b) = &btn {+ host.append(b);}- let btn = gtk::Button::builder()- .icon_name("mail-reply-sender-symbolic")- .tooltip_text("Reply in thread")- .css_classes(["flat", "circular", "reply-btn"])- .valign(gtk::Align::Center)- .build();- let (ui2, root2) = (ui.clone(), root.to_owned());- btn.connect_clicked(move |_| ui::open_thread(&ui2, &root2));- if end {- host.append(&btn);- host.append(w);- } else {- host.append(w);- host.append(&btn);+ host.append(w);+ if !end && let Some(b) = &btn {+ host.append(b);}let menu = {- let (ui2, root, text, host2) = (ui.clone(), root.to_owned(), text.to_owned(), host.clone());- move |x: f64, y: f64| message_menu(&ui2, &host2, x, y, &root, &text)+ let (ui2, root, text, host2) = (+ r.ui.clone(),+ r.root.map(str::to_owned),+ text.to_owned(),+ host.clone(),+ );+ move |x: f64, y: f64| {+ let mut items: Vec<ui::MenuItem> = vec![];+ let t = text.clone();+ items.push(ui::MenuItem::new(+ "edit-copy-symbolic",+ "Copy",+ Box::new(move || {+ if let Some(d) = gtk::gdk::Display::default() {+ d.clipboard().set_text(&t);+ }+ }),+ ));+ if let Some(root) = root.clone() {+ let ui3 = ui2.clone();+ items.push(ui::MenuItem::new(+ "mail-reply-sender-symbolic",+ "Reply in thread",+ Box::new(move || ui::open_thread(&ui3, &root)),+ ));+ }+ if agent {+ let ui3 = ui2.clone();+ items.push(ui::MenuItem::new(+ "view-list-symbolic",+ "Show what it did",+ Box::new(move || crate::dialogs::trace(&ui3)),+ ));+ }+ ui::popup_menu(&host2, Some((x, y)), items);+ }};// Capture phase: runs before the selectable label's own context menu.let click = gtk::GestureClick::builder()@@ -320,96 +546,123 @@ pub fn with_reply(ui: &App, w: >k::Widget, end: bool, root: &str, text: &str)host.upcast()}-/// The message's context menu: a popover of flat buttons, like the bot menu.-fn message_menu(ui: &App, host: >k::Box, x: f64, y: f64, root: &str, text: &str) {- let pop = gtk::Popover::builder()- .pointing_to(>k::gdk::Rectangle::new(x as i32, y as i32, 1, 1))- .has_arrow(false)- .build();- let col = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(2)- .build();- let reply = gtk::Button::builder()- .label("Reply in thread")- .css_classes(["flat"])- .build();- let copy = gtk::Button::builder()- .label("Copy text")- .css_classes(["flat"])- .build();- col.append(&reply);- col.append(©);- pop.set_child(Some(&col));- {- let (pop2, ui2, root) = (pop.clone(), ui.clone(), root.to_owned());- reply.connect_clicked(move |_| {- pop2.popdown();- ui::open_thread(&ui2, &root);- });- }- {- let (pop2, text) = (pop.clone(), text.to_owned());- copy.connect_clicked(move |b| {- b.clipboard().set_text(&text);- pop2.popdown();- });- }- // The chat re-renders often; the popover lives only while shown.- pop.connect_closed(|p| {- let p = p.clone();- gtk::glib::idle_add_local_once(move || p.unparent());- });- pop.set_parent(host);- pop.popup();-}-/// Under a message with a thread (Slack's): who replied, how many, how recently.-pub fn thread_chip(ui: &App, st: &State, e: &Value, end: bool) -> Option<gtk::Widget> {+pub fn thread_chip(ui: &App, st: &State, e: &Value, end: bool, indent: i32) -> Option<gtk::Widget> {let t = &e["data"]["thread"];let count = t["count"].as_i64().filter(|c| *c > 0)?;let inner = gtk::Box::builder().spacing(6).build();- let faces = gtk::Box::builder().spacing(2).build();- for b in t["authors"]+ let looks: Vec<(&str, &str, avatar::Mood)> = t["authors"].as_array().into_iter().flatten().filter_map(|a| st.bots.get(a.as_str()?)).take(3)- {- faces.append(&avatar::of(&st.bots, b, 18, false, ""));+ .map(|b| {+ (+ b["avatarShape"].as_str().unwrap_or("blob"),+ b["avatarColor"].as_str().unwrap_or("blue"),+ avatar::Mood::Idle,+ )+ })+ .collect();+ if !looks.is_empty() {+ inner.append(&avatar::row(&looks, 18, 6));}- inner.append(&faces);- inner.append(- >k::Label::builder()- .label(if count == 1 {- "1 reply".to_owned()- } else {- format!("{count} replies")- })- .css_classes(["small", "heading"])- .build(),- );- inner.append(- >k::Label::builder()- .label(ago(t["lastAt"].as_i64().unwrap_or(0)))- .css_classes(["small", "muted"])- .build(),- );- inner.append(>k::Image::from_icon_name("go-next-symbolic"));+ inner.append(&label(+ &if count == 1 {+ "1 reply".to_owned()+ } else {+ format!("{count} replies")+ },+ &["footnote", "semibold"],+ ));+ inner.append(&label(+ &day(t["lastAt"].as_i64().unwrap_or(0)),+ &["footnote", "tertiary"],+ ));+ let chevron = gtk::Image::from_icon_name("go-next-symbolic");+ chevron.set_pixel_size(10);+ chevron.add_css_class("tertiary");+ inner.append(&chevron);let btn = gtk::Button::builder().child(&inner).tooltip_text("View thread")- .css_classes(["flat", "thread-chip"])+ .css_classes(["thread-chip"]).halign(if end {gtk::Align::End} else {gtk::Align::Start})- .margin_start(if end { 0 } else { 36 })+ .margin_start(indent).margin_top(4).build();let (ui2, root) = (ui.clone(), e["id"].as_str().unwrap_or_default().to_owned());btn.connect_clicked(move |_| ui::open_thread(&ui2, &root));Some(btn.upcast())}++/// The bot's live activity line: a turning orb, what it's doing and for how long.+pub fn working(ui: &App, bot: &Value) -> gtk::Widget {+ let needs = bot["status"] == "needsInput";+ let inner = gtk::Box::builder().spacing(8).build();+ let o = orb::widget(needs, 16);+ o.add_css_class(if needs { "warning-text" } else { "secondary" });+ inner.append(&o);+ let act = bot["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Working…");+ let l = label(+ act,+ &["small", if needs { "warning-text" } else { "secondary" }],+ );+ l.set_ellipsize(gtk::pango::EllipsizeMode::End);+ inner.append(&l);+ if let Some(started) = bot["startedAt"].as_i64() {+ let timer = label("", &["footnote", "tertiary"]);+ let tick = {+ let timer = timer.downgrade();+ move || {+ let Some(timer) = timer.upgrade() else {+ return gtk::glib::ControlFlow::Break;+ };+ let s = ((ui::now_ms() - started) / 1000).max(0);+ timer.set_label(&if s >= 3600 {+ format!("{}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)+ } else {+ format!("{}:{:02}", s / 60, s % 60)+ });+ gtk::glib::ControlFlow::Continue+ }+ };+ tick();+ gtk::glib::timeout_add_seconds_local(1, tick);+ inner.append(&timer);+ }+ let chevron = gtk::Image::from_icon_name("go-next-symbolic");+ chevron.set_pixel_size(10);+ chevron.add_css_class("tertiary");+ inner.append(&chevron);+ let btn = gtk::Button::builder()+ .child(&inner)+ .css_classes(["working"])+ .halign(gtk::Align::Start)+ .tooltip_text("Show what it's doing")+ .margin_top(6)+ .build();+ let ui2 = ui.clone();+ btn.connect_clicked(move |_| crate::dialogs::trace(&ui2));+ btn.upcast()+}++#[cfg(test)]+mod tests {+ #[test]+ fn stamps() {+ let now = crate::ui::now_ms();+ assert!(super::separator(now).starts_with("Today "));+ assert!(super::separator(now - 86_400_000).starts_with("Yesterday "));+ assert!(super::clock(now).ends_with('M'));+ assert_eq!(super::day(now - 86_400_000), "Yesterday");+ }+}diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rsindex 78837ae1..5c730930 100644--- a/apps/linux/src/ui.rs+++ b/apps/linux/src/ui.rs@@ -1,13 +1,16 @@-//! Main window: roster sidebar + conversation (Grok Bot's desktop layout).+//! Main window, laid out like the Mac chat window (apps/macos/Views/ChatWindow.swift and+//! kit ThreadView): a roster sidebar (+, Search, rows, Account), and the conversation with+//! its header, the details panel or an open thread on the right, and the composer.use crate::client::{self, Event};use crate::rows::{- agent_bubble, author_label, notice, permission_card, thread_chip, user_bubble, with_reply,+ self, Reply, agent_bubble, hline, icon_button, label, notice, permission_card, thread_chip,+ user_bubble,};-use crate::{avatar, dialogs};+use crate::{avatar, compose, dialogs, orb};use adw::prelude::*;use serde_json::{Value, json};-use std::cell::RefCell;+use std::cell::{Cell, RefCell};use std::collections::HashMap;use std::rc::Rc;@@ -17,16 +20,24 @@ pub struct State {pub entries: HashMap<String, Vec<Value>>,pub usage: Value,pub hello: Value,+ /// Remote screen status (`screenStatus`), for the details panel.+ pub screen: Value,pub current: Option<String>,/// Root entry of the thread open beside the current chat.pub open_thread: Option<String>,+ /// The To: page is showing instead of a chat.+ pub composing: bool,+ /// The details panel beside the chat is closed.+ pub hide_details: bool,+ pub search: String,pub online: bool,}/// A message box: send, or stop while the chat (or thread) is working. In a group,/// typing `@` suggests its bots.-struct Composer {+pub struct Composer {view: gtk::TextView,+ placeholder: gtk::Label,send_btn: gtk::Button,stop_btn: gtk::Button,mentions: gtk::Box,@@ -39,44 +50,56 @@ fn composer() -> Composer {.wrap_mode(gtk::WrapMode::WordChar).accepts_tab(false).hexpand(true)- .top_margin(4)- .bottom_margin(4)+ .top_margin(6)+ .bottom_margin(6).build();- let frame = gtk::ScrolledWindow::builder()+ let scroll = gtk::ScrolledWindow::builder().child(&view)- .max_content_height(160)+ .max_content_height(150).propagate_natural_height(true).hscrollbar_policy(gtk::PolicyType::Never)- .css_classes(["composer"])+ .vscrollbar_policy(gtk::PolicyType::External).hexpand(true).build();+ let placeholder = gtk::Label::builder()+ .xalign(0.0)+ .css_classes(["tertiary"])+ .can_target(false)+ .ellipsize(gtk::pango::EllipsizeMode::End)+ .valign(gtk::Align::Center)+ .build();+ let field = gtk::Overlay::builder().child(&scroll).hexpand(true).build();+ field.add_overlay(&placeholder);let send_btn = gtk::Button::builder().icon_name("go-up-symbolic").tooltip_text("Send")- .css_classes(["round", "accent-fill"])+ .css_classes(["send"]).valign(gtk::Align::End)+ .margin_bottom(2).build();let stop_btn = gtk::Button::builder().icon_name("media-playback-stop-symbolic").tooltip_text("Stop")- .css_classes(["round"])+ .css_classes(["send"]).valign(gtk::Align::End)+ .margin_bottom(2).build();- let row = gtk::Box::builder()+ let pill = gtk::Box::builder().spacing(8)- .margin_start(12)- .margin_end(12)- .margin_top(8)- .margin_bottom(12)+ .css_classes(["composer"])+ .margin_start(16)+ .margin_end(16)+ .margin_top(6)+ .margin_bottom(16).build();- row.append(&frame);- row.append(&stop_btn);- row.append(&send_btn);+ pill.append(&field);+ pill.append(&stop_btn);+ pill.append(&send_btn);let mentions = gtk::Box::builder().spacing(6)- .margin_start(12)- .margin_end(12)- .margin_top(8)+ .margin_start(16)+ .margin_end(16)+ .margin_top(6).build();let mentions_rev = gtk::Revealer::builder().transition_type(gtk::RevealerTransitionType::SlideUp)@@ -87,11 +110,20 @@ fn composer() -> Composer {.build(),).build();+ let col = gtk::Box::new(gtk::Orientation::Vertical, 0);+ col.append(&mentions_rev);+ col.append(&pill);let root = gtk::Box::new(gtk::Orientation::Vertical, 0);- root.append(&mentions_rev);- root.append(&row);+ root.append(+ &adw::Clamp::builder()+ .maximum_size(820)+ .tightening_threshold(820)+ .child(&col)+ .build(),+ );Composer {view,+ placeholder,send_btn,stop_btn,mentions,@@ -104,34 +136,43 @@ pub struct Ui {pub window: adw::ApplicationWindow,pub toasts: adw::ToastOverlay,pub split: adw::NavigationSplitView,- roster: gtk::ListBox,- usage_box: gtk::Box,+ pub roster: gtk::ListBox,+ roster_empty: gtk::Label,banner: adw::Banner,- title: adw::WindowTitle,+ pub search: gtk::SearchEntry,+ content_stack: gtk::Stack,+ chat_header: adw::HeaderBar,head_avatar: gtk::Box,+ head_name: gtk::Label,+ details_btn: gtk::Button,chat_list: gtk::Box,scroller: gtk::ScrolledWindow,compose: Composer,convo: gtk::Box,- pane: gtk::Revealer,- pane_box: gtk::Box,- pane_sep: gtk::Separator,+ side: gtk::Revealer,+ side_stack: gtk::Stack,+ details_content: gtk::Box,+ details_gear: gtk::Button,thread_back: gtk::Button,close_thread: gtk::Button,/// Below the breakpoint an open thread covers the chat instead of sitting beside it.- narrow: std::cell::Cell<bool>,- pane_title: adw::WindowTitle,+ narrow: Cell<bool>,+ pane_sub: gtk::Label,+ pane_box: gtk::Box,pane_list: gtk::Box,pane_scroller: gtk::ScrolledWindow,reply: Composer,- content_stack: gtk::Stack,- chat_buttons: [gtk::Widget; 2],+ pub compose_page: compose::Page,/// Bot shown in the last render; switching bots jumps to the newest message.shown_bot: RefCell<String>,/// Thread shown in the last render; opening one jumps to its newest reply.shown_thread: RefCell<String>,pub state: RefCell<State>,- rendering: std::cell::Cell<bool>,+ rendering: Cell<bool>,+ /// Debug builds: `CODYNC_DEBUG_OPEN=compose | group | <bot name>[/thread]` opens a screen+ /// once the bots arrive (screenshot checks, like the Mac's).+ debug_open: RefCell<Option<String>>,+ account: gtk::Button,}pub type App = Rc<Ui>;@@ -146,111 +187,255 @@ impl Ui {}}-pub fn build(app: &adw::Application) {- // Sidebar+/// A flat header bar (44 px) whose title area is `title`.+pub fn flat_header(title: &impl IsA<gtk::Widget>) -> adw::HeaderBar {+ adw::HeaderBar::builder()+ .title_widget(title)+ .css_classes(["flat-header"])+ .build()+}++/// The header of a panel right of the chat: it carries the window's end buttons.+fn side_header(content: >k::Box) -> adw::HeaderBar {+ content.set_hexpand(true);+ let h = flat_header(content);+ h.set_show_start_title_buttons(false);+ h+}++fn sidebar(+ new_btn: >k::Button,+ search: >k::SearchEntry,+ banner: &adw::Banner,+) -> (gtk::Box, gtk::ListBox, gtk::Label, gtk::Button) {+ let header = flat_header(>k::Box::builder().hexpand(true).build());+ header.pack_end(new_btn);let roster = gtk::ListBox::builder()- .css_classes(["navigation-sidebar"])+ .css_classes(["roster"])+ .selection_mode(gtk::SelectionMode::Single)+ .margin_start(12)+ .margin_end(12)+ .margin_top(4).build();- let usage_box = gtk::Box::builder()- .spacing(6)+ let roster_empty = gtk::Label::builder()+ .justify(gtk::Justification::Center)+ .use_markup(true)+ .can_target(false)+ .valign(gtk::Align::Center)+ .build();+ let list = gtk::Overlay::builder()+ .child(+ >k::ScrolledWindow::builder()+ .vexpand(true)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .child(&roster)+ .build(),+ )+ .build();+ list.add_overlay(&roster_empty);+ let face = gtk::Image::builder()+ .icon_name("avatar-default-symbolic")+ .pixel_size(15)+ .width_request(28)+ .height_request(28)+ .css_classes(["person-circle"])+ .build();+ let acct_inner = gtk::Box::builder().spacing(10).build();+ acct_inner.append(&face);+ acct_inner.append(>k::Label::new(Some("Account")));+ let account = gtk::Button::builder()+ .child(&acct_inner)+ .css_classes(["footer-row"])+ .tooltip_text("Account menu")+ .build();+ let footer = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(4).margin_start(12).margin_end(12)- .margin_bottom(6)+ .margin_top(6)+ .margin_bottom(10).build();- let usage_scroll = gtk::ScrolledWindow::builder()- .vscrollbar_policy(gtk::PolicyType::Never)- .child(&usage_box)+ footer.append(&account);+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .css_classes(["surface"]).build();- let banner = adw::Banner::new("Reconnecting to the Codync host…");- let sidebar_box = gtk::Box::new(gtk::Orientation::Vertical, 0);- sidebar_box.append(&banner);- sidebar_box.append(&usage_scroll);- sidebar_box.append(- >k::ScrolledWindow::builder()- .vexpand(true)- .child(&roster)- .build(),- );- let new_btn = gtk::Button::builder()- .icon_name("document-edit-symbolic")- .tooltip_text("New bot")+ col.append(&header);+ search.set_margin_start(12);+ search.set_margin_end(12);+ search.set_margin_top(4);+ search.set_margin_bottom(8);+ col.append(search);+ col.append(banner);+ col.append(&list);+ col.append(&footer);+ (col, roster, roster_empty, account)+}++fn empty_page(ui_new: >k::Button) -> gtk::Box {+ let page = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .css_classes(["chat-bg"])+ .build();+ page.append(&flat_header(>k::Box::new(+ gtk::Orientation::Horizontal,+ 0,+ )));+ let center = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(14)+ .valign(gtk::Align::Center)+ .vexpand(true)+ .margin_start(32)+ .margin_end(32)+ .margin_bottom(44).build();- let group_btn = gtk::Button::builder()- .icon_name("system-users-symbolic")- .tooltip_text("New group chat")+ use avatar::Mood;+ center.append(&avatar::row(+ &[+ ("blob", "blue", Mood::Working),+ ("squircle", "orange", Mood::Idle),+ ("teardrop", "violet", Mood::Working),+ ],+ 60,+ 10,+ ));+ let title = gtk::Label::builder()+ .label("Your coding agents, as teammates.")+ .css_classes(["title2"]).build();- let settings_btn = gtk::Button::builder()- .icon_name("emblem-system-symbolic")- .tooltip_text("Settings & pairing")+ center.append(&title);+ center.append(+ >k::Label::builder()+ .label("Pick a bot, or create one for each kind of work and point it at a project.")+ .wrap(true)+ .justify(gtk::Justification::Center)+ .max_width_chars(52)+ .css_classes(["body13", "secondary"])+ .build(),+ );+ ui_new.set_halign(gtk::Align::Center);+ center.append(ui_new);+ page.append(¢er);+ page+}++pub fn build(app: &adw::Application) {+ let new_btn = icon_button("list-add-symbolic", "New chat (Ctrl+N)");+ let search = gtk::SearchEntry::builder()+ .placeholder_text("Search")+ .css_classes(["search-field"]).build();- let side_header = adw::HeaderBar::new();- side_header.pack_start(&settings_btn);- side_header.pack_end(&new_btn);- side_header.pack_end(&group_btn);- let side_view = adw::ToolbarView::new();- side_view.add_top_bar(&side_header);- side_view.set_content(Some(&sidebar_box));- let sidebar_page = adw::NavigationPage::new(&side_view, "Codync");-- // Conversation- let title = adw::WindowTitle::new("", "");+ let banner = adw::Banner::new("Reconnecting to the Codync host…");+ let (sidebar_box, roster, roster_empty, account_btn) = sidebar(&new_btn, &search, &banner);+ let sidebar_page = adw::NavigationPage::new(&sidebar_box, "Codync");++ // Chat header: avatar + name (toggles details), details toggle, more.let head_avatar = gtk::Box::new(gtk::Orientation::Horizontal, 0);- let head = gtk::Box::builder().spacing(8).build();- head.append(&head_avatar);- head.append(&title);- let trace_btn = gtk::Button::builder()- .icon_name("view-list-symbolic")- .tooltip_text("Full conversation")+ let head_name = gtk::Label::builder()+ .css_classes(["body13", "semibold"])+ .ellipsize(gtk::pango::EllipsizeMode::End).build();- let menu_btn = gtk::MenuButton::builder()- .icon_name("view-more-symbolic")- .tooltip_text("More")+ let head_inner = gtk::Box::builder().spacing(7).build();+ head_inner.append(&head_avatar);+ head_inner.append(&head_name);+ let head_btn = gtk::Button::builder()+ .child(&head_inner)+ .css_classes(["plain"])+ .tooltip_text("View conversation details").build();- let content_header = adw::HeaderBar::builder().title_widget(&head).build();- content_header.pack_end(&menu_btn);- content_header.pack_end(&trace_btn);- let chat_list = entry_list();- let clamp = adw::Clamp::builder()- .maximum_size(760)- .child(&chat_list)+ let details_btn = icon_button("sidebar-show-right-symbolic", "Conversation details");+ let menu_btn = icon_button("view-more-symbolic", "More");+ let head_row = gtk::Box::builder()+ .spacing(4)+ .hexpand(true)+ .margin_start(10).build();+ head_row.append(&head_btn);+ head_row.append(>k::Box::builder().hexpand(true).build());+ head_row.append(&details_btn);+ head_row.append(&menu_btn);+ let chat_header = flat_header(&head_row);++ let chat_list = entry_list();let scroller = gtk::ScrolledWindow::builder().vexpand(true)- .child(&clamp)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .child(+ &adw::Clamp::builder()+ .maximum_size(820)+ .tightening_threshold(820)+ .child(&chat_list)+ .build(),+ ).build();let compose = composer();- let convo = gtk::Box::new(gtk::Orientation::Vertical, 0);+ let convo = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .hexpand(true)+ .css_classes(["chat-bg"])+ .build();+ convo.append(&chat_header);+ convo.append(&hline());convo.append(&scroller);- convo.append(>k::Separator::new(gtk::Orientation::Horizontal));convo.append(&compose.root);- convo.set_hexpand(true);-- // Thread pane beside the chat (Slack's).- let pane_title = adw::WindowTitle::new("Thread", "");- let thread_back = gtk::Button::builder()- .icon_name("go-previous-symbolic")- .tooltip_text("Back to chat")- .css_classes(["flat", "circular"])- .valign(gtk::Align::Center)- .visible(false)++ // Details panel (the Mac inspector).+ let details_gear = icon_button("emblem-system-symbolic", "Bot settings");+ let details_close = icon_button("sidebar-show-right-symbolic", "Close details");+ let dh = gtk::Box::builder()+ .spacing(4)+ .margin_start(12)+ .margin_end(12)+ .height_request(44)+ .build();+ dh.append(>k::Box::builder().hexpand(true).build());+ dh.append(&details_gear);+ dh.append(&details_close);+ let details_content = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(22)+ .margin_start(16)+ .margin_end(16)+ .margin_bottom(16)+ .build();+ let details_box = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .width_request(292)+ .css_classes(["chat-bg"]).build();- let close_thread = gtk::Button::builder()- .icon_name("window-close-symbolic")- .tooltip_text("Close thread")- .css_classes(["flat", "circular"])+ details_box.append(&side_header(&dh));+ details_box.append(+ >k::ScrolledWindow::builder()+ .vexpand(true)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .child(&details_content)+ .build(),+ );++ // Thread pane (RepliesView).+ let pane_sub = label("", &["footnote", "tertiary"]);+ pane_sub.set_ellipsize(gtk::pango::EllipsizeMode::End);+ let titles = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .hexpand(true).valign(gtk::Align::Center).build();- let pane_head = gtk::Box::builder()+ titles.append(&label("Thread", &["semibold"]));+ titles.append(&pane_sub);+ let thread_back = icon_button("go-previous-symbolic", "Back to chat");+ thread_back.set_visible(false);+ let close_thread = icon_button("window-close-symbolic", "Close thread (Esc)");+ let ph = gtk::Box::builder().spacing(8)- .margin_start(8)- .margin_end(8)- .margin_top(6)- .margin_bottom(6)+ .margin_start(16)+ .margin_end(10)+ .height_request(48).build();- pane_title.set_hexpand(true);- pane_head.append(&thread_back);- pane_head.append(&pane_title);- pane_head.append(&close_thread);+ ph.append(&thread_back);+ ph.append(&titles);+ ph.append(&close_thread);let pane_list = entry_list();let pane_scroller = gtk::ScrolledWindow::builder().vexpand(true)@@ -260,41 +445,52 @@ pub fn build(app: &adw::Application) {let reply = composer();let pane_box = gtk::Box::builder().orientation(gtk::Orientation::Vertical)- .width_request(380)+ .width_request(420)+ .css_classes(["chat-bg"]).build();- pane_box.append(&pane_head);- pane_box.append(>k::Separator::new(gtk::Orientation::Horizontal));+ pane_box.append(&side_header(&ph));+ pane_box.append(&hline());pane_box.append(&pane_scroller);- pane_box.append(>k::Separator::new(gtk::Orientation::Horizontal));pane_box.append(&reply.root);- let pane_outer = gtk::Box::new(gtk::Orientation::Horizontal, 0);- let pane_sep = gtk::Separator::new(gtk::Orientation::Vertical);- pane_outer.append(&pane_sep);- pane_outer.append(&pane_box);- let pane = gtk::Revealer::builder()++ let side_stack = gtk::Stack::builder()+ .transition_type(gtk::StackTransitionType::Crossfade)+ .hhomogeneous(false)+ .build();+ side_stack.add_named(&details_box, Some("details"));+ side_stack.add_named(&pane_box, Some("thread"));+ let side_outer = gtk::Box::new(gtk::Orientation::Horizontal, 0);+ side_outer.append(>k::Box::builder().css_classes(["vline"]).build());+ side_outer.append(&side_stack);+ let side = gtk::Revealer::builder().transition_type(gtk::RevealerTransitionType::SlideLeft)- .child(&pane_outer)+ .child(&side_outer).build();let chat_area = gtk::Box::new(gtk::Orientation::Horizontal, 0);chat_area.append(&convo);- chat_area.append(&pane);- let empty = adw::StatusPage::builder()- .title("Your coding agents, as teammates")- .description("Pick a bot, or create one for each kind of work and point it at a project.")- .icon_name("user-available-symbolic")+ chat_area.append(&side);++ let new_bot = gtk::Button::builder()+ .label("New Bot")+ .css_classes(["primary-pill"])+ .build();+ let compose_page = compose::build();+ let content_stack = gtk::Stack::builder()+ .transition_type(gtk::StackTransitionType::Crossfade)+ .transition_duration(150).build();- let content_stack = gtk::Stack::new();- content_stack.add_named(&empty, Some("empty"));+ content_stack.add_named(&empty_page(&new_bot), Some("empty"));content_stack.add_named(&chat_area, Some("chat"));- let content_view = adw::ToolbarView::new();- content_view.add_top_bar(&content_header);- content_view.set_content(Some(&content_stack));- let content_page = adw::NavigationPage::new(&content_view, "Chat");+ content_stack.add_named(&compose_page.root, Some("compose"));+ let content_page = adw::NavigationPage::new(&content_stack, "Chat");let split = adw::NavigationSplitView::builder().sidebar(&sidebar_page).content(&content_page).min_sidebar_width(260.0)+ .max_sidebar_width(296.0)+ .sidebar_width_fraction(0.27)+ .sidebar_width_unit(adw::LengthUnit::Px).build();let toasts = adw::ToastOverlay::new();toasts.set_child(Some(&split));@@ -303,76 +499,133 @@ pub fn build(app: &adw::Application) {.title("Codync").default_width(1100).default_height(760)+ .width_request(360)+ .height_request(400).content(&toasts).build();let bp = adw::Breakpoint::new(adw::BreakpointCondition::new_length(adw::BreakpointConditionLengthType::MaxWidth,640.0,- adw::LengthUnit::Sp,+ adw::LengthUnit::Px,));bp.add_setter(&split, "collapsed", Some(&true.to_value()));window.add_breakpoint(bp.clone());+ // Below this the details panel starts closed (the Mac's 680 pt conversation width).+ let bp_details = adw::Breakpoint::new(adw::BreakpointCondition::new_length(+ adw::BreakpointConditionLengthType::MaxWidth,+ 980.0,+ adw::LengthUnit::Px,+ ));+ window.add_breakpoint(bp_details.clone());let ui: App = Rc::new(Ui {window,toasts,split,roster,- usage_box,+ roster_empty,banner,- title,+ search,+ content_stack,+ chat_header,head_avatar,+ head_name,+ details_btn: details_btn.clone(),chat_list,scroller,compose,convo,- pane,- pane_box,- pane_sep,+ side,+ side_stack,+ details_content,+ details_gear: details_gear.clone(),thread_back: thread_back.clone(),close_thread: close_thread.clone(),- narrow: std::cell::Cell::new(false),- pane_title,+ narrow: Cell::new(false),+ pane_sub,+ pane_box,pane_list,pane_scroller,reply,- content_stack,- chat_buttons: [trace_btn.clone().upcast(), menu_btn.clone().upcast()],+ compose_page,shown_bot: RefCell::new(String::new()),shown_thread: RefCell::new(String::new()),state: RefCell::new(State::default()),- rendering: std::cell::Cell::new(false),+ rendering: Cell::new(false),+ account: account_btn.clone(),+ debug_open: RefCell::new(if cfg!(debug_assertions) {+ std::env::var("CODYNC_DEBUG_OPEN").ok()+ } else {+ None+ }),});// Wiring{let ui2 = ui.clone();ui.roster.connect_row_activated(move |_, row| {- {- let mut st = ui2.state.borrow_mut();- st.current = Some(row.widget_name().to_string());- st.open_thread = None;- }- ui2.split.set_show_content(true);- mark_read(&ui2);- render(&ui2);+ select(&ui2, row.widget_name().as_str());+ });+ }+ {+ let ui2 = ui.clone();+ ui.search.connect_search_changed(move |s| {+ ui2.state.borrow_mut().search = s.text().to_string();+ render_roster(&ui2);});}{let ui2 = ui.clone();- new_btn.connect_clicked(move |_| dialogs::editor(&ui2, None));+ ui.search.connect_stop_search(move |s| {+ s.set_text("");+ ui2.roster.grab_focus();+ });+ }+ for b in [&new_btn, &new_bot] {+ let ui2 = ui.clone();+ b.connect_clicked(move |_| compose::open(&ui2));}{let ui2 = ui.clone();- group_btn.connect_clicked(move |_| dialogs::group_editor(&ui2, None));+ account_btn.connect_clicked(move |b| dialogs::account_menu(&ui2, b));}for b in [&close_thread, &thread_back] {+ let ui2 = ui.clone();+ b.connect_clicked(move |_| close_open_thread(&ui2));+ }+ for b in [&head_btn, &details_btn, &details_close] {let ui2 = ui.clone();b.connect_clicked(move |_| {- ui2.state.borrow_mut().open_thread = None;+ let mut st = ui2.state.borrow_mut();+ st.hide_details = !st.hide_details;+ drop(st);schedule(&ui2);});}+ {+ let ui2 = ui.clone();+ details_gear.connect_clicked(move |_| {+ let bot = {+ let st = ui2.state.borrow();+ st.current.as_ref().and_then(|id| st.bots.get(id)).cloned()+ };+ if let Some(b) = bot {+ if is_group(&b) {+ dialogs::group_editor(&ui2, Some(b));+ } else {+ dialogs::editor(&ui2, Some(b));+ }+ }+ });+ }+ {+ let ui2 = ui.clone();+ menu_btn.connect_clicked(move |b| {+ if let Some(id) = ui2.state.borrow().current.clone() {+ dialogs::bot_menu(&ui2, b.upcast_ref(), None, &id, false);+ }+ });+ }for narrow in [true, false] {let ui2 = ui.clone();let f = move |_: &adw::Breakpoint| {@@ -385,41 +638,79 @@ pub fn build(app: &adw::Application) {bp.connect_unapply(f);}}- {+ for compact in [true, false] {let ui2 = ui.clone();- settings_btn.connect_clicked(move |_| dialogs::settings(&ui2));+ let f = move |_: &adw::Breakpoint| {+ ui2.state.borrow_mut().hide_details = compact;+ schedule(&ui2);+ };+ if compact {+ bp_details.connect_apply(f);+ } else {+ bp_details.connect_unapply(f);+ }}+ // Ctrl+N: new chat; Ctrl+F: search; Esc closes an open thread.{+ let actions = gtk::gio::SimpleActionGroup::new();+ let new_chat = gtk::gio::SimpleAction::new("new-chat", None);let ui2 = ui.clone();- trace_btn.connect_clicked(move |_| dialogs::trace(&ui2));- }- {+ new_chat.connect_activate(move |_, _| compose::open(&ui2));+ actions.add_action(&new_chat);+ let find = gtk::gio::SimpleAction::new("search", None);let ui2 = ui.clone();- menu_btn.set_create_popup_func(move |btn| btn.set_popover(Some(&dialogs::bot_menu(&ui2))));- }- wire_composer(&ui, false);- wire_composer(&ui, true);- // Keep relative times fresh.- {+ find.connect_activate(move |_, _| {+ ui2.split.set_show_content(false);+ ui2.search.grab_focus();+ });+ actions.add_action(&find);+ ui.window.insert_action_group("codync", Some(&actions));+ app.set_accels_for_action("codync.new-chat", &["<Control>n"]);+ app.set_accels_for_action("codync.search", &["<Control>f"]);+ let keys = gtk::EventControllerKey::new();let ui2 = ui.clone();- gtk::glib::timeout_add_seconds_local(30, move || {- render_roster(&ui2);- gtk::glib::ControlFlow::Continue+ keys.connect_key_pressed(move |_, key, _, _| {+ if key == gtk::gdk::Key::Escape && ui2.state.borrow().open_thread.is_some() {+ close_open_thread(&ui2);+ return gtk::glib::Propagation::Stop;+ }+ gtk::glib::Propagation::Proceed});+ ui.window.add_controller(keys);}+ wire_composer(&ui, false);+ wire_composer(&ui, true);+ compose::wire(&ui);ui.window.present();connect(&ui);}+fn close_open_thread(ui: &App) {+ ui.state.borrow_mut().open_thread = None;+ schedule(ui);+}++/// Opens a bot's (or group's) chat.+pub fn select(ui: &App, id: &str) {+ {+ let mut st = ui.state.borrow_mut();+ st.current = Some(id.to_owned());+ st.open_thread = None;+ st.composing = false;+ }+ ui.split.set_show_content(true);+ mark_read(ui);+ render(ui);+}+fn entry_list() -> gtk::Box {gtk::Box::builder().orientation(gtk::Orientation::Vertical)- .spacing(4).margin_start(16).margin_end(16)- .margin_top(12)- .margin_bottom(12)+ .margin_top(8)+ .margin_bottom(8).build()}@@ -475,6 +766,7 @@ fn connect(ui: &App) {st.current = args.get(i + 1).cloned();}drop(st);+ refresh_screen(&ui2);let (tx, rx) = async_channel::unbounded();client::stream(tx);let ui3 = ui2.clone();@@ -488,6 +780,14 @@ fn connect(ui: &App) {});}+pub fn refresh_screen(ui: &App) {+ let ui2 = ui.clone();+ client::call("screenStatus", client::empty(), move |r| {+ ui2.state.borrow_mut().screen = r.unwrap_or(Value::Null);+ schedule(&ui2);+ });+}+pub fn reconnect(ui: &App) {client::reset_rev();connect(ui);@@ -499,8 +799,7 @@ fn handle(ui: &App, ev: Event) {match ev {Event::Online(on) => st.online = on,Event::Message(m) => match m["type"].as_str().unwrap_or_default() {- "hello" => st.usage = m["usage"].clone(),- "usage" => st.usage = m["usage"].clone(),+ "hello" | "usage" => st.usage = m["usage"].clone(),"bot" => {let bot = &m["bot"];let id = bot["id"].as_str().unwrap_or_default().to_owned();@@ -524,6 +823,59 @@ fn handle(ui: &App, ev: Event) {}}schedule(ui);+ debug_open(ui);+}++fn debug_open(ui: &App) {+ let Some(target) = ui.debug_open.borrow().clone() else {+ return;+ };+ // Bots arrive one event at a time: give the catch-up a moment.+ if ui.state.borrow().bots.len() < 2 {+ return;+ }+ let ui2 = ui.clone();+ let target = target.clone();+ ui.debug_open.replace(None);+ gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(800), move || {+ debug_open_now(&ui2, &target);+ });+}++fn debug_open_now(ui: &App, target: &str) {+ let (name, thread) = target.split_once('/').unwrap_or((target, ""));+ match name {+ "compose" => compose::open(ui),+ "group" => dialogs::group_editor(ui, None),+ "account" => {+ dialogs::account_menu(ui, &ui.account);+ }+ _ => {+ let st = ui.state.borrow();+ let Some(id) = st+ .bots+ .values()+ .find(|b| b["name"] == name)+ .and_then(|b| b["id"].as_str().map(str::to_owned))+ else {+ return;+ };+ let root = st.entries.get(&id).and_then(|l| {+ l.iter()+ .rev()+ .find(|e| e["data"]["thread"]["count"].as_i64().unwrap_or(0) > 0)+ .and_then(|e| e["id"].as_str().map(str::to_owned))+ });+ if !thread.is_empty() && root.is_none() {+ return;+ }+ drop(st);+ select(ui, &id);+ if let Some(root) = root.filter(|_| !thread.is_empty()) {+ open_thread(ui, &root);+ }+ }+ }}/// Desktop notification when a bot needs you or finishes, unless Codync is focused.@@ -598,10 +950,15 @@ pub fn schedule(ui: &App) {pub fn render(ui: &App) {ui.banner.set_revealed(!ui.state.borrow().online);- render_usage(ui);render_roster(ui);+ let composing = ui.state.borrow().composing;+ if composing {+ ui.content_stack.set_visible_child_name("compose");+ compose::render(ui);+ return;+ }render_chat(ui);- render_pane(ui);+ render_side(ui);}pub fn working(b: &Value) -> bool {@@ -615,11 +972,11 @@ pub fn working_in(b: &Value, chat: &str, thread: Option<&str>) -> bool {&& b["workingThread"].as_str() == thread}-fn is_group(b: &Value) -> bool {+pub fn is_group(b: &Value) -> bool {b["kind"] == "group"}-fn members<'a>(st: &'a State, group: &Value) -> Vec<&'a Value> {+pub fn members<'a>(st: &'a State, group: &Value) -> Vec<&'a Value> {group["members"].as_array().into_iter()@@ -662,65 +1019,11 @@ pub fn backend_name(st: &State, id: &str) -> String {pub fn folder(p: &str) -> String {std::path::Path::new(p).file_name()- .map(|s| s.to_string_lossy().into_owned())- .unwrap_or_else(|| p.to_owned())-}--pub fn ago(ms: i64) -> String {- let now = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_millis() as i64;- let s = ((now - ms) / 1000).max(0);- match s {- 0..60 => "now".into(),- 60..3600 => format!("{}m", s / 60),- 3600..86400 => format!("{}h", s / 3600),- _ => format!("{}d", s / 86400),- }-}--fn render_usage(ui: &App) {- while let Some(c) = ui.usage_box.first_child() {- ui.usage_box.remove(&c);- }- let st = ui.state.borrow();- for p in st.usage["providers"].as_array().into_iter().flatten() {- for w in p["windows"].as_array().into_iter().flatten().take(2) {- let pct = w["percent"].as_f64().unwrap_or(0.0);- let chip = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .css_classes(["chip"])- .build();- chip.append(- >k::Label::builder()- .label(format!(- "{} {}",- p["name"].as_str().unwrap_or(""),- w["label"].as_str().unwrap_or("")- ))- .css_classes(["small", "muted"])- .xalign(0.0)- .build(),- );- let value = gtk::Label::builder()- .label(format!("{pct:.0}%"))- .xalign(0.0)- .css_classes(["heading"])- .build();- if pct >= 90.0 {- value.add_css_class("error");- } else if pct >= 70.0 {- value.add_css_class("warning");- }- chip.append(&value);- ui.usage_box.append(&chip);- }- }+ .map_or_else(|| p.to_owned(), |s| s.to_string_lossy().into_owned())}-fn render_roster(ui: &App) {- let st = ui.state.borrow();+/// The sidebar's bots, pinned first then most recent (the Mac `roster`).+pub fn roster(st: &State) -> Vec<&Value> {let mut bots: Vec<&Value> = st.bots.values()@@ -732,111 +1035,126 @@ fn render_roster(ui: &App) {-b["lastAt"].as_i64().unwrap_or(0),)});+ bots+}++/// Live activity while working, otherwise the last message (BotRow's preview).+fn preview(st: &State, b: &Value) -> gtk::Widget {+ let row = gtk::Box::builder().spacing(6).hexpand(true).build();+ let text = |s: &str, class: &str| {+ let l = label(&s.replace('\n', " "), &["small", class]);+ l.set_ellipsize(gtk::pango::EllipsizeMode::End);+ l.set_hexpand(true);+ l+ };+ let activity = b["activity"].as_str().filter(|s| !s.is_empty());+ match b["status"].as_str() {+ Some("needsInput") => {+ let o = orb::widget(true, 16);+ o.add_css_class("warning-text");+ row.append(&o);+ row.append(&text(+ activity.unwrap_or("Needs your approval"),+ "warning-text",+ ));+ }+ Some("working") => {+ let o = orb::widget(false, 13);+ o.add_css_class("secondary");+ row.append(&o);+ row.append(&text(activity.unwrap_or("Working…"), "secondary"));+ }+ Some("error") => row.append(&text(+ b["lastMessage"].as_str().unwrap_or("Something went wrong"),+ "danger-text",+ )),+ _ => row.append(&text(+ &b["lastMessage"].as_str().map_or_else(+ || {+ if is_group(b) {+ member_names(st, b)+ } else {+ format!(+ "{} · {}",+ backend_name(st, b["backend"].as_str().unwrap_or("")),+ folder(b["cwd"].as_str().unwrap_or(""))+ )+ }+ },+ str::to_owned,+ ),+ "secondary",+ )),+ }+ row.upcast()+}++fn render_roster(ui: &App) {+ let st = ui.state.borrow();+ let q = st.search.trim().to_lowercase();+ let bots: Vec<&Value> = roster(&st)+ .into_iter()+ .filter(|b| {+ q.is_empty()+ || [&b["name"], &b["lastMessage"]]+ .iter()+ .any(|v| v.as_str().is_some_and(|s| s.to_lowercase().contains(&q)))+ })+ .collect();while let Some(c) = ui.roster.first_child() {ui.roster.remove(&c);}+ ui.roster_empty.set_visible(bots.is_empty());+ ui.roster_empty.set_markup(if q.is_empty() {+ "<span weight=\"500\" size=\"13pt\">No bots yet</span>\n<span size=\"12pt\" alpha=\"60%\">Use + to start a new chat.</span>"+ } else {+ "<span weight=\"500\" size=\"13pt\">No matching bots</span>\n<span size=\"12pt\" alpha=\"60%\">Try another name or message.</span>"+ });for b in bots {let id = b["id"].as_str().unwrap_or_default();let unread = b["unread"].as_i64().unwrap_or(0);- let status = if b["status"] == "needsInput" {- "needs"- } else if unread > 0 {- "unread"- } else {- ""- };- let row_box = gtk::Box::builder()- .spacing(10)- .margin_top(6)- .margin_bottom(6)- .build();- row_box.append(&avatar::of(&st.bots, b, 40, working(b), status));+ let row_box = gtk::Box::builder().spacing(8).build();+ row_box.append(&avatar::with_status(&st.bots, b, 30));let text = gtk::Box::builder().orientation(gtk::Orientation::Vertical)+ .spacing(1).hexpand(true)+ .valign(gtk::Align::Center).build();- let top = gtk::Box::builder().spacing(6).build();- top.append(- >k::Label::builder()- .label(b["name"].as_str().unwrap_or(""))- .xalign(0.0)- .hexpand(true)- .ellipsize(gtk::pango::EllipsizeMode::End)- .css_classes(["heading"])- .build(),- );- let time = gtk::Label::builder()- .label(ago(b["lastAt"].as_i64().unwrap_or(0)))- .css_classes(["small", "muted"])- .build();- top.append(&time);+ let top = gtk::Box::builder().spacing(4).build();+ if b["pinned"] == true {+ let pin = gtk::Image::from_icon_name("view-pin-symbolic");+ pin.set_pixel_size(10);+ pin.add_css_class("tertiary");+ top.append(&pin);+ }+ let name = label(b["name"].as_str().unwrap_or(""), &["name"]);+ name.set_ellipsize(gtk::pango::EllipsizeMode::End);+ top.append(&name);text.append(&top);- let (preview, class) = match b["status"].as_str() {- Some("needsInput") => (- format!(- "✋ {}",- b["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Needs your approval")- ),- "needs-text",- ),- Some("working") => (- b["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Working…")- .to_owned(),- "accent-text",- ),- Some("error") => (- b["lastMessage"]- .as_str()- .unwrap_or("Something went wrong")- .to_owned(),- "error",- ),- _ => (- b["lastMessage"]- .as_str()- .map(str::to_owned)- .unwrap_or_else(|| {- if is_group(b) {- return member_names(&st, b);- }- format!(- "{} · {}",- backend_name(&st, b["backend"].as_str().unwrap_or("")),- folder(b["cwd"].as_str().unwrap_or(""))- )- }),- "dim-label",- ),- };let bottom = gtk::Box::builder().spacing(6).build();- bottom.append(- >k::Label::builder()- .label(preview.replace('\n', " "))- .xalign(0.0)- .hexpand(true)- .ellipsize(gtk::pango::EllipsizeMode::End)- .css_classes([class])- .build(),- );+ bottom.append(&preview(&st, b));if unread > 0 {- bottom.append(- >k::Label::builder()- .label(unread.to_string())- .css_classes(["badge"])- .build(),- );+ bottom.append(&label(&unread.to_string(), &["badge"]));}text.append(&bottom);row_box.append(&text);- let row = gtk::ListBoxRow::builder().child(&row_box).name(id).build();+ let row = gtk::ListBoxRow::builder()+ .child(&row_box)+ .name(id)+ .tooltip_text(b["name"].as_str().unwrap_or(""))+ .build();+ // Right-click: the conversation menu (Pin, Mark as Read, Edit, …).+ let click = gtk::GestureClick::builder()+ .button(gtk::gdk::BUTTON_SECONDARY)+ .build();+ let (ui2, id2, row2) = (ui.clone(), id.to_owned(), row.clone());+ click.connect_pressed(move |_, _, x, y| {+ dialogs::bot_menu(&ui2, row2.upcast_ref(), Some((x, y)), &id2, true);+ });+ row.add_controller(click);ui.roster.append(&row);- if st.current.as_deref() == Some(id) {+ if st.current.as_deref() == Some(id) && !st.composing {ui.roster.select_row(Some(&row));}}@@ -850,7 +1168,7 @@ fn is_chat(e: &Value) -> bool {}}-fn clear(b: >k::Box) {+pub fn clear(b: >k::Box) {while let Some(c) = b.first_child() {b.remove(&c);}@@ -862,47 +1180,85 @@ fn near_bottom(s: >k::ScrolledWindow) -> bool {}fn scroll_to_end(s: >k::ScrolledWindow) {- let adj = s.vadjustment();- // Twice: labels finish wrapping (and the height settles) one frame later.- gtk::glib::idle_add_local_once(move || {- adj.set_value(adj.upper());- let adj2 = adj.clone();- gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(60), move || {- adj2.set_value(adj2.upper())- });+ // Labels finish wrapping (and the height settles) over the next frames: follow the+ // bottom for a moment.+ let start = std::time::Instant::now();+ s.add_tick_callback(move |s, _| {+ let adj = s.vadjustment();+ adj.set_value(adj.upper() - adj.page_size());+ if start.elapsed() < std::time::Duration::from_millis(800) {+ gtk::glib::ControlFlow::Continue+ } else {+ gtk::glib::ControlFlow::Break+ }});}+/// The start of an empty chat: who it is and how it works (IntroCard / GroupIntroCard).+fn intro(st: &State, bot: &Value) -> gtk::Box {+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .margin_top(40)+ .margin_start(24)+ .margin_end(24)+ .build();+ col.append(&avatar::of(&st.bots, bot, 72, true));+ let centered = |text: &str, classes: &[&str]| {+ let l = label(text, classes);+ l.set_xalign(0.5);+ l.set_wrap(true);+ l.set_justify(gtk::Justification::Center);+ l+ };+ col.append(¢ered(bot["name"].as_str().unwrap_or(""), &["title2"]));+ let desc = bot["description"].as_str().unwrap_or("");+ if is_group(bot) {+ col.append(¢ered(&member_names(st, bot), &["small", "secondary"]));+ if !desc.is_empty() {+ col.append(¢ered(desc, &["small", "secondary"]));+ }+ let tip = centered(+ "Everyone answers in turn. @mention a bot to ask just that one. Each bot works in its own folder.",+ &["footnote", "tertiary"],+ );+ tip.set_margin_top(4);+ col.append(&tip);+ } else {+ col.append(¢ered(+ &format!(+ "{} in {}",+ backend_name(st, bot["backend"].as_str().unwrap_or("")),+ bot["cwd"].as_str().unwrap_or("")+ ),+ &["footnote", "mono", "tertiary"],+ ));+ if !desc.is_empty() {+ col.append(¢ered(desc, &["small", "secondary"]));+ }+ let tip = centered(+ "Tell it what you need. You'll get a notification when it's done or needs you.",+ &["footnote", "tertiary"],+ );+ tip.set_margin_top(4);+ col.append(&tip);+ }+ col+}+fn render_chat(ui: &App) {let st = ui.state.borrow();let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) else {ui.content_stack.set_visible_child_name("empty");- ui.chat_buttons.iter().for_each(|b| b.set_visible(false));- ui.title.set_title("Codync");- ui.title.set_subtitle("");return;};let id = bot["id"].as_str().unwrap_or_default();- let group = is_group(bot);ui.content_stack.set_visible_child_name("chat");- ui.chat_buttons.iter().for_each(|b| b.set_visible(true));let switched = *ui.shown_bot.replace(id.to_owned()) != *id;let stick = switched || near_bottom(&ui.scroller);- ui.title.set_title(bot["name"].as_str().unwrap_or(""));- let sub = match bot["status"].as_str() {- Some("needsInput") => "Needs you".to_owned(),- Some("working") => "Working".to_owned(),- _ if group => member_names(&st, bot),- _ => format!(- "{} · {}",- backend_name(&st, bot["backend"].as_str().unwrap_or("")),- folder(bot["cwd"].as_str().unwrap_or(""))- ),- };- ui.title.set_subtitle(&sub);+ ui.head_name.set_label(bot["name"].as_str().unwrap_or(""));clear(&ui.head_avatar);- ui.head_avatar- .append(&avatar::of(&st.bots, bot, 28, working(bot), ""));+ ui.head_avatar.append(&avatar::of(&st.bots, bot, 22, true));clear(&ui.chat_list);let entries: Vec<&Value> = st@@ -911,79 +1267,204 @@ fn render_chat(ui: &App) {.map(|l| l.iter().filter(|e| e["threadId"].is_null()).collect()).unwrap_or_default();if !entries.iter().any(|e| is_chat(e)) {- let intro = adw::StatusPage::builder()- .title(bot["name"].as_str().unwrap_or(""))- .build();- if group {- intro.set_description(Some(&format!(- "{}\n\nEveryone answers in turn unless you @mention someone.",- member_names(&st, bot)- )));- } else {- intro.set_description(Some(&format!(- "{} in {}\n\n{}\n\nTell it what you need.",- backend_name(&st, bot["backend"].as_str().unwrap_or("")),- bot["cwd"].as_str().unwrap_or(""),- bot["description"].as_str().unwrap_or("")- )));- }- ui.chat_list.append(&intro);+ ui.chat_list.append(&intro(&st, bot));}append_entries(ui, &st, &ui.chat_list, bot, &entries, true);- if working_in(bot, id, None) {- ui.chat_list.append(&working_row(&st, bot));+ if working_in(bot, id, None) && st.online {+ ui.chat_list.append(&rows::working(ui, bot));}update_composer_for(ui, &st, bot, false);if stick {scroll_to_end(&ui.scroller);}+ if switched {+ ui.compose.view.grab_focus();+ }}-/// The thread open beside the chat: its root, the replies and a composer that replies there.-fn render_pane(ui: &App) {+/// The right side of a chat: an open thread, else the details panel (unless closed).+fn render_side(ui: &App) {let st = ui.state.borrow();- let (Some(bot), Some(root_id)) = (- st.current.as_ref().and_then(|id| st.bots.get(id)),- st.open_thread.as_deref(),- ) else {- layout_pane(ui, false);- ui.pane.set_reveal_child(false);+ let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) else {ui.shown_thread.replace(String::new());return;};+ let thread = st.open_thread.clone();+ let details = !st.hide_details && thread.is_none();+ ui.details_btn.set_visible(st.hide_details);+ let open = thread.is_some() || details;+ // The window's own buttons move into whatever is rightmost.+ ui.chat_header.set_show_end_title_buttons(!open);+ layout_side(ui, thread.is_some());+ ui.side.set_reveal_child(open);+ if details {+ ui.side_stack.set_visible_child_name("details");+ render_details(ui, &st, bot);+ }+ match thread {+ Some(root) => {+ ui.side_stack.set_visible_child_name("thread");+ render_thread(ui, &st, bot, &root);+ }+ None => {+ ui.shown_thread.replace(String::new());+ }+ }+}++fn render_details(ui: &App, st: &State, bot: &Value) {+ let c = &ui.details_content;+ clear(c);+ let group = is_group(bot);+ ui.details_gear+ .set_tooltip_text(Some(if group { "Edit group" } else { "Bot settings" }));+ if group {+ let list = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(2)+ .build();+ let ms = members(st, bot);+ let title = label(&format!("{} bots", ms.len()), &["body13", "semibold"]);+ title.set_margin_bottom(6);+ list.append(&title);+ for m in ms {+ let row = gtk::Box::builder()+ .spacing(10)+ .margin_top(6)+ .margin_bottom(6)+ .build();+ row.append(&avatar::of(&st.bots, m, 26, true));+ let text = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(1)+ .build();+ text.append(&label(m["name"].as_str().unwrap_or(""), &["body13"]));+ let sub = if working(m) {+ m["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Working…")+ .to_owned()+ } else {+ folder(m["cwd"].as_str().unwrap_or(""))+ };+ let s = label(&sub, &["small", "tertiary"]);+ s.set_ellipsize(gtk::pango::EllipsizeMode::End);+ text.append(&s);+ row.append(&text);+ let name = m["name"].as_str().unwrap_or("");+ let btn = gtk::Button::builder()+ .child(&row)+ .css_classes(["plain"])+ .tooltip_text(format!("Open {name}'s own chat"))+ .build();+ let (ui2, mid) = (ui.clone(), m["id"].as_str().unwrap_or_default().to_owned());+ btn.connect_clicked(move |_| select(&ui2, &mid));+ list.append(&btn);+ }+ c.append(&list);+ return;+ }+ let id = bot["id"].as_str().unwrap_or_default();+ let screen = &st.screen;+ let status = if !st.online {+ "Computer is offline"+ } else if screen["enabled"] != true {+ "Remote screen is off"+ } else if screen["connected"] != true {+ "Connecting to computer…"+ } else if screen["agentBot"] == id {+ "This bot is using your computer"+ } else {+ "Ready · View this computer from your iPhone"+ };+ let computer = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .css_classes(["details-box"])+ .height_request(164)+ .build();+ let icon = gtk::Image::from_icon_name("computer-symbolic");+ icon.set_pixel_size(32);+ let s = label(status, &["small", "secondary"]);+ s.set_xalign(0.5);+ s.set_wrap(true);+ s.set_justify(gtk::Justification::Center);+ // Centered in the 164 pt box.+ computer.append(>k::Box::builder().vexpand(true).build());+ computer.append(&icon);+ computer.append(&s);+ computer.append(>k::Box::builder().vexpand(true).build());+ let top = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(12)+ .build();+ top.append(&computer);+ let host = label(+ st.hello["name"].as_str().unwrap_or(""),+ &["footnote", "tertiary"],+ );+ host.set_xalign(0.5);+ top.append(&host);+ c.append(&top);+ let agent = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(8)+ .build();+ agent.append(&label("Agent", &["body13", "semibold"]));+ agent.append(&label(+ &backend_name(st, bot["backend"].as_str().unwrap_or("")),+ &["body13", "secondary"],+ ));+ let cwd = label(bot["cwd"].as_str().unwrap_or(""), &["secondary"]);+ cwd.set_selectable(true);+ cwd.set_wrap(true);+ cwd.set_wrap_mode(gtk::pango::WrapMode::WordChar);+ agent.append(&cwd);+ if let Some(d) = bot["description"].as_str().filter(|d| !d.is_empty()) {+ let l = label(d, &["body13", "secondary"]);+ l.set_wrap(true);+ agent.append(&l);+ }+ c.append(&agent);+}++/// The thread open beside the chat: its root, the replies and a composer that replies there.+fn render_thread(ui: &App, st: &State, bot: &Value, root_id: &str) {let id = bot["id"].as_str().unwrap_or_default();- layout_pane(ui, true);- ui.pane.set_reveal_child(true);- ui.pane_title- .set_subtitle(bot["name"].as_str().unwrap_or(""));+ ui.pane_sub.set_label(bot["name"].as_str().unwrap_or(""));let switched = *ui.shown_thread.replace(root_id.to_owned()) != *root_id;let stick = switched || near_bottom(&ui.pane_scroller);clear(&ui.pane_list);let all = st.entries.get(id).map(Vec::as_slice).unwrap_or_default();- if let Some(root) = all.iter().find(|e| e["id"] == root_id) {- append_entries(ui, &st, &ui.pane_list, bot, &[root], false);- }let replies: Vec<&Value> = all.iter().filter(|e| e["threadId"] == root_id).collect();- let n = replies.iter().filter(|e| is_chat(e)).count();- ui.pane_list.append(- >k::Label::builder()- .label(match n {+ if let Some(root) = all.iter().find(|e| e["id"] == root_id) {+ append_entries(ui, st, &ui.pane_list, bot, &[root], false);+ let n = replies.iter().filter(|e| is_chat(e)).count();+ let div = gtk::Box::builder()+ .spacing(10)+ .margin_top(12)+ .margin_bottom(12)+ .build();+ div.append(&label(+ &match n {0 => "No replies yet".to_owned(),1 => "1 reply".to_owned(),_ => format!("{n} replies"),- })- .xalign(0.0)- .css_classes(["small", "muted"])- .margin_top(12)- .build(),- );- ui.pane_list- .append(>k::Separator::new(gtk::Orientation::Horizontal));- append_entries(ui, &st, &ui.pane_list, bot, &replies, false);- if working_in(bot, id, Some(root_id)) {- ui.pane_list.append(&working_row(&st, bot));+ },+ &["footnote", "tertiary"],+ ));+ let line = hline();+ line.set_hexpand(true);+ line.set_valign(gtk::Align::Center);+ div.append(&line);+ ui.pane_list.append(&div);+ }+ append_entries(ui, st, &ui.pane_list, bot, &replies, false);+ if working_in(bot, id, Some(root_id)) && st.online {+ ui.pane_list.append(&rows::working(ui, bot));}- update_composer_for(ui, &st, bot, true);+ update_composer_for(ui, st, bot, true);if stick {scroll_to_end(&ui.pane_scroller);}@@ -994,18 +1475,17 @@ fn render_pane(ui: &App) {/// Wide windows keep the thread in a side pane; narrow ones let it cover the chat,/// with a back button in place of close.-fn layout_pane(ui: &App, open: bool) {- let cover = open && ui.narrow.get();+fn layout_side(ui: &App, thread: bool) {+ let cover = thread && ui.narrow.get();ui.convo.set_visible(!cover);- ui.pane.set_hexpand(cover);+ ui.side.set_hexpand(cover);ui.pane_box.set_hexpand(cover);- ui.pane_box.set_width_request(if cover { -1 } else { 380 });- ui.pane_sep.set_visible(!cover);+ ui.pane_box.set_width_request(if cover { -1 } else { 420 });ui.thread_back.set_visible(cover);ui.close_thread.set_visible(!cover);}-/// Chat-visible entries with time separators (gaps > 1 h) and author grouping.+/// Chat-visible entries with time separators (gaps > 1 h, main chat) and author grouping./// `main`: the main chat, where messages can start threads and show their summary.fn append_entries(ui: &App,@@ -1017,21 +1497,18 @@ fn append_entries() {let group = is_group(chat);let mut last_author = String::new();- let mut last_time = 0i64;+ let mut last_time: Option<i64> = None;for e in entries.iter().filter(|e| is_chat(e)) {let at = e["createdAt"].as_i64().unwrap_or(0);- if at - last_time > 3_600_000 {- list.append(- >k::Label::builder()- .label(ago(at))- .css_classes(["small", "muted"])- .margin_top(12)- .margin_bottom(6)- .build(),- );+ if main && last_time.is_none_or(|t| at - t > 3_600_000) {+ let sep = label(&rows::separator(at), &["footnote", "tertiary"]);+ sep.set_xalign(0.5);+ sep.set_margin_top(18);+ sep.set_margin_bottom(6);+ list.append(&sep);last_author.clear();}- last_time = at;+ last_time = Some(at);let kind = e["kind"].as_str().unwrap_or_default();// In a group each bot is its own author.let author = match kind {@@ -1045,82 +1522,24 @@ fn append_entries(String::new()};let entry_id = e["id"].as_str().unwrap_or_default();- let author_id = e["data"]["author"].as_str();- let reply = |w: gtk::Widget, end: bool| {- // Local echoes have no id on the host yet.- if main && !entry_id.starts_with("local-") {- with_reply(- ui,- &w,- end,- entry_id,- e["data"]["text"].as_str().unwrap_or(""),- )- } else {- w- }+ // Local echoes have no id on the host yet.+ let r = Reply {+ ui,+ root: (main && !entry_id.starts_with("local-")).then_some(entry_id),};match kind {- "user" => list.append(&reply(user_bubble(e, working(chat), start), true)),- "agent" => {- let deleted = json!({"avatarColor": "gray"});- let speaker = if group {- if start {- list.append(&author_label(st, author_id));- }- author_id.and_then(|a| st.bots.get(a)).unwrap_or(&deleted)- } else {- chat- };- list.append(&reply(agent_bubble(e, speaker, start), false));- }- "permission" => {- if group {- list.append(&author_label(st, author_id));- }- list.append(&permission_card(ui, st, e));- }+ "user" => list.append(&user_bubble(&r, e, working(chat), start)),+ "agent" => list.append(&agent_bubble(&r, st, e, group, start)),+ "permission" => list.append(&permission_card(ui, st, e, group)),_ => list.append(¬ice(e)),}- if main && let Some(chip) = thread_chip(ui, st, e, kind == "user") {+ let indent = if group && kind == "agent" { 34 } else { 0 };+ if main && let Some(chip) = thread_chip(ui, st, e, kind == "user", indent) {list.append(&chip);}}}-fn working_row(st: &State, bot: &Value) -> gtk::Box {- let row = gtk::Box::builder().spacing(8).margin_top(10).build();- row.append(&avatar::of(&st.bots, bot, 28, true, ""));- let col = gtk::Box::new(gtk::Orientation::Vertical, 2);- col.append(- >k::Label::builder()- .label("•••")- .css_classes(["bubble", "bubble-agent", "muted"])- .halign(gtk::Align::Start)- .build(),- );- let act = bot["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Working…");- col.append(- >k::Label::builder()- .label(act)- .xalign(0.0)- .css_classes([- "small",- if bot["status"] == "needsInput" {- "needs-text"- } else {- "dim-label"- },- ])- .build(),- );- row.append(&col);- row-}-/// Starts (or opens) the thread on a main-chat message and pages in its replies.pub fn open_thread(ui: &App, root: &str) {let Some(bot) = ui.state.borrow().current.clone() else {@@ -1128,6 +1547,7 @@ pub fn open_thread(ui: &App, root: &str) {};ui.state.borrow_mut().open_thread = Some(root.to_owned());schedule(ui);+ mark_read(ui);let ui2 = ui.clone();client::call("thread",@@ -1166,8 +1586,19 @@ fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {None};let busy = working_in(chat, chat["id"].as_str().unwrap_or_default(), lane);- c.stop_btn.set_visible(busy && !has_text);- c.send_btn.set_visible(!busy || has_text);+ let name = chat["name"].as_str().unwrap_or("");+ c.placeholder.set_label(&if in_thread {+ "Reply…".to_owned()+ } else if is_group(chat) {+ format!("Message {name} · @ to ask one bot")+ } else if busy {+ format!("Queue a message for {name}")+ } else {+ format!("Message {name}")+ });+ c.placeholder.set_visible(text.is_empty());+ c.stop_btn.set_visible(busy && text.is_empty());+ c.send_btn.set_visible(!(busy && text.is_empty()));c.send_btn.set_sensitive(has_text);// `@` suggests the group's bots.@@ -1183,12 +1614,12 @@ fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {continue;}let inner = gtk::Box::builder().spacing(6).build();- inner.append(&avatar::of(&st.bots, m, 18, false, ""));- inner.append(>k::Label::new(Some(&name)));+ inner.append(&avatar::of(&st.bots, m, 18, false));+ inner.append(&label(&name, &["small"]));let chip = gtk::Button::builder().child(&inner).tooltip_text(format!("Ask {name}"))- .css_classes(["flat", "thread-chip"])+ .css_classes(["mention-chip"]).build();let (buf2, view, text2) = (buf.clone(), c.view.clone(), text.clone());chip.connect_clicked(move |_| {@@ -1227,6 +1658,11 @@ fn send(ui: &App, in_thread: bool) {return;}buf.set_text("");+ send_text(ui, &bot, &text, thread);+}++/// Sends a message with a local echo that the host's copy replaces.+pub fn send_text(ui: &App, bot: &str, text: &str, thread: Option<String>) {let nonce = uuid::Uuid::new_v4().to_string();upsert(&mut ui.state.borrow_mut(),@@ -1238,7 +1674,7 @@ fn send(ui: &App, in_thread: bool) {if let Some(t) = thread {body["threadId"] = t.into();}- let ui2 = ui.clone();+ let (ui2, bot) = (ui.clone(), bot.to_owned());client::call("send", body, move |r| {let mut st = ui2.state.borrow_mut();match r {@@ -1258,11 +1694,10 @@ fn send(ui: &App, in_thread: bool) {});}-fn now_ms() -> i64 {+pub fn now_ms() -> i64 {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_millis() as i64+ .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))}pub fn mark_read(ui: &App) {@@ -1278,6 +1713,111 @@ pub fn toast(ui: &App, text: &str) {ui.toasts.add_toast(adw::Toast::new(text));}+// MARK: menus++/// One row of a floating menu panel.+pub struct MenuItem {+ icon: &'static str,+ title: String,+ detail: Option<String>,+ chevron: bool,+ destructive: bool,+ divider: bool,+ action: Box<dyn Fn()>,+}++impl MenuItem {+ pub fn new(icon: &'static str, title: &str, action: Box<dyn Fn()>) -> Self {+ Self {+ icon,+ title: title.to_owned(),+ detail: None,+ chevron: false,+ destructive: false,+ divider: false,+ action,+ }+ }+ pub fn detail(mut self, d: Option<String>) -> Self {+ self.detail = d;+ self+ }+ pub fn chevron(mut self) -> Self {+ self.chevron = true;+ self+ }+ pub fn destructive(mut self) -> Self {+ self.destructive = true;+ self+ }+ /// A line above this row.+ pub fn divider(mut self) -> Self {+ self.divider = true;+ self+ }+}++/// A floating panel of rows (DesktopActionMenu): at `point` inside `parent`, or under it.+pub fn popup_menu(parent: &impl IsA<gtk::Widget>, point: Option<(f64, f64)>, items: Vec<MenuItem>) {+ let pop = gtk::Popover::builder()+ .has_arrow(false)+ .css_classes(["panel"])+ .build();+ if let Some((x, y)) = point {+ pop.set_pointing_to(Some(>k::gdk::Rectangle::new(x as i32, y as i32, 1, 1)));+ pop.set_position(gtk::PositionType::Bottom);+ }+ let col = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(2)+ .width_request(246)+ .build();+ for item in items {+ if item.divider {+ col.append(>k::Box::builder().css_classes(["menu-divider"]).build());+ }+ let row = gtk::Box::builder().spacing(8).build();+ let icon = gtk::Image::from_icon_name(item.icon);+ icon.set_pixel_size(14);+ icon.set_width_request(20);+ row.append(&icon);+ let t = label(&item.title, &[]);+ t.set_hexpand(true);+ row.append(&t);+ if let Some(d) = &item.detail {+ row.append(&label(d, &["body13", "secondary"]));+ }+ if item.chevron {+ let c = gtk::Image::from_icon_name("go-next-symbolic");+ c.set_pixel_size(11);+ c.add_css_class("secondary");+ row.append(&c);+ }+ let btn = gtk::Button::builder()+ .child(&row)+ .css_classes(["menu-row"])+ .build();+ if item.destructive {+ btn.add_css_class("danger-text");+ }+ let pop2 = pop.clone();+ let action = item.action;+ btn.connect_clicked(move |_| {+ pop2.popdown();+ action();+ });+ col.append(&btn);+ }+ pop.set_child(Some(&col));+ // Rows re-render often; the popover lives only while shown.+ pop.connect_closed(|p| {+ let p = p.clone();+ gtk::glib::idle_add_local_once(move || p.unparent());+ });+ pop.set_parent(parent);+ pop.popup();+}+#[cfg(test)]mod tests {use super::mention_query;