diff --git a/Cargo.lock b/Cargo.lock index a4d75c1..783775f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,6 +182,12 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + [[package]] name = "arbitrary" version = "1.5.0" @@ -757,7 +763,7 @@ checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" dependencies = [ "borsh-derive", "bytes", - "cfg_aliases", + "cfg_aliases 0.2.2", ] [[package]] @@ -877,6 +883,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "cfg_aliases" version = "0.2.2" @@ -934,7 +946,7 @@ checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] name = "coderune-agents" -version = "0.3.2" +version = "0.3.4" dependencies = [ "coderune-domain", "serde", @@ -943,7 +955,7 @@ dependencies = [ [[package]] name = "coderune-app" -version = "0.3.2" +version = "0.3.4" dependencies = [ "coderune-agents", "coderune-collectors", @@ -955,14 +967,14 @@ dependencies = [ [[package]] name = "coderune-avatars" -version = "0.3.2" +version = "0.3.4" dependencies = [ "rune", ] [[package]] name = "coderune-collectors" -version = "0.3.2" +version = "0.3.4" dependencies = [ "coderune-domain", "globset", @@ -978,7 +990,7 @@ dependencies = [ [[package]] name = "coderune-desktop" -version = "0.3.2" +version = "0.3.4" dependencies = [ "coderune-agents", "coderune-app", @@ -986,8 +998,10 @@ dependencies = [ "coderune-domain", "coderune-ui", "directories", + "fontdb", "hex", "libc", + "portable-pty", "rune", "rune-kit", "semver", @@ -996,11 +1010,12 @@ dependencies = [ "sha2 0.10.9", "tempfile", "ureq", + "vt100", ] [[package]] name = "coderune-domain" -version = "0.3.2" +version = "0.3.4" dependencies = [ "chrono", "serde", @@ -1011,7 +1026,7 @@ dependencies = [ [[package]] name = "coderune-storage" -version = "0.3.2" +version = "0.3.4" dependencies = [ "async-trait", "coderune-domain", @@ -1026,7 +1041,7 @@ dependencies = [ [[package]] name = "coderune-ui" -version = "0.3.2" +version = "0.3.4" dependencies = [ "rune", "rune-kit", @@ -1685,6 +1700,17 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -1752,6 +1778,28 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree 0.20.0", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", +] + [[package]] name = "fontique" version = "0.12.0" @@ -2026,7 +2074,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" dependencies = [ "bitflags 2.13.2", - "cfg_aliases", + "cfg_aliases 0.2.2", "cgl", "dispatch2", "glutin_egl_sys", @@ -2049,7 +2097,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" dependencies = [ - "cfg_aliases", + "cfg_aliases 0.2.2", "glutin", "raw-window-handle 0.6.2", "winit", @@ -2763,7 +2811,7 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381" dependencies = [ - "nix", + "nix 0.31.3", "serde", "windows-sys 0.61.2", ] @@ -2899,7 +2947,7 @@ dependencies = [ "bit-set", "bitflags 2.13.2", "cfg-if", - "cfg_aliases", + "cfg_aliases 0.2.2", "codespan-reporting", "half", "hashbrown 0.17.1", @@ -2959,6 +3007,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases 0.1.1", + "libc", +] + [[package]] name = "nix" version = "0.31.3" @@ -2967,7 +3027,7 @@ checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ "bitflags 2.13.2", "cfg-if", - "cfg_aliases", + "cfg_aliases 0.2.2", "libc", "memoffset", ] @@ -3849,6 +3909,27 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix 0.28.0", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg", +] + [[package]] name = "postscript" version = "0.14.1" @@ -4743,6 +4824,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serial2" +version = "0.2.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c924c7ef58d1fb741cfecb65b9b38a9e049841edd1e419544089f0cbb5a127e7" +dependencies = [ + "cfg-if", + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "sha1" version = "0.11.0" @@ -4785,6 +4877,22 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "2.0.1" @@ -5897,6 +6005,27 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vt100" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +dependencies = [ + "itoa", + "unicode-width", + "vte", +] + +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "walkdir" version = "2.5.0" @@ -6142,7 +6271,7 @@ dependencies = [ "bitflags 2.13.2", "bytemuck", "cfg-if", - "cfg_aliases", + "cfg_aliases 0.2.2", "document-features", "hashbrown 0.17.1", "js-sys", @@ -6173,7 +6302,7 @@ dependencies = [ "bit-vec", "bitflags 2.13.2", "bytemuck", - "cfg_aliases", + "cfg_aliases 0.2.2", "document-features", "hashbrown 0.17.1", "indexmap", @@ -6225,7 +6354,7 @@ dependencies = [ "block2 0.6.2", "bytemuck", "cfg-if", - "cfg_aliases", + "cfg_aliases 0.2.2", "drm", "env_logger", "glam", @@ -6306,6 +6435,22 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -6315,6 +6460,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" @@ -6527,7 +6678,7 @@ dependencies = [ "block2 0.5.1", "bytemuck", "calloop", - "cfg_aliases", + "cfg_aliases 0.2.2", "concurrent-queue", "console_error_panic_hook", "core-foundation", @@ -6583,6 +6734,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 85231c1..a777325 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ default-members = [ name = "coderune" [workspace.package] -version = "0.3.2" +version = "0.3.4" edition = "2021" license = "AGPL-3.0" publish = false diff --git a/GLOSSARY.md b/GLOSSARY.md index 7e1884b..53b0f99 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -14,6 +14,10 @@ Shared vocabulary for Coderune's developer and project context, agent skills, ve **Agent connection**: A developer-configured connection to a coding agent and the models available through it. _Avoid_: Subscription, model provider +**Project chat** is a local conversation associated with one project. It opens in a workspace tab and can run a selected coding agent in the project folder. + +**Context readiness** is the completion of a project's folder, goals, collection scope, and first capture. + **Bot avatar**: The animated character that represents a subagent in the desktop app, showing whether it is idle, working, or asleep. _Avoid_: Coding agent logo, profile picture **Subagent** (defined subagent): A reusable Coderune specialist with a defined purpose and a configured default model assignment. The workspace destination for these specialists is labeled Subagents. _Avoid_: Coding agent, individual task, agent skill diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 9d11d2f..3892f3f 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -16,7 +16,9 @@ coderune-avatars.workspace = true coderune-domain.workspace = true coderune-ui.workspace = true directories.workspace = true +fontdb = "0.24.0" hex = "0.4" +portable-pty = "0.9" rune.workspace = true rune-kit.workspace = true semver = "1" @@ -25,6 +27,7 @@ serde_json.workspace = true sha2.workspace = true tempfile = "3" ureq = { version = "3.5", default-features = false, features = ["rustls"] } +vt100 = "0.16" [target.'cfg(target_os = "macos")'.dependencies] libc = "0.2" diff --git a/apps/desktop/src/agent_detection.rs b/apps/desktop/src/agent_detection.rs index acb007f..35a95f1 100644 --- a/apps/desktop/src/agent_detection.rs +++ b/apps/desktop/src/agent_detection.rs @@ -1,14 +1,16 @@ //! Background discovery for the coding agents shown in Settings. +use std::ffi::OsString; use std::sync::mpsc::{self, Receiver, TryRecvError}; use std::time::Duration; -use coderune_agents::{detect_cli_agents, CliAgentStatus}; +use coderune_agents::{detect_cli_agents_with_path, CliAgentStatus}; use rune::Tx; #[derive(Default)] pub(crate) struct AgentDetection { pub(crate) results: Vec, + pub(crate) path: Option, pub(crate) check: Check, } @@ -16,7 +18,7 @@ pub(crate) struct AgentDetection { pub(crate) enum Check { #[default] NotChecked, - Checking(Receiver>), + Checking(Receiver<(Vec, Option)>), Finished, Failed, } @@ -30,7 +32,7 @@ impl AgentDetection { let worker = std::thread::Builder::new() .name("coderune-agent-detection".into()) .spawn(move || { - let _ = sender.send(detect_cli_agents()); + let _ = sender.send(detect_cli_agents_with_path()); }); self.check = match worker { Ok(_) => Check::Checking(receiver), @@ -43,8 +45,9 @@ impl AgentDetection { return false; }; match receiver.try_recv() { - Ok(results) => { + Ok((results, path)) => { self.results = results; + self.path = path; self.check = Check::Finished; true } diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index b9b8ebd..fc2de2c 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -1,6 +1,6 @@ //! Coderune's native desktop application. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::path::PathBuf; use coderune_agents::CliAgentId; @@ -18,7 +18,9 @@ use coderune_ui::icons; use coderune_ui::theme::{self, BODY, HEADING}; use crate::agent_detection::{AgentDetection, Check}; -use crate::preferences::Preferences; +use crate::chat_terminal::Terminal; +use crate::chats::{Author, Chat, Chats}; +use crate::preferences::{AgentDock, Preferences}; use crate::screens; use crate::shell::{self, SidebarPane}; use crate::updates::Updates; @@ -83,14 +85,6 @@ impl View { Self::Avatars => "nav-avatars", } } - - pub const NAV: [Self; 5] = [ - Self::Home, - Self::Projects, - Self::Documents, - Self::Subagents, - Self::Capture, - ]; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -466,6 +460,11 @@ impl DocumentForm { } } +pub(crate) struct ContextItem { + pub label: &'static str, + pub done: bool, +} + pub struct CaptureDetail { pub capture: ContextCapture, pub contents: BTreeMap, @@ -482,20 +481,31 @@ pub struct CoderuneApp { pub profile_section: Option, pub(crate) profile_form: ProfileForm, pub(crate) project_form: ProjectForm, + pub(crate) project_scope_expanded: bool, pub(crate) document_form: DocumentForm, pub(crate) capture_session: Option, pub(crate) capture_reviewed: bool, pub(crate) captures: Vec, + projects_with_captures: BTreeSet, pub(crate) capture_detail: Option, pub(crate) confirm_delete_project: Option, pub(crate) confirm_delete_capture: Option, pub(crate) confirm_delete_all: bool, pub(crate) export_path: TextEdit, pub(crate) settings: Option, + /// The font list open in Settings, by row. + pub(crate) font_menu: Option<&'static str>, pub(crate) settings_feedback: Option>, preferences: Preferences, pub(crate) agent_detection: AgentDetection, pub(crate) updates: Updates, + /// Chats on disk and the tabs open in this window. + pub(crate) chats: Chats, + pub(crate) chat_draft: TextEdit, + chat_drafts: HashMap, + pub(crate) chat_terminals: HashMap, + /// The family lists last handed to the text system. + applied_fonts: Option<(String, String)>, pub error: Option, pub notice: Option, /// The animated avatars on screen, keyed by subagent or gallery id. @@ -558,6 +568,17 @@ impl CoderuneApp { None }) .unwrap_or_default(); + let mut chat_error = None; + let chats = workspace.as_ref().map_or_else(Chats::default, |workspace| { + let path = Chats::path(&workspace.data_path()); + Chats::load(&path).unwrap_or_else(|error| { + chat_error = Some(AppError::new( + coderune_domain::ErrorCode::UnreadablePath, + format!("Could not load saved chats: {error}"), + )); + Chats::unreadable(path) + }) + }); let mut app = Self { workspace, fatal, @@ -568,25 +589,42 @@ impl CoderuneApp { profile_section: None, profile_form, project_form, + project_scope_expanded: false, document_form: DocumentForm::empty(), capture_session: None, capture_reviewed: false, captures: Vec::new(), + projects_with_captures: BTreeSet::new(), capture_detail: None, confirm_delete_project: None, confirm_delete_capture: None, confirm_delete_all: false, export_path, settings: None, + font_menu: None, settings_feedback: None, preferences, agent_detection: AgentDetection::default(), updates: Updates::new(), - error: None, + chats, + chat_draft: TextEdit::default(), + chat_drafts: HashMap::new(), + chat_terminals: HashMap::new(), + applied_fonts: None, + error: chat_error, notice: None, avatars: BotAvatarStage::new(), }; + if let Some(workspace) = &app.workspace { + match workspace.projects_with_captures() { + Ok(projects) => app.projects_with_captures = projects, + Err(error) => app.error = Some(error), + } + } app.refresh_captures(); + if app.active_chat().is_some() { + app.refresh_chat_agents(); + } app.onboarding_step = app.initial_onboarding_step(); app } @@ -643,22 +681,21 @@ impl CoderuneApp { } fn refresh_captures(&mut self) { - let project_id = self - .workspace - .as_ref() - .and_then(|workspace| workspace.selected_project_id.clone()); - let result = project_id.as_deref().and_then(|id| { - self.workspace - .as_ref() - .map(|workspace| workspace.list_captures(id)) - }); - match result { - Some(Ok(captures)) => self.captures = captures, - Some(Err(error)) => { - self.captures.clear(); - self.error = Some(error); + self.captures.clear(); + if let Some(workspace) = &self.workspace { + if let Some(id) = &workspace.selected_project_id { + match workspace.list_captures(id) { + Ok(captures) => { + if captures.is_empty() { + self.projects_with_captures.remove(id); + } else { + self.projects_with_captures.insert(id.clone()); + } + self.captures = captures; + } + Err(error) => self.error = Some(error), + } } - None => self.captures.clear(), } } @@ -677,11 +714,13 @@ impl CoderuneApp { self.notice = None; self.confirm_delete_project = None; self.confirm_delete_capture = None; + self.show_workspace(); } pub(crate) fn select_settings(&mut self, section: SettingsSection) { self.settings = Some(section); self.settings_feedback = None; + self.font_menu = None; self.confirm_delete_all = false; if section == SettingsSection::Agents && matches!(self.agent_detection.check, Check::NotChecked) @@ -693,6 +732,7 @@ impl CoderuneApp { pub(crate) fn close_settings(&mut self) { self.settings = None; self.settings_feedback = None; + self.font_menu = None; self.confirm_delete_all = false; } @@ -705,12 +745,324 @@ impl CoderuneApp { self.update_preferences(|preferences| preferences.dark_mode = dark_mode); } + /// What a project still needs before a chat has full context. + pub(crate) fn context_items(&self, project_id: &str) -> Vec { + let Some(project) = self + .workspace + .as_ref() + .and_then(|workspace| workspace.projects.iter().find(|p| p.id == project_id)) + else { + return Vec::new(); + }; + vec![ + ContextItem { + label: "Project folder", + done: std::path::Path::new(&project.root_path).is_dir(), + }, + ContextItem { + label: "Goals", + done: !project.goals.is_empty(), + }, + ContextItem { + label: "Capture scope", + done: !project.scope.include_paths.is_empty() + || !project.scope.exclude_paths.is_empty(), + }, + ContextItem { + label: "First capture", + done: self.projects_with_captures.contains(project_id), + }, + ] + } + + pub(crate) fn context_done(&self, project_id: &str) -> (u8, u8) { + let items = self.context_items(project_id); + let done = items.iter().filter(|item| item.done).count() as u8; + (done, items.len() as u8) + } + + pub(crate) fn active_chat(&self) -> Option<&Chat> { + self.chats.active_chat() + } + + pub(crate) fn show_chat_project(&mut self) { + if let Some(project_id) = self.active_chat().map(|chat| chat.project_id.clone()) { + self.load_project_form(&project_id); + self.navigate(View::Projects); + } + } + + /// Creates a chat in the selected project and opens its tab. + pub(crate) fn new_chat(&mut self, project_id: &str) { + self.error = None; + self.notice = None; + if !self.has_project(project_id) { + return; + } + self.stash_chat_draft(); + self.chats.new_chat(project_id); + self.update_preferences(|preferences| preferences.set_project_expanded(project_id, true)); + self.save_chats(); + self.refresh_chat_agents(); + } + + pub(crate) fn open_chat(&mut self, id: &str) { + let project_id = self.chats.chat(id).map(|chat| chat.project_id.clone()); + if self.chats.active.as_deref() == Some(id) { + return; + } + let Some(project_id) = project_id else { return }; + self.error = None; + self.notice = None; + if !self.has_project(&project_id) { + return; + } + self.stash_chat_draft(); + self.chats.open_chat(id); + self.restore_chat_draft(); + self.save_chats(); + self.refresh_chat_agents(); + } + + pub(crate) fn show_workspace(&mut self) { + if self.chats.active.is_some() { + self.stash_chat_draft(); + self.chats.active = None; + self.save_chats(); + } + } + + pub(crate) fn close_chat(&mut self, id: &str) { + let active = self.chats.active.as_deref() == Some(id); + if active { + self.stash_chat_draft(); + } + self.chats.close_chat(id); + self.chat_terminals.remove(id); + if active { + self.restore_chat_draft(); + } + self.save_chats(); + } + + fn has_project(&self, project_id: &str) -> bool { + self.workspace.as_ref().is_some_and(|workspace| { + workspace + .projects + .iter() + .any(|project| project.id == project_id) + }) + } + + fn refresh_chat_agents(&mut self) { + if matches!(self.agent_detection.check, Check::NotChecked) { + self.agent_detection.refresh(); + } + } + + fn stash_chat_draft(&mut self) { + if let Some(id) = &self.chats.active { + self.chat_drafts + .insert(id.clone(), std::mem::take(&mut self.chat_draft)); + } + } + + fn restore_chat_draft(&mut self) { + self.chat_draft = self + .chats + .active + .as_ref() + .and_then(|id| self.chat_drafts.remove(id)) + .unwrap_or_default(); + } + + /// Sends the message to the running agent in the active tab. + pub(crate) fn send_chat_message(&mut self) { + let text = self.chat_draft.text.trim(); + let Some(id) = self.chats.active.clone() else { + return; + }; + if text.is_empty() { + return; + } + let Some(terminal) = self + .chat_terminals + .get_mut(&id) + .filter(|term| term.is_running()) + else { + return; + }; + if let Err(error) = terminal.send_line(text) { + self.chat_agent_error("Could not send message", error); + return; + } + self.error = None; + self.chats.add_message(&id, Author::Developer, text); + self.chat_draft = TextEdit::default(); + self.save_chats(); + } + + pub(crate) fn set_chat_agent(&mut self, agent: Option) { + let Some(id) = self.chats.active.clone() else { + return; + }; + if self.active_chat().is_some_and(|chat| chat.agent == agent) { + return; + } + self.chat_terminals.remove(&id); + self.chats.set_agent(&id, agent); + self.error = None; + self.save_chats(); + } + + pub(crate) fn start_chat_agent(&mut self) { + let Some(chat) = self.active_chat() else { + return; + }; + let Some(agent) = chat.agent.filter(|agent| self.agent_enabled(*agent)) else { + return; + }; + let Some(executable) = self + .agent_detection + .results + .iter() + .find(|status| status.id == agent) + .and_then(|status| status.executable.as_deref()) + else { + return; + }; + let Some(project) = self.workspace.as_ref().and_then(|workspace| { + workspace + .projects + .iter() + .find(|project| project.id == chat.project_id) + }) else { + return; + }; + if self + .chat_terminals + .get(&chat.id) + .is_some_and(Terminal::is_running) + { + return; + } + match Terminal::launch( + executable, + std::path::Path::new(&project.root_path), + self.agent_detection.path.as_deref(), + ) { + Ok(terminal) => { + self.chat_terminals.insert(chat.id.clone(), terminal); + self.error = None; + } + Err(error) => self.chat_agent_error("Could not start agent", error), + } + } + + pub(crate) fn active_terminal_mut(&mut self) -> Option<&mut Terminal> { + self.chat_terminals.get_mut(self.chats.active.as_deref()?) + } + + pub(crate) fn stop_chat_agent(&mut self) { + if let Some(Err(error)) = self.active_terminal_mut().map(Terminal::stop) { + self.chat_agent_error("Could not stop agent", error); + } + } + + pub(crate) fn clear_chat_terminal(&mut self) { + if let Some(id) = &self.chats.active { + self.chat_terminals.remove(id); + } + } + + fn chat_agent_error(&mut self, message: &str, error: std::io::Error) { + self.error = Some(AppError::new( + coderune_domain::ErrorCode::AgentFailed, + format!("{message}: {error}"), + )); + } + + pub(crate) fn agent_dock(&self) -> AgentDock { + self.preferences.agent_dock + } + + pub(crate) fn set_agent_dock(&mut self, dock: AgentDock) { + self.update_preferences(|preferences| preferences.agent_dock = dock); + } + + pub(crate) fn projects_collapsed(&self) -> bool { + self.preferences.projects_collapsed + } + + pub(crate) fn toggle_projects_section(&mut self) { + self.update_preferences(|preferences| { + preferences.projects_collapsed = !preferences.projects_collapsed; + }); + } + + pub(crate) fn project_expanded(&self, id: &str) -> bool { + self.preferences.project_expanded(id) + } + + pub(crate) fn toggle_project_chats(&mut self, id: &str) { + let expanded = !self.project_expanded(id); + let id = id.to_string(); + self.update_preferences(move |preferences| preferences.set_project_expanded(&id, expanded)); + } + + fn save_chats(&mut self) { + if let Err(error) = self.chats.save() { + self.error = Some(AppError::new( + coderune_domain::ErrorCode::UnreadablePath, + format!("Could not save chats: {error}"), + )); + } + } + + pub(crate) fn ui_font(&self) -> &str { + self.preferences + .ui_font + .as_deref() + .unwrap_or(crate::DEFAULT_UI_FONT) + } + + pub(crate) fn mono_font(&self) -> &str { + self.preferences + .mono_font + .as_deref() + .unwrap_or(crate::DEFAULT_MONO_FONT) + } + + pub(crate) fn set_ui_font(&mut self, family: String) { + self.update_preferences(|preferences| preferences.ui_font = Some(family)); + } + + pub(crate) fn set_mono_font(&mut self, family: String) { + self.update_preferences(|preferences| preferences.mono_font = Some(family)); + } + + /// The CSS family lists the text system should use: the chosen family + /// first, then the shipped one so missing glyphs still resolve. + fn font_families(&self) -> (String, String) { + ( + format!("{}, {}", self.ui_font(), crate::DEFAULT_UI_FONT), + format!("{}, {}", self.mono_font(), crate::DEFAULT_MONO_FONT), + ) + } + pub(crate) fn agent_enabled(&self, agent: CliAgentId) -> bool { self.preferences.agent_enabled(agent) } pub(crate) fn set_agent_enabled(&mut self, agent: CliAgentId, enabled: bool) { self.update_preferences(|preferences| preferences.set_agent_enabled(agent, enabled)); + if !enabled { + self.chat_terminals.retain(|id, _| { + self.chats + .chat(id) + .is_some_and(|chat| chat.agent != Some(agent)) + }); + } if self .document_form .agent @@ -881,6 +1233,7 @@ impl CoderuneApp { return; }; self.project_form = ProjectForm::from_project(&project); + self.project_scope_expanded = false; self.confirm_delete_project = None; self.error = None; self.reset_capture_state(); @@ -896,6 +1249,7 @@ impl CoderuneApp { .as_ref() .and_then(|workspace| workspace.launch_directory.clone()); self.project_form = ProjectForm::empty(initial_root); + self.project_scope_expanded = false; self.confirm_delete_project = None; self.error = None; self.reset_capture_state(); @@ -951,9 +1305,15 @@ impl CoderuneApp { }; match workspace.delete_project(&id) { Ok(()) => { - self.notice = Some("Project and its captures deleted.".to_string()); - self.error = None; + for chat in self.chats.chats_for(&id) { + self.chat_terminals.remove(&chat.id); + self.chat_drafts.remove(&chat.id); + } + self.chats.delete_for_project(&id); + self.projects_with_captures.remove(&id); self.new_project_form(); + self.save_chats(); + self.notice = Some("Project, captures, and chats deleted.".to_string()); } Err(error) => self.error = Some(error), } @@ -1222,8 +1582,14 @@ impl CoderuneApp { }; match workspace.delete_all_data() { Ok(()) => { - self.notice = - Some("All workspace data deleted. Onboarding is required again.".to_string()); + self.chat_terminals.clear(); + self.chat_drafts.clear(); + self.chat_draft = TextEdit::default(); + let clear_chats = self.chats.clear(); + self.projects_with_captures.clear(); + self.notice = clear_chats.is_ok().then(|| { + "All workspace data deleted. Onboarding is required again.".to_string() + }); self.error = None; self.close_settings(); self.view = View::Home; @@ -1234,6 +1600,9 @@ impl CoderuneApp { self.document_form = DocumentForm::empty(); self.refresh_profile_form(); self.refresh_captures(); + if let Err(error) = clear_chats { + self.chat_agent_error("Could not remove saved chats", error); + } } Err(error) => self.settings_feedback = Some(Err(error)), } @@ -1335,6 +1704,35 @@ pub fn scene_settings_agents(s: &mut CoderuneApp) { s.select_settings(SettingsSection::Agents); } +pub fn scene_chat(s: &mut CoderuneApp) { + seed_demo(s); + let project = s + .workspace + .as_ref() + .and_then(|workspace| workspace.selected_project_id.clone()); + if let Some(project) = project { + s.chats = Chats::default(); + let chat = s.chats.new_chat(&project); + s.agent_detection.results = coderune_agents::detect_cli_agents(); + s.agent_detection.check = Check::Finished; + s.chats.add_message( + &chat, + Author::Developer, + "Which parts of this project should the agent read first?", + ); + } +} + +pub fn scene_chat_floating(s: &mut CoderuneApp) { + scene_chat(s); + s.preferences.agent_dock = AgentDock::Floating; +} + +pub fn scene_settings_fonts(s: &mut CoderuneApp) { + scene_settings(s); + s.font_menu = Some("ui-font"); +} + pub fn scene_home_dark(s: &mut CoderuneApp) { scene_home(s); s.preferences.dark_mode = true; @@ -1358,8 +1756,17 @@ pub fn scene_avatars(s: &mut CoderuneApp) { /// Advances visible animations and applies completed background updates. pub fn poll(s: &mut CoderuneApp, t: f64, tx: &mut Tx) -> bool { + let families = s.font_families(); + if s.applied_fonts.as_ref() != Some(&families) { + tx.set_font_families(&families.0, &families.1); + s.applied_fonts = Some(families); + } let update_changed = s.updates.poll(tx); let detection_changed = s.agent_detection.poll(tx); + let mut chat_changed = false; + for terminal in s.chat_terminals.values_mut() { + chat_changed |= terminal.poll(tx); + } if detection_changed && matches!(s.agent_detection.check, Check::Finished) { if let Some(workspace) = s.workspace.as_mut() { workspace.agents = coderune_agents::draft_statuses(&s.agent_detection.results); @@ -1377,7 +1784,7 @@ pub fn poll(s: &mut CoderuneApp, t: f64, tx: &mut Tx) -> bool { false } }; - update_changed || detection_changed || avatar_changed + update_changed || detection_changed || avatar_changed || chat_changed } /// Onboarding's second step, with the first step's answers filled in. @@ -1660,7 +2067,10 @@ fn fatal(message: &str, inset: f32) -> El { pub fn on_key(s: &mut CoderuneApp, event: &KeyEvent, tx: &mut rune::Tx) -> bool { match event.key { - Key::Command('q') => std::process::exit(0), + Key::Command('q') => { + s.chat_terminals.clear(); + std::process::exit(0); + } Key::Command(',' | '7') if s.workspace.is_some() => { if s.settings.is_none() { s.select_settings(SettingsSection::General); @@ -1852,7 +2262,18 @@ mod tests { assert!(workspace.find("nav-capture").is_some()); assert!(workspace.find("sidebar-toggle").is_none()); - let [x, y, w, h] = workspace.presented("nav-projects").unwrap().0; + let project_id = workspace + .state + .workspace + .as_ref() + .unwrap() + .selected_project_id + .as_ref() + .unwrap(); + let [x, y, w, h] = workspace + .presented(&format!("project-{project_id}")) + .unwrap() + .0; workspace.pointer_down(x + w / 2.0, y + h / 2.0); workspace.pointer_up(x + w / 2.0, y + h / 2.0); workspace.frame(0.0); @@ -1917,6 +2338,67 @@ mod tests { assert_eq!(position(&workspace, "workspace-sidebar")[2], wide_sidebar); } + #[test] + fn chats_preserve_workspace_selection_and_the_floating_panel_leaves_send_visible() { + let _guard = ENV_LOCK.lock().unwrap(); + let dir = tempfile::tempdir().unwrap(); + std::env::set_var("CODERUNE_DATA_DIR", dir.path()); + let mut state = CoderuneApp::init(); + seed_demo(&mut state); + let first = state.project_form.editing.clone().unwrap(); + let other_folder = tempfile::tempdir().unwrap(); + state.project_form = ProjectForm::empty(Some(other_folder.path().to_path_buf())); + state.project_form.name = edit("Second project"); + state.project_form.goals = edit("Keep its chat separate"); + state.save_project(); + let second = state.project_form.editing.clone().unwrap(); + state.load_project_form(&first); + state.view = View::Projects; + state.agent_detection.check = Check::Finished; + state.new_chat(&second); + let chat_id = state.active_chat().unwrap().id.clone(); + state.chat_draft = edit("Draft only for this chat"); + state.set_agent_dock(AgentDock::Floating); + let mut app = Runtime::new( + state, + view, + (960.0, 640.0), + Env { + system_dark: false, + scale: 1.0, + }, + ); + app.frame(0.0); + app.frame(1.0 / 60.0); + let [_, panel_y, _, panel_height] = app.presented("agent-panel").unwrap().0; + let [_, send_y, _, _] = app.presented("send-message").unwrap().0; + assert!(panel_y + panel_height < send_y); + assert!(app.find(&format!("t-{chat_id}")).is_some()); + + app.update(|state, _| state.show_workspace()); + assert_eq!( + app.state + .workspace + .as_ref() + .unwrap() + .selected_project_id + .as_deref(), + Some(first.as_str()) + ); + assert_eq!( + app.state.project_form.editing.as_deref(), + Some(first.as_str()) + ); + app.update(|state, _| state.open_chat(&chat_id)); + assert_eq!(app.state.chat_draft.text, "Draft only for this chat"); + app.update(|state, _| state.new_chat(&first)); + assert!(app.state.chat_draft.text.is_empty()); + app.update(|state, _| state.close_chat(&chat_id)); + assert!(app.state.chats.chat(&chat_id).is_some()); + assert!(!app.state.chats.open.contains(&chat_id)); + assert!(CoderuneApp::init().chats.chat(&chat_id).is_some()); + } + #[test] fn settings_opens_over_the_current_page_and_groups_storage_actions() { let _guard = ENV_LOCK.lock().unwrap(); diff --git a/apps/desktop/src/chat_terminal.rs b/apps/desktop/src/chat_terminal.rs new file mode 100644 index 0000000..a832660 --- /dev/null +++ b/apps/desktop/src/chat_terminal.rs @@ -0,0 +1,638 @@ +//! Interactive coding-agent sessions. Terminal output stays in memory. + +use std::ffi::OsStr; +use std::io::{self, Read, Write}; +use std::path::Path; +use std::rc::Rc; +use std::sync::mpsc::{self, Receiver, SyncSender, TryRecvError}; +use std::thread; +use std::time::Duration; + +use coderune_ui::theme::{self, CODE_SM}; +use portable_pty::{native_pty_system, Child, CommandBuilder, MasterPty, PtySize}; +use rune::{col, grid, text, Color, El, GridRow, Key, KeyEvent, Span, Tx}; + +const CELL_WIDTH: f32 = 6.6; +const CELL_HEIGHT: f32 = 15.0; +const INSET: f32 = 8.0; +const SCROLLBACK_ROWS: usize = 1_000; +const CHUNK: usize = 4_096; +const IO_QUEUE: usize = 32; +const MAX_LINE_BYTES: usize = 64 * 1_024; + +pub(crate) struct Terminal { + screen: vt100::Parser, + // Drop the output receiver before closing the PTY so the reader cannot + // remain blocked writing to a full queue during teardown. + output: Option>>, + process: Option, + status: Option, +} + +struct Process { + child: Box, + input: SyncSender>, + master: Box, +} + +impl Drop for Process { + fn drop(&mut self) { + if !matches!(self.child.try_wait(), Ok(Some(_))) && self.child.kill().is_ok() { + let _ = self.child.wait(); + } + } +} + +impl Terminal { + /// Starts the selected executable directly in its project directory. + pub(crate) fn launch(executable: &Path, cwd: &Path, path: Option<&OsStr>) -> io::Result { + if !executable.is_absolute() || !cwd.is_absolute() || !cwd.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Choose an installed agent and an available project folder.", + )); + } + let size = size(24, 80); + let pair = native_pty_system() + .openpty(size) + .map_err(io::Error::other)?; + let mut reader = pair.master.try_clone_reader().map_err(io::Error::other)?; + let mut writer = pair.master.take_writer().map_err(io::Error::other)?; + let mut command = agent_command(executable)?; + command.cwd(cwd); + command.env("TERM", "xterm-256color"); + command.env("COLORTERM", "truecolor"); + command.env_remove("NO_COLOR"); + if let Some(path) = path { + command.env("PATH", path); + } + let child = pair + .slave + .spawn_command(command) + .map_err(io::Error::other)?; + drop(pair.slave); + + let (input, input_rx) = mpsc::sync_channel::>(IO_QUEUE); + let process = Process { + child, + master: pair.master, + input, + }; + let (output_tx, output) = mpsc::sync_channel(IO_QUEUE); + thread::Builder::new() + .name("coderune-terminal-output".into()) + .spawn(move || loop { + let mut bytes = vec![0; CHUNK]; + match reader.read(&mut bytes) { + Ok(0) => break, + Ok(count) => { + bytes.truncate(count); + if output_tx.send(bytes).is_err() { + break; + } + } + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(_) => break, + } + })?; + thread::Builder::new() + .name("coderune-terminal-input".into()) + .spawn(move || { + while let Ok(bytes) = input_rx.recv() { + if writer.write_all(&bytes).is_err() { + break; + } + } + })?; + Ok(Self { + screen: vt100::Parser::new_with_callbacks( + size.rows, + size.cols, + SCROLLBACK_ROWS, + TerminalReplies::default(), + ), + process: Some(process), + output: Some(output), + status: None, + }) + } + + pub(crate) fn is_running(&self) -> bool { + self.process.is_some() + } + + pub(crate) fn stop(&mut self) -> io::Result<()> { + if let Some(process) = &mut self.process { + if process.child.try_wait()?.is_none() { + process.child.kill()?; + } + self.status = Some("Agent stopped".into()); + } + Ok(()) + } + + /// Sends one composer line to a running interactive agent. + pub(crate) fn send_line(&mut self, text: &str) -> io::Result<()> { + if text.len() > MAX_LINE_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "The message exceeds the terminal's 64 KiB input limit.", + )); + } + let text: String = text.chars().filter(|ch| !ch.is_control()).collect(); + if text.trim().is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "Write a message first.", + )); + } + let mut line = Vec::with_capacity(text.len() + 13); + if self.screen.screen().bracketed_paste() { + line.extend_from_slice(b"\x1b[200~"); + line.extend_from_slice(text.as_bytes()); + line.extend_from_slice(b"\x1b[201~"); + } else { + line.extend_from_slice(text.as_bytes()); + } + line.push(b'\r'); + self.send(line) + } + + pub(crate) fn poll(&mut self, tx: &mut Tx) -> bool { + let changed = self.read_output(); + if self.is_running() || self.output.is_some() { + tx.wake_after(Duration::from_millis(32)); + } + changed + } + + fn read_output(&mut self) -> bool { + let mut changed = false; + if let Some(output) = &self.output { + for _ in 0..IO_QUEUE { + match output.try_recv() { + Ok(bytes) => { + self.screen.process(&bytes); + changed = true; + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + self.output = None; + break; + } + } + } + } + if let Some(process) = &mut self.process { + let reply = std::mem::take(&mut self.screen.callbacks_mut().bytes); + if !reply.is_empty() { + if let Err(mpsc::TrySendError::Full(reply)) = process.input.try_send(reply) { + self.screen.callbacks_mut().bytes = reply; + } + } + match process.child.try_wait() { + Ok(None) => {} + Ok(Some(exit)) => { + self.status + .get_or_insert_with(|| format!("Agent exited ({exit})")); + self.finish_process(); + changed = true; + } + Err(error) => { + self.status = Some(format!("Could not check agent process: {error}")); + self.finish_process(); + changed = true; + } + } + } + changed + } + + fn finish_process(&mut self) { + let process = self.process.take(); + // Closing ConPTY may block while the reader flushes the last output. + // Keep polling its bounded queue from the UI while the handles close. + #[cfg(windows)] + let _ = thread::Builder::new() + .name("coderune-terminal-close".into()) + .spawn(move || drop(process)); + #[cfg(not(windows))] + drop(process); + } + + fn send(&mut self, bytes: Vec) -> io::Result<()> { + let process = self.process.as_ref().ok_or_else(|| { + io::Error::new( + io::ErrorKind::BrokenPipe, + "Start the coding agent before sending.", + ) + })?; + process.input.try_send(bytes).map_err(|error| match error { + mpsc::TrySendError::Full(_) => io::Error::new( + io::ErrorKind::WouldBlock, + "The terminal input queue is full.", + ), + mpsc::TrySendError::Disconnected(_) => io::Error::new( + io::ErrorKind::BrokenPipe, + "The agent stopped accepting input.", + ), + })?; + self.screen.screen_mut().set_scrollback(0); + Ok(()) + } + + fn resize(&mut self, width: f32, height: f32, cell_width: f32) { + if width < cell_width || height < CELL_HEIGHT { + return; + } + let dimension = |points: f32, cell: f32| (points / cell).floor().clamp(1.0, 240.0) as u16; + let cols = dimension(width, cell_width); + let rows = dimension(height, CELL_HEIGHT); + if self.screen.screen().size() == (rows, cols) { + return; + } + if let Some(process) = &self.process { + let mut pty_size = size(rows, cols); + pty_size.pixel_width = (f32::from(cols) * cell_width).round() as u16; + if let Err(error) = process.master.resize(pty_size) { + self.status = Some(format!("Could not resize terminal: {error}")); + return; + } + } + self.screen.screen_mut().set_size(rows, cols); + } + + fn scroll(&mut self, lines: isize) -> bool { + let screen = self.screen.screen_mut(); + let before = screen.scrollback(); + screen.set_scrollback(before.saturating_add_signed(lines)); + screen.scrollback() != before + } + + pub(crate) fn view(&self, current: fn(&mut S) -> Option<&mut Self>) -> El { + let screen = self.screen.screen(); + let (rows, cols) = screen.size(); + let cell_width = rune::text::advance("M", CODE_SM).max(1.0); + let cursor = (self.is_running() && !screen.hide_cursor() && screen.scrollback() == 0) + .then(|| screen.cursor_position()); + let lines = (0..rows) + .map(|row| Rc::new(grid_row(screen, row, cols, cursor))) + .collect(); + let mut surface = grid(cols, cell_width, CELL_HEIGHT, lines) + .key("chat-terminal") + .label("Coding agent terminal. Press F6 for panel controls.") + .w_full() + .grow(1.0) + .min_h(0.0) + .focusable(true) + .on_layout(move |state: &mut S, [_, _, width, height]| { + if let Some(terminal) = current(state) { + terminal.resize(width, height, cell_width); + } + }) + .on_wheel(move |state: &mut S, wheel, _| { + let lines = (wheel.dy / CELL_HEIGHT).round() as isize; + current(state).is_some_and(|terminal| terminal.scroll(lines)) + }) + .on_key(move |state: &mut S, key, tx| { + if key.key == Key::Function(6) { + tx.focus("dock-left", true); + return true; + } + let Some(terminal) = current(state) else { + return false; + }; + if key.mods.shift { + let page = terminal.screen.screen().size().0 as isize; + match key.key { + Key::PageUp => return terminal.scroll(page), + Key::PageDown => return terminal.scroll(-page), + _ => {} + } + } + let application_cursor = terminal.screen.screen().application_cursor(); + let Some(bytes) = terminal_input(key, tx.key_base(), application_cursor) else { + return false; + }; + if let Err(error) = terminal.send(bytes) { + if !terminal.is_running() { + return false; + } + terminal.status = Some(error.to_string()); + } + true + }); + if let Some((row, col)) = cursor { + surface = surface.grid_caret(col, row); + } + let mut pane = col() + .w_full() + .grow(1.0) + .min_h(0.0) + .padding(INSET) + .fill(theme::canvas()) + .clip_rounded(0.0) + .child(surface); + if let Some(status) = &self.status { + pane = pane.child( + text(status) + .font(theme::BODY_SM) + .color(theme::muted()) + .wrap(), + ); + } + pane + } +} + +#[derive(Default)] +struct TerminalReplies { + bytes: Vec, +} + +impl vt100::Callbacks for TerminalReplies { + fn unhandled_csi( + &mut self, + screen: &mut vt100::Screen, + first: Option, + second: Option, + params: &[&[u16]], + command: char, + ) { + // A CLI can query the terminal in the middle of a redraw and wait + // synchronously for a reply before showing its prompt. + if second.is_some() || self.bytes.len() >= CHUNK { + return; + } + let number = params + .first() + .and_then(|param| param.first()) + .copied() + .unwrap_or(0); + match (first, command, number) { + (None, 'c', 0) => self.bytes.extend_from_slice(b"\x1b[?1;2c"), + (Some(b'>'), 'c', 0) => self.bytes.extend_from_slice(b"\x1b[>0;0;0c"), + (None, 'n', 5) => self.bytes.extend_from_slice(b"\x1b[0n"), + (None, 'n', 6) | (Some(b'?'), 'n', 6) => { + let (row, col) = screen.cursor_position(); + let prefix = if first.is_some() { "?" } else { "" }; + self.bytes + .extend_from_slice(format!("\x1b[{prefix}{};{}R", row + 1, col + 1).as_bytes()); + } + _ => {} + } + } +} + +#[cfg(not(windows))] +fn agent_command(executable: &Path) -> io::Result { + Ok(CommandBuilder::new(executable)) +} + +#[cfg(windows)] +fn agent_command(executable: &Path) -> io::Result { + let batch = executable + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")); + if !batch { + return Ok(CommandBuilder::new(executable)); + } + + let root = std::env::var_os("SystemRoot").map(std::path::PathBuf::from); + let shell = root.map(|root| root.join("System32").join("cmd.exe")); + let shell = shell + .filter(|path| path.is_absolute() && path.is_file()) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "Windows Command Prompt could not be located.", + ) + })?; + let mut quoted_path = std::ffi::OsString::from("\""); + quoted_path.push(executable.as_os_str()); + quoted_path.push("\""); + // ConPTY uses CreateProcessW, which expects an executable. Pass the entire + // quoted launcher path as one environment value to a fixed cmd expression. + let mut command = CommandBuilder::new(shell); + command.args(["/d", "/v:off", "/c", "%CODERUNE_AGENT_LAUNCHER%"]); + command.env("CODERUNE_AGENT_LAUNCHER", quoted_path); + Ok(command) +} + +fn size(rows: u16, cols: u16) -> PtySize { + PtySize { + rows, + cols, + pixel_width: (f32::from(cols) * CELL_WIDTH).round() as u16, + pixel_height: (f32::from(rows) * CELL_HEIGHT).round() as u16, + } +} + +fn terminal_input(key: &KeyEvent, base: Option, application_cursor: bool) -> Option> { + if key.mods.logo || (key.mods.cmd && !key.mods.ctrl) { + return None; + } + if key.mods.ctrl && !key.mods.alt { + let control = match key.key { + Key::Command(ch) => Some(ch), + _ => base, + }; + match control?.to_ascii_uppercase() { + ch @ '@'..='_' => return Some(vec![ch as u8 & 0x1f]), + ' ' => return Some(vec![0]), + _ => return None, + } + } + + let cursor_key = |normal: &'static [u8], application: &'static [u8]| { + if application_cursor { + application + } else { + normal + } + }; + let bytes: &[u8] = match &key.key { + Key::Text(text) => text.as_bytes(), + Key::Enter => b"\r", + Key::Backspace => b"\x7f", + Key::Escape => b"\x1b", + Key::Tab if key.mods.shift => b"\x1b[Z", + Key::Tab => b"\t", + Key::Up => cursor_key(b"\x1b[A", b"\x1bOA"), + Key::Down => cursor_key(b"\x1b[B", b"\x1bOB"), + Key::Right => cursor_key(b"\x1b[C", b"\x1bOC"), + Key::Left => cursor_key(b"\x1b[D", b"\x1bOD"), + Key::Home => cursor_key(b"\x1b[H", b"\x1bOH"), + Key::End => cursor_key(b"\x1b[F", b"\x1bOF"), + Key::Insert => b"\x1b[2~", + Key::Delete => b"\x1b[3~", + Key::PageUp => b"\x1b[5~", + Key::PageDown => b"\x1b[6~", + Key::Function(1) => b"\x1bOP", + Key::Function(2) => b"\x1bOQ", + Key::Function(3) => b"\x1bOR", + Key::Function(4) => b"\x1bOS", + Key::Function(5) => b"\x1b[15~", + Key::Function(7) => b"\x1b[18~", + Key::Function(8) => b"\x1b[19~", + Key::Function(9) => b"\x1b[20~", + Key::Function(10) => b"\x1b[21~", + Key::Function(11) => b"\x1b[23~", + Key::Function(12) => b"\x1b[24~", + _ => return None, + }; + Some(bytes.to_vec()) +} + +fn grid_row(screen: &vt100::Screen, row: u16, cols: u16, cursor: Option<(u16, u16)>) -> GridRow { + let base_ink = theme::ink(); + let base_fill = theme::canvas(); + let mut line = String::with_capacity(usize::from(cols)); + let mut spans = Vec::new(); + let mut wide = Vec::new(); + let mut fills = Vec::new(); + for col in 0..cols { + let Some(cell) = screen.cell(row, col) else { + line.push(' '); + continue; + }; + let foreground = cell_color(cell.fgcolor(), base_ink); + let background = cell_color(cell.bgcolor(), base_fill); + let (foreground, background) = if cell.inverse() || cursor == Some((row, col)) { + (background, foreground) + } else { + (foreground, background) + }; + if background != base_fill { + fills.push((col, background)); + } + let contents = cell.contents(); + if cell.is_wide_continuation() || contents.is_empty() { + line.push(' '); + } else if cell.is_wide() { + line.push(' '); + wide.push((col, contents, foreground)); + } else { + let start = line.len(); + line.push_str(contents); + let mut span = Span::new(start, line.len()).color(foreground); + if cell.bold() { + span = span.bold(); + } + if cell.italic() { + span = span.italic(); + } + if cell.underline() { + span = span.underline(foreground); + } + spans.push(span); + } + } + let mut result = GridRow::new(line, spans, CODE_SM).wraps(screen.row_wrapped(row)); + for (col, contents, foreground) in wide { + result = result.cell(col, 2, contents, CODE_SM, foreground); + } + for (col, background) in fills { + result = result.fill(col, col + 1, background); + } + result +} + +fn cell_color(color: vt100::Color, default: Color) -> Color { + const ANSI: [[u8; 3]; 16] = [ + [0, 0, 0], + [205, 49, 49], + [13, 139, 60], + [171, 114, 0], + [36, 114, 200], + [160, 66, 170], + [10, 132, 147], + [229, 229, 229], + [102, 102, 102], + [241, 76, 76], + [35, 209, 139], + [244, 194, 70], + [69, 139, 219], + [214, 112, 214], + [41, 184, 219], + [255, 255, 255], + ]; + let [r, g, b] = match color { + vt100::Color::Default => return default, + vt100::Color::Rgb(r, g, b) => [r, g, b], + vt100::Color::Idx(index @ 0..=15) => ANSI[usize::from(index)], + vt100::Color::Idx(index @ 16..=231) => { + let index = index - 16; + let levels = [0, 95, 135, 175, 215, 255]; + [index / 36, index / 6 % 6, index % 6].map(|channel| levels[usize::from(channel)]) + } + vt100::Color::Idx(index) => [8 + 10 * (index - 232); 3], + }; + let decode = |value| rune::color::srgb_decode(f32::from(value) / 255.0); + Color { + r: decode(r), + g: decode(g), + b: decode(b), + a: 1.0, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Instant; + + fn wait_for(terminal: &mut Terminal, ready: impl Fn(&Terminal) -> bool) { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + terminal.read_output(); + if ready(terminal) { + break; + } + assert!(Instant::now() < deadline, "agent terminal did not respond"); + thread::sleep(Duration::from_millis(5)); + } + } + + #[test] + #[cfg(unix)] + fn coding_agent_session_accepts_input_and_keeps_output_after_stop() { + let dir = tempfile::tempdir().unwrap(); + let mut terminal = Terminal::launch(Path::new("/bin/cat"), dir.path(), None).unwrap(); + terminal.resize(340.0, 300.0, CELL_WIDTH); + terminal.send_line("Coderune PTY check\x07").unwrap(); + wait_for(&mut terminal, |terminal| { + terminal + .screen + .screen() + .contents() + .matches("Coderune PTY check") + .count() + == 2 + }); + terminal.stop().unwrap(); + wait_for(&mut terminal, |terminal| !terminal.is_running()); + assert!(terminal + .screen + .screen() + .contents() + .contains("Coderune PTY check")); + } + + #[test] + #[cfg(windows)] + fn coding_agent_session_runs_batch_launchers_with_spaces_and_ampersands() { + let dir = tempfile::tempdir().unwrap(); + let launcher = dir.path().join("agent & helper.cmd"); + std::fs::write(&launcher, "@echo off\r\necho Coderune Windows shim\r\n").unwrap(); + let mut terminal = Terminal::launch(&launcher, dir.path(), None).unwrap(); + wait_for(&mut terminal, |terminal| { + terminal + .screen + .screen() + .contents() + .contains("Coderune Windows shim") + }); + wait_for(&mut terminal, |terminal| !terminal.is_running()); + } +} diff --git a/apps/desktop/src/chats.rs b/apps/desktop/src/chats.rs new file mode 100644 index 0000000..181cfb2 --- /dev/null +++ b/apps/desktop/src/chats.rs @@ -0,0 +1,304 @@ +//! Local chats, the tabs that hold them, and the agent each chat points at. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, ErrorKind, Write}; +use std::path::{Path, PathBuf}; + +use coderune_agents::CliAgentId; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +/// Who wrote a message. Coderune writes the notes the app itself adds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) enum Author { + Developer, + Coderune, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct Message { + pub author: Author, + pub text: String, + pub at: String, +} + +/// One conversation inside a project. A chat keeps the agent chosen for it, +/// so returning to a tab returns to the same context. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct Chat { + pub id: String, + pub project_id: String, + pub title: String, + #[serde(default)] + pub agent: Option, + pub created_at: String, + pub updated_at: String, + #[serde(default)] + pub messages: Vec, +} + +impl Chat { + pub(crate) fn new(project_id: &str) -> Self { + let at = coderune_domain::now_iso(); + Self { + id: coderune_domain::new_id(), + project_id: project_id.to_string(), + title: "New chat".to_string(), + agent: None, + created_at: at.clone(), + updated_at: at, + messages: Vec::new(), + } + } + + /// The first words of a message make a better tab label than "New chat". + fn retitle(&mut self, text: &str) { + if self.title != "New chat" || self.messages.iter().any(|m| m.author == Author::Developer) { + return; + } + let mut title: String = text.split_whitespace().collect::>().join(" "); + if title.is_empty() { + return; + } + if title.chars().count() > 42 { + title = title.chars().take(42).collect::(); + title.push('…'); + } + self.title = title; + } +} + +/// The chats on disk and the tabs open in this window. +#[derive(Debug, Default, Deserialize, Serialize)] +#[serde(default)] +pub(crate) struct Chats { + pub chats: Vec, + /// Tab order. A chat can exist without being open. + pub open: Vec, + pub active: Option, + #[serde(skip)] + path: Option, + #[serde(skip)] + saved_digest: Option<[u8; 32]>, +} + +impl Chats { + pub(crate) fn path(data_path: &Path) -> PathBuf { + data_path.with_file_name("chats.json") + } + + pub(crate) fn load(path: &Path) -> io::Result { + let mut chats = match read_saved_chats(path)? { + Some(contents) => { + let mut chats: Self = + serde_json::from_slice(&contents).map_err(io::Error::other)?; + chats.saved_digest = Some(Sha256::digest(&contents).into()); + chats + } + None => Self::default(), + }; + chats.path = Some(path.to_path_buf()); + // Drop tabs whose chat vanished, then the active one if it closed elsewhere. + chats + .open + .retain(|id| chats.chats.iter().any(|chat| &chat.id == id)); + if chats + .active + .as_ref() + .is_some_and(|id| !chats.open.contains(id)) + { + chats.active = chats.open.last().cloned(); + } + Ok(chats) + } + + pub(crate) fn unreadable(path: PathBuf) -> Self { + Self { + path: Some(path), + ..Self::default() + } + } + + pub(crate) fn save(&mut self) -> io::Result<()> { + let Some(path) = &self.path else { + return Ok(()); + }; + let folder = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(folder)?; + let _lock = lock_chats(path)?; + let current_digest: Option<[u8; 32]> = + read_saved_chats(path)?.map(|bytes| Sha256::digest(bytes).into()); + if current_digest != self.saved_digest { + return Err(io::Error::other( + "Saved chats changed. Reopen Coderune before editing them.", + )); + } + let contents = serde_json::to_vec(self).map_err(io::Error::other)?; + let mut file = tempfile::NamedTempFile::new_in(folder)?; + file.write_all(&contents)?; + file.as_file().sync_all()?; + file.persist(path)?; + self.saved_digest = Some(Sha256::digest(contents).into()); + Ok(()) + } + + pub(crate) fn clear(&mut self) -> io::Result<()> { + self.chats.clear(); + self.open.clear(); + self.active = None; + if let Some(path) = &self.path { + let _lock = lock_chats(path)?; + match fs::remove_file(path) { + Err(error) if error.kind() != ErrorKind::NotFound => return Err(error), + _ => {} + } + } + self.saved_digest = None; + Ok(()) + } + + pub(crate) fn active_chat(&self) -> Option<&Chat> { + let id = self.active.as_deref()?; + self.chat(id) + } + + pub(crate) fn chat(&self, id: &str) -> Option<&Chat> { + self.chats.iter().find(|chat| chat.id == id) + } + + fn chat_mut(&mut self, id: &str) -> Option<&mut Chat> { + self.chats.iter_mut().find(|chat| chat.id == id) + } + + pub(crate) fn chats_for<'a>(&'a self, project_id: &'a str) -> impl Iterator { + self.chats + .iter() + .filter(move |chat| chat.project_id == project_id) + } + + /// Creates a chat in `project_id`, opens its tab, and makes it the active one. + pub(crate) fn new_chat(&mut self, project_id: &str) -> String { + let chat = Chat::new(project_id); + let id = chat.id.clone(); + self.chats.push(chat); + self.open.push(id.clone()); + self.active = Some(id.clone()); + id + } + + pub(crate) fn open_chat(&mut self, id: &str) { + if self.chat(id).is_none() { + return; + } + if !self.open.iter().any(|open| open == id) { + self.open.push(id.to_string()); + } + self.active = Some(id.to_string()); + } + + /// Closes a tab and activates its neighbour. The chat itself is kept. + pub(crate) fn close_chat(&mut self, id: &str) { + let Some(index) = self.open.iter().position(|open| open == id) else { + return; + }; + self.open.remove(index); + if self.active.as_deref() == Some(id) { + self.active = self + .open + .get(index.saturating_sub(1)) + .or_else(|| self.open.first()) + .cloned(); + } + } + + pub(crate) fn delete_for_project(&mut self, project_id: &str) { + let closed: Vec = self + .chats + .iter() + .filter(|chat| chat.project_id == project_id) + .map(|chat| chat.id.clone()) + .collect(); + self.chats.retain(|chat| chat.project_id != project_id); + self.open.retain(|id| !closed.contains(id)); + if self.active.as_ref().is_some_and(|id| closed.contains(id)) { + self.active = self.open.first().cloned(); + } + } + + pub(crate) fn add_message(&mut self, id: &str, author: Author, text: &str) -> bool { + let Some(chat) = self.chat_mut(id) else { + return false; + }; + chat.retitle(text); + chat.updated_at = coderune_domain::now_iso(); + chat.messages.push(Message { + author, + text: text.to_string(), + at: chat.updated_at.clone(), + }); + true + } + + pub(crate) fn set_agent(&mut self, id: &str, agent: Option) -> bool { + let Some(chat) = self.chat_mut(id) else { + return false; + }; + chat.agent = agent; + chat.updated_at = coderune_domain::now_iso(); + true + } +} + +fn read_saved_chats(path: &Path) -> io::Result>> { + match fs::read(path) { + Ok(bytes) => Ok(Some(bytes)), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +fn lock_chats(path: &Path) -> io::Result { + let lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path.with_extension("lock"))?; + lock.lock()?; + Ok(lock) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn stale_window_cannot_resurrect_deleted_chats() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("chats.json"); + let mut first = Chats::load(&path).unwrap(); + let chat = first.new_chat("project-id"); + first.save().unwrap(); + let mut other = Chats::load(&path).unwrap(); + first.clear().unwrap(); + other.add_message(&chat, Author::Developer, "A late message"); + assert!(other.save().is_err()); + assert!(!path.exists()); + } + + #[test] + fn damaged_chat_file_can_be_deleted_without_being_overwritten() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("chats.json"); + fs::write(&path, "incomplete data").unwrap(); + assert!(Chats::load(&path).is_err()); + let mut chats = Chats::unreadable(path.clone()); + assert!(chats.save().is_err()); + assert_eq!(fs::read_to_string(&path).unwrap(), "incomplete data"); + chats.clear().unwrap(); + assert!(!path.exists()); + } +} diff --git a/apps/desktop/src/fonts.rs b/apps/desktop/src/fonts.rs new file mode 100644 index 0000000..4d01c50 --- /dev/null +++ b/apps/desktop/src/fonts.rs @@ -0,0 +1,46 @@ +//! The fonts installed on this computer, for the appearance choices. + +use std::collections::BTreeSet; +use std::sync::OnceLock; + +/// Family names of every installed face, sorted and deduplicated. Loading the +/// system database costs a few hundred milliseconds, so it happens once, when +/// a settings page first asks. +pub(crate) fn installed() -> &'static [String] { + static FAMILIES: OnceLock> = OnceLock::new(); + FAMILIES + .get_or_init(|| { + let mut database = fontdb::Database::new(); + database.load_system_fonts(); + let mut seen = BTreeSet::new(); + let mut names: Vec = database + .faces() + .filter_map(|face| face.families.first()) + .map(|(name, _)| name.trim()) + // Dot-prefixed families are private faces the system hides. + .filter(|name| !name.is_empty() && !name.starts_with('.')) + .filter(|name| seen.insert(name.to_lowercase())) + .map(str::to_owned) + .collect(); + names.sort_by_key(|name| name.to_lowercase()); + names + }) + .as_slice() +} + +/// A family is offered when the system lists it, and the app's own families +/// are always offered so a choice can be undone on a machine that lacks them. +pub(crate) fn choices(current: Option<&str>) -> Vec { + let mut choices: Vec = installed().to_vec(); + for fallback in [crate::DEFAULT_UI_FONT, crate::DEFAULT_MONO_FONT] { + if !choices.iter().any(|name| name == fallback) { + choices.push(fallback.to_string()); + } + } + if let Some(current) = current { + if !choices.iter().any(|name| name == current) { + choices.push(current.to_string()); + } + } + choices +} diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 5ba3a71..fc4de4e 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -1,5 +1,8 @@ mod agent_detection; mod app; +mod chat_terminal; +mod chats; +mod fonts; mod preferences; mod screens; mod shell; @@ -14,6 +17,10 @@ pub(crate) const VERSION: &str = match option_env!("CODERUNE_BUILD_VERSION") { None => env!("CARGO_PKG_VERSION"), }; +/// The families the app ships with, used until another is chosen. +pub(crate) const DEFAULT_UI_FONT: &str = "Geist"; +pub(crate) const DEFAULT_MONO_FONT: &str = "Paper Mono"; + fn main() { update_install::finish_on_launch(); if std::env::args_os() @@ -45,7 +52,7 @@ fn main() { include_bytes!("../../../packages/tokens/fonts/Geist-Variable.ttf"), include_bytes!("../../../packages/tokens/fonts/PaperMono-Variable.ttf"), ], - families: ("Geist", "Paper Mono"), + families: (DEFAULT_UI_FONT, DEFAULT_MONO_FONT), on_key: Some(app::on_key), poll: Some(app::poll), scenes: &[ @@ -65,6 +72,9 @@ fn main() { ("settings-shortcuts", app::scene_shortcuts), ("settings-agents", app::scene_settings_agents), ("home-dark", app::scene_home_dark), + ("chat", app::scene_chat), + ("chat-floating", app::scene_chat_floating), + ("settings-fonts", app::scene_settings_fonts), ("settings-dark", app::scene_settings_dark), ("settings-agents-dark", app::scene_settings_agents_dark), ("onboarding-start", app::scene_onboarding_start), diff --git a/apps/desktop/src/preferences.rs b/apps/desktop/src/preferences.rs index d50f29a..8d55db9 100644 --- a/apps/desktop/src/preferences.rs +++ b/apps/desktop/src/preferences.rs @@ -7,10 +7,28 @@ use std::path::{Path, PathBuf}; use coderune_agents::CliAgentId; use serde::{Deserialize, Serialize}; +/// Where a chat's agent panel sits inside the content area. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] +pub(crate) enum AgentDock { + #[default] + Right, + Left, + Floating, + Hidden, +} + #[derive(Default, Deserialize, Serialize)] #[serde(default)] pub(crate) struct Preferences { pub(crate) dark_mode: bool, + /// The family behind ordinary text, and the one behind code and paths. + pub(crate) ui_font: Option, + pub(crate) mono_font: Option, + /// Whether the sidebar's Projects section shows its rows. + pub(crate) projects_collapsed: bool, + /// Projects whose chats are listed under them. + pub(crate) expanded_projects: Vec, + pub(crate) agent_dock: AgentDock, disabled_agents: Vec, } @@ -50,6 +68,20 @@ impl Preferences { Ok(preferences) } + pub(crate) fn project_expanded(&self, id: &str) -> bool { + self.expanded_projects.iter().any(|project| project == id) + } + + pub(crate) fn set_project_expanded(&mut self, id: &str, expanded: bool) { + if expanded { + if !self.project_expanded(id) { + self.expanded_projects.push(id.to_string()); + } + } else { + self.expanded_projects.retain(|project| project != id); + } + } + pub(crate) fn agent_enabled(&self, agent: CliAgentId) -> bool { !self.disabled_agents.contains(&agent) } diff --git a/apps/desktop/src/screens/chat.rs b/apps/desktop/src/screens/chat.rs new file mode 100644 index 0000000..fb4bee9 --- /dev/null +++ b/apps/desktop/src/screens/chat.rs @@ -0,0 +1,489 @@ +//! A chat tab: the conversation, its project context, and the agent panel. + +use crate::agent_detection::Check; +use crate::app::CoderuneApp; +use crate::chat_terminal::Terminal; +use crate::chats::{Author, Chat}; +use crate::preferences::AgentDock; +use crate::widgets::*; +use coderune_agents::CliAgentId; +use coderune_ui::components as ui; +use coderune_ui::components::PushButtonExt; +use coderune_ui::icons; +use coderune_ui::theme::{self, BODY, LABEL, LABEL_SM}; +use coderune_ui::WhenExt; +use rune::{col, row, text, El, ScrollSpec}; +use rune_kit::{Button, ButtonVariant, ControlSize, IconButton, IconButtonVariant, Kit, Progress}; + +const PANEL_WIDTH: f32 = 320.0; +const FLOAT_WIDTH: f32 = 316.0; +const FLOAT_INSET: f32 = 12.0; + +pub(crate) fn chat(s: &CoderuneApp, k: &Kit) -> El { + let Some(chat) = s.active_chat() else { + return ui::page("chat-missing").child(ui::subtle("This chat is no longer available.")); + }; + let project = s + .workspace + .as_ref() + .and_then(|workspace| workspace.projects.iter().find(|p| p.id == chat.project_id)); + let project_name = project.map_or("No project", |project| project.name.as_str()); + let dock = s.agent_dock(); + let header = row() + .w_full() + .h(theme::TOPBAR) + .px(16.0) + .items_center() + .gap(10.0) + .border_sides([0.0, 0.0, 1.0, 0.0], theme::row_line()) + .child( + text(&chat.title) + .font(LABEL) + .color(theme::ink()) + .grow(1.0) + .min_w(0.0) + .truncate(), + ) + .child( + text(project_name) + .font(LABEL_SM) + .color(theme::muted()) + .truncate(), + ) + .child( + Button::new("Project settings") + .variant(ButtonVariant::Ghost) + .on_press(CoderuneApp::show_chat_project) + .build_push(k) + .key("chat-project-settings"), + ) + .when(dock == AgentDock::Hidden, |header| { + header.child( + IconButton::new(&icons::PANEL_RIGHT) + .variant(IconButtonVariant::Ghost) + .label("Show agent panel") + .on_press(|s: &mut CoderuneApp| s.set_agent_dock(AgentDock::Right)) + .build(k) + .key("show-agent-panel"), + ) + }); + let transcript = transcript(s, k, chat, dock == AgentDock::Floating); + let body = match dock { + AgentDock::Hidden => transcript, + AgentDock::Left => row() + .w_full() + .grow(1.0) + .min_h(0.0) + .child(agent_panel(s, k, chat, dock)) + .child(transcript), + AgentDock::Right => row() + .w_full() + .grow(1.0) + .min_h(0.0) + .child(transcript) + .child(agent_panel(s, k, chat, dock)), + AgentDock::Floating => transcript, + }; + col() + .key("chat") + .w_full() + .h_full() + .child(header) + .when(s.error.is_some(), |page| { + let error = s.error.as_ref(); + page.children(error.map(|error| { + col() + .w_full() + .px(16.0) + .py(8.0) + .child(ui::alert(Some(error.code.as_str()), &error.message)) + })) + }) + .child(body) +} + +fn transcript(s: &CoderuneApp, k: &Kit, chat: &Chat, floating: bool) -> El { + let mut messages = col().w_full().gap(14.0).pb(8.0); + if chat.messages.is_empty() { + messages = messages.child(empty_chat(s, k, chat)); + } + let running = s + .chat_terminals + .get(&chat.id) + .is_some_and(Terminal::is_running); + for message in &chat.messages { + let mine = message.author == Author::Developer; + messages = messages.child( + col() + .w_full() + .gap(3.0) + .items_start() + .child( + text(match message.author { + Author::Developer => "You", + Author::Coderune => "Coderune", + }) + .font(LABEL_SM) + .color(if mine { theme::ink() } else { theme::faint() }), + ) + .child( + text(&message.text) + .font(BODY) + .color(if mine { theme::ink() } else { theme::muted() }) + .wrap(), + ), + ); + } + let composer = row() + .w_full() + .padding(12.0) + .gap(8.0) + .items_center() + .border_sides([1.0, 0.0, 0.0, 0.0], theme::row_line()) + .child( + col().grow(1.0).min_w(0.0).child( + text_input( + &s.chat_draft, + if running { + "Write a message…" + } else { + "Start an agent to send a message" + }, + "Message", + |s| &mut s.chat_draft, + k, + ) + .on_submit(|s: &mut CoderuneApp, _: &mut rune::Tx| s.send_chat_message()), + ), + ) + .child( + Button::new("Send") + .variant(ButtonVariant::Contrast) + .disabled(!running || s.chat_draft.text.trim().is_empty()) + .on_press(|s: &mut CoderuneApp| s.send_chat_message()) + .build_push(k) + .key("send-message"), + ); + col() + .key("chat-transcript") + .grow(1.0) + .min_w(0.0) + .h_full() + .child( + col() + .key("chat-message-area") + .w_full() + .grow(1.0) + .min_h(0.0) + .child( + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { stick_bottom: true }) + .pl(16.0) + .pr(if floating { + FLOAT_WIDTH + 2.0 * FLOAT_INSET + } else { + 16.0 + }) + .py(14.0) + .items_center() + .child(col().w_full().max_w(720.0).child(messages)), + ) + .when(floating, |area| area.child(floating_panel(s, k, chat))), + ) + .child(composer) +} + +fn empty_chat(s: &CoderuneApp, k: &Kit, chat: &Chat) -> El { + let done = s.context_done(&chat.project_id); + col() + .w_full() + .py(24.0) + .gap(10.0) + .items_start() + .child( + text("This chat has no messages") + .font(theme::HEADING_XS) + .color(theme::ink()), + ) + .child(ui::subtle( + "Start an agent in the panel to write your first message.", + )) + .child( + row() + .items_center() + .gap(10.0) + .child( + Progress::new((done.1 > 0).then(|| f32::from(done.0) / f32::from(done.1))) + .build(k) + .w(140.0), + ) + .child(ui::tiny(&format!("{} of {} context items", done.0, done.1))), + ) +} + +fn agent_panel(s: &CoderuneApp, k: &Kit, chat: &Chat, dock: AgentDock) -> El { + let terminal = s.chat_terminals.get(&chat.id); + let running = terminal.is_some_and(Terminal::is_running); + let available = chat.agent.is_some_and(|id| { + s.agent_enabled(id) + && s.agent_detection + .results + .iter() + .any(|status| status.id == id && status.executable.is_some()) + }); + let mut panel = col() + .key("agent-panel") + .w(PANEL_WIDTH) + .min_h(0.0) + .fill(theme::surface()) + .when(dock == AgentDock::Right, |panel| { + panel + .h_full() + .border_sides([0.0, 0.0, 0.0, 1.0], theme::row_line()) + }) + .when(dock == AgentDock::Left, |panel| { + panel + .h_full() + .border_sides([0.0, 1.0, 0.0, 0.0], theme::row_line()) + }) + .child(panel_header(s, k, chat)); + if let Some(terminal) = terminal { + panel = panel.child(terminal.view::(CoderuneApp::active_terminal_mut)); + } else { + panel = panel.child( + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec { + stick_bottom: false, + }) + .padding(12.0) + .gap(14.0) + .child(agent_list(s, k, chat)) + .child(context_section(s, k, chat)), + ); + } + panel.child( + row() + .w_full() + .padding(8.0) + .gap(6.0) + .border_sides([1.0, 0.0, 0.0, 0.0], theme::row_line()) + .child(if running { + Button::new("Stop agent") + .variant(ButtonVariant::Ghost) + .on_press(CoderuneApp::stop_chat_agent) + .build_push(k) + .key("stop-chat-agent") + } else { + Button::new("Start agent") + .variant(ButtonVariant::Contrast) + .disabled(!available) + .on_press(CoderuneApp::start_chat_agent) + .build_push(k) + .key("start-chat-agent") + }) + .when(terminal.is_some() && !running, |footer| { + footer.child( + Button::new("Choose agent") + .variant(ButtonVariant::Ghost) + .on_press(CoderuneApp::clear_chat_terminal) + .build_push(k), + ) + }), + ) +} + +fn floating_panel(s: &CoderuneApp, k: &Kit, chat: &Chat) -> El { + let mut panel = agent_panel(s, k, chat, AgentDock::Floating) + .pin( + None, + Some(FLOAT_INSET), + Some(FLOAT_INSET), + Some(FLOAT_INSET), + ) + .w(FLOAT_WIDTH) + .border(1.0, theme::row_line()) + .radius(k.radius.xl) + .continuous_corners() + .clip_rounded(k.radius.xl); + for shadow in &k.elevation.overlay { + panel = panel.box_shadow(*shadow); + } + panel +} + +fn panel_header(s: &CoderuneApp, k: &Kit, chat: &Chat) -> El { + let dock = s.agent_dock(); + let dock_button = + |key: &'static str, icon: &'static rune::Icon, target: AgentDock, hint: &str| { + IconButton::new(icon) + .variant(if dock == target { + IconButtonVariant::Neutral + } else { + IconButtonVariant::Ghost + }) + .control_size(ControlSize::Small) + .label(hint) + .on_press(move |s: &mut CoderuneApp| s.set_agent_dock(target)) + .build(k) + .key(key) + }; + row() + .w_full() + .h(theme::TOPBAR) + .px(12.0) + .gap(4.0) + .items_center() + .border_sides([0.0, 0.0, 1.0, 0.0], theme::row_line()) + .child( + text( + s.agent_detection + .results + .iter() + .find(|agent| Some(agent.id) == chat.agent) + .map_or("Agents", |agent| agent.name), + ) + .font(LABEL) + .color(theme::ink()) + .grow(1.0) + .min_w(0.0) + .truncate(), + ) + .child(dock_button( + "dock-left", + &icons::PANEL_LEFT, + AgentDock::Left, + "Dock agent panel left", + )) + .child(dock_button( + "dock-right", + &icons::PANEL_RIGHT, + AgentDock::Right, + "Dock agent panel right", + )) + .child(dock_button( + "dock-float", + &icons::PANEL_FLOAT, + AgentDock::Floating, + "Float agent panel", + )) + .child( + IconButton::new(&icons::PANEL_HIDDEN) + .variant(IconButtonVariant::Ghost) + .control_size(ControlSize::Small) + .label("Hide agent panel") + .on_press(|s: &mut CoderuneApp| s.set_agent_dock(AgentDock::Hidden)) + .build(k) + .key("dock-hidden"), + ) +} + +fn agent_list(s: &CoderuneApp, k: &Kit, chat: &Chat) -> El { + let mut ready: Vec<(CliAgentId, &'static str)> = Vec::new(); + for status in &s.agent_detection.results { + if status.executable.is_some() && s.agent_enabled(status.id) { + ready.push((status.id, status.name)); + } + } + let mut rows = col().w_full().gap(2.0); + if ready.is_empty() { + rows = rows + .child(ui::subtle( + if matches!(s.agent_detection.check, Check::Checking(_)) { + "Checking for installed agents…" + } else { + "No coding agent is ready." + }, + )) + .child(row().child(ghost( + "Open Agents settings", + |s| s.select_settings(crate::app::SettingsSection::Agents), + k, + ))); + } + for (id, name) in ready { + let selected = chat.agent == Some(id); + rows = rows.child( + row() + .key(format!("chat-agent-{id:?}")) + .hit() + .focusable(true) + .role("button") + .label(name) + .w_full() + .h(32.0) + .px(8.0) + .gap(8.0) + .items_center() + .radius(6.0) + .when(selected, |this| this.fill(theme::accent_soft())) + .when(!selected, |this| this.hover(theme::hover())) + .child(super::coding_agents::logo(id, k.dark)) + .child(text(name).font(LABEL).color(theme::ink()).grow(1.0)) + .child(ui::tiny(if selected { "Selected" } else { "Ready" })) + .on_press(move |s: &mut CoderuneApp| s.set_chat_agent(Some(id))), + ); + } + col() + .key("chat-agent-list") + .w_full() + .gap(6.0) + .child(text("Coding agent").font(LABEL_SM).color(theme::faint())) + .child(rows) +} + +fn context_section(s: &CoderuneApp, k: &Kit, chat: &Chat) -> El { + let items = s.context_items(&chat.project_id); + let done = items.iter().filter(|item| item.done).count(); + let total = items.len(); + let mut rows = col().w_full().gap(6.0).child( + row() + .items_center() + .gap(8.0) + .child( + Progress::new((total > 0).then(|| done as f32 / total as f32)) + .build(k) + .w(120.0), + ) + .child(ui::tiny(&format!("{done} of {total}"))), + ); + for item in items { + rows = rows.child( + row() + .w_full() + .gap(8.0) + .items_center() + .child( + row() + .size(6.0, 6.0) + .radius(3.0) + .fill(if item.done { + theme::muted() + } else { + theme::line() + }) + .a11y_hidden(), + ) + .child( + text(item.label) + .font(theme::BODY_SM) + .color(if item.done { + theme::muted() + } else { + theme::ink() + }) + .grow(1.0), + ), + ); + } + rows.child(row().child(ghost( + "Review in project settings", + CoderuneApp::show_chat_project, + k, + ))) +} diff --git a/apps/desktop/src/screens/coding_agents.rs b/apps/desktop/src/screens/coding_agents.rs index d5751d6..125620a 100644 --- a/apps/desktop/src/screens/coding_agents.rs +++ b/apps/desktop/src/screens/coding_agents.rs @@ -129,7 +129,7 @@ fn agent_row(agent: &CliAgentStatus, status: Option<&str>, action: El, k: &Kit) .child(action) } -fn logo(agent: CliAgentId, dark: bool) -> El { +pub(super) fn logo(agent: CliAgentId, dark: bool) -> El { use CliAgentId::*; static IMAGES: LazyLock = LazyLock::new(|| ImageCache::new(Arc::new(|| {}))); const SIZE: f32 = 20.0; diff --git a/apps/desktop/src/screens/home.rs b/apps/desktop/src/screens/home.rs index afc4ee5..d8d27c6 100644 --- a/apps/desktop/src/screens/home.rs +++ b/apps/desktop/src/screens/home.rs @@ -1,156 +1,85 @@ //! The home screen. use crate::app::{CoderuneApp, View}; -use crate::widgets::*; +use crate::widgets::{primary, secondary}; use coderune_ui::components as ui; -use coderune_ui::theme::{self, HEADING_XS, LABEL}; -use rune::{col, row, text, El}; +use coderune_ui::icons; +use coderune_ui::theme::{self, HEADING_LG, HEADING_SM}; +use rune::{col, icon, row, text, El}; use rune_kit::Kit; -use std::path::PathBuf; pub(crate) fn home(s: &CoderuneApp, k: &Kit) -> El { - let workspace = s.workspace.as_ref(); - let profile = workspace.and_then(|workspace| workspace.profile()); - let projects = workspace - .map(|workspace| workspace.projects.len()) - .unwrap_or(0); - let captures = s.captures.len(); + let project = s.workspace.as_ref().and_then(|workspace| { + workspace + .selected_project() + .or_else(|| workspace.projects.first()) + }); - let baseline = col() - .items_end() - .gap(2.0) - .child( - text( - profile - .map(|p| p.display_name.as_str()) - .unwrap_or("Not set"), - ) - .font(LABEL) - .color(theme::ink()), - ) - .child(ui::tiny( - &profile - .map(|p| format!("v{} · {}", p.version, p.experience_stage.label())) - .unwrap_or_else(|| "Complete onboarding first".to_string()), - )); - let mut body = ui::page("home-page") - .child(ui::page_header( - "Workspace", - "Local context about you and the projects you work on. Nothing leaves this machine unless you start an explicit agent draft.", - vec![secondary("Open projects", |s| s.navigate(View::Projects), k)], - )) - .child(ui::section( + let mut header = row() + .w_full() + .items_center() + .justify_between() + .gap(12.0) + .child(text("Home").font(HEADING_LG).color(theme::ink())); + let start = if let Some(project) = project { + header = header.child(secondary("New project", new_project, k).key("home-new-project")); + let id = project.id.clone(); + let (done, total) = s.context_done(&id); + ui::section( k, - "home-summary", - "Workspace", - [ - ui::setting_row( - "Developer baseline", - Some("Starting description for later progress.".to_string()), - baseline, - ), - ui::setting_row( - "Projects", - Some(format!( - "{} configured", - if projects == 1 { "project" } else { "projects" } - )), - text(projects.to_string()) - .font(HEADING_XS) - .color(theme::ink()), - ), - ui::setting_row( - "Context captures", - Some("Reviewed snapshots for the selected project.".to_string()), - text(captures.to_string()) - .font(HEADING_XS) - .color(theme::ink()), - ), - ], - )); - - if let Some(project) = workspace.and_then(|workspace| workspace.selected_project()) { - let root = PathBuf::from(&project.root_path); - let root2 = root.clone(); - body = body.child(ui::section( + "home-project", + "Continue with", + [ui::setting_row( + &project.name, + Some(format!("{done} of {total} context items ready")), + primary("New chat", move |s| s.new_chat(&id), k).key("home-new-chat"), + )], + ) + } else { + ui::rows_card( k, "home-project", - "Project", [col() .w_full() - .gap(10.0) + .items_center() + .py(32.0) + .gap(12.0) .child( row() - .gap(8.0) - .items_center() - .child(text(&project.name).font(HEADING_XS).color(theme::ink())) - .child(ui::badge(&format!("v{}", project.version), k)), + .size(36.0, 36.0) + .center() + .radius(k.radius.md) + .fill(theme::code()) + .child(icon(&icons::FOLDER, theme::ICON).color(theme::muted())) + .a11y_hidden(), ) - .child(ui::mono_line(&project.root_path, theme::muted())) - .child(ui::subtle(&format!( - "{} goal(s) · active project context", - project.goals.len() - ))) - .child( - row() - .gap(8.0) - .child(secondary( - "Open folder", - move |s| s.open_folder(root.clone()), - k, - )) - .child(ghost( - "Open in VS Code", - move |s| s.open_editor("code", root2.clone()), - k, - )), - )], - )); - } else { - body = body.child(ui::section( - k, - "home-project", - "Project", - [col() - .w_full() - .gap(10.0) - .child(text("No project yet").font(LABEL).color(theme::ink())) + .child(text("No projects yet").font(HEADING_SM).color(theme::ink())) .child(ui::subtle( - "Choose a folder, name the project, and add at least one goal.", + "Add a project folder to start a chat and collect context.", )) - .child(primary("Create project", |s| s.navigate(View::Projects), k))], - )); - } - - let details = s.profile_form.details_count(); - body = body.child(ui::section( - k, - "home-profile", - "Profile", - [col() - .w_full() - .gap(10.0) - .child( - text(if details == 0 { - "Finish your profile when you are ready" - } else { - "Your profile has more to say" - }) - .font(LABEL) - .color(theme::ink()), - ) - .child(ui::subtle(if details == 0 { - "Onboarding kept it short. Add detail later; nothing is required to start a project." - } else { - "You have added optional profile detail. You can keep it current from here." - })) - .child(row().child(ghost( - "Complete profile", - |s| s.open_profile_details(), - k, - )))], - )); + .child(primary("Create project", new_project, k).key("home-new-project"))], + ) + }; + let profile_action = if s.profile_form.details_count() == 0 { + "Complete profile" + } else { + "Edit profile" + }; + let mut body = ui::page("home-page") + .child(header) + .child(start) + .child(ui::section( + k, + "home-profile", + "Profile", + [ui::setting_row( + "Developer profile", + Some("Add details about how you work and what you want to learn.".to_string()), + secondary(profile_action, CoderuneApp::open_profile_details, k) + .key("home-profile-action"), + )], + )); if let Some(notice) = &s.notice { body = body.child(ui::alert(None, notice)); } @@ -159,3 +88,8 @@ pub(crate) fn home(s: &CoderuneApp, k: &Kit) -> El { } body } + +fn new_project(s: &mut CoderuneApp) { + s.new_project_form(); + s.navigate(View::Projects); +} diff --git a/apps/desktop/src/screens/mod.rs b/apps/desktop/src/screens/mod.rs index 21c4e91..cfdb397 100644 --- a/apps/desktop/src/screens/mod.rs +++ b/apps/desktop/src/screens/mod.rs @@ -2,6 +2,7 @@ pub(crate) mod avatars; pub(crate) mod capture; +pub(crate) mod chat; mod coding_agents; pub(crate) mod documents; pub(crate) mod home; @@ -13,6 +14,7 @@ pub(crate) mod subagents; pub(crate) use avatars::{avatar_gallery, register_gallery}; pub(crate) use capture::capture; +pub(crate) use chat::chat; pub(crate) use documents::documents; pub(crate) use home::home; pub(crate) use onboarding::onboarding; diff --git a/apps/desktop/src/screens/projects.rs b/apps/desktop/src/screens/projects.rs index 8d84dda..87578fc 100644 --- a/apps/desktop/src/screens/projects.rs +++ b/apps/desktop/src/screens/projects.rs @@ -1,73 +1,114 @@ -//! The projects screen. +//! Project creation and settings. Project navigation lives in the sidebar. -use crate::app::CoderuneApp; +use std::path::PathBuf; + +use crate::app::{CoderuneApp, View}; use crate::widgets::*; +use coderune_domain::Project; use coderune_ui::components as ui; -use coderune_ui::theme::{self, CODE_SM, LABEL}; -use coderune_ui::WhenExt; -use rune::{col, row, text, El}; -use rune_kit::{Badge, Kit}; +use rune::{col, row, El}; +use rune_kit::{Accordion, AccordionItem, Kit, Progress}; pub(crate) fn projects(s: &CoderuneApp, k: &Kit) -> El { - let workspace = s.workspace.as_ref(); - let projects = workspace - .map(|workspace| workspace.projects.as_slice()) - .unwrap_or(&[]); - let selected = s.project_form.editing.as_deref(); - let mut list = col().w_full().gap(4.0); - for project in projects { - let active = selected == Some(project.id.as_str()); - let id = project.id.clone(); - list = list.child( - col() - .key(format!("project-{}", project.id)) - .hit() - .focusable(true) - .focus_ring(2.0, -2.0, theme::ink()) - .role("button") - .label(&project.name) - .w_full() - .padding(12.0) - .gap(4.0) - .radius(6.0) - .when(active, |this| this.fill(theme::accent_soft())) - .when(!active, |this| this.hover(theme::pressed())) - .child( - row() - .gap(8.0) - .items_center() - .child( - text(&project.name) - .font(LABEL) - .color(theme::ink()) - .grow(1.0) - .min_w(0.0) - .truncate() - .a11y_hidden(), - ) - .child( - Badge::new(format!("v{}", project.version)) - .build(k) - .a11y_hidden(), - ), - ) - .child( - text(&project.root_path) - .font(CODE_SM) - .color(theme::faint()) - .truncate() - .a11y_hidden(), - ) - .on_press(move |s: &mut CoderuneApp| s.load_project_form(&id)), - ); + let project = s.project_form.editing.as_deref().and_then(|id| { + s.workspace + .as_ref()? + .projects + .iter() + .find(|project| project.id == id) + }); + let (title, description, save_label) = match project { + Some(project) => ( + "Project settings", + format!("{} · v{}", project.name, project.version), + "Save new version", + ), + None => ( + "New project", + "Choose a local folder and add a goal to get started.".to_string(), + "Create project", + ), + }; + let mut actions = vec![primary(save_label, |s| s.save_project(), k).key("save-project")]; + if project.is_none() { + actions.insert(0, ghost("Clear", |s| s.new_project_form(), k)); } - if projects.is_empty() { - list = list.child(ui::subtle("No projects yet.")); + let mut page = ui::page("projects-page") + .max_w(640.0) + .child(ui::page_header(title, &description, actions)); + if let Some(error) = &s.error { + page = page.child(ui::alert(Some(error.code.as_str()), &error.message)); } - let editing = s.project_form.editing.is_some(); - let confirm_delete = s.confirm_delete_project.is_some(); - let identity = vec![ - ui::field( + if let Some(notice) = &s.notice { + page = page.child(ui::alert(None, notice)); + } + if let Some(project) = project { + page = page.child(context_progress(s, project, k)); + } + page = page + .child(project_details(s, project, k)) + .child(project_goals(s, k)); + if project.is_some() { + page = page.child(capture_scope(s, k)).child(delete_project(s, k)); + } + page +} + +fn context_progress(s: &CoderuneApp, project: &Project, k: &Kit) -> El { + let items = s.context_items(&project.id); + let total = items.len(); + let missing: Vec<_> = items + .iter() + .filter(|item| !item.done) + .map(|item| item.label) + .collect(); + let done = total - missing.len(); + let summary = if missing.is_empty() { + "All context items are ready.".to_string() + } else { + format!("Still to add · {}", missing.join(", ")) + }; + let context = col() + .w_full() + .py(ui::ROW_PAD) + .gap(8.0) + .child( + Progress::new(Some(done as f32 / total.max(1) as f32)) + .label(format!("{done} of {total} context items ready")) + .build(k), + ) + .child(ui::subtle(&summary)); + let captured = items + .iter() + .find(|item| item.label == "First capture") + .is_some_and(|item| item.done); + let (detail, action) = if captured { + ("Context is saved for this project.", "View captures") + } else { + ("Review and save the repository context.", "Start a capture") + }; + ui::section( + k, + "project-context", + "Context readiness", + [ + context, + ui::setting_row( + "First capture", + Some(detail.to_string()), + secondary(action, |s| s.navigate(View::Capture), k).key("project-capture"), + ) + .py(6.0), + ], + ) +} + +fn project_details(s: &CoderuneApp, project: Option<&Project>, k: &Kit) -> El { + let mut fields = col() + .w_full() + .py(ui::ROW_PAD) + .gap(12.0) + .child(ui::field( "Project name", None, text_input( @@ -76,46 +117,86 @@ pub(crate) fn projects(s: &CoderuneApp, k: &Kit) -> El { "Project name", |s| &mut s.project_form.name, k, - ), - ), - ui::field( + ) + .key("project-name"), + )) + .child(ui::field( "Root folder", - Some("Absolute path. The folder must exist and be readable."), + Some("Enter the absolute path to a readable directory."), text_input( &s.project_form.root, "/path/to/project", "Root folder", |s| &mut s.project_form.root, k, - ), - ), - ui::field( - "Goals", - Some("At least one. Separate several goals with commas."), + ) + .key("project-root"), + )); + if let Some(project) = project { + let folder = PathBuf::from(&project.root_path); + let editor_folder = folder.clone(); + fields = fields.child( + row() + .flex_wrap() + .gap(8.0) + .child( + secondary("Open folder", move |s| s.open_folder(folder.clone()), k) + .key("open-project-folder"), + ) + .child( + secondary( + "Open in VS Code", + move |s| s.open_editor("code", editor_folder.clone()), + k, + ) + .key("open-project-editor"), + ), + ); + } + ui::section(k, "project-identity", "Project details", [fields]) +} + +fn project_goals(s: &CoderuneApp, k: &Kit) -> El { + ui::section( + k, + "project-goals", + "Goals", + [ui::field( + "What are you building?", + Some("Add at least one goal. Separate multiple goals with commas."), text_input( &s.project_form.goals, - "At least one goal", + "Ship the native desktop app", "Goals", |s| &mut s.project_form.goals, k, - ), - ), - ]; - let scope = vec![ - ui::field( + ) + .key("project-goals-input"), + ) + .py(ui::ROW_PAD)], + ) +} + +fn capture_scope(s: &CoderuneApp, k: &Kit) -> El { + let fields = col() + .w_full() + .padding(ui::ROW_PAD) + .gap(12.0) + .child(ui::field( "Include paths", - Some("Empty means the whole repository. Comma separated, relative to the root."), + Some("Use comma-separated paths relative to the root."), text_input( &s.project_form.include_paths, "src, docs", "Include paths", |s| &mut s.project_form.include_paths, k, - ), - ), - ui::field( + ) + .key("project-include-paths"), + )) + .child(ui::field( "Exclude paths", - Some("Comma separated paths, directory names, or glob patterns."), + Some("Use comma-separated paths, directory names, or glob patterns."), text_input( &s.project_form.exclude_paths, "generated, dist", @@ -123,8 +204,8 @@ pub(crate) fn projects(s: &CoderuneApp, k: &Kit) -> El { |s| &mut s.project_form.exclude_paths, k, ), - ), - ui::field( + )) + .child(ui::field( "Capture limits", Some("Defaults are 1024 KiB per file and 20 MiB per capture."), row() @@ -153,96 +234,81 @@ pub(crate) fn projects(s: &CoderuneApp, k: &Kit) -> El { k, ), ))), - ), - ui::field( + )) + .child(ui::field( "Gitignore", Some("Only the root .gitignore is read."), - row().gap(8.0).child(option_chip( + option_chip( "project-gitignore".to_string(), "Respect .gitignore", s.project_form.respect_gitignore, |s: &mut CoderuneApp| { s.project_form.respect_gitignore = !s.project_form.respect_gitignore }, - )), - ), - ]; - let mut editor = col() - .key("project-editor") - .grow(1.0) - .min_w(336.0) - .gap(16.0) - .child(ui::section( - k, - "project-identity", - if editing { - "Project details" - } else { - "New project details" - }, - [col().w_full().gap(12.0).children(identity)], - )) - .child(ui::section( - k, - "project-scope", - "Capture scope", - [col().w_full().gap(12.0).children(scope)], + ), )); - if confirm_delete { - editor = editor.child(ui::alert(None, "Deleting a project also deletes its captures and project-linked documents. Click Confirm delete to proceed.")); - } - if let Some(error) = &s.error { - editor = editor.child(ui::alert(Some(error.code.as_str()), &error.message)); - } - if let Some(notice) = &s.notice { - editor = editor.child(ui::alert(None, notice)); - } - let mut actions = row().flex_wrap().gap(8.0).child(primary( - if editing { - "Save new version" - } else { - "Create project" - }, - |s| s.save_project(), + ui::section( + k, + "project-scope", + "Capture scope", + [col() + .w_full() + .py(ui::ROW_PAD) + .gap(8.0) + .child(ui::subtle( + "Captures default to allowed files across the repository. Set include or exclude paths to narrow the scope.", + )) + .child( + Accordion::new() + .item( + AccordionItem::new(if s.project_scope_expanded { + "Hide paths and limits" + } else { + "Show paths and limits" + }) + .expanded(s.project_scope_expanded) + .on_toggle(|s: &mut CoderuneApp| { + s.project_scope_expanded = !s.project_scope_expanded; + }) + .child(fields), + ) + .build(k) + .key("project-scope-disclosure"), + )], + ) +} + +fn delete_project(s: &CoderuneApp, k: &Kit) -> El { + let action = if s.confirm_delete_project.is_some() { + row() + .key("confirm-project-delete") + .flex_wrap() + .gap(8.0) + .child(ghost("Cancel", |s| s.confirm_delete_project = None, k)) + .child(destructive("Confirm delete", |s| s.delete_project(), k)) + } else { + secondary( + "Delete project", + |s| s.confirm_delete_project = s.project_form.editing.clone(), + k, + ) + .key("request-project-delete") + }; + ui::section( k, - )); - if editing { - actions = actions.child(destructive( - if confirm_delete { - "Confirm delete" + "project-delete", + "Manage project", + [ui::setting_row( + if s.confirm_delete_project.is_some() { + "Permanently delete this project?" } else { - "Delete project" + "Remove this project from Coderune" }, - |s| { - if s.confirm_delete_project.is_some() { - s.delete_project(); - } else { - s.confirm_delete_project = s.project_form.editing.clone(); - } - }, - k, - )); - } else { - actions = actions.child(ghost("Clear", |s| s.new_project_form(), k)); - } - ui::page("projects-page") - .child(ui::page_header( - "Projects", - "Project context is stored locally and reused on later captures.", - vec![secondary("New project", |s| s.new_project_form(), k)], - )) - .child( - row() - .w_full() - .flex_wrap() - .gap(24.0) - .items_start() - .child(col().key("project-list").w(216.0).child(ui::section( - k, - "project-saved", - "Saved projects", - [list], - ))) - .child(editor.child(actions)), + Some( + "This also deletes its chats, captures, and project-linked documents.".to_string(), + ), + action, ) + .py(6.0)], + ) } diff --git a/apps/desktop/src/screens/settings.rs b/apps/desktop/src/screens/settings.rs index 546a565..efc8e86 100644 --- a/apps/desktop/src/screens/settings.rs +++ b/apps/desktop/src/screens/settings.rs @@ -5,7 +5,10 @@ use crate::updates::Status; use crate::widgets::text_input; use coderune_ui::{components as ui, components::PushButtonExt, icons, theme}; use rune::{col, el, row, text, El, ScrollSpec}; -use rune_kit::{Button, ButtonVariant, ControlSize, IconButton, IconButtonVariant, Kit, Switch}; +use rune_kit::{ + Button, ButtonVariant, ControlSize, IconButton, IconButtonVariant, Kit, Placement, Select, + SelectAppearance, Switch, +}; pub(crate) fn dialog(s: &CoderuneApp, section: SettingsSection, k: &Kit, overlays: &mut Vec) { let nav = col().w(166.0).h_full().px(10.0).py(8.0).gap(4.0).children( @@ -32,8 +35,9 @@ pub(crate) fn dialog(s: &CoderuneApp, section: SettingsSection, k: &Kit, overlay .focus_selected(selected) }), ); + let mut menus = Vec::new(); let content = match section { - SettingsSection::General => general(s, k), + SettingsSection::General => general(s, k, &mut menus), SettingsSection::Storage => storage(s, k), SettingsSection::Agents => super::coding_agents::coding_agents(s, k), SettingsSection::Shortcuts => shortcuts(k), @@ -115,9 +119,11 @@ pub(crate) fn dialog(s: &CoderuneApp, section: SettingsSection, k: &Kit, overlay .token_motion(k.motion.overlay), layer("settings-layer").padding(16.0).center().child(dialog), ]); + // A font list opens above the dialog that owns it. + overlays.extend(menus); } -fn general(s: &CoderuneApp, k: &Kit) -> El { +fn general(s: &CoderuneApp, k: &Kit, menus: &mut Vec) -> El { let busy = matches!( s.updates.status, Status::Checking | Status::Downloading | Status::Ready(_) @@ -176,7 +182,7 @@ fn general(s: &CoderuneApp, k: &Kit) -> El { if let Some(status) = status { updates = updates.child(col().w_full().pb(12.0).items_start().child(status)); } - let appearance = ui::setting_row( + let dark = ui::setting_row( "Dark mode", None, Switch::new(s.dark_mode()) @@ -186,7 +192,76 @@ fn general(s: &CoderuneApp, k: &Kit) -> El { .build(theme::switch_kit(k.dark)) .key("dark-mode"), ); - ui::settings_card(k, "general-options", [updates, appearance]) + let ui_font = font_row( + s, + k, + "ui-font", + "Interface font", + "Text, labels, and headings.", + s.ui_font(), + CoderuneApp::set_ui_font, + menus, + ); + let mono_font = font_row( + s, + k, + "mono-font", + "Code font", + "Code, paths, IDs, and hashes.", + s.mono_font(), + CoderuneApp::set_mono_font, + menus, + ); + col() + .w_full() + .gap(ui::SECTION_GAP) + .child(ui::section( + k, + "general-application", + "Application", + [updates], + )) + .child(ui::section( + k, + "general-appearance", + "Appearance", + [dark, ui_font, mono_font], + )) +} + +fn font_row( + s: &CoderuneApp, + k: &Kit, + key: &'static str, + title: &str, + detail: &str, + current: &str, + choose: fn(&mut CoderuneApp, String), + menus: &mut Vec, +) -> El { + let choices = crate::fonts::choices(Some(current)); + let open = s.font_menu == Some(key); + let select = Select::new(key, &choices) + .appearance(SelectAppearance::Inline) + .current(Some(current)) + .width(220.0) + .label(title) + .open(open) + .placement(Placement::BottomEnd) + .on_toggle(move |s: &mut CoderuneApp| { + s.font_menu = if s.font_menu == Some(key) { + None + } else { + Some(key) + }; + }) + .on_close(|s: &mut CoderuneApp| s.font_menu = None) + .on_choose(move |s: &mut CoderuneApp, value: &str, _: &mut rune::Tx| { + s.font_menu = None; + choose(s, value.to_string()); + }) + .build(k, menus); + ui::setting_row(title, Some(detail.to_string()), select) } fn storage(s: &CoderuneApp, k: &Kit) -> El { @@ -255,7 +330,8 @@ fn storage(s: &CoderuneApp, k: &Kit) -> El { ui::setting_row( "Delete all data", Some( - "Permanently removes your profile, projects, documents, and captures.".to_string(), + "Permanently removes your profile, projects, chats, documents, and captures." + .to_string(), ), delete, ), diff --git a/apps/desktop/src/shell.rs b/apps/desktop/src/shell.rs index 8e1b3b5..853eb5f 100644 --- a/apps/desktop/src/shell.rs +++ b/apps/desktop/src/shell.rs @@ -5,9 +5,10 @@ use coderune_ui::icons; use coderune_ui::theme::{self, LABEL, LABEL_SM}; use rune::{col, el, row, text, Color, Cursor, Cx, Drag, El, Phase, ScrollSpec}; use rune_kit::shell::{ - PaneState, Sidebar, TabItem, TabOrientation, TabOverflow, TabStrip, WindowTitlebar, + PaneState, Sidebar, SidebarRow, SidebarSection, TabItem, TabOrientation, TabOverflow, TabStrip, + WindowTitlebar, }; -use rune_kit::Kit; +use rune_kit::{ControlSize, IconButton, IconButtonVariant, Kit}; use crate::app::{CoderuneApp, SettingsSection, View}; use crate::screens; @@ -97,6 +98,7 @@ const WORKSPACE_KEY: &str = "workspace"; pub(crate) fn workspace(s: &CoderuneApp, k: &Kit, cx: &mut Cx) -> El { let active = s.view; + let chat = s.active_chat(); let page = match active { View::Home => screens::home(s, k), View::Profile => screens::profile(s, k), @@ -109,11 +111,21 @@ pub(crate) fn workspace(s: &CoderuneApp, k: &Kit, cx: &mut Cx) -> E let content = ui::surface_frame(k, theme::canvas(), k.radius.lg) .key("workspace-panel") .role("group") - .label(active.label()) + .label(if chat.is_some() { + "Chat" + } else { + active.label() + }) .grow(1.0) .min_w(0.0) .h_full() - .child( + .child(if let Some(chat) = chat { + col() + .key(format!("t-chat-{}", chat.id)) + .w_full() + .h_full() + .child(screens::chat(s, k)) + } else { col() .key(active.id()) .w_full() @@ -129,8 +141,8 @@ pub(crate) fn workspace(s: &CoderuneApp, k: &Kit, cx: &mut Cx) -> E .py(24.0) .items_center() .child(col().w_full().max_w(theme::CONTAINER).child(page)), - ), - ); + ) + }); let mut layout = row() .key("workspace-layout") @@ -210,46 +222,141 @@ pub(crate) fn workspace(s: &CoderuneApp, k: &Kit, cx: &mut Cx) -> E .h_full() .fill(theme::surface()) .instant_changes() - .child(titlebar(cx, k)) + .child(titlebar(s, cx, k, narrow, pane.is_open())) .child(layout.child(grip).child(content)) .child(width_class) } -fn titlebar(cx: &Cx, k: &Kit) -> El { +fn titlebar( + s: &CoderuneApp, + cx: &Cx, + k: &Kit, + narrow: bool, + sidebar_open: bool, +) -> El { let mut tab_kit = k.clone(); tab_kit.c.layer_03 = Color::TRANSPARENT; tab_kit.c.pressed = theme::accent_soft(); - let tabs = TabStrip::new(TAB_STRIP_KEY, TabOrientation::Horizontal) - .label("Window tabs") - .active(Some("workspace")) + let mut tabs = vec![TabItem::::new("workspace", "Workspace") + .icon(s.view.icon()) + .closable(false)]; + for id in &s.chats.open { + if let Some(chat) = s.chats.chat(id) { + tabs.push( + TabItem::::new(chat.id.as_str(), chat.title.as_str()) + .icon(&icons::MESSAGE) + .closable(true), + ); + } + } + let strip = TabStrip::new(TAB_STRIP_KEY, TabOrientation::Horizontal) + .label("Chat tabs") + .active(Some(s.chats.active.as_deref().unwrap_or("workspace"))) .row_height(32.0) .overflow(TabOverflow::ShrinkThenScroll { min_width: 96.0, - max_width: 144.0, + max_width: 168.0, pinned_width: 36.0, fade_width: 16.0, }) .fill(theme::surface()) - .tabs([TabItem::::new("workspace", "Workspace") - .icon(View::Home.icon()) - .closable(false)]) + .tabs(tabs) + .on_select(|s: &mut CoderuneApp, id: &str, _: &mut rune::Tx| { + if id == "workspace" { + s.show_workspace(); + } else { + s.open_chat(id); + } + }) + .on_close(|s: &mut CoderuneApp, id: &str, _: &mut rune::Tx| s.close_chat(id)) .build(&tab_kit); - WindowTitlebar::from_insets(cx.chrome_insets()) + let mut titlebar = WindowTitlebar::from_insets(cx.chrome_insets()) .height(theme::TOPBAR) .fill(theme::surface()) - .tabs(tabs) - .build(k) + .tabs(strip); + if narrow || !sidebar_open { + titlebar = titlebar.leading( + IconButton::new(&icons::PANEL_LEFT) + .variant(IconButtonVariant::Ghost) + .control_size(ControlSize::Small) + .label(if sidebar_open { + "Hide sidebar" + } else { + "Show sidebar" + }) + .on_press(move |s: &mut CoderuneApp| { + s.sidebar.set_narrow(narrow); + s.sidebar.toggle(); + }) + .build(k) + .key("sidebar-toggle"), + ); + } + titlebar.build(k) } fn sidebar(s: &CoderuneApp, k: &Kit) -> El { let mut nav = Sidebar::new() .label("Workspace navigation") - .inset(10.0) - .header_padding(0.0, 8.0) - .row_gap(2.0); - for view in View::NAV { - nav = nav.child(nav_item(s, view)); + .inset(8.0) + .header_padding(0.0, 6.0) + .row_gap(1.0); + nav = nav.child( + SidebarRow::new("Home") + .icon(&icons::HOUSE) + .selected(s.view == View::Home && s.active_chat().is_none()) + .on_select(|s: &mut CoderuneApp, _: &mut rune::Tx| s.navigate(View::Home)) + .build(k) + .key(View::Home.nav_key()), + ); + + let mut projects = SidebarSection::new("Projects") + .key("nav-projects") + .collapsed(s.projects_collapsed()) + .on_toggle(|s: &mut CoderuneApp, _: &mut rune::Tx| s.toggle_projects_section()) + .action( + IconButton::new(&icons::PLUS) + .variant(IconButtonVariant::Ghost) + .control_size(ControlSize::Small) + .label("New project") + .on_press(|s: &mut CoderuneApp| { + s.new_project_form(); + s.navigate(View::Projects); + }) + .build(k) + .key("sidebar-new-project"), + ); + for project in s.workspace.iter().flat_map(|workspace| &workspace.projects) { + projects = projects.row(project_row(s, project, k)); + if s.project_expanded(&project.id) { + for chat in s.chats.chats_for(&project.id) { + projects = projects.row(chat_row(s, chat, k)); + } + let project_id = project.id.clone(); + projects = projects.row( + SidebarRow::new("New chat") + .icon(&icons::PLUS) + .depth(1) + .on_select(move |s: &mut CoderuneApp, tx: &mut rune::Tx| { + s.new_chat(&project_id); + tx.instant(); + }) + .build(k) + .key(format!("new-chat-{}", project.id)), + ); + } } + nav = nav.section(projects); + + let tools = SidebarSection::new("Workspace") + .key("workspace-tools") + .rows( + [View::Documents, View::Subagents, View::Capture] + .into_iter() + .map(|view| nav_item(s, view, k)), + ); + nav = nav.section(tools); + let settings = ui::nav_item( "nav-data-footer", "Settings", @@ -260,14 +367,92 @@ fn sidebar(s: &CoderuneApp, k: &Kit) -> El { nav.footer(settings).footer(profile_item(s)).build(k) } -fn nav_item(s: &CoderuneApp, view: View) -> El { - ui::nav_item( - view.nav_key(), - view.label(), - view.icon(), - s.view == view, - move |s: &mut CoderuneApp| s.navigate(view), - ) +fn project_row(s: &CoderuneApp, project: &coderune_domain::Project, k: &Kit) -> El { + let id = project.id.clone(); + let select = id.clone(); + let chevron = id.clone(); + let open = s.project_expanded(&id); + let selected = s.active_chat().is_none() + && s.view == View::Projects + && s.project_form.editing.as_deref() == Some(id.as_str()); + let (done, total) = s.context_done(&id); + SidebarRow::new(&project.name) + .icon(&icons::FOLDER) + .subtitle(format!("{done} of {total} context items")) + .height(46.0) + .selected(selected) + .trailing( + row() + .gap(4.0) + .items_center() + .child(progress_bar(done, total)) + .child( + IconButton::new(if open { + k.glyph.triangle_down + } else { + k.glyph.triangle_right + }) + .variant(IconButtonVariant::Ghost) + .control_size(ControlSize::Mini) + .label(if open { "Hide chats" } else { "Show chats" }) + .on_press(move |s: &mut CoderuneApp| s.toggle_project_chats(&chevron)) + .build(k) + .key(format!("project-chats-{id}")), + ), + ) + .on_select(move |s: &mut CoderuneApp, tx: &mut rune::Tx| { + s.load_project_form(&select); + s.navigate(View::Projects); + tx.instant(); + }) + .build(k) + .key(format!("project-{id}")) +} + +fn chat_row(s: &CoderuneApp, chat: &crate::chats::Chat, k: &Kit) -> El { + let id = chat.id.clone(); + let select = id.clone(); + let close = id.clone(); + SidebarRow::new(&chat.title) + .icon(&icons::MESSAGE) + .depth(1) + .selected(s.chats.active.as_deref() == Some(id.as_str())) + .on_select(move |s: &mut CoderuneApp, tx: &mut rune::Tx| { + s.open_chat(&select); + tx.instant(); + }) + .on_close(move |s: &mut CoderuneApp, _: &mut rune::Tx| s.close_chat(&close)) + .build(k) + .key(format!("chat-{id}")) +} + +fn progress_bar(done: u8, total: u8) -> El { + let fraction = if total == 0 { + 0.0 + } else { + f32::from(done) / f32::from(total) + }; + row() + .w(36.0) + .h(3.0) + .radius(2.0) + .clip_rounded(2.0) + .fill(theme::line()) + .a11y_hidden() + .child(el().h_full().w_frac(fraction).fill(if fraction >= 1.0 { + theme::muted() + } else { + theme::ink() + })) +} + +fn nav_item(s: &CoderuneApp, view: View, k: &Kit) -> El { + SidebarRow::new(view.label()) + .icon(view.icon()) + .selected(s.view == view && s.active_chat().is_none()) + .on_select(move |s: &mut CoderuneApp, _: &mut rune::Tx| s.navigate(view)) + .build(k) + .key(view.nav_key()) } fn profile_item(s: &CoderuneApp) -> El { diff --git a/crates/agents/src/cli.rs b/crates/agents/src/cli.rs index dcb1d54..7450743 100644 --- a/crates/agents/src/cli.rs +++ b/crates/agents/src/cli.rs @@ -108,7 +108,13 @@ pub struct CliAgentStatus { /// /// Shell startup can take a few seconds, so call from a background worker. pub fn detect_cli_agents() -> Vec { - detect_cli_agents_on(&SearchPath::discover()) + detect_cli_agents_with_path().0 +} + +/// Detect coding agents and supply the same PATH to their child processes. +pub fn detect_cli_agents_with_path() -> (Vec, Option) { + let path = SearchPath::discover(); + (detect_cli_agents_on(&path), path.joined().ok()) } fn detect_cli_agents_on(path: &SearchPath) -> Vec { diff --git a/crates/agents/src/lib.rs b/crates/agents/src/lib.rs index f33bf00..2ff9baa 100644 --- a/crates/agents/src/lib.rs +++ b/crates/agents/src/lib.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; mod cli; use cli::SearchPath; -pub use cli::{detect_cli_agents, CliAgentId, CliAgentStatus}; +pub use cli::{detect_cli_agents, detect_cli_agents_with_path, CliAgentId, CliAgentStatus}; use coderune_domain::{ AgentAvailability, AgentDraft, AgentId, AgentStatus, AppError, DocumentKind, ErrorCode, diff --git a/crates/app/src/lib.rs b/crates/app/src/lib.rs index ce34027..ebd8b63 100644 --- a/crates/app/src/lib.rs +++ b/crates/app/src/lib.rs @@ -4,7 +4,7 @@ //! extraction, agent detection, and OS integration, and converts infrastructure //! failures into the domain error taxonomy. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use coderune_agents::{self as agents, DraftSharingPreview}; @@ -145,6 +145,10 @@ impl Workspace { self.storage.list_captures(project_id).map_err(map_storage) } + pub fn projects_with_captures(&self) -> AppResult> { + self.storage.projects_with_captures().map_err(map_storage) + } + pub fn capture_contents(&self, capture_id: &str) -> AppResult> { self.storage .capture_contents(capture_id) diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index fc51707..7154862 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -29,7 +29,7 @@ use migration::Migrator; use sea_orm::sea_query::OnConflict; use sea_orm::{ ActiveModelTrait, ColumnTrait, ConnectionTrait, Database, DatabaseConnection, EntityTrait, - QueryFilter, QueryOrder, Set, TransactionTrait, + QueryFilter, QueryOrder, QuerySelect, Set, TransactionTrait, }; use sea_orm_migration::MigratorTrait; @@ -516,6 +516,19 @@ impl Storage { .collect() } + pub fn projects_with_captures(&self) -> Result> { + self.run(async { + let ids = capture::Entity::find() + .select_only() + .column(capture::Column::ProjectId) + .distinct() + .into_tuple::() + .all(&self.conn) + .await?; + Ok(ids.into_iter().collect()) + }) + } + pub fn capture_contents(&self, capture_id: &str) -> Result> { let files = self.run(async { capture_file::Entity::find() diff --git a/crates/ui/src/components.rs b/crates/ui/src/components.rs index 10bfa4a..db0f8d3 100644 --- a/crates/ui/src/components.rs +++ b/crates/ui/src/components.rs @@ -59,10 +59,11 @@ pub fn surface_frame(k: &Kit, fill: rune::Color, radius: f32) -> El { } /// A row's inset inside its card, and the gap between sections. -pub const ROW_PAD: f32 = 16.0; -pub const ROW_H: f32 = 48.0; -pub const ROW_H_DESCRIBED: f32 = 60.0; -pub const SECTION_GAP: f32 = 24.0; +pub const ROW_PAD: f32 = 14.0; +pub const ROW_H: f32 = 44.0; +pub const ROW_H_DESCRIBED: f32 = 56.0; +pub const SECTION_GAP: f32 = 20.0; +pub const SECTION_LABEL_GAP: f32 = 6.0; /// The page column every workspace destination stacks its sections in. pub fn page(key: &str) -> El { @@ -74,7 +75,7 @@ pub fn section(k: &Kit, key: &str, title: &str, rows: impl IntoIterator"#, }; + +pub static MESSAGE: Icon = Icon { + name: "coderune-message", + view: 24.0, + body: r#""#, +}; + +pub static PLUS: Icon = Icon { + name: "coderune-plus", + view: 24.0, + body: r#""#, +}; + +pub static PANEL_LEFT: Icon = Icon { + name: "coderune-panel-left", + view: 24.0, + body: r#""#, +}; + +pub static PANEL_RIGHT: Icon = Icon { + name: "coderune-panel-right", + view: 24.0, + body: r#""#, +}; + +pub static PANEL_FLOAT: Icon = Icon { + name: "coderune-panel-float", + view: 24.0, + body: r#""#, +}; + +pub static PANEL_HIDDEN: Icon = Icon { + name: "coderune-panel-hidden", + view: 24.0, + body: r#""#, +}; diff --git a/crates/ui/src/theme.rs b/crates/ui/src/theme.rs index efb13f2..5efd24c 100644 --- a/crates/ui/src/theme.rs +++ b/crates/ui/src/theme.rs @@ -162,25 +162,27 @@ pub fn inverse() -> Color { kit().c.text_inverse } -pub const SIDEBAR: f32 = 236.0; -pub const TOPBAR: f32 = 48.0; +pub const SIDEBAR: f32 = 264.0; +pub const TOPBAR: f32 = 44.0; pub const FRAME: f32 = 8.0; -pub const GUTTER: f32 = 32.0; -pub const CONTAINER: f32 = 1120.0; -pub const PAGE_HEADER_MAX: f32 = 720.0; +pub const GUTTER: f32 = 28.0; +pub const CONTAINER: f32 = 1080.0; +pub const PAGE_HEADER_MAX: f32 = 640.0; pub const FIELD_MAX_HEIGHT: f32 = 176.0; pub const ICON: f32 = 20.0; -pub const HEADING_LG: TextStyle = TextStyle::new(32.0, 400.0).lh(36.0); -pub const HEADING: TextStyle = TextStyle::new(24.0, 400.0).lh(28.0); -pub const HEADING_SM: TextStyle = TextStyle::new(20.0, 400.0).lh(24.0); -pub const HEADING_XS: TextStyle = TextStyle::new(16.0, 400.0).lh(20.0); -pub const BODY: TextStyle = TextStyle::new(14.0, 400.0).lh(20.0); -pub const BODY_SM: TextStyle = TextStyle::new(13.0, 400.0).lh(18.0); -pub const LABEL: TextStyle = TextStyle::new(14.0, 400.0).lh(16.0); -pub const LABEL_SM: TextStyle = TextStyle::new(12.0, 400.0).lh(16.0); -pub const CODE: TextStyle = TextStyle::new(13.0, 400.0).lh(20.0).mono(); -pub const CODE_SM: TextStyle = TextStyle::new(12.0, 400.0).lh(16.0).mono(); +/// A compact scale. Titles sit close to body size, as desktop shells do, and +/// hierarchy comes from weight and colour more than from size. +pub const HEADING_LG: TextStyle = TextStyle::new(20.0, 500.0).lh(26.0).tracking(-0.3); +pub const HEADING: TextStyle = TextStyle::new(17.0, 500.0).lh(22.0).tracking(-0.2); +pub const HEADING_SM: TextStyle = TextStyle::new(15.0, 500.0).lh(20.0).tracking(-0.1); +pub const HEADING_XS: TextStyle = TextStyle::new(13.5, 500.0).lh(18.0); +pub const BODY: TextStyle = TextStyle::new(13.0, 400.0).lh(19.0); +pub const BODY_SM: TextStyle = TextStyle::new(12.0, 400.0).lh(16.0); +pub const LABEL: TextStyle = TextStyle::new(13.0, 450.0).lh(16.0); +pub const LABEL_SM: TextStyle = TextStyle::new(11.0, 450.0).lh(14.0); +pub const CODE: TextStyle = TextStyle::new(12.0, 400.0).lh(18.0).mono(); +pub const CODE_SM: TextStyle = TextStyle::new(11.0, 400.0).lh(15.0).mono(); #[cfg(test)] mod tests { diff --git a/docs/rune/06-project-workspace.md b/docs/rune/06-project-workspace.md new file mode 100644 index 0000000..e6e4735 --- /dev/null +++ b/docs/rune/06-project-workspace.md @@ -0,0 +1,32 @@ +# Project workspace + +Home offers a new chat for the current project or a first-project action. +The sidebar lists projects and their context readiness. Select a project to +open its settings, or use its disclosure to show chats. Each open chat gets +a closable titlebar tab. The Workspace tab returns to the previous page +and project selection. + +Project settings show readiness for the folder, goals, collection scope, and +first capture. Create a project with its name, folder, and goals. Set paths +and capture limits in the Capture scope disclosure. An empty path list uses +the default collection scope. + +## Run a coding agent + +Choose an enabled agent and select **Start agent**. The agent starts in +that project's folder with its own sign-in, permissions, models, and settings. +The panel can dock left or right inside the chat or float above the composer. +Type into the terminal for interactive prompts, or use the composer to send +a line. F6 returns focus from the terminal to the panel controls. + +Each open tab keeps its own running process and draft input. Closing the tab +stops the process. Coderune saves the chat, its chosen agent, and composer +messages locally. Starting the agent again creates a fresh process. The agent +owns its session history, and Coderune keeps terminal output in memory while +the terminal stays open. + +## Verify + +Use `bun run test:desktop` for workspace navigation, chat persistence, and +terminal input tests. Use `bun run verify:ui` to render Home, Project settings, +and the docked and floating chat scenes. diff --git a/scripts/verify-ui.sh b/scripts/verify-ui.sh index c49d33a..bfddbf4 100755 --- a/scripts/verify-ui.sh +++ b/scripts/verify-ui.sh @@ -18,13 +18,13 @@ export CODERUNE_DATA_DIR="$DATA" for scene in onboarding-start onboarding-review; do "$BIN" --snap "$OUT/$scene.png" --scene "$scene" --size 1280x860 done -for scene in home profile profile-details projects documents subagents avatars capture settings storage settings-agents home-dark settings-dark settings-agents-dark settings-shortcuts; do +for scene in home profile profile-details projects documents subagents avatars capture chat chat-floating settings storage settings-agents settings-fonts home-dark settings-dark settings-agents-dark settings-shortcuts; do "$BIN" --snap "$OUT/$scene.png" --scene "$scene" --size 1280x860 done "$BIN" --snap "$OUT/home-narrow.png" --scene home --size 980x680 "$BIN" --snap "$OUT/capture-preview.png" --scene capture-preview --size 1280x860 -for file in onboarding onboarding-narrow home home-narrow profile profile-details projects documents subagents avatars capture capture-preview settings storage settings-agents home-dark settings-dark settings-agents-dark settings-shortcuts onboarding-start onboarding-review; do +for file in onboarding onboarding-narrow home home-narrow profile profile-details projects documents subagents avatars capture capture-preview chat chat-floating settings storage settings-agents settings-fonts home-dark settings-dark settings-agents-dark settings-shortcuts onboarding-start onboarding-review; do test -s "$OUT/$file.png" || { echo "missing $OUT/$file.png" >&2; exit 1; } done echo "UI snapshots written to $OUT"