diff --git a/CHANGELOG.md b/CHANGELOG.md index 1472d105..97fdb518 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,22 @@ All notable changes to Tarn are documented in this file. The format is based on ### Added +- Assistant chats are kept: each profile lists its chats to search, open, rename and delete, and + Settings › AI deletes them all. An answer can be copied and retried and its question edited; + code blocks get Copy; `/` lists the commands; the chat header picks the provider and Claude + model. On macOS and Windows, Insert into Page types an answer into the page's focused field, as + Insert Snippet does. Never in a private space, a burner tab or under Lockdown. +- Settings and the assistant are redesigned on every client: each pane has a short summary, + row actions are icon buttons with tooltips, editors open from an Add button, and empty lists say + what to do. The assistant's header names the chat and its model, the composer holds attachments + and Send or Stop, and `/` opens a command menu you can move through with the arrow keys on macOS + and Windows. +- Settings › AI: choose the Claude model (Opus 5.5, Sonnet 5.5, Haiku 5.5) and write your own + commands with `{page}`, `{selection}` and `{question}`. +- Settings › Snippets: search, and a switch for `;name` expansion in the address and command bar. +- Settings › Notes: sort by last edited or title, Ask the assistant about a note, and export all + notes as one Markdown file. + - Install with one command: `brew install --cask quavon-dev/tarn/tarn` on macOS (the cask follows each release; Tarn keeps updating itself), and on Windows `irm https://github.com/Quavon-dev/tarn-browser/releases/latest/download/install.ps1 | iex`, diff --git a/PRIVACY.md b/PRIVACY.md index 874a37fe..07e95613 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -12,7 +12,7 @@ is at https://tarnbrowser.com/privacy. History (and, only if you turn on Settings › Search › Search the text of visited pages, up to 4 KB of each visited page's text), cookies, cache, open tabs, permissions, downloads, favicons, settings, -how often and when each shortcut tip was shown, your snippets, your notes, and the Shield card's counters (tracking parameters removed, pages upgraded to HTTPS, local-network +how often and when each shortcut tip was shown, your snippets, your notes, the assistant chats you had (your questions, its answers and the addresses of the pages you attached, without query, fragment or sign-in parts, kept so content from a site you later put in Lockdown can be removed), and the Shield card's counters (tracking parameters removed, pages upgraded to HTTPS, local-network visits blocked, pages on block lists stopped, pop-ups blocked and requests blocked by the Chromium engine's filter; in total, per day for the last seven days and per site for the sites protected most) with its design value are stored only on your Mac, separately for each profile, in @@ -77,7 +77,7 @@ Settings › Privacy › Connections Tarn makes on macOS and Windows. | Theme catalog and downloads | GitHub (the repository you name, or the official catalog in `Quavon-dev/tarn-themes`, not offered yet because its signing key is not set) | Your IP address and which repository or theme you install or check | Only when you click Install, Check for Updates or Show Official Themes in Settings › Appearance, on every client; on macOS and Windows switch off with the same Settings › Privacy switch as extensions; Linux, iOS and Android have no such switch yet (themes from a file or the clipboard keep working) | | Site icon | The site you are on, or a server it already loaded from (such as its CDN, without cookies), through the tab's web engine with your Shield rules | Same as visiting the site | After a page loads over https; never under Lockdown; cleared with history | | Translation (builds with the `translation` feature) | Nobody: Apple's Translation framework runs on your Mac | Nothing. Only language packs you installed in System Settings › General › Language & Region › Translation Languages are used; Tarn never downloads one | Only when you click Translate on the banner; never under Lockdown | -| AI request (only if you enable AI) | Anthropic, or Ollama on your own computer (loopback only, never one of Ollama's cloud models) | Your question, the earlier turns of that chat and only what you attach: a page's address without query or fragment, its title and text, or a note; when you ask it to sort tabs, the host name and title of each loose web tab in the space (never a path, a local file or a home-network page) | Only when you press Send, a command or Group with Assistant, in a profile whose switch in Settings › AI is on; never from a private space, a burner tab or a Lockdown page. On macOS, Windows, Linux, iOS and Android (Ollama on macOS, Windows and Linux only) | +| AI request (only if you enable AI) | Anthropic, or Ollama on your own computer (loopback only, never one of Ollama's cloud models) | Your question, the earlier turns of that chat and only what you attach: a page's address without query or fragment, its title and text, or a note; when you ask it to sort tabs, the host name and title of each loose web tab in the space (never a path, a local file or a home-network page) | Only when you press Send, Retry, a command or Group with Assistant, in a profile whose switch in Settings › AI is on; never from a private space, a burner tab or a Lockdown page. On macOS, Windows, Linux, iOS and Android (Ollama on macOS, Windows and Linux only) | A local model makes no connection beyond your own device. "Local" means Apple's on-device model (builds with the `foundation-models` feature, on macOS and iOS; only the system's on-device model, diff --git a/crates/ai/src/markdown.rs b/crates/ai/src/markdown.rs index 1dc4b389..440c066a 100644 --- a/crates/ai/src/markdown.rs +++ b/crates/ai/src/markdown.rs @@ -3,6 +3,11 @@ use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd}; +/// The most blocks an answer draws, so output steered into thousands of tiny items cannot stall +/// the window that lays them out. +pub const MAX_BLOCKS: usize = 2_000; +const CUT: &str = "The rest of this answer is not shown."; + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct Style { pub bold: bool, @@ -156,11 +161,24 @@ pub fn parse(markdown: &str) -> Vec { } } b.flush(); + if b.blocks.len() > MAX_BLOCKS { + b.blocks.truncate(MAX_BLOCKS); + b.blocks.push(Block::Paragraph(vec![Span { text: CUT.to_owned(), style: Style::default(), link: None }])); + } b.blocks } #[cfg(test)] mod tests { + + #[test] + fn a_long_answer_draws_its_first_blocks_and_says_the_rest_is_cut() { + let blocks = parse(&"- x\n".repeat(MAX_BLOCKS * 2)); + assert_eq!(blocks.len(), MAX_BLOCKS + 1); + assert!(matches!(&blocks[MAX_BLOCKS], Block::Paragraph(spans) if spans[0].text == CUT)); + assert_eq!(parse("a\n\nb").len(), 2); + } + use super::*; fn all_spans(blocks: &[Block]) -> Vec { diff --git a/crates/ai/src/transport.rs b/crates/ai/src/transport.rs index 9f0ba87f..3a3464d9 100644 --- a/crates/ai/src/transport.rs +++ b/crates/ai/src/transport.rs @@ -97,6 +97,7 @@ mod ureq_transport { ) .http_status_as_error(false) .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(60))) .timeout_global(Some(timeout)) .build() .into() diff --git a/crates/app/src/assistant.rs b/crates/app/src/assistant.rs index 6777e908..f37a1ca9 100644 --- a/crates/app/src/assistant.rs +++ b/crates/app/src/assistant.rs @@ -1,4 +1,4 @@ -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::ops::Range; use std::rc::Rc; @@ -9,21 +9,22 @@ use std::time::{Duration, Instant}; use ai::local::Model; use ai::markdown::{Block, Span}; use browser_core::assistant::links::{self, LinkAction}; -use browser_core::assistant::settings::Provider as Choice; +use browser_core::assistant::settings::{self as ai_settings, CLAUDE_MODELS, Provider as Choice}; use browser_core::assistant::{self as core, ChatView, Effect, Event, Origin, Pill, ProfileKind, Role, Session, commands}; use browser_core::tabs::TabKey; +use gpui::ScrollHandle; use gpui::{ - AnyElement, AppContext, Context, Entity, Focusable, FontStyle, FontWeight, HighlightStyle, InteractiveElement, InteractiveText, IntoElement, ParentElement, - PromptLevel, StatefulInteractiveElement, StrikethroughStyle, Styled, StyledText, Subscription, Task, UnderlineStyle, Window, actions, div, + AnyElement, AppContext, ClipboardItem, Context, Entity, Focusable, FontStyle, FontWeight, HighlightStyle, InteractiveElement, InteractiveText, IntoElement, + ParentElement, PromptLevel, StatefulInteractiveElement, StrikethroughStyle, Styled, StyledText, Subscription, Task, UnderlineStyle, Window, actions, div, prelude::FluentBuilder, px, }; use shield::ShieldLevel; -use ui::controls::{button, field, icon_button, note, tab_stop, tooltip}; +use ui::controls::{button, caption, field, icon_button, icon_frame, note, row_action, segment, segmented, shown_on_hover, tab_stop, text_lines, tooltip}; use ui::icon::{Icon, icon}; use ui::motion::{FADE, SLIDE, progress}; use ui::text::OneLine; use ui::text_input::{TextInput, TextInputEvent}; -use ui::theme::{TEXT_SMALL, TEXT_TITLE, Theme}; +use ui::theme::{TEXT, TEXT_SMALL, TEXT_TITLE, Theme}; use url::Url; use crate::browser::{Browser, Msg}; @@ -79,7 +80,26 @@ pub(crate) struct Assistant { grouping: Option, /// Each answer row's text and its parsed blocks, parsed again only when the text changed. parsed: RefCell>, - _submit: Subscription, + /// The saved chats list is shown in place of the chat. + chats: bool, + chat_search: Entity, + rename: Entity, + renaming: Option, + /// The provider and model picker under the header is open. + models: bool, + /// The question starts with `/`, so the column lists commands. + slash: bool, + /// The command the `/` menu has selected, by its place in the menu. + slash_ix: usize, + /// The chat's rows, kept at the newest while an answer streams. + scroll: ScrollHandle, + menu_scroll: ScrollHandle, + rows_seen: Cell, + /// The saved chat's title as last read, for the header. + title: RefCell>, + /// The provider and Claude model, read again only when a setting changed. + choice: Cell>, + _inputs: [Subscription; 3], } impl Assistant { @@ -97,9 +117,49 @@ impl Assistant { pub(crate) fn new(window: &mut Window, cx: &mut Context) -> Self { let input = cx.new(|cx| TextInput::new("Ask about the pills above, or anything", cx)); - let submit = cx.subscribe_in(&input, window, |b: &mut Browser, _, event, window, cx| match event { - TextInputEvent::Submit => b.send_question(cx), + let submit = cx.subscribe_in(&input, window, |b: &mut Browser, input, event, window, cx| match event { + TextInputEvent::Submit => { + let typed = input.read(cx).text().to_owned(); + if commands::slash(&typed, &b.chat_commands()).is_some() || !b.pick_command(false, cx) { + b.send_question(cx); + } + } + TextInputEvent::Cancel if !b.slash_menu(cx).is_empty() => { + b.assistant.slash = false; + cx.notify(); + } TextInputEvent::Cancel => b.toggle_assistant(false, window, cx), + TextInputEvent::Up | TextInputEvent::Down => { + let shown = b.slash_menu(cx).len(); + if shown > 0 { + let at = b.assistant.slash_ix.min(shown - 1); + b.assistant.slash_ix = if matches!(event, TextInputEvent::Up) { at.saturating_sub(1) } else { (at + 1).min(shown - 1) }; + cx.notify(); + } + } + TextInputEvent::Changed => { + let slash = input.read(cx).text().trim_start().starts_with('/'); + b.assistant.slash_ix = 0; + if slash || b.assistant.slash { + b.assistant.slash = slash; + cx.notify(); + } + } + _ => {} + }); + let chat_search = cx.new(|cx| TextInput::new("Search chats", cx)); + let rename = cx.new(|cx| TextInput::new("Title", cx)); + let search = cx.subscribe(&chat_search, |_: &mut Browser, _, event, cx| { + if matches!(event, TextInputEvent::Changed) { + cx.notify(); + } + }); + let renamed = cx.subscribe(&rename, |b: &mut Browser, _, event, cx| match event { + TextInputEvent::Submit => b.rename_chat(cx), + TextInputEvent::Cancel => { + b.assistant.renaming = None; + cx.notify(); + } _ => {} }); Assistant { @@ -113,7 +173,19 @@ impl Assistant { picking: false, grouping: None, parsed: RefCell::default(), - _submit: submit, + chats: false, + chat_search, + rename, + renaming: None, + models: false, + slash: false, + slash_ix: 0, + scroll: ScrollHandle::new(), + menu_scroll: ScrollHandle::new(), + rows_seen: Cell::new(0), + title: RefCell::default(), + choice: Cell::default(), + _inputs: [submit, search, renamed], } } } @@ -196,6 +268,7 @@ impl Browser { if keep { return; } + self.save_chat(); self.end_run(); self.assistant.session = origin.and_then(|(o, on)| Session::new(o, on)); } @@ -279,7 +352,7 @@ impl Browser { } } - fn sync_assistant_menus(&self) { + pub(crate) fn sync_assistant_menus(&self) { self.views.keys().for_each(|key| self.sync_assistant_menu(*key)); } @@ -320,7 +393,18 @@ impl Browser { } let custom = self.core.disk.ai_commands(origin.profile).unwrap_or_default(); if let Some(template) = command.and_then(|name| commands::for_selection(&custom, &name)) { - self.send(String::new(), &template, cx); + self.send(String::new(), &template, false, cx); + } + } + + /// Opens the chat with `note` as a pill, for Settings › Notes' Ask. + pub(crate) fn ask_note(&mut self, note: &store::Note, window: &mut Window, cx: &mut Context) { + window.activate_window(); + self.toggle_assistant(true, window, cx); + if let Some((origin, true)) = self.assistant_origin() + && let Some(pill) = browser_core::notes::as_pill(note, origin.profile) + { + self.add_pill(origin, pill, cx); } } @@ -346,14 +430,59 @@ impl Browser { cx.notify(); } + /// Sends the question field; `/name rest` runs that command with `rest` as its question. fn send_question(&mut self, cx: &mut Context) { let question = self.assistant.input.read(cx).text().to_owned(); - if !question.trim().is_empty() { - self.send(question, core::ASK, cx); + if question.trim().is_empty() { + return; + } + let all = self.chat_commands(); + match commands::slash(&question, &all) { + Some((ix, rest)) => self.send(rest.to_owned(), &all[ix].1, true, cx), + None => self.send(question, core::ASK, true, cx), + } + } + + /// Built-in and the profile's own commands, as the `/` menu lists them. + fn chat_commands(&self) -> Vec<(String, String)> { + let custom = self.assistant.session.as_ref().and_then(|s| self.core.disk.ai_commands(s.profile()).ok()).unwrap_or_default(); + commands::all(&custom) + } + + /// The commands the `/` menu lists for the question field now, by their index in `chat_commands`. + fn slash_menu(&self, cx: &Context) -> Vec { + if !self.assistant.slash || self.assistant.session.as_ref().is_none_or(|s| !core::view(s).can_send) { + return Vec::new(); + } + commands::slash_menu(self.assistant.input.read(cx).text(), &self.chat_commands()) + } + + /// Runs the command the `/` menu has selected, or with `run` false writes its name into the + /// field to add a question; false while the menu is closed. + fn pick_command(&mut self, run: bool, cx: &mut Context) -> bool { + let shown = self.slash_menu(cx); + let Some(&ix) = shown.get(self.assistant.slash_ix.min(shown.len().saturating_sub(1))) else { return false }; + if run { + self.run_command(ix, cx); + } else if let Some((name, _)) = self.chat_commands().get(ix) { + let typed = format!("/{name} "); + self.assistant.input.update(cx, |i, cx| { + i.set_text(typed, cx); + i.append_selected("", cx); + }); + } + cx.notify(); + true + } + + fn run_command(&mut self, ix: usize, cx: &mut Context) { + if let Some((_, template)) = self.chat_commands().get(ix) { + self.send(String::new(), &template.clone(), true, cx); } } - fn send(&mut self, question: String, template: &str, cx: &mut Context) { + /// `from_input`: the question came from the field, which empties once it is sent. + fn send(&mut self, question: String, template: &str, from_input: bool, cx: &mut Context) { self.sync_session(); if self.assistant.session.as_ref().is_none_or(|s| !core::view(s).can_send) { return; @@ -365,19 +494,161 @@ impl Browser { let (shell, profile) = (&self.core, session.profile()); let level_of = |url: &Url| shell.level(false, profile, Some(url)).unwrap_or(ShieldLevel::Lockdown); let effects = session.send(&question, template, browser_core::now(), origin, on, level_of); - if template == core::ASK && effects.iter().any(|e| matches!(e, Effect::Start { .. })) { + if from_input && effects.iter().any(|e| matches!(e, Effect::Start { .. })) { self.assistant.input.update(cx, |i, cx| i.set_text("", cx)); } self.run_effects(effects, Some((answer, core::on_device_task(template))), cx); + self.save_chat(); + } + + /// Asks the last question again in place of its answer. + fn retry_answer(&mut self, cx: &mut Context) { + self.sync_session(); + let Some((origin, on)) = self.page_origin() else { return }; + let answer = provider(&self.core.disk); + self.assistant.connect = false; + let Some(session) = self.assistant.session.as_mut() else { return }; + let (shell, profile) = (&self.core, session.profile()); + let level_of = |url: &Url| shell.level(false, profile, Some(url)).unwrap_or(ShieldLevel::Lockdown); + let effects = session.retry(browser_core::now(), origin, on, level_of); + let on_device = session.last_was_command(); + self.run_effects(effects, Some((answer, on_device)), cx); + self.save_chat(); + } + + /// Takes the last question back into the field to change and send again. + fn edit_question(&mut self, window: &mut Window, cx: &mut Context) { + let Some(question) = self.assistant.session.as_mut().and_then(Session::edit_last) else { return }; + self.save_chat(); + self.assistant.input.update(cx, |i, cx| { + i.set_text(question, cx); + i.append_selected("", cx); + }); + window.focus(&self.assistant.input.focus_handle(cx)); + cx.notify(); } fn cancel_answer(&mut self, cx: &mut Context) { + let Some(session) = self.assistant.session.as_mut().filter(|s| core::view(s).can_cancel) else { return }; + let effects = session.apply(Event::Cancel); + self.run_effects(effects, None, cx); + self.save_chat(); + } + + /// Keeps the chat in the profile once no answer streams; the store refuses a private profile. + fn save_chat(&mut self) { + let shell = &self.core; if let Some(session) = self.assistant.session.as_mut() { - let effects = session.apply(Event::Cancel); - self.run_effects(effects, None, cx); + let profile = session.profile(); + session.save_with(&shell.disk, |url| shell.level(false, profile, Some(url)).unwrap_or(ShieldLevel::Lockdown)); } } + fn new_chat(&mut self, window: &mut Window, cx: &mut Context) { + self.cancel_answer(cx); + self.end_run(); + self.assistant.chats = false; + self.assistant.session = self.assistant_origin().and_then(|(o, on)| Session::new(o, on)); + self.assistant.input.update(cx, |i, cx| i.set_text("", cx)); + window.focus(&self.assistant.input.focus_handle(cx)); + cx.notify(); + } + + /// Continues a saved chat of the current profile, under the rules of a new one. + fn open_chat(&mut self, id: store::Id, window: &mut Window, cx: &mut Context) { + let Some((origin, on)) = self.page_origin() else { return }; + if self.assistant.session.as_ref().and_then(Session::chat) == Some(id) { + self.assistant.chats = false; + return cx.notify(); + } + self.cancel_answer(cx); + let saved = self.core.disk.chat(origin.profile, id).ok().flatten(); + let shell = &self.core; + let level_of = |url: &Url| shell.level(false, origin.profile, Some(url)).unwrap_or(ShieldLevel::Lockdown); + let Some(session) = saved.and_then(|c| Session::restore(origin, on, &c, level_of)) else { + return self.show_toast_as(browser_core::toast::Tone::Warning, "This chat could not be opened.", None, cx); + }; + self.end_run(); + self.assistant.session = Some(session); + self.save_chat(); + self.assistant.chats = false; + window.focus(&self.assistant.input.focus_handle(cx)); + cx.notify(); + } + + fn delete_chat(&mut self, id: store::Id, window: &mut Window, cx: &mut Context) { + let Some(profile) = self.assistant.session.as_ref().map(Session::profile) else { return }; + if self.core.disk.delete_chat(profile, id).is_ok() && self.assistant.session.as_ref().and_then(Session::chat) == Some(id) { + let chats = self.assistant.chats; + self.new_chat(window, cx); + self.assistant.chats = chats; + } + cx.notify(); + } + + fn start_rename(&mut self, id: store::Id, title: String, window: &mut Window, cx: &mut Context) { + self.assistant.renaming = Some(id); + self.assistant.rename.update(cx, |i, cx| { + i.set_text(title, cx); + i.select_all_from_start(cx); + }); + window.focus(&self.assistant.rename.focus_handle(cx)); + cx.notify(); + } + + fn rename_chat(&mut self, cx: &mut Context) { + let (Some(id), Some(profile)) = (self.assistant.renaming.take(), self.assistant.session.as_ref().map(Session::profile)) else { return }; + let title = self.assistant.rename.read(cx).text().to_owned(); + self.assistant.title.take(); + if let Err(e) = self.core.disk.rename_chat(profile, id, &title) { + self.show_toast_as(browser_core::toast::Tone::Warning, core::rename_problem(&e), None, cx); + } + cx.notify(); + } + + /// Ends `profile`'s chat once its saved chats are deleted, so it is not saved again. + pub(crate) fn forget_chats(&mut self, profile: store::Id, cx: &mut Context) { + if self.assistant.session.as_ref().is_some_and(|s| s.profile() == profile) { + self.end_run(); + self.assistant.session = None; + self.sync_session(); + } + cx.notify(); + } + + /// Types the last answer into the page's focused field, as Insert Snippet does. + fn insert_last_answer(&mut self, cx: &mut Context) { + if !self.chat_profile_shown() || !self.assistant_allowed() { + return; + } + if let Some(text) = self.assistant.session.as_ref().and_then(|s| s.last_answer().map(str::to_owned)) { + self.insert_answer(&text, cx); + } + } + + fn choose_model(&mut self, provider: Choice, model: Option, cx: &mut Context) { + ai_settings::set_provider(&self.core.disk, provider); + if let Some(ix) = model { + ai_settings::set_claude_model(&self.core.disk, ix); + } + self.assistant.connect = false; + crate::shared::others(cx, |_, _, cx| cx.notify()); + cx.notify(); + } + + /// The chosen provider and Claude model. + fn chosen_model(&self) -> (Choice, usize) { + let changes = self.core.disk.settings_changes(); + if let Some((seen, provider, model)) = self.assistant.choice.get() + && seen == changes + { + return (provider, model); + } + let (provider, model) = (ai_settings::provider(&self.core.disk), ai_settings::claude_model(&self.core.disk)); + self.assistant.choice.set(Some((changes, provider, model))); + (provider, model) + } + fn remove_pill(&mut self, ix: usize, cx: &mut Context) { if let Some(session) = self.assistant.session.as_mut() { let effects = session.apply(Event::RemovePill(ix)); @@ -457,6 +728,9 @@ impl Browser { self.assistant.run = None; } self.run_effects(effects, None, cx); + if !going || self.assistant.run.is_none() { + self.save_chat(); + } going } @@ -587,14 +861,17 @@ impl Browser { /// stays on this Mac where its on-device model can answer. pub(crate) fn provider(store: &store::Store) -> Answer { let transport: Arc = Arc::new(ai::UreqTransport); - match browser_core::assistant::settings::provider(store) { - Choice::ClaudeApi => Box::new(move |req, on_device, cancel, named, on_text| { - let token = ai::secrets::load_token(&ai::secrets::Keyring)?.ok_or_else(|| ai::AiError::Unavailable(core::NOT_CONNECTED.into()))?; - let api = ai::ClaudeApi::new(token, None, transport); - ai::local::answer(Model::Cloud(&api, Choice::ClaudeApi.name()), on_device_model(), on_device, req, cancel, named, on_text) - }), + match ai_settings::provider(store) { + Choice::ClaudeApi => { + let model = ai_settings::claude_model_id(store); + Box::new(move |req, on_device, cancel, named, on_text| { + let token = ai::secrets::load_token(&ai::secrets::Keyring)?.ok_or_else(|| ai::AiError::Unavailable(core::NOT_CONNECTED.into()))?; + let api = ai::ClaudeApi::new(token, Some(model), transport); + ai::local::answer(Model::Cloud(&api, Choice::ClaudeApi.name()), on_device_model(), on_device, req, cancel, named, on_text) + }) + } Choice::Ollama => { - let name = browser_core::assistant::settings::ollama_model(store); + let name = ai_settings::ollama_model(store); let label = format!("{} ({name})", Choice::Ollama.name()); let model = ai::Ollama::new(name, transport); Box::new(move |req, on_device, cancel, named, on_text| { @@ -626,9 +903,48 @@ pub(crate) fn render(b: &mut Browser, window: &mut Window, cx: &mut Context chat_list(session.profile(), session.chat(), b, window, cx), Some(session) => chat(&core::view(session), b, window, cx), None => unavailable(b, cx), }; + let saved = b.assistant.session.as_ref().is_some(); + let title = match b.assistant.session.as_ref() { + None => "Assistant".to_owned(), + Some(_) if b.assistant.chats => "Chats".to_owned(), + Some(session) => chat_title(b, session), + }; + let (provider, model) = b.chosen_model(); + let model_name = match provider { + Choice::ClaudeApi => CLAUDE_MODELS[model].1, + Choice::Ollama => "Ollama", + }; + let models = b.assistant.models; + let chip = tab_stop( + div() + .id("assistant-model") + .flex_none() + .h(px(24.)) + .pl_2p5() + .pr_1p5() + .flex() + .items_center() + .gap_1() + .rounded_full() + .border_1() + .border_color(Theme::hairline()) + .bg(if models { Theme::selected() } else { Theme::control() }) + .text_size(px(TEXT_SMALL)) + .cursor_pointer() + .hover(|s| s.bg(Theme::hover())) + .active(|s| s.bg(Theme::pressed())) + .child(model_name) + .child(icon(if models { Icon::ChevronUp } else { Icon::ChevronDown }, 10., Theme::muted())), + ) + .tooltip(tooltip("Choose the provider and model", None)) + .on_click(cx.listener(|b, _, _, cx| { + b.assistant.models = !b.assistant.models; + cx.notify(); + })); let column = div() .id("assistant") .flex_none() @@ -640,86 +956,317 @@ pub(crate) fn render(b: &mut Browser, window: &mut Window, cx: &mut Context {} + (false, true) => w.focus_prev(), + (false, false) => w.focus_next(), } cx.stop_propagation(); } - }) + })) .child( div() .h(px(ui::theme::TOOLBAR_HEIGHT)) .flex_none() - .px_3() + .pl_4() + .pr_2() .flex() .items_center() - .gap_2() - .child(icon(Icon::Sparkles, ui::icon::ICON, Theme::muted())) - .child(div().flex_1().text_size(px(TEXT_TITLE)).font_weight(FontWeight::SEMIBOLD).one_line("Assistant")) + .gap_1() + .border_b_1() + .border_color(Theme::separator()) + .child(div().flex_1().min_w_0().pr_1().text_size(px(TEXT)).font_weight(FontWeight::SEMIBOLD).one_line(title)) + .when(saved, |d| { + d.child(chip) + .child( + tab_stop(icon_button("assistant-chats", Icon::History, true)) + .when(b.assistant.chats, |d| d.bg(Theme::selected())) + .tooltip(tooltip(if b.assistant.chats { "Back to the Chat" } else { "Saved Chats" }, None)) + .on_click(cx.listener(|b, _, _, cx| { + b.assistant.chats = !b.assistant.chats; + b.assistant.renaming = None; + cx.notify(); + })), + ) + .child( + tab_stop(icon_button("assistant-new", Icon::Plus, true)) + .tooltip(tooltip("New Chat", None)) + .on_click(cx.listener(|b, _, w, cx| b.new_chat(w, cx))), + ) + }) .child( tab_stop(icon_button("assistant-close", Icon::Close, true)) .tooltip(tooltip("Close Assistant", Some("⇧Esc".into()))) .on_click(cx.listener(|b, _, w, cx| b.toggle_assistant(false, w, cx))), ), ) + .when(saved && models, |d| d.child(model_picker(provider, model, cx))) .child(body); let outer = div().flex_none().h_full().overflow_hidden(); Some(if reduce { outer.w(px(WIDTH)).opacity(shown).child(column).into_any_element() } else { outer.w(px(WIDTH * shown)).child(column).into_any_element() }) } +/// The saved chat's title, read again only when the chat changes or is renamed; "New Chat" until +/// it is saved. +fn chat_title(b: &Browser, session: &Session) -> String { + let Some(id) = session.chat() else { return "New Chat".to_owned() }; + let mut cached = b.assistant.title.borrow_mut(); + if let Some((seen, title)) = cached.as_ref() + && *seen == id + { + return title.clone(); + } + let title = b.core.disk.chat_titles(session.profile()).ok().and_then(|all| all.into_iter().find(|c| c.id == id)).map(|c| c.title); + let title = title.unwrap_or_else(|| "New Chat".to_owned()); + *cached = Some((id, title.clone())); + title +} + +/// A centred glyph, a line and what follows it, for a column with nothing to list yet. +fn centered(glyph: Icon, line: &'static str) -> gpui::Div { + div() + .flex_1() + .min_h_0() + .px_6() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap_3() + .child(div().w(px(40.)).h(px(40.)).flex().items_center().justify_center().rounded_full().bg(Theme::accent_soft()).child(icon( + glyph, + ui::icon::ICON_LARGE, + Theme::accent_text(), + ))) + .child(div().text_center().font_weight(FontWeight::SEMIBOLD).child(line)) +} + fn unavailable(b: &Browser, cx: &mut Context) -> AnyElement { - let (text, settings) = match b.assistant_origin() { + let (text, settings) = match b.page_origin() { Some((o, _)) if !core::allowed(o) => (core::NOT_HERE, false), Some(_) => ("The assistant is off for this profile. Turn it on in Settings › AI; nothing is sent until you press Send.", true), None => ("No profile is open.", false), }; + centered(Icon::Sparkles, "Assistant") + .child(div().max_w(px(260.)).text_center().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child(text)) + .when(settings, |d| d.child(open_settings_button("assistant-settings", cx))) + .into_any_element() +} + +fn open_settings_button(id: &'static str, cx: &mut Context) -> gpui::Stateful { + tab_stop(button(id, "Open Settings › AI", false)).on_click(cx.listener(|b, _, w, cx| b.open_settings_pane(SettingsPane::Ai, w, cx))) +} + +/// Where questions go, written to the same settings as Settings › AI. +fn model_picker(provider: Choice, model: usize, cx: &mut Context) -> AnyElement { + let providers = segmented().children(Choice::ALL.into_iter().enumerate().map(|(ix, choice)| { + tab_stop(segment(("assistant-provider", ix), choice.name(), choice == provider)) + .on_click(cx.listener(move |b, _, _, cx| b.choose_model(choice, None, cx))) + })); + let models = (provider == Choice::ClaudeApi).then(|| { + segmented().children(CLAUDE_MODELS.iter().enumerate().map(|(ix, (_, name))| { + tab_stop(segment(("assistant-claude-model", ix), *name, ix == model)) + .on_click(cx.listener(move |b, _, _, cx| b.choose_model(Choice::ClaudeApi, Some(ix), cx))) + })) + }); div() - .p_3() + .flex_none() + .px_4() + .py_3() .flex() .flex_col() .gap_2() - .child(note(text).pt_0()) - .when(settings, |d| d.child(open_settings_button("assistant-settings", cx))) + .text_size(px(TEXT_SMALL)) + .bg(Theme::panel_row()) + .border_b_1() + .border_color(Theme::separator()) + .child(caption("Provider")) + .child(providers) + .when_some(models, |d, models| d.child(caption("Model")).child(models)) .into_any_element() } -fn open_settings_button(id: &'static str, cx: &mut Context) -> gpui::Stateful { - tab_stop(button(id, "Open Settings › AI", false)).on_click(cx.listener(|b, _, w, cx| b.open_settings_pane(SettingsPane::Ai, w, cx))) +fn chat_list(profile: store::Id, open: Option, b: &Browser, window: &mut Window, cx: &mut Context) -> AnyElement { + let all = b.core.disk.chat_titles(profile).unwrap_or_default(); + let shown = core::find_chats(&all, b.assistant.chat_search.read(cx).text()); + let search_focused = b.assistant.chat_search.focus_handle(cx).is_focused(window); + let rename_focused = b.assistant.rename.focus_handle(cx).is_focused(window); + if all.is_empty() { + return centered(Icon::History, "No saved chats yet") + .child(div().max_w(px(240.)).text_center().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child("A chat is kept once it has an answer.")) + .into_any_element(); + } + let now = browser_core::now(); + let rows = shown.iter().enumerate().map(|(ix, chat)| { + let id = chat.id; + if b.assistant.renaming == Some(id) { + return div().py_0p5().child(field(rename_focused).child(b.assistant.rename.clone())).into_any_element(); + } + let title = chat.title.clone(); + let reveal = |control| shown_on_hover(control, "assistant-chat-row"); + div() + .group("assistant-chat-row") + .flex() + .items_center() + .gap_0p5() + .pr_1() + .rounded(px(Theme::radius_row())) + .when(open == Some(id), |d| d.bg(Theme::selected())) + .when(open != Some(id), |d| d.hover(|s| s.bg(Theme::hover()))) + .child( + tab_stop( + div() + .id(("assistant-chat", ix)) + .flex_1() + .min_w_0() + .px_2p5() + .py_1p5() + .cursor_pointer() + .child(text_lines(chat.title.clone(), browser_core::library::ago(&b.core.disk, chat.updated, now))), + ) + .on_click(cx.listener(move |b, _, w, cx| b.open_chat(id, w, cx))), + ) + .child( + reveal(row_action(("assistant-chat-rename", ix), Icon::Pencil, "Rename")) + .on_click(cx.listener(move |b, _, w, cx| b.start_rename(id, title.clone(), w, cx))), + ) + .child(reveal(row_action(("assistant-chat-delete", ix), Icon::Trash, "Delete")).on_click(cx.listener(move |b, _, w, cx| b.delete_chat(id, w, cx)))) + .into_any_element() + }); + div() + .flex_1() + .min_h_0() + .flex() + .flex_col() + .child(div().flex_none().px_3().pt_3().pb_2().child(field(search_focused).py_0p5().child(b.assistant.chat_search.clone()))) + .child( + div() + .id("assistant-chat-list") + .flex_1() + .min_h_0() + .overflow_y_scroll() + .px_2() + .pb_3() + .flex() + .flex_col() + .gap_0p5() + .when(shown.is_empty(), |d| d.child(note("No chats match.").px_2())) + .children(rows), + ) + .into_any_element() } fn chat(view: &ChatView, b: &Browser, window: &mut Window, cx: &mut Context) -> AnyElement { let me = cx.entity().downgrade(); + let last = view.rows.len().checked_sub(1); + let scroll = &b.assistant.scroll; + let streaming = view.rows.last().is_some_and(|r| r.streaming); + let at_end = scroll.max_offset().height + scroll.offset().y <= px(48.); + if b.assistant.rows_seen.replace(view.rows.len()) != view.rows.len() || (streaming && at_end) { + scroll.scroll_to_bottom(); + } let rows = view .rows .iter() .enumerate() - .map(|(ix, row)| match row.role { - Role::You => div() - .ml_auto() - .max_w(px(WIDTH - 48.)) - .px_3() - .py_2() - .rounded(px(Theme::radius_row())) - .bg(Theme::accent_soft()) - .child(row.text.clone()) - .into_any_element(), - Role::Assistant => { - let blocks = b.assistant.blocks(ix, &row.text); - let mut answer = div().flex().flex_col().gap_2().children(markdown(&blocks, ix, &me)); - if row.streaming { - answer = answer.child(ui::controls::spinner(ui::icon::ICON_SMALL, Theme::muted())); - } else { - answer = answer.children(link_list(&blocks, ix, cx)); + .map(|(ix, row)| { + let is_last = Some(ix) == last; + let actions = (!row.streaming && !view.can_cancel).then(|| turn_actions(ix, row, is_last, cx)).flatten(); + let turn = div().group("assistant-turn").flex().flex_col(); + match row.role { + Role::You => turn + .items_end() + .gap_1() + .child(div().max_w(px(WIDTH * 0.82)).px_3().py_2().rounded(px(Theme::radius_group())).bg(Theme::accent_soft()).child(row.text.clone())) + .children(actions) + .into_any_element(), + Role::Assistant => { + let blocks = b.assistant.blocks(ix, &row.text); + let mut answer = turn.gap_2().children(markdown(&blocks, ix, &me)); + if row.streaming { + answer = answer.child(ui::controls::spinner(ui::icon::ICON_SMALL, Theme::muted())); + } else { + answer = answer.children(link_list(&blocks, ix, cx)); + } + let by = row.by.clone().map(|by| div().flex_1().min_w_0().text_size(px(TEXT_SMALL)).text_color(Theme::faint()).one_line(by)); + answer + .when(by.is_some() || actions.is_some(), |d| { + d.child(div().flex().items_center().gap_1().children(actions).child(div().flex_1()).children(by.map(|by| by.flex_initial()))) + }) + .into_any_element() } - answer.children(row.by.clone().map(|by| note(by).pt_0())).into_any_element() } }) .collect::>(); + let typed = b.assistant.input.read(cx).text().to_owned(); + let commands = if b.assistant.slash { b.chat_commands() } else { Vec::new() }; + let menu = commands::slash_menu(&typed, &commands); + let selected = b.assistant.slash_ix.min(menu.len().saturating_sub(1)); + b.assistant.menu_scroll.scroll_to_item(selected); + let menu = (!menu.is_empty()).then(|| { + let enter = if cfg!(windows) { "Enter" } else { "Return" }; + popover_card() + .absolute() + .bottom_full() + .left_3() + .right_3() + .mb_1() + .p_1() + .flex() + .flex_col() + .child( + div().id("assistant-commands").track_scroll(&b.assistant.menu_scroll).max_h(px(280.)).overflow_y_scroll().flex().flex_col().gap_0p5().children( + menu.into_iter().enumerate().map(|(at, ix)| { + let (name, template) = &commands[ix]; + tab_stop( + div() + .id(("assistant-command", ix)) + .px_2() + .py_1p5() + .flex() + .flex_col() + .rounded(px(Theme::radius_small())) + .cursor_pointer() + .when(at == selected, |d| d.bg(Theme::selected())) + .when(at != selected, |d| d.hover(|s| s.bg(Theme::hover()))) + .child(div().font_weight(FontWeight::MEDIUM).one_line(format!("/{name}"))) + .child(div().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).one_line(template.clone())), + ) + .on_click({ + let typed = format!("/{name} "); + let picked = name.clone(); + cx.listener(move |b, _, _, cx| { + if !b.chat_commands().iter().any(|(n, _)| *n == picked) { + b.assistant.slash = false; + return cx.notify(); + } + b.assistant.input.update(cx, |i, cx| { + i.set_text(typed.clone(), cx); + i.append_selected("", cx); + }); + cx.notify(); + }) + }) + }), + ), + ) + .child( + div() + .px_2() + .pt_1p5() + .pb_1() + .mt_1() + .border_t_1() + .border_color(Theme::separator()) + .text_size(px(ui::theme::TEXT_TINY)) + .text_color(Theme::muted()) + .child(format!("{enter} runs · Tab completes · Esc closes")), + ) + }); let picker = b.assistant.picking.then(|| tab_picker(b, cx)); let chips = view .chips @@ -731,15 +1278,20 @@ fn chat(view: &ChatView, b: &Browser, window: &mut Window, cx: &mut Context gpui::Div { + ui::controls::surface(Theme::radius_row()).occlude().shadow(ui::theme::Elevation::Popover.shadow()) +} + +/// What an empty chat shows: how sending works, and commands to start from. A suggestion only +/// fills the question field; nothing is sent until Send. +fn empty_chat(cx: &mut Context) -> AnyElement { + centered(Icon::Sparkles, "Ask about this page, or anything") + .child( + div() + .max_w(px(260.)) + .text_center() + .text_size(px(TEXT_SMALL)) + .text_color(Theme::muted()) + .child("Nothing leaves this computer until you press Send. Type / for commands, or start with one:"), + ) + .child(div().pt_1().flex().flex_wrap().justify_center().gap_1p5().children(commands::BUILT_IN.iter().enumerate().map(|(ix, (name, _))| { + tab_stop( + div() + .id(("assistant-suggest", ix)) + .h(px(26.)) + .px_3() + .flex() + .items_center() + .rounded_full() + .border_1() + .border_color(Theme::hairline()) + .bg(Theme::control()) + .text_size(px(TEXT_SMALL)) + .cursor_pointer() + .hover(|s| s.bg(Theme::hover())) + .active(|s| s.bg(Theme::pressed())) + .child(*name), + ) + .on_click(cx.listener(move |b, _, w, cx| { + b.assistant.input.update(cx, |i, cx| { + i.set_text(format!("/{name} "), cx); + i.append_selected("", cx); + }); + w.focus(&b.assistant.input.focus_handle(cx)); + cx.notify(); + })) + }))) + .into_any_element() +} + +/// Copy on every answer; on the last turn also Retry and Edit Question, and Insert into Page for +/// an answer. Earlier turns show theirs while the pointer is over the turn. +fn turn_actions(ix: usize, row: &core::Row, last: bool, cx: &mut Context) -> Option { + let answer = row.role == Role::Assistant && !row.text.is_empty() && row.text != core::FORGOTTEN; + if !answer && !last { + return None; + } + let text = row.text.clone(); + let action = |id: &'static str, glyph: Icon, tip: &'static str| { + let button = row_action((id, ix), glyph, tip); + if last { button } else { shown_on_hover(button, "assistant-turn") } + }; + Some( + div() + .flex() + .gap_0p5() + .when(answer, |d| { + d.child(action("assistant-copy", Icon::Copy, "Copy").on_click(move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string(text.clone())))) + }) + .when(last, |d| { + d.child(action("assistant-retry", Icon::Reload, "Retry").on_click(cx.listener(|b, _, _, cx| b.retry_answer(cx)))) + .child(action("assistant-edit", Icon::Pencil, "Edit Question").on_click(cx.listener(|b, _, w, cx| b.edit_question(w, cx)))) + }) + .when(last && answer, |d| { + d.child(action("assistant-insert", Icon::FileDown, "Insert into Page").on_click(cx.listener(|b, _, _, cx| b.insert_last_answer(cx)))) + }), + ) +} + /// The current space's other tabs the assistant may read; a sleeping one is shown but cannot be /// chosen, since adding it would load its page. fn tab_picker(b: &Browser, cx: &Context) -> AnyElement { @@ -900,14 +1553,22 @@ fn markdown(blocks: &[Block], row: usize, me: &gpui::WeakEntity) -> Vec Block::Quote(spans) => { div().pl_2().border_l_2().border_color(Theme::separator()).text_color(Theme::muted()).child(spans_text(id, spans, me)).into_any_element() } - Block::Code { code, .. } => div() - .p_2() - .rounded(px(Theme::radius_small())) - .bg(Theme::control()) - .font_family(ui::theme::MONO_FONT) - .text_size(px(TEXT_SMALL)) - .child(code.trim_end().to_owned()) - .into_any_element(), + Block::Code { code, .. } => { + let copied = code.clone(); + div() + .flex() + .gap_1() + .p_2() + .rounded(px(Theme::radius_small())) + .bg(Theme::control()) + .child(div().flex_1().min_w_0().font_family(ui::theme::MONO_FONT).text_size(px(TEXT_SMALL)).child(copied.trim_end().to_owned())) + .child( + tab_stop(icon_button(("assistant-code-copy", row * 10_000 + ix), Icon::Copy, true)) + .tooltip(tooltip("Copy Code", None)) + .on_click(move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new_string(copied.clone()))), + ) + .into_any_element() + } Block::Rule => div().h(px(1.)).bg(Theme::separator()).into_any_element(), } }) diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index a4aea8e8..c5f791d7 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -60,36 +60,81 @@ pub enum SettingsPane { Ai, } -const PANES: [(SettingsPane, Icon, &str, &str); 14] = [ - (SettingsPane::Profile, Icon::Shield, "Protection", "shield level standard strict lockdown card filter lists site overrides connections default browser"), - (SettingsPane::Profiles, Icon::Person, "Profiles", "profile new edit delete space rules"), - (SettingsPane::General, Icon::Gear, "General", "updates nightly web engine chromium webkit downloads import about version licence source privacy imprint"), +const PANES: [(SettingsPane, Icon, &str, &str, &str); 14] = [ + ( + SettingsPane::Profile, + Icon::Shield, + "Protection", + "Shield level, what it blocked and the default browser.", + "shield level standard strict lockdown card filter lists site overrides connections default browser", + ), + (SettingsPane::Profiles, Icon::Person, "Profiles", "Your profiles and the rules that open sites in a space.", "profile new edit delete space rules"), + ( + SettingsPane::General, + Icon::Gear, + "General", + "Updates, web engine, downloads, import and this version.", + "updates nightly web engine chromium webkit downloads import about version licence source privacy imprint", + ), ( SettingsPane::Appearance, Icon::Palette, "Appearance", + "Theme, accent colour, motion and layout.", "theme dark light match system accent colour color motion reduce toolbar compact density sidebar search bar effect tips", ), ( SettingsPane::Tabs, Icon::AppWindow, "Tabs", + "When tabs sleep, close and open.", "awake sleep memory new tab start page close archive gestures swipe trackpad touchpad drag tear off temporary full window", ), - (SettingsPane::Search, Icon::Search, "Search", "search engine suggestions history text shortcuts bangs"), + (SettingsPane::Search, Icon::Search, "Search", "Search engine and suggestions.", "search engine suggestions history text shortcuts bangs"), ( SettingsPane::Privacy, Icon::Hand, "Privacy", + "Blocking, what sites keep and your data.", "block ads trackers cookie banners youtube pop-ups malware adult zoom muted hidden elements connections history clear export delete data localhost passkeys security keys sign-in", ), - (SettingsPane::Permissions, Icon::Camera, "Permissions", "camera microphone location pop-ups site answers allow block"), - (SettingsPane::Ai, Icon::Sparkles, "AI", "assistant chat claude api key ollama model connect disconnect ask"), - (SettingsPane::Developer, Icon::Code, "Developer", "web inspector developer tools profile local servers localhost"), - (SettingsPane::Extensions, Icon::Braces, "Extensions", "install github file bitwarden every site official catalog store updates"), - (SettingsPane::Snippets, Icon::FileText, "Snippets", "text expansion insert templates signature"), - (SettingsPane::Notes, Icon::Pencil, "Notes", "notes write search ideas assistant"), - (SettingsPane::Shortcuts, Icon::Keyboard, "Shortcuts", "keyboard keys"), + ( + SettingsPane::Permissions, + Icon::Camera, + "Permissions", + "Your answers to sites that asked for a device or pop-ups.", + "camera microphone location pop-ups site answers allow block", + ), + ( + SettingsPane::Ai, + Icon::Sparkles, + "AI", + "The assistant, where questions go, commands and chats.", + "assistant chat chats claude api key ollama model connect disconnect ask commands prompts", + ), + ( + SettingsPane::Developer, + Icon::Code, + "Developer", + "Web Inspector, the developer profile and local servers.", + "web inspector developer tools profile local servers localhost", + ), + ( + SettingsPane::Extensions, + Icon::Braces, + "Extensions", + "Installed extensions, their access and new ones.", + "install github file bitwarden every site official catalog store updates", + ), + (SettingsPane::Snippets, Icon::FileText, "Snippets", "Short names that expand into longer text.", "text expansion expand insert templates signature"), + ( + SettingsPane::Notes, + Icon::Pencil, + "Notes", + "Your notes, to search, sort, export and ask about.", + "notes write search sort export markdown ideas assistant", + ), + (SettingsPane::Shortcuts, Icon::Keyboard, "Shortcuts", "Keyboard shortcuts, and keys you set yourself.", "keyboard keys"), ]; fn pane_matches(query: &str, name: &str, words: &str) -> bool { @@ -130,6 +175,37 @@ fn heading(title: impl Into, action: impl IntoElement) -> Div { section(title).flex().items_center().justify_between().gap_3().child(action) } +fn warning(text: impl Into) -> Div { + note(text).text_color(Theme::warning()) +} + +fn search_field(input: &gpui::Entity, focused: bool) -> Div { + div().child(field(focused).w(px(320.)).py_0p5().child(input.clone())) +} + +type Click = Box; + +/// A list editor's buttons: Cancel, then Save while an item is edited or Add. +fn editor_actions(id: &'static str, editing: bool, cancel: Click, save: Click) -> Div { + div() + .pt_2() + .flex() + .justify_end() + .gap_2() + .child(tab_stop(button((id, 0usize), "Cancel", false)).on_click(cancel)) + .child(tab_stop(button((id, 1usize), if editing { "Save" } else { "Add" }, true)).on_click(save)) +} + +/// One labelled field of a list editor. +fn editor_row(first: bool, name: &'static str, input: &gpui::Entity, focused: bool) -> Div { + row(first).child(div().w(px(64.)).flex_none().text_color(Theme::muted()).child(name)).child(field(focused).flex_1().min_w_0().py_0p5().child(input.clone())) +} + +/// A list's title with its Add button, which opens the list's editor. +fn list_heading(title: &'static str, add: Option>) -> Div { + heading(title, div().h(px(26.)).children(add)) +} + fn licenses() -> Option { static PATH: std::sync::LazyLock> = std::sync::LazyLock::new(|| { let exe = std::env::current_exe().ok()?; @@ -179,6 +255,9 @@ struct Snapshot { burner: bool, ai_provider: browser_core::assistant::settings::Provider, ollama_model: String, + claude_model: usize, + ai_commands: Vec, + chats: usize, overrides: Vec<(String, ShieldLevel)>, zooms: Vec<(String, f64)>, muted: Vec, @@ -377,6 +456,15 @@ impl SettingsWindow { burner: b.model.burner_shown(), ai_provider: browser_core::assistant::settings::provider(&b.core.disk), ollama_model: if self.pane == SettingsPane::Ai { browser_core::assistant::settings::ollama_model(&b.core.disk) } else { String::new() }, + claude_model: if self.pane == SettingsPane::Ai { browser_core::assistant::settings::claude_model(&b.core.disk) } else { 0 }, + ai_commands: match (self.pane, b.model.profile()) { + (SettingsPane::Ai, Some((false, id))) => b.core.disk.ai_commands(id).unwrap_or_default(), + _ => Vec::new(), + }, + chats: match (self.pane, b.model.profile()) { + (SettingsPane::Ai, Some((false, id))) => b.core.disk.chat_titles(id).map(|c| c.len()).unwrap_or_default(), + _ => 0, + }, overrides: if matches!(self.pane, SettingsPane::Privacy | SettingsPane::Profile) { b.site_overrides() } else { Vec::new() }, zooms: if self.pane == SettingsPane::Privacy { b.site_zooms() } else { Vec::new() }, muted: if self.pane == SettingsPane::Privacy { b.muted_sites() } else { Vec::new() }, @@ -466,7 +554,7 @@ impl SettingsWindow { fn found_panes(&self, cx: &App) -> Vec { let query = self.search.read(cx).text(); - PANES.iter().filter(|(_, _, name, words)| pane_matches(query, name, words)).map(|(pane, ..)| *pane).collect() + PANES.iter().filter(|(_, _, name, _, words)| pane_matches(query, name, words)).map(|(pane, ..)| *pane).collect() } fn on_search(&mut self, event: &TextInputEvent, cx: &mut Context) { @@ -612,7 +700,7 @@ impl Render for SettingsWindow { .window_control_area(gpui::WindowControlArea::Drag) .child(field(search_focused).mb_1().occlude().py_0p5().child(self.search.clone())) .when(found.is_empty(), |d| d.child(note("No settings match.").px_2())) - .children(PANES.iter().enumerate().filter(|(_, (pane, ..))| found.contains(pane)).flat_map(|(ix, &(pane, glyph, text, _))| { + .children(PANES.iter().enumerate().filter(|(_, (pane, ..))| found.contains(pane)).flat_map(|(ix, &(pane, glyph, text, ..))| { let selected = pane == current; let group = match ix { _ if searching => None, @@ -672,7 +760,7 @@ impl Render for SettingsWindow { (SettingsPane::Shortcuts, Some(_)) => self.shortcuts(cx), (SettingsPane::Ai, Some(s)) => self.ai(&s, window, cx), }; - let name = PANES.iter().find(|(p, ..)| *p == current).map_or("", |(_, _, t, _)| *t); + let (name, subtitle) = PANES.iter().find(|(p, ..)| *p == current).map_or(("", ""), |(_, _, t, sub, _)| (*t, *sub)); let content = div() .flex_1() @@ -682,16 +770,23 @@ impl Render for SettingsWindow { .flex_col() .child( div() - .h(px(HEADER_HEIGHT)) + .h(px(PANE_HEADER_HEIGHT)) .flex_none() .px_8() .flex() .items_center() .border_b_1() .border_color(Theme::separator()) - .text_size(px(TEXT_TITLE)) - .font_weight(FontWeight::SEMIBOLD) - .child(div().flex_1().one_line(name)) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap_0p5() + .child(div().text_size(px(TEXT_TITLE)).font_weight(FontWeight::SEMIBOLD).one_line(name)) + .child(div().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).one_line(subtitle)), + ) .when(cfg!(windows), |d| { d.pr_2().window_control_area(gpui::WindowControlArea::Drag).child(div().flex_1()).children(ui::controls::window_controls()) }), @@ -702,7 +797,7 @@ impl Render for SettingsWindow { .flex_1() .min_h_0() .overflow_y_scroll() - .child(div().w_full().max_w(px(CONTENT_WIDTH)).mx_auto().px_8().pt_1().pb_8().child(body)), + .child(div().w_full().max_w(px(CONTENT_WIDTH)).mx_auto().px_8().pb_10().child(body)), name, reduce, )); @@ -772,6 +867,7 @@ fn default_browser() -> Option { const SIDEBAR_WIDTH: f32 = 196.; /// Tall enough to clear the traffic lights, which sit 18 pt from the top. const HEADER_HEIGHT: f32 = 52.; +const PANE_HEADER_HEIGHT: f32 = 64.; const CONTENT_WIDTH: f32 = 760.; impl SettingsWindow { @@ -864,11 +960,13 @@ impl SettingsWindow { } fn link_row(&self, id: &'static str, title: &'static str, detail: &'static str, url: &'static str, cx: &mut Context) -> Div { - row(false).child(text_block(title, detail)).child(button(id, "Open", false).on_click(cx.listener(move |this, _, _, cx| { - if let Ok(url) = url::Url::parse(url) { - this.with_browser(cx, |b, w, cx| b.new_tab(&url, w, cx)); - } - }))) + row(false).child(text_block(title, detail)).child(ui::controls::row_action(id, Icon::ExternalLink, "Open").on_click(cx.listener( + move |this, _, _, cx| { + if let Ok(url) = url::Url::parse(url) { + this.with_browser(cx, |b, w, cx| b.new_tab(&url, w, cx)); + } + }, + ))) } fn web_engine_row(&self, s: &Snapshot, cx: &mut Context) -> Div { @@ -1079,8 +1177,9 @@ mod tests { #[test] fn search_finds_panes_by_word_starts() { - let found = - |q: &str| super::PANES.iter().filter(|(_, _, name, words)| super::pane_matches(q, name, words)).map(|(_, _, name, _)| *name).collect::>(); + let found = |q: &str| { + super::PANES.iter().filter(|(_, _, name, _, words)| super::pane_matches(q, name, words)).map(|(_, _, name, ..)| *name).collect::>() + }; assert_eq!(found("lockd"), ["Protection"]); assert_eq!(found("COOKIE ban"), ["Privacy"]); assert_eq!(found("density"), ["Appearance"]); diff --git a/crates/app/src/settings/ai.rs b/crates/app/src/settings/ai.rs index 08d39361..536304e1 100644 --- a/crates/app/src/settings/ai.rs +++ b/crates/app/src/settings/ai.rs @@ -1,12 +1,18 @@ -use browser_core::assistant::settings::{self as ai_settings, Provider}; -use gpui::{AnyElement, AppContext, Context, Entity, Focusable, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Subscription, Window, div}; +use browser_core::assistant::commands::BUILT_IN; +use browser_core::assistant::settings::{self as ai_settings, CLAUDE_MODELS, Provider}; +use gpui::{AnyElement, AppContext, Context, Entity, Focusable, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Subscription, Window, div, px}; use shield::ShieldLevel; -use ui::controls::{button, field, group, note, row, section, segment, segmented, switch_row, tab_stop, text_block, wide_row}; +use store::{AiCommand, Id}; +use ui::controls::{ + button, empty_state, field, group, icon_text_button, leading_icon, note, row, row_action, section, segment, segmented, switch_row, tab_stop, text_block, + text_lines, wide_row, +}; +use ui::icon::Icon; use ui::text::bounded_title; use ui::text_input::{TextInput, TextInputEvent}; -use ui::theme::Theme; +use ui::theme::{TEXT_SMALL, Theme}; -use super::{SettingsWindow, Snapshot, label, value}; +use super::{SettingsWindow, Snapshot, editor_actions, editor_row, label, list_heading, value, warning}; pub(super) struct Pane { token: Entity, @@ -14,13 +20,39 @@ pub(super) struct Pane { /// Whether the secret store holds a token; `None` until a background read answers. connected: Option, message: Option, - _subscriptions: [Subscription; 2], + command_name: Entity, + command_template: Entity, + editing: Option, + /// The profile the command being edited belongs to. + editing_in: Option, + /// The editor for a new command is open. + adding: bool, + command_error: Option, + chats_error: Option, + _subscriptions: [Subscription; 4], +} + +fn placeholders() -> String { + format!( + "In a command's text, {{page}} stands for the page, {{selection}} for the selected text and {{question}} for what you type after it. A selection's menu lists the first {} commands.", + engine::view_policy::MAX_MENU_COMMANDS + ) } impl Pane { pub(super) fn new(cx: &mut Context) -> Pane { let token = cx.new(|cx| TextInput::new("Claude API key", cx).masked()); let model = cx.new(|cx| TextInput::new(ai_settings::DEFAULT_OLLAMA_MODEL, cx)); + let command_name = cx.new(|cx| TextInput::new("Name", cx)); + let command_template = cx.new(|cx| TextInput::new("Rewrite {selection} as a haiku. {question}", cx)); + let submit = |this: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| match event { + TextInputEvent::Submit => this.save_command(cx), + TextInputEvent::Cancel => { + this.clear_command_editor(cx); + cx.notify(); + } + _ => {} + }; let subscriptions = [ cx.subscribe(&token, |this: &mut SettingsWindow, _, event, cx| { if matches!(event, TextInputEvent::Submit) { @@ -32,6 +64,8 @@ impl Pane { this.save_model(cx); } }), + cx.subscribe(&command_name, submit), + cx.subscribe(&command_template, submit), ]; cx.spawn(async move |this, cx| { let found = cx.background_spawn(async { ai::secrets::load_token(&ai::secrets::Keyring).ok().flatten().is_some() }).await; @@ -42,7 +76,20 @@ impl Pane { .ok(); }) .detach(); - Pane { token, model, connected: None, message: None, _subscriptions: subscriptions } + Pane { + token, + model, + connected: None, + message: None, + command_name, + command_template, + editing: None, + editing_in: None, + adding: false, + command_error: None, + chats_error: None, + _subscriptions: subscriptions, + } } } @@ -54,10 +101,17 @@ impl SettingsWindow { return; } self.ai.token.update(cx, |t, cx| t.set_text("", cx)); - let stored = ai::secrets::store_token(&ai::secrets::Keyring, &ai::ApiToken::new(key)); - self.ai.message = stored.as_ref().err().map(|e| format!("Could not store the key: {e}.")); - self.ai.connected = Some(stored.is_ok()); - cx.notify(); + let token = ai::ApiToken::new(key); + cx.spawn(async move |this, cx| { + let stored = cx.background_spawn(async move { ai::secrets::store_token(&ai::secrets::Keyring, &token).map_err(|e| e.to_string()) }).await; + this.update(cx, |this, cx| { + this.ai.message = stored.as_ref().err().map(|e| format!("Could not store the key: {e}.")); + this.ai.connected = Some(stored.is_ok()); + cx.notify(); + }) + .ok(); + }) + .detach(); } fn disconnect(&mut self, cx: &mut Context) { @@ -75,32 +129,163 @@ impl SettingsWindow { cx.notify(); } + fn save_command(&mut self, cx: &mut Context) { + let Some(profile) = self.saved_profile(cx) else { return }; + if self.ai.editing_in.is_some_and(|p| p != profile) { + self.ai.command_error = Some("This command belongs to another profile. Open Settings from one of its spaces to save it.".to_owned()); + return cx.notify(); + } + let pane = &self.ai; + let (name, template) = (pane.command_name.read(cx).text().trim().to_owned(), pane.command_template.read(cx).text().to_owned()); + let core = crate::shared::core(cx); + let customs = core.disk.ai_commands(profile).unwrap_or_default(); + if let Err(problem) = browser_core::assistant::commands::check(&name, &template, &customs, pane.editing) { + self.ai.command_error = Some(problem); + return cx.notify(); + } + let saved = match pane.editing { + Some(id) => core.disk.update_ai_command(profile, id, &name, &template), + None => core.disk.create_ai_command(profile, &name, &template).map(drop), + }; + match saved { + Ok(()) => { + self.clear_command_editor(cx); + commands_changed(cx); + } + Err(e) => self.ai.command_error = Some(e.to_string()), + } + cx.notify(); + } + + fn clear_command_editor(&mut self, cx: &mut Context) { + self.ai.editing = None; + self.ai.editing_in = None; + self.ai.adding = false; + self.ai.command_error = None; + self.ai.command_name.update(cx, |i, cx| i.set_text("", cx)); + self.ai.command_template.update(cx, |i, cx| i.set_text("", cx)); + } + + fn edit_command(&mut self, command: AiCommand, window: &mut Window, cx: &mut Context) { + self.ai.command_name.update(cx, |i, cx| i.set_text(command.name.clone(), cx)); + self.ai.command_template.update(cx, |i, cx| i.set_text(command.template.clone(), cx)); + window.focus(&self.ai.command_template.focus_handle(cx)); + self.ai.editing = Some(command.id); + self.ai.editing_in = Some(command.profile_id); + self.ai.command_error = None; + cx.notify(); + } + + fn delete_command(&mut self, profile: Id, id: Id, cx: &mut Context) { + if crate::shared::core(cx).disk.delete_ai_command(profile, id).is_ok() { + if self.ai.editing == Some(id) { + self.clear_command_editor(cx); + } + commands_changed(cx); + } + cx.notify(); + } + + fn delete_chats(&mut self, profile: Id, window: &mut Window, cx: &mut Context) { + let detail = "Every chat saved for this profile is deleted from this computer. This cannot be undone."; + self.ask("Delete all chats?", Some(detail), &["Delete All Chats"], window, cx, move |this, _, cx| { + match crate::shared::core(cx).disk.delete_chats(profile) { + Ok(()) => { + this.ai.chats_error = None; + crate::shared::each(cx, |b, _, cx| b.forget_chats(profile, cx)); + } + Err(e) => this.ai.chats_error = Some(format!("Could not delete the chats: {e}.")), + } + cx.notify(); + }); + } + + fn add_command(&mut self, window: &mut Window, cx: &mut Context) { + self.clear_command_editor(cx); + self.ai.adding = true; + window.focus(&self.ai.command_name.focus_handle(cx)); + cx.notify(); + } + + fn commands(&self, s: &Snapshot, profile: Id, window: &mut Window, cx: &mut Context) -> gpui::Div { + let tag = || div().flex_none().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child("Built in"); + let built_in = BUILT_IN.iter().enumerate().map(|(ix, (name, template))| row(ix == 0).child(text_lines(*name, *template)).child(tag())); + let custom = s.ai_commands.iter().enumerate().map(|(ix, command)| { + let (id, edit) = (command.id, command.clone()); + row(false) + .child(text_lines(command.name.clone(), command.template.clone())) + .child( + row_action(("command-edit", ix), Icon::Pencil, "Edit") + .on_click(cx.listener(move |this, _, window, cx| this.edit_command(edit.clone(), window, cx))), + ) + .child( + row_action(("command-delete", ix), Icon::Trash, "Delete").on_click(cx.listener(move |this, _, _, cx| this.delete_command(profile, id, cx))), + ) + }); + let pane = &self.ai; + let editing = pane.editing.is_some(); + let open = editing || pane.adding; + let add = (!open) + .then(|| icon_text_button("command-add", Icon::Plus, "Add Command").on_click(cx.listener(|this, _, window, cx| this.add_command(window, cx)))); + let page = div().child(list_heading("Commands", add)).child(group().children(built_in).children(custom)); + if !open { + return page; + } + let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); + let actions = editor_actions( + "command-editor", + editing, + Box::new(cx.listener(|this, _, _, cx| { + this.clear_command_editor(cx); + cx.notify(); + })), + Box::new(cx.listener(|this, _, _, cx| this.save_command(cx))), + ); + page.child(section(if editing { "Edit command" } else { "New command" })) + .child(group().child(editor_row(true, "Name", &pane.command_name, focused(&pane.command_name))).child(editor_row( + false, + "Text", + &pane.command_template, + focused(&pane.command_template), + ))) + .child(note(placeholders())) + .children(pane.command_error.clone().map(warning)) + .child(actions) + } + pub(super) fn ai(&mut self, s: &Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { - let Some(profile) = s.profile.clone() else { return note("No profile is open.").into_any_element() }; - if s.private || s.burner || profile.shield_level == ShieldLevel::Lockdown { - return div().child(section("Assistant")).child(note(browser_core::assistant::NOT_HERE)).into_any_element(); + let Some(profile) = s.profile.clone() else { return div().pt_6().child(empty_state(Icon::Person, "No profile is open.")).into_any_element() }; + if s.private || s.burner { + return div().pt_6().child(empty_state(Icon::Lock, browser_core::assistant::NOT_HERE)).into_any_element(); + } + if profile.shield_level == ShieldLevel::Lockdown { + return div().pt_6().child(empty_state(Icon::Lock, browser_core::assistant::NOT_HERE)).child(self.chats(s, profile.id, cx)).into_any_element(); } let provider = s.ai_provider; let on = profile.ai_enabled; let id = profile.id; - let mut page = div() - .child(section("Assistant")) - .child( - group().child( - switch_row( - "ai-enabled", - true, - text_block(format!("Assistant for {}", bounded_title(&profile.name)), "Each profile has its own switch; it starts off."), - on, - ) - .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_profile_ai(id, !on, cx)))), - ), - ) - .child(note(browser_core::assistant::SENT)); + let mut page = + div() + .child(section("Assistant")) + .child( + group().child( + switch_row( + "ai-enabled", + true, + div().flex_1().min_w_0().flex().items_center().gap_3().child(leading_icon(Icon::Sparkles)).child(text_block( + format!("Assistant for {}", bounded_title(&profile.name)), + "Each profile has its own switch; it starts off.", + )), + on, + ) + .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.set_profile_ai(id, !on, cx)))), + ), + ) + .child(note(browser_core::assistant::SENT)); if !on { - return page.into_any_element(); + return page.child(self.chats(s, id, cx)).into_any_element(); } - page = page.child(section("Provider")).child(group().child(wide_row( + let providers = wide_row( true, text_block("Where questions go", "Only after you press Send."), segmented().children(Provider::ALL.into_iter().enumerate().map(|(ix, choice)| { @@ -111,44 +296,83 @@ impl SettingsWindow { cx.notify(); })) })), - ))); + ); + page = page.child(section("Provider")); page = match provider { Provider::ClaudeApi => { let connected = self.ai.connected.unwrap_or(false); let account = if connected { - row(true) + row(false) + .child(leading_icon(Icon::KeyRound)) .child(label("Claude API key")) .child(value("Connected")) .child(tab_stop(button("ai-disconnect", "Disconnect", false)).on_click(cx.listener(|this, _, _, cx| this.disconnect(cx)))) } else { let focused = self.ai.token.focus_handle(cx).is_focused(window); - row(true) - .child(div().flex_1().child(field(focused).child(self.ai.token.clone()))) + row(false) + .child(leading_icon(Icon::KeyRound)) + .child(div().flex_1().child(field(focused).py_0p5().child(self.ai.token.clone()))) .child(tab_stop(button("ai-connect", "Connect", true)).on_click(cx.listener(|this, _, _, cx| this.connect(cx)))) }; - page.child(section("Claude API")) - .child(group().child(account)) - .child(note(if cfg!(windows) { - "The key is kept in Windows Credential Manager, never in Tarn's settings or database. Questions go to api.anthropic.com over HTTPS. Disconnect deletes the key." - } else { - "The key is kept in the Keychain, never in Tarn's settings or database. Questions go to api.anthropic.com over HTTPS. Disconnect deletes the key." - })) + let models = wide_row( + false, + text_block("Model", "Used for questions sent to the Claude API."), + segmented().children(CLAUDE_MODELS.iter().enumerate().map(|(ix, (_, name))| { + tab_stop(segment(("ai-claude-model", ix), *name, ix == s.claude_model)).on_click(cx.listener(move |this, _, _, cx| { + this.with_browser(cx, |b, _, cx| { + ai_settings::set_claude_model(&b.core.disk, ix); + cx.notify(); + }); + cx.notify(); + })) + })), + ); + page.child(group().child(providers).child(account).child(models)).child(note(if cfg!(windows) { + "The key is kept in Windows Credential Manager, never in Tarn's settings or database. Questions go to api.anthropic.com over HTTPS. Disconnect deletes the key." + } else { + "The key is kept in the Keychain, never in Tarn's settings or database. Questions go to api.anthropic.com over HTTPS. Disconnect deletes the key." + })) } Provider::Ollama => { let focused = self.ai.model.focus_handle(cx).is_focused(window); let current = &s.ollama_model; - page.child(section("Ollama")) - .child( - group().child( - row(true) - .child(label("Model")) - .child(div().w(gpui::px(220.)).child(field(focused).child(self.ai.model.clone()))) - .child(tab_stop(button("ai-model", "Save", false)).on_click(cx.listener(|this, _, _, cx| this.save_model(cx)))), - ), - ) - .child(note(format!("Using {current}. Tarn talks to Ollama at 127.0.0.1:11434 only; nothing leaves this computer."))) + page.child( + group().child(providers).child( + row(false) + .child(label("Model")) + .child(div().w(gpui::px(220.)).child(field(focused).py_0p5().child(self.ai.model.clone()))) + .child(tab_stop(button("ai-model", "Save", false)).on_click(cx.listener(|this, _, _, cx| this.save_model(cx)))), + ), + ) + .child(note(format!("Using {current}. Tarn talks to Ollama at 127.0.0.1:11434 only; nothing leaves this computer."))) } }; - page.children(self.ai.message.clone().map(|m| note(m).text_color(Theme::warning()))).into_any_element() + page = page.children(self.ai.message.clone().map(warning)); + page.child(self.commands(s, id, window, cx)).child(self.chats(s, id, cx)).into_any_element() } + + /// The profile's saved chats, which can be deleted whether or not the assistant is on. + fn chats(&self, s: &Snapshot, id: Id, cx: &mut Context) -> gpui::Div { + let chats = match s.chats { + 0 => "No saved chats".to_owned(), + 1 => "1 saved chat".to_owned(), + n => format!("{n} saved chats"), + }; + let delete = (s.chats > 0).then(|| { + tab_stop(button("ai-delete-chats", "Delete All Chats", false)).on_click(cx.listener(move |this, _, window, cx| this.delete_chats(id, window, cx))) + }); + div() + .child(section("Chats")) + .child(group().child(row(true).child(leading_icon(Icon::History)).child(label(chats)).children(delete))) + .child(note("Chats are kept on this computer for this profile, and reopened from the chat list in the assistant.")) + .children(self.ai.chats_error.clone().map(warning)) + } +} + +/// Every window's selection menus list the commands again. +fn commands_changed(cx: &mut gpui::App) { + crate::shared::each(cx, |b, _, cx| { + b.sync_assistant_menus(); + cx.notify(); + }); } diff --git a/crates/app/src/settings/extensions.rs b/crates/app/src/settings/extensions.rs index f1c7af4d..6256d63c 100644 --- a/crates/app/src/settings/extensions.rs +++ b/crates/app/src/settings/extensions.rs @@ -1,11 +1,12 @@ use super::*; +use ui::controls::{empty_state, leading_icon, row_action}; const OFF: &str = "Extension downloads are off in Privacy settings."; impl SettingsWindow { pub(super) fn extensions(&self, s: Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { if !s.extensions_allowed { - return div().child(section("Extensions")).child(note("Extensions are off in private and Lockdown profiles.")).into_any_element(); + return div().pt_6().child(empty_state(Icon::Lock, "Extensions are off in private and Lockdown profiles.")).into_any_element(); } let mut page = div(); if cfg!(windows) { @@ -175,7 +176,7 @@ impl SettingsWindow { fn installed_extensions(&self, extensions: Vec, cx: &mut Context) -> Div { if extensions.is_empty() { - note("No extensions yet. Apps with a Safari web extension, such as Bitwarden from the Mac App Store, appear here.") + empty_state(Icon::Braces, "No extensions yet. Apps with a Safari web extension, such as Bitwarden from the Mac App Store, appear here.") } else { let mut list = group(); for (ix, e) in extensions.into_iter().enumerate() { @@ -199,21 +200,24 @@ impl SettingsWindow { ); } if let Some(id) = e.install_id.clone() { - actions = actions.child(button(("extension-forget", ix), "Forget Site Answers", false).on_click(cx.listener(move |this, _, _, cx| { - let id = id.clone(); - this.with_browser(cx, move |b, w, cx| b.forget_extension_answers(&id, w, cx)) - }))); + actions = + actions.child(row_action(("extension-forget", ix), Icon::Undo, "Forget Site Answers").on_click(cx.listener(move |this, _, _, cx| { + let id = id.clone(); + this.with_browser(cx, move |b, w, cx| b.forget_extension_answers(&id, w, cx)) + }))); } if let Some(id) = e.install_id { let question = format!("Remove the extension \u{201C}{}\u{201D}?", bounded_title(&e.name)); - actions = actions.child(button(("extension-remove", ix), "Remove\u{2026}", false).on_click(cx.listener(move |this, _, window, cx| { - let id = id.clone(); - this.ask(&question, Some("Its files and the data it stored are deleted."), &["Remove"], window, cx, move |this, _, cx| { - this.with_browser(cx, move |b, _, cx| b.remove_extension(&id, cx)) - }); - }))); + actions = + actions.child(row_action(("extension-remove", ix), Icon::Trash, "Remove\u{2026}").on_click(cx.listener(move |this, _, window, cx| { + let id = id.clone(); + this.ask(&question, Some("Its files and the data it stored are deleted."), &["Remove"], window, cx, move |this, _, cx| { + this.with_browser(cx, move |b, _, cx| b.remove_extension(&id, cx)) + }); + }))); } let r = row(ix == 0) + .child(leading_icon(Icon::Braces)) .child( div() .flex_1() @@ -242,13 +246,13 @@ impl SettingsWindow { let input = self.repo_input.clone(); let focused = input.focus_handle(cx).is_focused(window); group() - .child(row(true).child(field(focused).flex_1().py_0p5().child(input)).child(available( + .child(row(true).child(leading_icon(Icon::Code)).child(field(focused).flex_1().py_0p5().child(input)).child(available( button("install-github", "Install", false).when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.install_from_github(cx)))), downloads, OFF, ))) - .child(row(false).child(label("A .zip or .crx file")).child(button("install-file", "Choose File\u{2026}", false).on_click(cx.listener( - |this, _, _, cx| { + .child(row(false).child(leading_icon(Icon::FileArchive)).child(label("A .zip or .crx file")).child( + button("install-file", "Choose File\u{2026}", false).on_click(cx.listener(|this, _, _, cx| { let paths = cx.prompt_for_paths(gpui::PathPromptOptions { files: true, directories: false, multiple: false, prompt: None }); let main = this.main; cx.spawn(async move |_, cx| { @@ -265,10 +269,10 @@ impl SettingsWindow { .ok(); }) .detach(); - }, - )))) + })), + )) .child( - row(false).child(label("Installed from GitHub or the catalog")).child(available( + row(false).child(leading_icon(Icon::Reload)).child(label("Installed from GitHub or the catalog")).child(available( button("extension-updates", "Check for Updates", false) .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.check_extension_updates(cx))))), downloads, @@ -280,7 +284,7 @@ impl SettingsWindow { fn official_extensions(&self, mut page: Div, catalog: (Vec, bool), downloads: bool, cx: &mut Context) -> Div { let (rows, old) = catalog; let mut official = group().child( - row(true).child(label("Reviewed and signed by Tarn")).child(available( + row(true).child(leading_icon(Icon::ShieldCheck)).child(label("Reviewed and signed by Tarn")).child(available( button("catalog", "Show Official Extensions", false) .when(downloads, |d| d.on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.fetch_catalog(cx))))), downloads, @@ -331,13 +335,13 @@ impl SettingsWindow { .child(value(shield_badge(p.shield_level))) .when(!p.is_private, |d| { d.child( - button(("edit-profile", ix), "Edit…", false) + row_action(("edit-profile", ix), Icon::Pencil, "Edit…") .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(Some(id), w, cx)))), ) }) .when(!p.is_private && deletable, |d| { let question = format!("Delete the profile \u{201C}{}\u{201D}?", bounded_title(&p.name)); - d.child(button(("delete-profile", ix), "Delete…", false).on_click(cx.listener(move |this, _, window, cx| { + d.child(row_action(("delete-profile", ix), Icon::Trash, "Delete…").on_click(cx.listener(move |this, _, window, cx| { let detail = "Its spaces, tabs, history and website data are deleted. Website data another profile shares stays for that profile."; this.ask(&question, Some(detail), &["Delete Profile"], window, cx, move |this, _, cx| { this.with_browser(cx, |b, w, cx| b.delete_profile(id, w, cx)) @@ -350,13 +354,13 @@ impl SettingsWindow { let deletable = s.profiles.iter().filter(|p| !p.is_private).count() > 1; let list = s.profiles.iter().enumerate().fold(group(), |list, (ix, p)| list.child(self.profile_row(s, ix, p, deletable, cx))); let rules = if s.space_rules.is_empty() { - note("No rules. \u{201c}Always open in\u{201d} in a site's settings opens its new tabs in the space you pick.") + empty_state(Icon::Folder, "No rules. \u{201c}Always open in\u{201d} in a site's settings opens its new tabs in the space you pick.") } else { let mut list = group(); for (ix, (id, pattern, space)) in s.space_rules.iter().cloned().enumerate() { list = list.child( row(ix == 0).child(label(bounded_title(&pattern))).child(value(space)).child( - button(("delete-space-rule", ix), "Remove", false) + row_action(("delete-space-rule", ix), Icon::Trash, "Remove") .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, _, cx| b.delete_space_rule(id, cx)))), ), ); @@ -366,7 +370,7 @@ impl SettingsWindow { div() .child(heading( "Profiles", - button("new-profile", "New Profile…", true) + icon_text_button("new-profile", Icon::Plus, "New Profile…") .on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_profile_editor(None, w, cx)))), )) .child(list) diff --git a/crates/app/src/settings/notes.rs b/crates/app/src/settings/notes.rs index 0160623d..8595b70a 100644 --- a/crates/app/src/settings/notes.rs +++ b/crates/app/src/settings/notes.rs @@ -1,21 +1,24 @@ -use browser_core::notes::{Draft, EMPTY, INTRO, NO_MATCH, PRIVATE, rows}; +use browser_core::notes::{Draft, EMPTY, EXPORT_NAME, INTRO, NO_MATCH, PRIVATE, Sort, markdown, sorted}; use gpui::{ AnyElement, AppContext, Context, Entity, Focusable, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Subscription, Window, div, - prelude::FluentBuilder, px, + prelude::FluentBuilder, }; +use shield::ShieldLevel; use store::{Id, Note}; -use ui::controls::{button, field, group, note, row, section, tab_stop}; +use ui::controls::{button, empty_state, group, icon_text_button, note, row, row_action, section, segment, segmented, tab_stop, text_lines}; +use ui::icon::Icon; use ui::text_input::{TextInput, TextInputEvent}; -use ui::theme::Theme; -use super::{SettingsWindow, Snapshot, label, value}; +use super::{SettingsWindow, Snapshot, editor_actions, editor_row, heading, search_field, warning}; pub(super) struct Pane { search: Entity, title: Entity, body: Entity, editing: Option, + adding: bool, error: Option, + exported: Option, _inputs: [Subscription; 3], } @@ -24,10 +27,13 @@ impl Pane { let search = cx.new(|cx| TextInput::new("Search notes", cx)); let title = cx.new(|cx| TextInput::new("Title", cx)); let body = cx.new(|cx| TextInput::new("Note", cx)); - let submit = |this: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| { - if matches!(event, TextInputEvent::Submit) { - this.save_note(cx); + let submit = |this: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| match event { + TextInputEvent::Submit => this.save_note(cx), + TextInputEvent::Cancel => { + this.clear_note_editor(cx); + cx.notify(); } + _ => {} }; let filter = |_: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| { if matches!(event, TextInputEvent::Changed) { @@ -40,7 +46,9 @@ impl Pane { title, body, editing: None, + adding: false, error: None, + exported: None, } } } @@ -67,6 +75,7 @@ impl SettingsWindow { fn clear_note_editor(&mut self, cx: &mut Context) { self.notes.editing = None; + self.notes.adding = false; self.notes.error = None; self.notes.title.update(cx, |i, cx| i.set_text("", cx)); self.notes.body.update(cx, |i, cx| i.set_text("", cx)); @@ -88,55 +97,112 @@ impl SettingsWindow { cx.notify(); } + /// Writes every note as one Markdown file where the person picks; nothing leaves this computer. + fn export_notes(&mut self, notes: Vec, cx: &mut Context) { + let dir = std::env::home_dir().map(|h| h.join("Downloads")).unwrap_or_default(); + let path = cx.prompt_for_new_path(&dir, Some(EXPORT_NAME)); + cx.spawn(async move |this, cx| { + let Ok(Ok(Some(path))) = path.await else { return }; + let written = std::fs::write(&path, markdown(¬es)); + this.update(cx, |this, cx| { + (this.notes.exported, this.notes.error) = match written { + Ok(()) => (Some(format!("Saved to {}.", path.display())), None), + Err(e) => (None, Some(format!("The notes could not be saved: {e}"))), + }; + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + fn add_note(&mut self, window: &mut Window, cx: &mut Context) { + self.clear_note_editor(cx); + self.notes.adding = true; + window.focus(&self.notes.title.focus_handle(cx)); + cx.notify(); + } + pub(super) fn notes(&self, s: &Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { - let page = div().pt_3().child(note(INTRO)); + let page = div().child(note(INTRO).pt_6()); let Some(profile) = s.profile.as_ref().filter(|_| !s.private).map(|p| p.id) else { - return page.child(note(PRIVATE)).into_any_element(); + return page.child(div().pt_4().child(empty_state(Icon::Lock, PRIVATE))).into_any_element(); }; let pane = &self.notes; let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); let saved = &s.notes; let query = pane.search.read(cx).text().to_owned(); - let shown = rows(saved, &query); - let list = if shown.is_empty() { - note(if saved.is_empty() { EMPTY } else { NO_MATCH }).into_any_element() + let sort = Sort::load(&crate::shared::core(cx).disk); + let shown = sorted(saved, &query, sort); + let ask = s.profile.as_ref().is_some_and(|p| p.ai_enabled && p.shield_level != ShieldLevel::Lockdown && !s.burner); + let editing = pane.editing.is_some(); + let open = editing || pane.adding; + let add = || icon_text_button("note-add", Icon::Plus, "New Note").on_click(cx.listener(|this, _, window, cx| this.add_note(window, cx))); + let list = if saved.is_empty() { + empty_state(Icon::Pencil, EMPTY).child(div().pt_1().children((!open).then(add))).into_any_element() + } else if shown.is_empty() { + empty_state(Icon::Search, NO_MATCH).into_any_element() } else { - let mut list = group(); - for (ix, r) in shown.into_iter().enumerate() { - let (id, edit) = (r.id, saved.iter().find(|n| n.id == r.id).cloned()); - list = list.child( + group() + .children(shown.into_iter().enumerate().map(|(ix, r)| { + let (id, edit) = (r.id, saved.iter().find(|n| n.id == r.id).cloned()); + let asked = edit.clone().filter(|_| ask); row(ix == 0) - .child(div().w(px(180.)).flex_none().child(label(r.title))) - .child(value(r.preview).flex_1().min_w_0().overflow_hidden()) - .child(tab_stop(button(("note-edit", ix), "Edit", false)).on_click(cx.listener(move |this, _, window, cx| { + .child(text_lines(r.title, r.preview)) + .children(asked.map(|note| { + row_action(("note-ask", ix), Icon::Sparkles, "Ask Assistant").on_click(cx.listener(move |this, _, _, cx| { + let note = note.clone(); + this.with_browser(cx, move |b, window, cx| b.ask_note(¬e, window, cx)); + })) + })) + .child(row_action(("note-edit", ix), Icon::Pencil, "Edit").on_click(cx.listener(move |this, _, window, cx| { if let Some(note) = edit.clone() { this.edit_note(note, window, cx); } }))) .child( - tab_stop(button(("note-delete", ix), "Delete", false)) + row_action(("note-delete", ix), Icon::Trash, "Delete") .on_click(cx.listener(move |this, _, _, cx| this.delete_note(profile, id, cx))), - ), - ); - } - list.into_any_element() + ) + })) + .into_any_element() }; - let editing = pane.editing.is_some(); - let editor = group() - .child(row(true).child(label("Title")).child(field(focused(&pane.title)).w(px(420.)).py_0p5().child(pane.title.clone()))) - .child(row(false).child(label("Note")).child(field(focused(&pane.body)).w(px(420.)).py_0p5().child(pane.body.clone()))); - let actions = div() - .pt_2() - .flex() - .justify_end() - .gap_2() - .when(editing, |d| d.child(tab_stop(button("note-cancel", "Cancel", false)).on_click(cx.listener(|this, _, _, cx| this.clear_note_editor(cx))))) - .child(tab_stop(button("note-save", if editing { "Save" } else { "Add" }, true)).on_click(cx.listener(|this, _, _, cx| this.save_note(cx)))); - page.child(div().pt_2().child(field(focused(&pane.search)).w(px(320.)).py_0p5().child(pane.search.clone()))) - .child(div().pt_2().child(list)) - .child(section(if editing { "Edit note" } else { "New note" })) - .child(editor) - .children(pane.error.clone().map(|e| note(e).text_color(Theme::warning()))) + let order = segmented().children(Sort::ALL.into_iter().enumerate().map(|(ix, choice)| { + tab_stop(segment(("note-sort", ix), choice.name(), choice == sort)).on_click(cx.listener(move |_, _, _, cx| { + choice.save(&crate::shared::core(cx).disk); + cx.notify(); + })) + })); + let all = saved.clone(); + let export = tab_stop(button("note-export", "Export\u{2026}", false)).on_click(cx.listener(move |this, _, _, cx| this.export_notes(all.clone(), cx))); + let actions = div().flex().gap_2().when(!saved.is_empty(), |d| d.child(export)).children((!open && !saved.is_empty()).then(add)); + let mut page = page.child(heading("Your notes", actions)); + if !saved.is_empty() { + page = page.child( + div().pb_2().flex().items_center().justify_between().gap_3().flex_wrap().child(search_field(&pane.search, focused(&pane.search))).child(order), + ); + } + page = page.child(list).children(pane.exported.clone().map(note)); + if !open { + return page.into_any_element(); + } + let actions = editor_actions( + "note-editor", + editing, + Box::new(cx.listener(|this, _, _, cx| { + this.clear_note_editor(cx); + cx.notify(); + })), + Box::new(cx.listener(|this, _, _, cx| this.save_note(cx))), + ); + page.child(section(if editing { "Edit note" } else { "New note" })) + .child(group().child(editor_row(true, "Title", &pane.title, focused(&pane.title))).child(editor_row( + false, + "Note", + &pane.body, + focused(&pane.body), + ))) + .children(pane.error.clone().map(warning)) .child(actions) .into_any_element() } diff --git a/crates/app/src/settings/privacy.rs b/crates/app/src/settings/privacy.rs index 9798fd16..1ef0a552 100644 --- a/crates/app/src/settings/privacy.rs +++ b/crates/app/src/settings/privacy.rs @@ -1,9 +1,13 @@ use super::*; +use ui::controls::{empty_state, row_action}; impl SettingsWindow { pub(super) fn permissions(&self, s: Snapshot, cx: &mut Context) -> AnyElement { let body = if s.permissions.is_empty() { - note("No site has asked yet. When a site asks for the camera, microphone, location or pop-ups and you choose Remember, the answer shows here.") + empty_state( + Icon::Camera, + "No site has asked yet. When a site asks for the camera, microphone, location or pop-ups and you choose Remember, the answer shows here.", + ) } else { let mut list = group(); for (ix, p) in s.permissions.into_iter().enumerate() { @@ -16,19 +20,20 @@ impl SettingsWindow { list = list.child( row(ix == 0) .child(text_block(bounded_title(&p.site), p.label.clone())) - .child(button(("allow", ix), "Allow", p.allowed).on_click(set(Some(true), p.origin.clone(), p.kind.clone()))) - .child(button(("block", ix), "Block", !p.allowed).on_click(set(Some(false), p.origin.clone(), p.kind.clone()))) - .child(button(("forget", ix), "Forget", false).on_click(set(None, p.origin, p.kind))), + .child( + segmented() + .child(segment(("allow", ix), "Allow", p.allowed).on_click(set(Some(true), p.origin.clone(), p.kind.clone()))) + .child(segment(("block", ix), "Block", !p.allowed).on_click(set(Some(false), p.origin.clone(), p.kind.clone()))), + ) + .child(row_action(("forget", ix), Icon::Trash, "Forget").on_click(set(None, p.origin, p.kind))), ); } list }; div() - .flex() - .flex_col() - .gap_2() - .child(note("This profile's answers to sites. A site you forget asks again next time; Lockdown sites never ask.")) + .child(section("Sites")) .child(body) + .child(note("This profile's answers to sites. A site you forget asks again next time; Lockdown sites never ask.")) .into_any_element() } @@ -58,13 +63,13 @@ impl SettingsWindow { let profile_name = s.profile.as_ref().map(|p| bounded_title(&p.name)).unwrap_or_default(); let sites = if s.overrides.is_empty() { - note("No site overrides. Use the Shield button in the address bar to set one for a site.") + empty_state(Icon::Shield, "No site overrides. Use the Shield button in the address bar to set one for a site.") } else { let mut list = group(); for (ix, (host, l)) in s.overrides.into_iter().enumerate() { list = list.child( row(ix == 0).child(label(bounded_title(&host))).child(value(shield_badge(l))).child( - button(("remove-override", ix), "Remove", false) + row_action(("remove-override", ix), Icon::Trash, "Remove") .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.remove_site_override(&host, w, cx)))), ), ); @@ -81,17 +86,20 @@ impl SettingsWindow { })) }); let zooms = if s.zooms.is_empty() { - note(format!( - "No saved zoom levels. {} and {} remember the zoom for the site; {} forgets it.", - crate::shortcuts::shown(&crate::ZoomIn, cx), - crate::shortcuts::shown(&crate::ZoomOut, cx), - crate::shortcuts::shown(&crate::ZoomReset, cx) - )) + empty_state( + Icon::ZoomIn, + format!( + "No saved zoom levels. {} and {} remember the zoom for the site; {} forgets it.", + crate::shortcuts::shown(&crate::ZoomIn, cx), + crate::shortcuts::shown(&crate::ZoomOut, cx), + crate::shortcuts::shown(&crate::ZoomReset, cx) + ), + ) } else { let mut list = group(); for (ix, (host, zoom)) in s.zooms.into_iter().enumerate() { list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(value(format!("{:.0} %", zoom * 100.))).child( - button(("remove-zoom", ix), "Remove", false).on_click(cx.listener(move |this, _, _, cx| { + row_action(("remove-zoom", ix), Icon::Trash, "Remove").on_click(cx.listener(move |this, _, _, cx| { let Some((private, id)) = target else { return }; this.with_browser(cx, |b, _, cx| b.remove_site_zoom(private, id, Some(&host), cx)); })), @@ -101,14 +109,14 @@ impl SettingsWindow { }; let zapped = if s.private { - note("A private space keeps no hidden elements.") + empty_state(Icon::Lock, "A private space keeps no hidden elements.") } else if s.zapped.is_empty() { - note("No hidden elements. Zap Element in the command bar hides an element on a site in this profile.") + empty_state(Icon::Zap, "No hidden elements. Zap Element in the command bar hides an element on a site in this profile.") } else { let mut list = group(); for (ix, (host, selector)) in s.zapped.into_iter().enumerate() { list = list.child(row(ix == 0).child(label(bounded_title(&format!("{host} — {selector}")))).child( - button(("unzap", ix), "Show Again", false).on_click(cx.listener(move |this, _, _, cx| { + row_action(("unzap", ix), Icon::Undo, "Show Again").on_click(cx.listener(move |this, _, _, cx| { let (host, selector) = (host.clone(), selector.clone()); this.with_browser(cx, move |b, _, cx| b.unzap(&host, Some(&selector), cx)); })), @@ -118,19 +126,19 @@ impl SettingsWindow { }; let muted = if s.muted.is_empty() { - note("No muted sites. Mute Site in the Tabs menu or a tab's menu silences a site in this profile.") + empty_state(Icon::VolumeX, "No muted sites. Mute Site in the Tabs menu or a tab's menu silences a site in this profile.") } else { let mut list = group(); for (ix, host) in s.muted.into_iter().enumerate() { - list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(button(("unmute", ix), "Unmute", false).on_click(cx.listener( - move |this, _, _, cx| { + list = list.child(row(ix == 0).child(label(bounded_title(&host))).child(row_action(("unmute", ix), Icon::Volume, "Unmute").on_click( + cx.listener(move |this, _, _, cx| { let Some((private, id)) = target else { return }; this.with_browser(cx, |b, _, cx| { b.set_site_muted(private, id, Some(&host), false, true); cx.notify(); }); - }, - )))); + }), + ))); } list }; @@ -150,13 +158,13 @@ impl SettingsWindow { .child(self.pref_row(false, Pref::BlockMalware, "Block dangerous sites", format!("Malware, phishing and scam lists{}.{}", if cfg!(windows) { "" } else { ", plus WebKit's fraudulent-website check, which asks Apple's Safe Browsing service about hashed addresses" }, count("malware", "domains")), on(Pref::BlockMalware), cx)) .child(self.pref_row(false, Pref::BlockAdult, "Block adult content", format!("Pornographic and other adult websites, with no way past the warning page.{}", count("adult", "domains")), on(Pref::BlockAdult), cx)); let paused = if s.paused.is_empty() { - note("Blocking runs on every site. Turn it off for one site with the Shield button in the address bar.") + empty_state(Icon::ShieldCheck, "Blocking runs on every site. Turn it off for one site with the Shield button in the address bar.") } else { let mut list = group(); for (ix, host) in s.paused.into_iter().enumerate() { list = list.child( row(ix == 0).child(label(bounded_title(&host))).child( - button(("resume-blocking", ix), "Turn On", false) + row_action(("resume-blocking", ix), Icon::ShieldCheck, "Turn Blocking On") .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.set_site_paused(&host, false, w, cx)))), ), ); @@ -197,7 +205,7 @@ impl SettingsWindow { .when(cfg!(feature = "translation"), |d| { d.child(connection(false, "Translation", "None. Pages are translated on this Mac with the language packs installed in System Settings; Tarn never downloads them.".into())) }) - .child(connection(false, "AI requests", format!("Not built yet; no page content leaves {}.", ui::controls::THIS_DEVICE))); + .child(connection(false, "AI requests", "Anthropic, or Ollama on this computer, only when you press Send, Retry or a command in a profile whose assistant is on in Settings › AI; never from a private space, a burner tab or a Lockdown page.".into())); let mut data = group(); if !s.private { @@ -277,14 +285,14 @@ impl SettingsWindow { let on = s.developer; let dev_profile = s.profiles.iter().find(|p| p.is_dev).map(|p| bounded_title(&p.name)); let servers = match &s.local_servers { - None => note("Not checked yet."), - Some(ports) if ports.is_empty() => note("Nothing is listening on the common dev ports (3000, 5173, 8080 and others)."), + None => empty_state(Icon::Code, "Not checked yet."), + Some(ports) if ports.is_empty() => empty_state(Icon::Code, "Nothing is listening on the common dev ports (3000, 5173, 8080 and others)."), Some(ports) => { let mut list = group(); for (ix, port) in ports.iter().copied().enumerate() { list = list.child( row(ix == 0).child(label(format!("localhost:{port}"))).child( - button(("open-server", ix), "Open", false) + row_action(("open-server", ix), Icon::ExternalLink, "Open") .on_click(cx.listener(move |this, _, _, cx| this.with_browser(cx, |b, w, cx| b.open_local_server(port, w, cx)))), ), ); @@ -310,7 +318,7 @@ impl SettingsWindow { .child(note("Web Inspector and the developer tools are always on there; caches are cleared after every page load and Reload bypasses the cache.")) .child(heading( "Local servers", - button("refresh-servers", "Refresh", false).on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.refresh_local_servers(cx)))), + icon_text_button("refresh-servers", Icon::Reload, "Refresh").on_click(cx.listener(|this, _, _, cx| this.with_browser(cx, |b, _, cx| b.refresh_local_servers(cx)))), )) .child(servers) .into_any_element() diff --git a/crates/app/src/settings/profile_card.rs b/crates/app/src/settings/profile_card.rs index b74993fc..5f254843 100644 --- a/crates/app/src/settings/profile_card.rs +++ b/crates/app/src/settings/profile_card.rs @@ -220,7 +220,7 @@ impl SettingsWindow { .child(row(false).child(label("Update checks")).child(value(updates))) .child( row(false) - .child(text_block("Nothing else", "No accounts, no telemetry, no AI requests.")) + .child(text_block("Nothing else", "No accounts and no telemetry. The assistant sends only when you ask it to.")) .child(to_privacy("connections-details", "Details…")), ), ) diff --git a/crates/app/src/settings/snippets.rs b/crates/app/src/settings/snippets.rs index 9811661d..59aca1ec 100644 --- a/crates/app/src/settings/snippets.rs +++ b/crates/app/src/settings/snippets.rs @@ -1,33 +1,52 @@ -use browser_core::snippets::{NAME_RULE, NOTE, preview, valid_name}; +use browser_core::snippets::{EXPAND, EXPAND_NOTE, NAME_RULE, NO_MATCH, NOTE, matching, preview, valid_name}; use gpui::{ AnyElement, AppContext, Context, Entity, Focusable, IntoElement, ParentElement, StatefulInteractiveElement, Styled, Subscription, Window, div, - prelude::FluentBuilder, px, + prelude::FluentBuilder, }; use store::{Id, Snippet}; -use ui::controls::{button, field, group, note, row, section, tab_stop}; +use ui::controls::{empty_state, group, icon_text_button, note, row, row_action, section, switch_row, text_block, text_lines}; +use ui::icon::Icon; use ui::text_input::{TextInput, TextInputEvent}; -use ui::theme::Theme; -use super::{SettingsWindow, Snapshot, label, value}; +use super::{SettingsWindow, Snapshot, editor_actions, editor_row, list_heading, search_field, warning}; pub(super) struct Pane { + search: Entity, name: Entity, body: Entity, editing: Option, + adding: bool, error: Option, - _submit: [Subscription; 2], + _inputs: [Subscription; 3], } impl Pane { pub(super) fn new(cx: &mut Context) -> Pane { + let search = cx.new(|cx| TextInput::new("Search snippets", cx)); let name = cx.new(|cx| TextInput::new("name", cx)); let body = cx.new(|cx| TextInput::new("Text to insert", cx)); - let submit = |this: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| { - if matches!(event, TextInputEvent::Submit) { - this.save_snippet(cx); + let submit = |this: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| match event { + TextInputEvent::Submit => this.save_snippet(cx), + TextInputEvent::Cancel => { + this.clear_snippet_editor(cx); + cx.notify(); } + _ => {} }; - Pane { _submit: [cx.subscribe(&name, submit), cx.subscribe(&body, submit)], name, body, editing: None, error: None } + let filter = |_: &mut SettingsWindow, _: Entity, event: &TextInputEvent, cx: &mut Context| { + if matches!(event, TextInputEvent::Changed) { + cx.notify(); + } + }; + Pane { + _inputs: [cx.subscribe(&search, filter), cx.subscribe(&name, submit), cx.subscribe(&body, submit)], + search, + name, + body, + editing: None, + adding: false, + error: None, + } } } @@ -68,6 +87,7 @@ impl SettingsWindow { fn clear_snippet_editor(&mut self, cx: &mut Context) { self.snippets.editing = None; + self.snippets.adding = false; self.snippets.error = None; self.snippets.name.update(cx, |i, cx| i.set_text("", cx)); self.snippets.body.update(cx, |i, cx| i.set_text("", cx)); @@ -92,53 +112,78 @@ impl SettingsWindow { cx.notify(); } + fn add_snippet(&mut self, window: &mut Window, cx: &mut Context) { + self.clear_snippet_editor(cx); + self.snippets.adding = true; + window.focus(&self.snippets.name.focus_handle(cx)); + cx.notify(); + } + pub(super) fn snippets(&self, s: &Snapshot, window: &mut Window, cx: &mut Context) -> AnyElement { - let page = div().pt_3().child(note(NOTE)); let Some(profile) = s.profile.as_ref().filter(|_| !s.private).map(|p| p.id) else { - return page.child(note("Snippets belong to a saved profile. Open Settings from one of its spaces to edit them.")).into_any_element(); + return div() + .pt_6() + .child(empty_state(Icon::Lock, "Snippets belong to a saved profile. Open Settings from one of its spaces to edit them.")) + .into_any_element(); }; + let pane = &self.snippets; + let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); + let expand = EXPAND.on(&crate::shared::core(cx).disk); + let toggle = + group().child(switch_row("snippet-expand", true, text_block("Expand ;name in the address and command bar", EXPAND_NOTE), expand).on_click( + cx.listener(move |_, _, _, cx| { + EXPAND.set(&crate::shared::core(cx).disk, !expand); + cx.notify(); + }), + )); + let editing = pane.editing.is_some(); + let open = editing || pane.adding; + let add = || icon_text_button("snippet-add", Icon::Plus, "Add Snippet").on_click(cx.listener(|this, _, window, cx| this.add_snippet(window, cx))); + let shown = matching(pane.search.read(cx).text(), &s.snippets); let list = if s.snippets.is_empty() { - note("No snippets yet.").into_any_element() + empty_state(Icon::FileText, "No snippets yet.").child(div().pt_1().children((!open).then(add))).into_any_element() + } else if shown.is_empty() { + empty_state(Icon::Search, NO_MATCH).into_any_element() } else { - let mut list = group(); - for (ix, snippet) in s.snippets.iter().enumerate() { - let (id, edit) = (snippet.id, snippet.clone()); - list = list.child( + group() + .children(shown.into_iter().enumerate().map(|(ix, snippet)| { + let (id, edit) = (snippet.id, snippet.clone()); row(ix == 0) - .child(div().w(px(140.)).flex_none().child(label(snippet.name.clone()))) - .child(value(preview(&snippet.body)).flex_1().min_w_0().overflow_hidden()) + .child(text_lines(snippet.name.clone(), preview(&snippet.body))) .child( - tab_stop(button(("snippet-edit", ix), "Edit", false)) + row_action(("snippet-edit", ix), Icon::Pencil, "Edit") .on_click(cx.listener(move |this, _, window, cx| this.edit_snippet(edit.clone(), window, cx))), ) .child( - tab_stop(button(("snippet-delete", ix), "Delete", false)) + row_action(("snippet-delete", ix), Icon::Trash, "Delete") .on_click(cx.listener(move |this, _, _, cx| this.delete_snippet(profile, id, cx))), - ), - ); - } - list.into_any_element() + ) + })) + .into_any_element() }; - let pane = &self.snippets; - let focused = |input: &Entity| input.focus_handle(cx).is_focused(window); - let editing = pane.editing.is_some(); - let editor = group() - .child(row(true).child(label("Name")).child(field(focused(&pane.name)).w(px(260.)).py_0p5().child(pane.name.clone()))) - .child(row(false).child(label("Text")).child(field(focused(&pane.body)).w(px(420.)).py_0p5().child(pane.body.clone()))); - let actions = div() - .pt_2() - .flex() - .justify_end() - .gap_2() - .when(editing, |d| { - d.child(tab_stop(button("snippet-cancel", "Cancel", false)).on_click(cx.listener(|this, _, _, cx| this.clear_snippet_editor(cx)))) - }) - .child(tab_stop(button("snippet-save", if editing { "Save" } else { "Add" }, true)).on_click(cx.listener(|this, _, _, cx| this.save_snippet(cx)))); - page.child(list) - .child(section(if editing { "Edit snippet" } else { "New snippet" })) - .child(editor) + let page = div() + .child(section("Expansion")) + .child(toggle) + .child(note(NOTE)) + .child(list_heading("Your snippets", (!open && !s.snippets.is_empty()).then(add))) + .when(!s.snippets.is_empty(), |d| d.child(div().pb_2().child(search_field(&pane.search, focused(&pane.search))))) + .child(list); + if !open { + return page.into_any_element(); + } + let actions = editor_actions( + "snippet-editor", + editing, + Box::new(cx.listener(|this, _, _, cx| { + this.clear_snippet_editor(cx); + cx.notify(); + })), + Box::new(cx.listener(|this, _, _, cx| this.save_snippet(cx))), + ); + page.child(section(if editing { "Edit snippet" } else { "New snippet" })) + .child(group().child(editor_row(true, "Name", &pane.name, focused(&pane.name))).child(editor_row(false, "Text", &pane.body, focused(&pane.body)))) .child(note(NAME_RULE)) - .children(pane.error.clone().map(|e| note(e).text_color(Theme::warning()))) + .children(pane.error.clone().map(warning)) .child(actions) .into_any_element() } diff --git a/crates/app/src/snippets.rs b/crates/app/src/snippets.rs index 4b383633..0a10e6ad 100644 --- a/crates/app/src/snippets.rs +++ b/crates/app/src/snippets.rs @@ -43,7 +43,7 @@ impl Browser { return; } let text = input.text().to_owned(); - if let Some(expanded) = snippets::expand(&text, &self.profile_snippets()) { + if let Some(expanded) = self.core.expand_snippet(self.model.profile(), &text) { self.command.update(cx, |input, cx| { input.set_text(expanded, cx); input.append_selected("", cx); @@ -52,13 +52,28 @@ impl Browser { } fn insert_snippet(&mut self, window: &mut Window, cx: &mut Context) { - let Some(key) = self.model.active else { return }; + if self.aim_insert(NO_INSERT, cx) { + self.open_command(CommandMode::Snippets, window, cx); + } + } + + /// Types an answer into the active page's focused field, like a snippet. + pub(crate) fn insert_answer(&mut self, text: &str, cx: &mut Context) { + if self.aim_insert("Answers cannot be typed into a Lockdown page", cx) { + self.type_snippet(text, cx); + } + } + + /// Remembers the active page as the one to type into; false, with a notice, on a Lockdown page. + fn aim_insert(&mut self, refused: &'static str, cx: &mut Context) -> bool { + let Some(key) = self.model.active else { return false }; if self.level_for_tab(key, &self.tab_url(key).unwrap_or_default()) == ShieldLevel::Lockdown { - self.notify_offer(key, NO_INSERT.into(), None); - return cx.notify(); + self.notify_offer(key, refused.into(), None); + cx.notify(); + return false; } self.snippet_page = self.tab_url(key).map(|url| (key, url)); - self.open_command(CommandMode::Snippets, window, cx); + true } pub(crate) fn snippet_rows(&mut self, query: &str, cx: &mut Context) { diff --git a/crates/browser-core/src/assistant.rs b/crates/browser-core/src/assistant.rs index 3d5e1d34..8c06979b 100644 --- a/crates/browser-core/src/assistant.rs +++ b/crates/browser-core/src/assistant.rs @@ -14,6 +14,13 @@ pub const MIN_SEND_INTERVAL_MS: i64 = 2_000; const MAX_URL_BYTES: usize = 2048; const MAX_NOTICE_BYTES: usize = 300; const TAG: &str = "tarn-block"; +const WAIT: &str = "Wait a moment before sending again."; +/// What an answer reads once it used content from a site now in Lockdown. +pub const FORGOTTEN: &str = "Removed: this answer used content from a site now in Lockdown."; +/// Why a new chat was not kept. +pub const CHATS_FULL: &str = "This chat was not saved: the profile holds as many chats as it keeps. Delete some in the chat list or Settings › AI."; +/// Why a chat stopped being kept. +pub const NOT_SAVED: &str = "This chat could not be saved: it was deleted or reached its size limit. Start a new chat to keep going."; pub const ASK: &str = "{question}"; @@ -163,6 +170,8 @@ pub struct Turn { pub interrupted: bool, /// The model that gave an answer. pub by: Option, + /// A question a command sent, which a local model answers where it can; a retry goes the same way. + pub command: bool, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -214,6 +223,8 @@ struct Attached { #[derive(Clone, Debug)] pub struct Session { profile: Id, + /// The saved chat this session continues; none until its first answer is saved. + chat: Option, pills: Vec, added: [usize; 4], history: Vec, @@ -230,6 +241,7 @@ impl Session { pub fn new(origin: Origin, ai_enabled: bool) -> Option { (ai_enabled && allowed(origin)).then_some(Self { profile: origin.profile, + chat: None, pills: Vec::new(), added: [0; 4], history: Vec::new(), @@ -246,6 +258,157 @@ impl Session { self.profile } + /// The saved chat `saved` continued, under the rules of `new`. Its sources count as removed + /// pills, so a send still forgets what a site now in Lockdown gave to it, and what one that is + /// in Lockdown now (`level_of`) gave is forgotten before the chat shows, so it is never copied + /// or inserted either. + pub fn restore(origin: Origin, ai_enabled: bool, saved: &store::Chat, level_of: impl Fn(&url::Url) -> ShieldLevel) -> Option { + let mut session = Self::new(origin, ai_enabled).filter(|_| saved.profile_id == origin.profile)?; + session.chat = Some(saved.id); + session.history = saved + .turns + .iter() + .map(|t| Turn { + role: if t.you { Role::You } else { Role::Assistant }, + text: t.text.clone(), + interrupted: t.interrupted, + by: t.by.clone(), + command: t.command, + }) + .collect(); + let len = session.history.len(); + session.removed = saved.sources.iter().map(|(url, since)| (url.clone(), (*since).min(len))).collect(); + session.forget_locked(&level_of); + Some(session) + } + + /// Drops attached content whose site is in Lockdown now (`level_of`) and forgets what it, or + /// a removed source now in Lockdown, gave the chat; true when anything was forgotten. + fn forget_locked(&mut self, level_of: &impl Fn(&url::Url) -> ShieldLevel) -> bool { + let locked = |u: &str| url::Url::parse(u).map_or(true, |u| level_of(&u) == ShieldLevel::Lockdown); + let attached = self.pills.iter().filter(|a| a.pill.source().is_some_and(locked)).map(|a| a.since); + let Some(since) = attached.chain(self.removed.iter().filter(|(u, _)| locked(u)).map(|(_, s)| *s)).min() else { return false }; + self.pills.retain(|a| !a.pill.source().is_some_and(locked)); + self.removed.retain(|(u, _)| !locked(u)); + self.forget_since(since); + true + } + + /// The saved chat this session continues. + pub fn chat(&self) -> Option { + self.chat + } + + /// Saves the chat in `store` once no answer is streaming and it holds a turn; the saved id. + /// What a site in Lockdown now (`level_of`) gave the chat is forgotten first, so it is never + /// written. The title is the first question's first line. Notes are never sources: they stay + /// in the profile. A chat whose every turn was taken back is deleted. + pub fn save_with(&mut self, store: &store::Store, level_of: impl Fn(&url::Url) -> ShieldLevel) -> Option { + if self.streaming.is_some() { + return None; + } + self.forget_locked(&level_of); + if self.history.is_empty() { + if let Some(id) = self.chat { + match store.delete_chat(self.profile, id) { + Ok(()) => self.chat = None, + Err(_) => self.notice = Some(NOT_SAVED.to_owned()), + } + } + return None; + } + let turns: Vec = self + .history + .iter() + .map(|t| store::ChatTurn { you: t.role == Role::You, text: t.text.clone(), by: t.by.clone(), interrupted: t.interrupted, command: t.command }) + .collect(); + let mut sources = self.removed.clone(); + let asked = self.history.len(); + for a in self.pills.iter().filter(|a| a.since < asked) { + if let Some(url) = a.pill.source().map(strip_url) { + match sources.iter_mut().find(|(u, _)| *u == url) { + Some((_, since)) => *since = (*since).min(a.since), + None => sources.push((url, a.since)), + } + } + } + let title = self.chat.is_none().then(|| chat_title(&self.history)); + match store.save_chat(self.profile, self.chat, title.as_deref(), &turns, &sources) { + Ok(id) => { + self.chat = Some(id); + Some(id) + } + Err(_) => { + let full = self.chat.is_none() && store.chat_titles(self.profile).is_ok_and(|t| t.len() >= store::MAX_CHATS); + self.notice = Some(if full { CHATS_FULL } else { NOT_SAVED }.to_owned()); + None + } + } + } + + /// Whether the last question came from a command, so a retry goes where the command went. + pub fn last_was_command(&self) -> bool { + self.history.iter().rev().find(|t| t.role == Role::You).is_some_and(|t| t.command) + } + + /// The last answer's text, for Copy and Insert; none while it streams or when there is none. + pub fn last_answer(&self) -> Option<&str> { + self.history + .last() + .filter(|t| t.role == Role::Assistant && !t.text.is_empty() && t.text != FORGOTTEN && self.streaming.is_none()) + .map(|t| t.text.as_str()) + } + + /// Takes the last question back out of the chat, with its answer, so it can be edited and sent + /// again; none while an answer streams. + pub fn edit_last(&mut self) -> Option { + if self.streaming.is_some() { + return None; + } + let at = self.history.iter().rposition(|t| t.role == Role::You)?; + let question = self.history[at].text.clone(); + self.cut_at(at); + Some(question) + } + + /// Sends the last question again in place of its answer, under the rules of `send`. The old + /// exchange is never sent with it; a send refused for where it comes from leaves it interrupted. + pub fn retry(&mut self, at_ms: i64, origin: Origin, ai_enabled: bool, level_of: impl Fn(&url::Url) -> ShieldLevel) -> Vec { + if self.streaming.is_some() { + return Vec::new(); + } + let Some(at) = self.history.iter().rposition(|t| t.role == Role::You) else { return Vec::new() }; + if self.too_soon(at_ms) { + self.notice = Some(WAIT.to_owned()); + return vec![Effect::Render]; + } + let question = self.history[at].text.clone(); + let before = self.history.len(); + let command = self.history[at].command; + self.history[at..].iter_mut().for_each(|t| t.interrupted = true); + let effects = self.send(&question, ASK, at_ms, origin, ai_enabled, level_of); + if effects.iter().any(|e| matches!(e, Effect::Start { .. })) { + self.history[before].command = command; + self.history.drain(at..before); + self.pills.iter_mut().for_each(|a| a.since = a.since.min(at)); + self.removed.iter_mut().for_each(|(_, since)| *since = (*since).min(at)); + } + effects + } + + fn too_soon(&self, at_ms: i64) -> bool { + // A clock set back must not block sending until it catches up. + self.last_sent.is_some_and(|last| (0..MIN_SEND_INTERVAL_MS).contains(&at_ms.saturating_sub(last))) + } + + fn cut_at(&mut self, at: usize) { + self.history.truncate(at); + self.pills.iter_mut().for_each(|a| a.since = a.since.min(at)); + self.removed.iter_mut().for_each(|(_, since)| *since = (*since).min(at)); + self.notice = None; + self.refreshed(vec![Effect::Render]); + } + /// Whether `pill` is attached, so a command over it may be sent. pub fn holds(&self, pill: &Pill) -> bool { self.pills.iter().any(|a| a.pill == *pill) @@ -313,9 +476,8 @@ impl Session { if request.question.trim().is_empty() { return Vec::new(); } - // A clock set back must not block sending until it catches up. - if self.last_sent.is_some_and(|last| (0..MIN_SEND_INTERVAL_MS).contains(&at_ms.saturating_sub(last))) { - self.notice = Some("Wait a moment before sending again.".to_owned()); + if self.too_soon(at_ms) { + self.notice = Some(WAIT.to_owned()); return vec![Effect::Render]; } let id = self.next_id; @@ -323,8 +485,8 @@ impl Session { self.last_sent = Some(at_ms); self.streaming = Some(id); self.notice = None; - self.history.push(Turn { role: Role::You, text: request.question.clone(), interrupted: false, by: None }); - self.history.push(Turn { role: Role::Assistant, text: String::new(), interrupted: false, by: None }); + self.history.push(Turn { role: Role::You, text: request.question.clone(), interrupted: false, by: None, command: template != ASK }); + self.history.push(Turn { role: Role::Assistant, text: String::new(), interrupted: false, by: None, command: false }); vec![Effect::Start { id, request }, Effect::Render] } @@ -343,10 +505,10 @@ impl Session { Event::RemovePill(ix) => { if ix < self.pills.len() { let gone = self.pills.remove(ix); - if let Some(url) = gone.pill.source().filter(|_| gone.since < self.history.len()) { - match self.removed.iter_mut().find(|(u, _)| u == url) { + if let Some(url) = gone.pill.source().filter(|_| gone.since < self.history.len()).map(strip_url) { + match self.removed.iter_mut().find(|(u, _)| *u == url) { Some((_, since)) => *since = (*since).min(gone.since), - None => self.removed.push((url.to_owned(), gone.since)), + None => self.removed.push((url, gone.since)), } } } @@ -415,12 +577,39 @@ impl Session { } } - /// Every exchange since `since` may hold text from content that may no longer be sent. + /// Every exchange since `since` may hold text from content that may no longer be sent, so it + /// is never sent again and its answers lose their text, which a save would otherwise keep. fn forget_since(&mut self, since: usize) { - self.history.iter_mut().skip(since).for_each(|t| t.interrupted = true); + for turn in self.history.iter_mut().skip(since) { + turn.interrupted = true; + if turn.role == Role::Assistant && !turn.text.is_empty() { + FORGOTTEN.clone_into(&mut turn.text); + } + } + } +} + +/// The saved chats whose title holds `query`, without case, in the store's order. +pub fn find_chats<'a>(titles: &'a [store::ChatTitle], query: &str) -> Vec<&'a store::ChatTitle> { + let query = query.trim().to_lowercase(); + titles.iter().filter(|c| c.title.to_lowercase().contains(&query)).collect() +} + +/// What a client says when renaming a saved chat failed. +pub fn rename_problem(error: &store::Error) -> String { + match error { + store::Error::Invalid(what) if *what == store::MISSING_CHAT => "This chat was deleted, so it cannot be renamed.".to_owned(), + _ => format!("A title has 1 to {} characters.", store::MAX_NOTE_TITLE), } } +/// A chat's title: its first question's first line, bounded, or "Chat". +pub fn chat_title(history: &[Turn]) -> String { + let first = history.iter().find(|t| t.role == Role::You).map(|t| crate::notes::first_line(&t.text)).unwrap_or_default(); + let title = crate::text::bounded_title(first); + if title.trim().is_empty() { "Chat".to_owned() } else { title } +} + /// The request for `template` over the session's pills and history. `{question}`, `{page}` and /// `{selection}` are replaced in one pass over the template only, so text they insert is never /// expanded again; `{page}` and `{selection}` name a block rather than copy it. @@ -560,6 +749,66 @@ pub mod commands { all(custom).into_iter().map(|(name, _)| name).take(engine::view_policy::MAX_MENU_COMMANDS).collect() } + /// The `/name` command `input` runs, by its index in `all`, and the question after the name; + /// the longest whole name wins, without case. + pub fn slash<'a>(input: &'a str, all: &[(String, String)]) -> Option<(usize, &'a str)> { + let typed = input.trim_start().strip_prefix('/')?; + all.iter() + .enumerate() + .filter_map(|(ix, (name, _))| { + let end = name_end(typed, name)?; + typed[end..].chars().next().is_none_or(char::is_whitespace).then_some((ix, name.chars().count(), end)) + }) + .max_by_key(|(_, chars, _)| *chars) + .map(|(ix, _, end)| (ix, typed[end..].trim())) + } + + /// The commands the `/` menu offers while `input` is a `/` and the start of their name. + pub fn slash_menu(input: &str, all: &[(String, String)]) -> Vec { + let Some(typed) = input.trim_start().strip_prefix('/') else { return Vec::new() }; + all.iter().enumerate().filter(|(_, (name, _))| name_end(name, typed).is_some()).map(|(ix, _)| ix).collect() + } + + /// Where `name` ends in `text` when `text` starts with it, comparing characters without case: + /// the one rule for the menu, a send and a duplicate name. + fn name_end(text: &str, name: &str) -> Option { + let mut chars = text.char_indices(); + for n in name.chars() { + let (_, t) = chars.next()?; + if !t.to_lowercase().eq(n.to_lowercase()) { + return None; + } + } + Some(chars.next().map_or(text.len(), |(at, _)| at)) + } + + fn same_name(a: &str, b: &str) -> bool { + name_end(a, b) == Some(a.len()) + } + + /// Why the profile's command `editing` (none for a new one) cannot be saved as `name` and + /// `template` among its `custom` commands, before the store is asked. + pub fn check(name: &str, template: &str, custom: &[store::AiCommand], editing: Option) -> Result<(), String> { + let name = name.trim(); + if name.is_empty() { + return Err("Name the command.".into()); + } + if name.len() > store::MAX_AI_NAME { + return Err(format!("A command name holds up to {} bytes.", store::MAX_AI_NAME)); + } + if template.trim().is_empty() { + return Err("Write what the command asks.".into()); + } + if template.len() > store::MAX_AI_TEMPLATE { + return Err(format!("A command's text holds up to {} bytes.", store::MAX_AI_TEMPLATE)); + } + let taken = BUILT_IN.iter().any(|(n, _)| same_name(n, name)) || custom.iter().any(|c| Some(c.id) != editing && same_name(c.name.trim(), name)); + if taken { + return Err(format!("A command named {name} already exists.")); + } + Ok(()) + } + /// The template of the command `name` run on a selection, where `{page}` names the selection /// too, so Summarize from a selection summarizes that selection. pub fn for_selection(custom: &[store::AiCommand], name: &str) -> Option { @@ -611,6 +860,24 @@ pub mod settings { store.set_setting(PROVIDER_KEY, provider.key()).is_ok() } + pub const CLAUDE_MODEL_KEY: &str = "ai_claude_model"; + /// The Claude models Settings and the chat offer, by id and name; the first is the default. + pub const CLAUDE_MODELS: [(&str, &str); 3] = [("claude-opus-5-5", "Opus 5.5"), ("claude-sonnet-5-5", "Sonnet 5.5"), ("claude-haiku-5-5", "Haiku 5.5")]; + + /// The chosen Claude model's index in `CLAUDE_MODELS`. + pub fn claude_model(store: &Store) -> usize { + let stored = store.setting(CLAUDE_MODEL_KEY).ok().flatten(); + CLAUDE_MODELS.iter().position(|(id, _)| Some(*id) == stored.as_deref()).unwrap_or(0) + } + + pub fn claude_model_id(store: &Store) -> String { + CLAUDE_MODELS[claude_model(store)].0.to_owned() + } + + pub fn set_claude_model(store: &Store, ix: usize) -> bool { + CLAUDE_MODELS.get(ix).is_some_and(|(id, _)| store.set_setting(CLAUDE_MODEL_KEY, id).is_ok()) + } + pub fn valid_model(name: &str) -> bool { (1..=MAX_MODEL_CHARS).contains(&name.chars().count()) && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | ':' | '/')) } @@ -1151,6 +1418,213 @@ mod tests { assert_eq!(compose(&session(), ASK, "why?").user_message(), "why?"); } + fn saved(s: &mut Session, store: &store::Store) -> Option { + s.save_with(store, |_| ShieldLevel::Standard) + } + + fn answered(s: &mut Session, question: &str, answer: &str, at_ms: i64) { + let me = Origin { profile: s.profile(), ..ME }; + let (id, _) = started(&s.send(question, ASK, at_ms, me, true, |_| ShieldLevel::Standard)); + s.apply(Event::Chunk { id, text: answer.into() }); + s.apply(Event::Done { id }); + } + + #[test] + fn a_chat_is_saved_and_restored_with_its_sources() { + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let store = &core.disk; + let me = Origin { profile: store.create_profile("P", "u9", false).unwrap().id, ..ME }; + let mut s = Session::new(me, true).unwrap(); + assert!(saved(&mut s, store).is_none(), "an empty chat is not kept"); + s.apply(Event::AddPill(me, page("body"))); + answered(&mut s, "What is\nit?", "A page.", 0); + let id = saved(&mut s, store).unwrap(); + assert_eq!(saved(&mut s, store), Some(id), "saving again replaces it"); + let saved = store.chat(me.profile, id).unwrap().unwrap(); + assert_eq!(saved.title, "What is"); + assert_eq!(saved.sources, [("https://a.test/p".to_owned(), 0)]); + let open = |_: &url::Url| ShieldLevel::Standard; + assert!(Session::restore(ME, true, &saved, open).is_none(), "another profile's chat"); + assert!(Session::restore(Origin { kind: ProfileKind::Private, ..me }, true, &saved, open).is_none()); + let shut = Session::restore(me, true, &saved, |_| ShieldLevel::Lockdown).unwrap(); + assert_eq!(view(&shut).rows[1].text, FORGOTTEN, "what a site now in Lockdown gave is not shown, copied or inserted"); + assert_eq!(shut.last_answer(), None, "a removed answer is not copied or inserted"); + let mut back = Session::restore(me, true, &saved, open).unwrap(); + assert_eq!(back.chat(), Some(id)); + assert_eq!(view(&back).rows.len(), 2); + let (_, next) = started(&back.send("More?", ASK, 0, me, true, |_| ShieldLevel::Standard)); + assert_eq!(labels(&next), ["Question 1", "Answer 1"]); + let mut locked = Session::restore(me, true, &saved, open).unwrap(); + assert!(!locked.send("More?", ASK, 0, me, true, |_| ShieldLevel::Lockdown).iter().any(|e| matches!(e, Effect::Start { .. }))); + assert!(view(&locked).rows.iter().all(|r| r.interrupted), "what a site now in Lockdown gave is never sent again"); + } + + #[test] + fn retry_replaces_the_last_answer_and_edit_takes_the_question_back() { + let mut s = session(); + assert!(s.retry(0, ME, true, |_| ShieldLevel::Standard).is_empty(), "nothing to retry"); + answered(&mut s, "One?", "1", 0); + answered(&mut s, "Two?", "2", MIN_SEND_INTERVAL_MS); + assert_eq!(s.last_answer(), Some("2")); + assert_eq!(s.retry(MIN_SEND_INTERVAL_MS + 1, ME, true, |_| ShieldLevel::Standard), [Effect::Render], "too soon"); + let effects = s.retry(2 * MIN_SEND_INTERVAL_MS, ME, true, |_| ShieldLevel::Standard); + let (id, request) = started(&effects); + assert_eq!(request.question, "Two?"); + assert_eq!(labels(&request), ["Question 1", "Answer 1"], "the old answer is not sent"); + assert_eq!(s.last_answer(), None, "it streams"); + s.apply(Event::Chunk { id, text: "two".into() }); + s.apply(Event::Done { id }); + assert_eq!(view(&s).rows.iter().map(|r| r.text.as_str()).collect::>(), ["One?", "1", "Two?", "two"]); + assert_eq!(s.edit_last().as_deref(), Some("Two?")); + assert_eq!(view(&s).rows.len(), 2); + let refused = s.retry(9 * MIN_SEND_INTERVAL_MS, Origin { level: ShieldLevel::Lockdown, ..ME }, true, |_| ShieldLevel::Standard); + assert!(!refused.iter().any(|e| matches!(e, Effect::Start { .. }))); + assert!(view(&s).rows.iter().all(|r| r.interrupted), "a refused retry never sends the exchange later"); + } + + #[test] + fn answers_from_a_site_now_in_lockdown_lose_their_text_before_a_save() { + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let store = &core.disk; + let me = Origin { profile: store.create_profile("P", "u8", false).unwrap().id, ..ME }; + let mut s = Session::new(me, true).unwrap(); + s.apply(Event::AddPill(me, page("secret page"))); + answered(&mut s, "What?", "The secret is 42.", 0); + s.send("More?", ASK, MIN_SEND_INTERVAL_MS, me, true, |_| ShieldLevel::Lockdown); + let id = saved(&mut s, store).unwrap(); + let saved = store.chat(me.profile, id).unwrap().unwrap(); + assert_eq!(saved.turns.iter().map(|t| t.text.as_str()).collect::>(), ["What?", FORGOTTEN]); + assert!(saved.turns.iter().all(|t| t.interrupted)); + } + + #[test] + fn a_retry_goes_where_its_command_went_and_a_failed_save_is_said() { + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let store = &core.disk; + let me = Origin { profile: store.create_profile("P", "u7", false).unwrap().id, ..ME }; + let mut s = Session::new(me, true).unwrap(); + s.apply(Event::AddPill(me, sel("text"))); + let (id, _) = started(&s.send("", "Explain {selection}. {question}", 0, me, true, |_| ShieldLevel::Standard)); + s.apply(Event::Chunk { id, text: "It means x.".into() }); + s.apply(Event::Done { id }); + assert!(s.last_was_command()); + let (id, _) = started(&s.retry(MIN_SEND_INTERVAL_MS, me, true, |_| ShieldLevel::Standard)); + assert!(s.last_was_command(), "a retried command still runs on the device where it can"); + s.apply(Event::Done { id }); + answered(&mut s, "Plain?", "Yes.", 2 * MIN_SEND_INTERVAL_MS); + assert!(!s.last_was_command()); + let chat = saved(&mut s, store).unwrap(); + store.delete_chat(me.profile, chat).unwrap(); + assert_eq!(saved(&mut s, store), None); + assert_eq!(view(&s).notice.as_deref(), Some(NOT_SAVED)); + let fresh = Session::new(me, true).map(|mut f| { + answered(&mut f, "New?", "Yes.", 0); + saved(&mut f, store).unwrap() + }); + assert_ne!(fresh, Some(chat), "a deleted chat's id is never given again"); + answered(&mut s, "Stale?", "Late.", 9 * MIN_SEND_INTERVAL_MS); + assert_eq!(saved(&mut s, store), None, "a window still holding the deleted chat cannot save it"); + let kept = store.chat(me.profile, fresh.unwrap()).unwrap().unwrap(); + assert_eq!(kept.turns.iter().map(|t| t.text.as_str()).collect::>(), ["New?", "Yes."], "the new chat is untouched"); + let mut one = Session::new(me, true).unwrap(); + answered(&mut one, "Only?", "Yes.", 0); + let only = saved(&mut one, store).unwrap(); + one.edit_last(); + assert_eq!(saved(&mut one, store), None); + assert!(store.chat(me.profile, only).unwrap().is_none(), "a chat whose every turn was taken back is deleted"); + } + + #[test] + fn a_slash_runs_the_longest_whole_command_name() { + use commands::{slash, slash_menu}; + let all = [("Summarize", "s"), ("Translate", "t"), ("Translate Formal", "f")].map(|(n, t)| (n.to_owned(), t.to_owned())).to_vec(); + assert_eq!(slash("/summarize", &all), Some((0, ""))); + assert_eq!(slash(" /Translate into German ", &all), Some((1, "into German"))); + assert_eq!(slash("/translate formal hi", &all), Some((2, "hi"))); + assert_eq!(slash("/Summarized", &all), None, "a name ends at white space"); + assert_eq!(slash("/tr", &all), None, "a part of a name runs nothing"); + assert_eq!(slash("Summarize", &all), None); + assert_eq!(slash("/é", &all), None); + assert_eq!(slash_menu("/", &all), [0, 1, 2]); + assert_eq!(slash_menu("/TRANS", &all), [1, 2]); + assert!(slash_menu("/translate x", &all).is_empty()); + assert!(slash_menu("why", &all).is_empty()); + let mine = [("Écrire".to_owned(), "e".to_owned())]; + assert_eq!(slash_menu("/éc", &mine), [0], "case without ASCII"); + assert_eq!(slash("/écrire vite", &mine), Some((0, "vite")), "the menu's match also runs"); + let custom = [store::AiCommand { id: 1, profile_id: 1, name: "Écrire".into(), template: "x".into() }]; + assert!(commands::check("écrire", "y", &custom, None).is_err(), "the same name in another case"); + } + + #[test] + fn a_restored_command_retries_on_its_route_and_a_save_forgets_lockdown_content() { + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let store = &core.disk; + let me = Origin { profile: store.create_profile("P", "u6", false).unwrap().id, ..ME }; + let open = |_: &url::Url| ShieldLevel::Standard; + let mut s = Session::new(me, true).unwrap(); + s.apply(Event::AddPill(me, sel("text"))); + let (id, _) = started(&s.send("", "Explain {selection}. {question}", 0, me, true, open)); + s.apply(Event::Chunk { id, text: "It means x.".into() }); + s.apply(Event::Done { id }); + answered(&mut s, "Plain?", "Yes.", MIN_SEND_INTERVAL_MS); + let chat = s.save_with(store, open).unwrap(); + let mut back = Session::restore(me, true, &store.chat(me.profile, chat).unwrap().unwrap(), open).unwrap(); + assert!(!back.last_was_command()); + back.edit_last(); + assert!(back.last_was_command(), "the command before keeps its route"); + let preview: Vec = view(&back).will_send.into_iter().map(|(label, _)| label).collect(); + assert_eq!(preview, ["Question 1", "Answer 1"], "the preview follows the cut"); + let mut live = Session::new(me, true).unwrap(); + live.apply(Event::AddPill(me, page("secret page"))); + answered(&mut live, "What?", "The secret is 42.", 0); + let id = live.save_with(store, |_| ShieldLevel::Lockdown).unwrap(); + assert_eq!(store.chat(me.profile, id).unwrap().unwrap().turns[1].text, FORGOTTEN, "a save forgets what a site now in Lockdown gave"); + } + + #[test] + fn a_command_needs_a_free_name_and_some_text() { + use commands::check; + let mine = store::AiCommand { id: 4, profile_id: 1, name: "Tone".into(), template: "x".into() }; + let custom = [mine]; + assert!(check(" ", "x", &custom, None).is_err()); + assert!(check("summarize", "x", &custom, None).is_err(), "built-in names are taken without case"); + assert!(check("TONE", "x", &custom, None).is_err()); + assert_eq!(check("Tone", "y", &custom, Some(4)), Ok(()), "an edit keeps its own name"); + assert!(check("Haiku", " ", &custom, None).is_err()); + assert!(check(&"a".repeat(store::MAX_AI_NAME + 1), "x", &custom, None).is_err()); + assert!(check("Haiku", &"x".repeat(store::MAX_AI_TEMPLATE + 1), &custom, None).is_err()); + assert_eq!(check("Haiku", "Rewrite {selection} as a haiku.", &custom, None), Ok(())); + } + + #[test] + fn chats_are_found_by_any_part_of_their_title() { + let chat = |id, title: &str| store::ChatTitle { id, title: title.to_owned(), updated: 0 }; + let chats = [chat(1, "Trip to Lisbon"), chat(2, "Rust lifetimes")]; + let ids = |q| find_chats(&chats, q).into_iter().map(|c| c.id).collect::>(); + assert_eq!(ids(""), [1, 2]); + assert_eq!(ids(" LIS "), [1]); + assert!(ids("zzz").is_empty()); + } + + #[test] + fn the_claude_model_falls_back_to_the_first() { + use settings::*; + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let store = &core.disk; + assert_eq!(claude_model_id(store), CLAUDE_MODELS[0].0); + assert!(set_claude_model(store, 2)); + assert_eq!((claude_model(store), claude_model_id(store)), (2, CLAUDE_MODELS[2].0.to_owned())); + assert!(!set_claude_model(store, 3)); + store.set_setting(CLAUDE_MODEL_KEY, "gpt").unwrap(); + assert_eq!(claude_model(store), 0); + } + #[test] fn provider_and_model_settings_fall_back_to_defaults() { use settings::*; diff --git a/crates/browser-core/src/notes.rs b/crates/browser-core/src/notes.rs index 22bd4763..44ebdcb4 100644 --- a/crates/browser-core/src/notes.rs +++ b/crates/browser-core/src/notes.rs @@ -13,6 +13,42 @@ pub const PRIVATE: &str = "Notes belong to a saved profile. Open them outside a pub const EMPTY: &str = "No notes yet."; pub const NO_MATCH: &str = "No notes match."; pub const UNTITLED: &str = "Untitled"; +pub const SORT_KEY: &str = "notes_sort"; + +/// How the notes list is ordered, kept in Settings for every client. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sort { + #[default] + Edited, + Title, +} + +impl Sort { + pub const ALL: [Sort; 2] = [Sort::Edited, Sort::Title]; + + pub fn name(self) -> &'static str { + match self { + Sort::Edited => "Last Edited", + Sort::Title => "Title", + } + } + + fn key(self) -> &'static str { + match self { + Sort::Edited => "edited", + Sort::Title => "title", + } + } + + pub fn load(store: &Store) -> Sort { + let stored = store.setting(SORT_KEY).ok().flatten(); + Sort::ALL.into_iter().find(|s| Some(s.key()) == stored.as_deref()).unwrap_or_default() + } + + pub fn save(self, store: &Store) -> bool { + store.set_setting(SORT_KEY, self.key()).is_ok() + } +} #[derive(Clone, Debug, PartialEq, Eq)] pub struct Row { @@ -24,6 +60,11 @@ pub struct Row { /// The list for `query`: every note when it is blank, else notes whose title or text contains it /// without case, title matches first; each keeps the store's order (last edited first). pub fn rows(notes: &[Note], query: &str) -> Vec { + sorted(notes, query, Sort::Edited) +} + +/// `rows` in `sort`'s order within title and text matches. +pub fn sorted(notes: &[Note], query: &str, sort: Sort) -> Vec { let query = query.trim().to_lowercase(); let mut found: Vec<(bool, &Note)> = notes .iter() @@ -33,7 +74,11 @@ pub fn rows(notes: &[Note], query: &str) -> Vec { }) .collect(); found.sort_by_key(|(in_body, _)| *in_body); - found.into_iter().map(|(_, n)| Row { id: n.id, title: title(n), preview: preview(n) }).collect() + let mut rows: Vec<(bool, Row)> = found.into_iter().map(|(in_body, n)| (in_body, Row { id: n.id, title: title(n), preview: preview(n) })).collect(); + if sort == Sort::Title { + rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.title.to_lowercase().cmp(&b.1.title.to_lowercase()))); + } + rows.into_iter().map(|(_, r)| r).collect() } /// The note's title, else its first line, else `UNTITLED`, bounded for display. @@ -55,9 +100,18 @@ pub fn preview(note: &Note) -> String { crate::text::bounded_title(lines.next().unwrap_or_default()) } -/// The pill that attaches `note` to an assistant question: its title and text. -pub fn as_pill(note: &Note) -> Pill { - Pill::Note(note.id, if note.title.is_empty() { note.body.clone() } else { format!("{}\n\n{}", note.title, note.body) }) +/// Every note as one Markdown file, in the store's order: each a heading, its text and a rule. +pub fn markdown(notes: &[Note]) -> String { + notes.iter().map(|n| format!("# {}\n\n{}\n", title(n).replace('#', "\\#"), n.body.trim_end())).collect::>().join("\n---\n\n") +} + +pub const EXPORT_NAME: &str = "Tarn Notes.md"; + +/// The pill that attaches `note` to an assistant question in `profile`: its title and text; +/// none for another profile's note. +pub fn as_pill(note: &Note, profile: Id) -> Option { + (note.profile_id == profile) + .then(|| Pill::Note(note.id, if note.title.is_empty() { note.body.clone() } else { format!("{}\n\n{}", note.title, note.body) })) } /// A note being written (`id` none) or edited. @@ -110,10 +164,31 @@ mod tests { assert_eq!(shown[3].title, UNTITLED); } + #[test] + fn title_order_sorts_within_title_and_text_matches_and_is_kept() { + let all = [note(1, "b reef", ""), note(2, "", "reef"), note(3, "A reef", ""), note(4, "C", "x reef")]; + let ids = |q, sort| sorted(&all, q, sort).into_iter().map(|r| r.id).collect::>(); + assert_eq!(ids("reef", Sort::Title), [3, 1, 4, 2]); + assert_eq!(ids("reef", Sort::Edited), [1, 3, 2, 4]); + let store = Store::open_in_memory().unwrap(); + assert_eq!(Sort::load(&store), Sort::Edited); + assert!(Sort::Title.save(&store)); + assert_eq!(Sort::load(&store), Sort::Title); + store.set_setting(SORT_KEY, "other").unwrap(); + assert_eq!(Sort::load(&store), Sort::Edited); + } + + #[test] + fn markdown_gives_each_note_a_heading_that_cannot_nest() { + assert_eq!(markdown(&[note(1, "# Trip", "Day 1\n\n"), note(2, "", "only")]), "# \\# Trip\n\nDay 1\n\n---\n\n# only\n\nonly\n"); + assert_eq!(markdown(&[]), ""); + } + #[test] fn a_pill_carries_title_and_text() { - assert_eq!(as_pill(¬e(7, "T", "b")), Pill::Note(7, "T\n\nb".into())); - assert_eq!(as_pill(¬e(8, "", "b")), Pill::Note(8, "b".into())); + assert_eq!(as_pill(¬e(7, "T", "b"), 1), Some(Pill::Note(7, "T\n\nb".into()))); + assert_eq!(as_pill(¬e(8, "", "b"), 1), Some(Pill::Note(8, "b".into()))); + assert_eq!(as_pill(¬e(8, "", "b"), 2), None, "another profile's note"); } #[test] diff --git a/crates/browser-core/src/shield_card.rs b/crates/browser-core/src/shield_card.rs index efc1d8c1..a02ec8b4 100644 --- a/crates/browser-core/src/shield_card.rs +++ b/crates/browser-core/src/shield_card.rs @@ -23,9 +23,22 @@ pub struct Card { const DAY_MS: i64 = 86_400_000; +/// A new file `file` in a directory only its owner can open; the earlier exports of this run go, +/// so at most one copy of what was shared stays behind. pub fn export_path(file: &str) -> std::io::Result { static EXPORTS: AtomicU64 = AtomicU64::new(0); - let dir = std::env::temp_dir().join(format!("tarn-card-{}-{}", std::process::id(), EXPORTS.fetch_add(1, Ordering::Relaxed))); + let n = EXPORTS.fetch_add(1, Ordering::Relaxed); + let prefix = format!("tarn-card-{}-", std::process::id()); + if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) { + for entry in entries.flatten() { + let name = entry.file_name(); + let earlier = name.to_str().and_then(|n| n.strip_prefix(&prefix)).and_then(|k| k.parse::().ok()).is_some_and(|k| k < n); + if earlier { + std::fs::remove_dir_all(entry.path()).ok(); + } + } + } + let dir = std::env::temp_dir().join(format!("{prefix}{n}")); #[cfg(unix)] let builder = { let mut builder = std::fs::DirBuilder::new(); @@ -531,7 +544,10 @@ mod tests { let path = export_path("card.png").unwrap(); let dir = path.parent().unwrap(); assert_eq!(std::fs::metadata(dir).unwrap().permissions().mode() & 0o777, 0o700); - std::fs::remove_dir(dir).unwrap(); + std::fs::write(&path, "notes").unwrap(); + let next = export_path("card.png").unwrap(); + assert!(!dir.exists(), "an earlier export goes with the next"); + std::fs::remove_dir(next.parent().unwrap()).unwrap(); } #[test] diff --git a/crates/browser-core/src/snippets.rs b/crates/browser-core/src/snippets.rs index e3a88df7..652692ac 100644 --- a/crates/browser-core/src/snippets.rs +++ b/crates/browser-core/src/snippets.rs @@ -26,6 +26,10 @@ pub const NO_INSERT: &str = "Snippets cannot be typed into a Lockdown page"; pub const PAGE_CHANGED: &str = "The page changed, so the snippet was not typed"; /// What Insert Snippet lists when the profile has none. pub const EMPTY: &str = "No snippets yet. Add them in Settings \u{203a} Snippets."; +/// Settings' switch for `;name` in the address and command bar, on every client. +pub const EXPAND: crate::prefs::Switch = crate::prefs::Switch { key: "snippet_expand", default: true }; +pub const EXPAND_NOTE: &str = "Off, ;name stays as you typed it; Insert Snippet\u{2026} still works."; +pub const NO_MATCH: &str = "No snippets match."; /// `text` with a trailing `;name` replaced by that snippet's body on one line, when `name` is one /// of `snippets` and the `;` starts the text or follows white space; `None` otherwise. @@ -89,6 +93,12 @@ impl Core { pub fn snippets_changed(&self) { self.snippets.borrow_mut().take(); } + + /// A shell field's `text` with a trailing `;name` of `profile`'s snippets expanded, while + /// Settings' `EXPAND` switch is on. + pub fn expand_snippet(&self, profile: Option<(bool, Id)>, text: &str) -> Option { + EXPAND.on(&self.disk).then(|| expand(text, &self.snippets(profile))).flatten() + } } #[cfg(test)] @@ -110,6 +120,18 @@ mod tests { assert!(core.snippets(Some((false, p))).is_empty()); } + #[test] + fn expansion_follows_the_settings_switch() { + let dir = tempfile::tempdir().unwrap(); + let core = crate::TestCore::open(dir.path(), false); + let id = core.disk.profiles().unwrap().remove(0).id; + let p = Some((false, id)); + core.disk.save_snippet(id, "sig", "Ada").unwrap(); + assert_eq!(core.expand_snippet(p, "hi ;sig").as_deref(), Some("hi Ada")); + assert!(EXPAND.set(&core.disk, false)); + assert_eq!(core.expand_snippet(p, "hi ;sig"), None); + } + fn snippet(name: &str, body: &str) -> Snippet { Snippet { id: 0, profile_id: 1, name: name.into(), body: body.into() } } diff --git a/crates/store/src/db.rs b/crates/store/src/db.rs index 3cc832c0..cfdd4136 100644 --- a/crates/store/src/db.rs +++ b/crates/store/src/db.rs @@ -10,8 +10,8 @@ use rusqlite::{Connection, OptionalExtension, Row, params}; use shield::ShieldLevel; use crate::models::{ - AiCommand, Bookmark, Counter, Download, Folder, Group, HistoryEntry, Id, InstalledExtension, InstalledTheme, Layout, Note, Profile, SavedWindow, Schedule, - ShieldDay, ShieldStats, Slot, Snapshot, Snippet, Space, SpaceRule, Tab, TabKind, WebEngine, + AiCommand, Bookmark, Chat, ChatTitle, ChatTurn, Counter, Download, Folder, Group, HistoryEntry, Id, InstalledExtension, InstalledTheme, Layout, Note, + Profile, SavedWindow, Schedule, ShieldDay, ShieldStats, Slot, Snapshot, Snippet, Space, SpaceRule, Tab, TabKind, WebEngine, }; const MIGRATIONS: &[&str] = &[ @@ -228,12 +228,21 @@ const MIGRATIONS: &[&str] = &[ body TEXT NOT NULL, updated INTEGER NOT NULL );", + "CREATE TABLE chats ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + profile_id INTEGER NOT NULL REFERENCES profiles(id) ON DELETE CASCADE, + title TEXT NOT NULL, + turns TEXT NOT NULL, + sources TEXT NOT NULL, + updated INTEGER NOT NULL + ); + CREATE INDEX chats_profile ON chats(profile_id, updated);", ]; /// Tables that belong to no profile: never exported, reset or synced with one. #[cfg(test)] -const PROFILE_NEUTRAL: [&str; 3] = ["settings", "themes", "windows"]; +const PROFILE_NEUTRAL: [&str; 4] = ["settings", "themes", "windows", "sqlite_sequence"]; /// Every table holding profile data, with the filter that selects one profile's rows. -const PROFILE_TABLES: [(&str, &str); 30] = [ +const PROFILE_TABLES: [(&str, &str); 31] = [ ("profiles", "id = ?1"), ("spaces", "profile_id = ?1"), ("folders", "space_id IN (SELECT id FROM spaces WHERE profile_id = ?1)"), @@ -264,6 +273,7 @@ const PROFILE_TABLES: [(&str, &str); 30] = [ ("feature_hints", "profile_id = ?1"), ("snippets", "profile_id = ?1"), ("notes", "profile_id = ?1"), + ("chats", "profile_id = ?1"), ]; /// Sites kept per profile for the privacy report's list. const MAX_SHIELD_SITES: i64 = 200; @@ -293,6 +303,11 @@ pub fn valid_snippet_name(name: &str) -> bool { pub const MAX_NOTE_TITLE: usize = 200; pub const MAX_NOTE: usize = 64 * 1024; pub const MAX_NOTES: usize = 1000; +/// The most chats a profile keeps and the most bytes one chat's turns and sources take. +pub const MAX_CHATS: usize = 200; +pub const MAX_CHAT: usize = 1024 * 1024; +/// What `rename_chat` refuses when the profile has no such chat, as opposed to a bad title. +pub const MISSING_CHAT: &str = "missing chat"; /// The most CSS one site may keep, in bytes. pub const MAX_SITE_CSS: usize = 64 * 1024; @@ -1224,6 +1239,90 @@ impl Store { Ok(()) } + /// The profile's chats without their turns, last changed first. + pub fn chat_titles(&self, profile_id: Id) -> Result> { + let mut stmt = self.conn.prepare("SELECT id, title, updated FROM chats WHERE profile_id = ?1 ORDER BY updated DESC, id DESC")?; + let rows = stmt.query_map([profile_id], |r| Ok(ChatTitle { id: r.get(0)?, title: r.get(1)?, updated: r.get(2)? }))?; + Ok(rows.collect::>()?) + } + + /// The profile's chat `id`; none when it has no such chat or its rows cannot be read. + pub fn chat(&self, profile_id: Id, id: Id) -> Result> { + let row = self.conn.query_row("SELECT title, turns, sources, updated FROM chats WHERE profile_id = ?1 AND id = ?2", params![profile_id, id], |r| { + Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, i64>(3)?)) + }); + let (title, turns, sources, updated) = match row { + Err(rusqlite::Error::QueryReturnedNoRows) => return Ok(None), + other => other?, + }; + let (Some(turns), Some(sources)) = (chat_turns(&turns), chat_sources(&sources)) else { return Ok(None) }; + Ok(Some(Chat { id, profile_id, title, turns, sources, updated })) + } + + /// Adds a chat (`id` none) or replaces the profile's chat `id`, its title `visible` on one + /// line (`None` keeps a saved chat's title) and its text `visible`. Refused for a private + /// profile, an empty chat, a new chat without a title, a title past `MAX_NOTE_TITLE` + /// characters, turns and sources past `MAX_CHAT` bytes, or a new chat past `MAX_CHATS`. + pub fn save_chat(&self, profile_id: Id, id: Option, title: Option<&str>, turns: &[ChatTurn], sources: &[(String, usize)]) -> Result { + use serde_json::json; + let title = title.map(|t| visible(t).split_whitespace().collect::>().join(" ")); + let turns_json = serde_json::Value::Array( + turns.iter().map(|t| json!({ "you": t.you, "text": visible(&t.text), "by": t.by.as_deref().map(visible), "interrupted": t.interrupted, "command": t.command })).collect(), + ) + .to_string(); + let sources_json = serde_json::Value::Array(sources.iter().map(|(url, since)| json!([visible(url), since])).collect()).to_string(); + let bad_title = title.as_ref().map_or(id.is_none(), |t| t.is_empty() || t.chars().count() > MAX_NOTE_TITLE); + if turns.is_empty() || bad_title || turns_json.len() + sources_json.len() > MAX_CHAT { + return Err(Error::Invalid("chat")); + } + let updated = now_ms(); + let id = match id { + None => self.conn.query_row( + "INSERT INTO chats (profile_id, title, turns, sources, updated) + SELECT id, ?2, ?3, ?4, ?5 FROM profiles + WHERE id = ?1 AND NOT is_private AND (SELECT COUNT(*) FROM chats WHERE profile_id = ?1) < ?6 + RETURNING id", + params![profile_id, title, turns_json, sources_json, updated, MAX_CHATS as i64], + |r| r.get(0), + ), + Some(id) => self.conn.query_row( + "UPDATE chats SET title = COALESCE(?3, title), turns = ?4, sources = ?5, updated = ?6 + WHERE id = ?2 AND profile_id = ?1 AND profile_id IN (SELECT id FROM profiles WHERE NOT is_private) + RETURNING id", + params![profile_id, id, title, turns_json, sources_json, updated], + |r| r.get(0), + ), + }; + match id { + Err(rusqlite::Error::QueryReturnedNoRows) => Err(Error::Invalid("chat")), + other => Ok(other?), + } + } + + /// Renames the profile's chat `id`, with the rules of `save_chat`'s title. + pub fn rename_chat(&self, profile_id: Id, id: Id, title: &str) -> Result<()> { + let title = visible(title).split_whitespace().collect::>().join(" "); + if title.is_empty() || title.chars().count() > MAX_NOTE_TITLE { + return Err(Error::Invalid("chat title")); + } + match self.conn.execute("UPDATE chats SET title = ?3 WHERE profile_id = ?1 AND id = ?2", params![profile_id, id, title])? { + 0 => Err(Error::Invalid(MISSING_CHAT)), + _ => Ok(()), + } + } + + pub fn delete_chat(&self, profile_id: Id, id: Id) -> Result<()> { + self.conn.execute("DELETE FROM chats WHERE profile_id = ?1 AND id = ?2", params![profile_id, id])?; + self.checkpoint().ok(); + Ok(()) + } + + pub fn delete_chats(&self, profile_id: Id) -> Result<()> { + self.conn.execute("DELETE FROM chats WHERE profile_id = ?1", [profile_id])?; + self.checkpoint().ok(); + Ok(()) + } + /// When the profile was created, when it last showed any feature hint, and how often it /// showed `hint`. pub fn hint_counts(&self, profile_id: Id, hint: &str) -> Result<(i64, Option, i64)> { @@ -2074,6 +2173,27 @@ fn check_ai_command(name: &str, template: &str) -> Result { Ok(visible(template)) } +fn chat_turns(json: &str) -> Option> { + let list = serde_json::from_str::(json).ok()?; + list.as_array()? + .iter() + .map(|t| { + Some(ChatTurn { + you: t.get("you")?.as_bool()?, + text: t.get("text")?.as_str()?.to_owned(), + by: t.get("by").and_then(|b| b.as_str()).map(str::to_owned), + interrupted: t.get("interrupted")?.as_bool()?, + command: t.get("command").and_then(serde_json::Value::as_bool).unwrap_or(true), + }) + }) + .collect() +} + +fn chat_sources(json: &str) -> Option> { + let list = serde_json::from_str::(json).ok()?; + list.as_array()?.iter().map(|s| Some((s.get(0)?.as_str()?.to_owned(), usize::try_from(s.get(1)?.as_u64()?).ok()?))).collect() +} + /// `text` without invisible characters (`is_invisible`) or control characters other than line /// breaks and tabs. fn visible(text: &str) -> String { @@ -2547,6 +2667,48 @@ mod tests { assert_eq!(store.conn.query_row("SELECT COUNT(*) FROM feature_hints", [], |r| r.get::<_, i64>(0)).unwrap(), 0); } + #[test] + fn chats_are_clean_capped_per_profile_and_go_with_the_profile_and_its_reset() { + let mut store = store_before("CREATE TABLE chats"); + store.conn.execute_batch("INSERT INTO profiles (id, name, data_store_uuid, created_at) VALUES (1, 'P', 'u1', 5), (2, 'Q', 'u2', 6);").unwrap(); + store.migrate().unwrap(); + let private = store.create_profile("Private", "u3", true).unwrap().id; + let turn = |you: bool, text: &str| ChatTurn { you, text: text.into(), by: (!you).then(|| "M".into()), interrupted: false, command: you }; + let turns = [turn(true, "Why\u{202e}?"), turn(false, "Because\u{7}.")]; + let sources = [("https://a.test/p".to_owned(), 0)]; + let id = store.save_chat(1, None, Some(" Why\n sky "), &turns, &sources).unwrap(); + let chat = store.chat(1, id).unwrap().unwrap(); + assert_eq!(chat.title, "Why sky"); + assert_eq!(chat.turns, [turn(true, "Why?"), turn(false, "Because.")]); + assert_eq!(chat.sources, sources); + assert_eq!(store.save_chat(1, Some(id), None, &turns[..1], &[]).unwrap(), id); + assert_eq!(store.chat(1, id).unwrap().unwrap().title, "Why sky", "None keeps the title"); + assert!(store.save_chat(1, None, None, &turns, &[]).is_err(), "a new chat needs a title"); + assert_eq!(store.chat(1, id).unwrap().unwrap().turns.len(), 1); + assert!(store.chat(2, id).unwrap().is_none(), "chats are per profile"); + assert!(store.save_chat(2, Some(id), Some("x"), &turns, &[]).is_err(), "another profile cannot edit it"); + assert!(store.save_chat(private, None, Some("x"), &turns, &[]).is_err(), "nothing of a private profile is written"); + assert!(store.save_chat(1, None, Some("x"), &[], &[]).is_err(), "an empty chat is not kept"); + assert!(store.save_chat(1, None, Some(" "), &turns, &[]).is_err()); + assert!(store.save_chat(1, None, Some("x"), &[turn(true, &"x".repeat(MAX_CHAT))], &[]).is_err()); + store.rename_chat(1, id, "Sky").unwrap(); + assert!(matches!(store.rename_chat(2, id, "Not mine"), Err(Error::Invalid(MISSING_CHAT))), "another profile's chat is not renamed"); + assert!(matches!(store.rename_chat(1, id, " "), Err(Error::Invalid(what)) if what != MISSING_CHAT), "a bad title is told apart from a missing chat"); + assert_eq!(store.chat_titles(1).unwrap().iter().map(|c| c.title.as_str()).collect::>(), ["Sky"]); + assert!(store.rename_chat(1, id, "\u{200b}").is_err()); + store.delete_chat(2, id).unwrap(); + assert_eq!(store.chat_titles(1).unwrap().len(), 1, "another profile's id deletes nothing"); + assert!(store.export_profile(1).unwrap().contains("\"chats\"")); + store.reset_profile(1, "S").unwrap(); + assert!(store.chat_titles(1).unwrap().is_empty()); + store.save_chat(2, None, Some("x"), &turns, &[]).unwrap(); + store.delete_chats(2).unwrap(); + assert!(store.chat_titles(2).unwrap().is_empty()); + store.save_chat(2, None, Some("x"), &turns, &[]).unwrap(); + store.delete_profile(2).unwrap(); + assert_eq!(store.conn.query_row("SELECT COUNT(*) FROM chats", [], |r| r.get::<_, i64>(0)).unwrap(), 0); + } + #[test] fn notes_are_clean_capped_per_profile_and_go_with_the_profile_and_its_reset() { let mut store = store_before("CREATE TABLE notes"); diff --git a/crates/store/src/lib.rs b/crates/store/src/lib.rs index 3aefec75..48160dfe 100644 --- a/crates/store/src/lib.rs +++ b/crates/store/src/lib.rs @@ -4,12 +4,12 @@ mod db; mod models; pub use db::{ - Error, MAX_AI_NAME, MAX_AI_TEMPLATE, MAX_HISTORY_TEXT, MAX_NOTE, MAX_NOTE_TITLE, MAX_NOTES, MAX_SITE_CSS, MAX_SNIPPET, MAX_SNIPPET_NAME, MAX_THEME_CSS, - Store, clip_history_text, valid_snippet_name, + Error, MAX_AI_NAME, MAX_AI_TEMPLATE, MAX_CHAT, MAX_CHATS, MAX_HISTORY_TEXT, MAX_NOTE, MAX_NOTE_TITLE, MAX_NOTES, MAX_SITE_CSS, MAX_SNIPPET, + MAX_SNIPPET_NAME, MAX_THEME_CSS, MISSING_CHAT, Store, clip_history_text, valid_snippet_name, }; pub use models::{ - AiCommand, Bookmark, Counter, Download, Folder, Group, HistoryEntry, Id, InstalledExtension, InstalledTheme, Layout, Note, Profile, SavedWindow, Schedule, - ShieldDay, ShieldStats, Slot, Snapshot, Snippet, Space, SpaceRule, Tab, TabKind, WebEngine, + AiCommand, Bookmark, Chat, ChatTitle, ChatTurn, Counter, Download, Folder, Group, HistoryEntry, Id, InstalledExtension, InstalledTheme, Layout, Note, + Profile, SavedWindow, Schedule, ShieldDay, ShieldStats, Slot, Snapshot, Snippet, Space, SpaceRule, Tab, TabKind, WebEngine, }; pub fn is_bidi(c: char) -> bool { diff --git a/crates/store/src/models.rs b/crates/store/src/models.rs index 8c0a9e0e..d5f59d8f 100644 --- a/crates/store/src/models.rs +++ b/crates/store/src/models.rs @@ -223,6 +223,36 @@ pub struct Snippet { pub body: String, } +/// One turn of a saved assistant chat: a question (`you`) or an answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChatTurn { + pub you: bool, + pub text: String, + pub by: Option, + pub interrupted: bool, + /// A question a command sent; unknown counts as one, so a retry stays on the device where it can. + pub command: bool, +} + +/// A saved assistant chat. `sources` are the addresses of content attached to it, each with the +/// first turn that may hold text from it, so a send can still drop what a site now in Lockdown gave. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Chat { + pub id: Id, + pub profile_id: Id, + pub title: String, + pub turns: Vec, + pub sources: Vec<(String, usize)>, + pub updated: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChatTitle { + pub id: Id, + pub title: String, + pub updated: i64, +} + /// A note the user wrote in a profile; `updated` is in milliseconds since the epoch. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Note { diff --git a/crates/ui/src/controls.rs b/crates/ui/src/controls.rs index fa18a3b9..a714bde1 100644 --- a/crates/ui/src/controls.rs +++ b/crates/ui/src/controls.rs @@ -671,12 +671,46 @@ pub fn focus_ring() -> Vec { vec![ring(Theme::accent_text(), 2., 0.)] } +/// The widest a paragraph of help text runs before it wraps. +pub const READABLE_WIDTH: f32 = 600.; + pub fn section(title: impl Into) -> Div { - div().pt_5().pb_2().px_1().text_size(px(TEXT)).font_weight(FontWeight::SEMIBOLD).text_color(Theme::text()).child(title.into()) + div().pt_6().pb_2().px_1().text_size(px(TEXT)).font_weight(FontWeight::SEMIBOLD).text_color(Theme::text()).child(title.into()) } pub fn note(text: impl Into) -> Div { - div().pt_1p5().px_1().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child(text.into()) + div().pt_1p5().px_1().max_w(px(READABLE_WIDTH)).text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child(text.into()) +} + +/// A compact icon button for an action on one row of a list, named by its tooltip. +pub fn row_action(id: impl Into, glyph: Icon, tip: impl Into) -> Stateful
{ + icon_frame(id, true).child(icon(glyph, 15., Theme::muted())).tooltip(tooltip(tip, None)) +} + +/// Hides `control` until the pointer is over the element marked `.group(group)`, or the +/// keyboard reaches it. +pub fn shown_on_hover(control: Stateful
, group: &'static str) -> Stateful
{ + control.opacity(0.).group_hover(group, |s| s.opacity(1.)).focus(|s| s.shadow(focus_ring()).opacity(1.)) +} + +/// A row's leading glyph on a soft tile. +pub fn leading_icon(glyph: Icon) -> Div { + div().w(px(28.)).h(px(28.)).flex().flex_none().items_center().justify_center().rounded(px(Theme::radius_row())).bg(Theme::control()).child(icon( + glyph, + 14., + Theme::muted(), + )) +} + +/// What a card of rows shows while it has none: a glyph, one line and, from the caller, an action. +pub fn empty_state(glyph: Icon, text: impl Into) -> Div { + group() + .py_5() + .px_4() + .items_center() + .gap_2() + .child(div().w(px(36.)).h(px(36.)).flex().items_center().justify_center().rounded_full().bg(Theme::control()).child(icon(glyph, 16., Theme::muted()))) + .child(div().max_w(px(READABLE_WIDTH - 120.)).text_center().text_size(px(TEXT_SMALL)).text_color(Theme::muted()).child(text.into())) } #[cfg(test)] diff --git a/docs/media/assistant/chat-commands.png b/docs/media/assistant/chat-commands.png new file mode 100644 index 00000000..235ac97e Binary files /dev/null and b/docs/media/assistant/chat-commands.png differ diff --git a/docs/media/assistant/chat-conversation.png b/docs/media/assistant/chat-conversation.png new file mode 100644 index 00000000..44ccee62 Binary files /dev/null and b/docs/media/assistant/chat-conversation.png differ diff --git a/docs/media/assistant/chat-list.png b/docs/media/assistant/chat-list.png new file mode 100644 index 00000000..02f66159 Binary files /dev/null and b/docs/media/assistant/chat-list.png differ diff --git a/docs/media/assistant/chat-note.png b/docs/media/assistant/chat-note.png new file mode 100644 index 00000000..c8cce73c Binary files /dev/null and b/docs/media/assistant/chat-note.png differ diff --git a/docs/media/assistant/settings-ai.png b/docs/media/assistant/settings-ai.png new file mode 100644 index 00000000..a735228c Binary files /dev/null and b/docs/media/assistant/settings-ai.png differ diff --git a/docs/media/assistant/settings-notes.png b/docs/media/assistant/settings-notes.png new file mode 100644 index 00000000..7088dba9 Binary files /dev/null and b/docs/media/assistant/settings-notes.png differ diff --git a/docs/media/assistant/settings-permissions.png b/docs/media/assistant/settings-permissions.png new file mode 100644 index 00000000..599b6c33 Binary files /dev/null and b/docs/media/assistant/settings-permissions.png differ diff --git a/docs/media/assistant/settings-privacy.png b/docs/media/assistant/settings-privacy.png new file mode 100644 index 00000000..77ea5f1f Binary files /dev/null and b/docs/media/assistant/settings-privacy.png differ diff --git a/docs/media/assistant/settings-profiles.png b/docs/media/assistant/settings-profiles.png new file mode 100644 index 00000000..04a2189f Binary files /dev/null and b/docs/media/assistant/settings-profiles.png differ diff --git a/docs/media/assistant/settings-snippets.png b/docs/media/assistant/settings-snippets.png new file mode 100644 index 00000000..bc11c267 Binary files /dev/null and b/docs/media/assistant/settings-snippets.png differ diff --git a/docs/media/assistant/window-with-chat.png b/docs/media/assistant/window-with-chat.png new file mode 100644 index 00000000..52eb6e9b Binary files /dev/null and b/docs/media/assistant/window-with-chat.png differ diff --git a/docs/port-backlog.md b/docs/port-backlog.md index 45c7d790..da4ef17e 100644 --- a/docs/port-backlog.md +++ b/docs/port-backlog.md @@ -21,6 +21,19 @@ Reference: . ## Open +### Insert an assistant answer into the page (2026-11-24) + +What it does: the chat's Insert into Page types the last answer into the page's focused field, as +Insert Snippet does, refused under Lockdown. +Shared API: `browser_core::assistant::Session::last_answer`, then each client's Insert Snippet path +(`page_scripts::insert_text_script`, `snippets::inserted`). +Reference: `crates/app/src/assistant.rs` (`insert_last_answer`), `crates/app/src/snippets.rs`. + +- [ ] Linux — a bubble action in `nsh-shared/src/assistant.rs` through a new `Host` method that + `linux/src/browser/snippets.rs` answers with its Insert Snippet request. +- [ ] iOS — the same `Host` method answered by `mobile/app/src/snippets.rs`. +- [ ] Android — as iOS; the insert script runs in the page's world there (threat model S1). + ### Portable download (2026-11-24) What it does: a download that runs without installing and keeps all its data in a `Data` folder diff --git a/docs/threat-model.md b/docs/threat-model.md index 4ba5db80..fec0b4c4 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -8,7 +8,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | ID | Severity | Threat | Mitigation | Status | |---|---|---|---|---| -| S1 | Critical | A web page reaches shell functions through a JS bridge or an internal page | No script message handlers in tab web views. Internal pages use a separate configuration and data store, bundled assets only, strict CSP; web content cannot link to, embed or navigate to them. | Tab web views get no script message handler; `tarn:` is blocked for web sources in `nav_policy`. Popups use WebKit's own configuration, so they keep the opener's request context. Snippets reach a page only through the user's Insert Snippet command: `page_scripts::insert_text_script` runs once in the isolated world (none under Lockdown) and types the text into the focused field with `execCommand`, skipping password fields; `;name` expansion happens in shell fields only, and no world of the page gets a key listener. Capture Area and Measure draw over a still snapshot in the shell; the Capture Element picker answers only a rectangle. Ask Assistant about Selection and its commands read the selection with the same `SELECTED_TEXT` script after the user picks the entry in the page's own menu (isolated world on macOS, Windows, Linux and iOS; on Android the page-world answer goes through `page_ops::selection_answer`), so no text comes from a password, one-time-code or card field and nothing is read under Lockdown (`ask_assistant_reads_the_selection_with_its_command_but_never_a_secret_field`, `the_selection_is_read_but_never_from_a_secret_field`); the menu entries add no script or listener to the page. | +| S1 | Critical | A web page reaches shell functions through a JS bridge or an internal page | No script message handlers in tab web views. Internal pages use a separate configuration and data store, bundled assets only, strict CSP; web content cannot link to, embed or navigate to them. | Tab web views get no script message handler; `tarn:` is blocked for web sources in `nav_policy`. Popups use WebKit's own configuration, so they keep the opener's request context. Snippets, and an assistant answer the user inserts with Insert into Page (macOS and Windows), reach a page only through the user's command; an answer may carry what another attached page said, so it reaches the focused field's site only by that click: `page_scripts::insert_text_script` runs once in the isolated world (none under Lockdown) and types the text into the focused field with `execCommand`, skipping password fields; `;name` expansion happens in shell fields only, and no world of the page gets a key listener. Capture Area and Measure draw over a still snapshot in the shell; the Capture Element picker answers only a rectangle. Ask Assistant about Selection and its commands read the selection with the same `SELECTED_TEXT` script after the user picks the entry in the page's own menu (isolated world on macOS, Windows, Linux and iOS; on Android the page-world answer goes through `page_ops::selection_answer`), so no text comes from a password, one-time-code or card field and nothing is read under Lockdown (`ask_assistant_reads_the_selection_with_its_command_but_never_a_secret_field`, `the_selection_is_read_but_never_from_a_secret_field`); the menu entries add no script or listener to the page. | | S17 | Critical | Page text injects instructions into the Claude CLI, which can run commands and read files | Helper runs the CLI with tools and MCP disabled, fixed arguments, no shell, prompt on stdin, minimal environment, empty temporary working directory, timeout and output cap. Binary path is absolute, chosen by the user, and must not be world-writable. The helper accepts connections only from our signed app. If tool disabling cannot be confirmed, the provider refuses to run. | `tarn-cli-bridge` enforces the CLI rules: fixed arguments, `--help` probe, stdin prompt, only `HOME` and `PATH=/usr/bin:/bin`, own process group killed when the run ends or times out, and the binary plus every ancestor directory owned by the user or root and writable only by them, `wheel` or `admin`. Cancelling in the app stops the bridge, not the CLI it started. Not reachable from the packaged app only because `scripts/bundle.sh` does not ship the helper: the app runs without the App Sandbox, so a child would no longer inherit one. The XPC helper and its caller check are not built. An npm-installed CLI (`#!/usr/bin/env node`) does not start with that `PATH`. | | S2 | High | Prompt injection makes the AI leak data or act | The model has no tools in any provider. Output is rendered natively as text: no remote images, no auto-opened links. Grouping returns schema-validated JSON limited to the tab IDs sent and is applied after confirmation. Context is limited to the active profile; query strings are stripped from URLs. | Linux, iOS and Android draw the chat from `browser_core::assistant::view` with `tarn_nsh_shared::assistant`: answers are drawn natively from `ai::markdown` (images as alt text, HTML as text), and a link opens only through `links::classify` and a confirmation that shows the whole address, a web link in a new tab of the chat's profile; Clean Up's Group with Assistant checks the answer with `ai::grouping::parse` against the tabs it sent and files them only after a confirmation, undoably (`a_grouping_answer_is_checked_against_the_tabs_sent`, `the_assistant_groups_only_what_it_was_sent_and_undo_takes_it_back`); the chat ends once the window shows another profile, a private space, a burner tab, a Lockdown page or AI turned off, checked on every change and again after a link's confirmation, so a link opens only in the chat's own profile (`the_chat_ends_once_the_window_shows_another_profile_or_a_space_it_may_not_see`), and a page's text is read for a pill only where the assistant may see it. On every client a grouping is shown and applied only while the space it was asked in is current with the assistant allowed (`sidebar::grouping_here`), and group names lose control, bidi and invisible characters (`names_lose_bidi_and_zero_width_characters`); macOS and Windows stop the grouping request when the window closes or its answer passes `MAX_OUTPUT_BYTES`. A selection or a tab's text reaches the chat only with the address it was read from, and every client drops it once the tab no longer shows that address (`assistant::read_here`: `text_counts_only_from_the_address_its_tab_shows_now`; macOS and Windows read it with `page_scripts::with_address`); a tab is read for a pill only where `assistant_offered` allows its address (`a_selection_and_a_loaded_tab_reach_the_assistant_and_a_sleeping_tab_is_never_read` on Linux, iOS and Android). On Android the selection is read in the page's own world (see "Page scripts on Android"), so the page can forge it: it is treated as untrusted page content like page text, bounded by `page_ops::selection` and sent as a data block, never as instructions. macOS and Windows (`crates/app/src/assistant.rs`) draw answers natively with `ai::markdown` (no images, every link with its whole address shown), open a link only through `assistant::links` and a confirmation naming its host and address, and sort tabs only after a confirmation listing each proposed group. The core rules in `browser_core::assistant`: query strings, fragments and sign-in parts stripped (`urls_lose_query_fragment_and_sign_in_and_text_loses_control_and_bidi`), templates expanded once (`a_placeholder_inside_page_text_or_the_question_stays_literal`), no text can open or close a block: each request's block tag holds a random nonce of its own and `tarn-block` is removed whatever its case or the invisible characters inside it (`no_text_can_open_or_close_a_block`, `invisible_characters_and_case_folding_cannot_hide_a_block_tag`), every link opens only after a confirmation that shows the whole address, `mailto` loses its headers and is refused when its address encodes `?`, `&`, a control or an invisible character, local and home-network hosts and other schemes are refused (`web_links_and_mail_open_only_after_a_confirmation`, `link_text_never_replaces_the_address`), answers stop at their size limit (`an_answer_stops_at_its_size_limit`), cancelled, failed or empty exchanges are never sent again (`cancel_drops_an_empty_answer_and_marks_a_partial_one`, `an_answer_that_ends_empty_counts_as_interrupted`), pills only from the chat's profile (`pills_from_private_burner_lockdown_or_another_profile_are_refused`); tab grouping sends only the id, host and title of loose web tabs, never local files, home-network pages or Lockdown pages, and files only tabs it sent (`browser_core::cleanup::ai`: `local_files_and_home_network_pages_are_never_sent`, `only_tabs_that_were_sent_can_be_filed`). A selection command's answer goes only to the chat, never into the page; the answer's links are also listed as keyboard stops under it (macOS and Windows tab stops, NSH buttons) that open through the same `links::classify` confirmation. | | S3 | High | API token or page content leaks | Token only in the platform secret store (Keychain, Credential Manager, Secret Service, Android Keystore). Content leaves the device only after an explicit click with a visible indicator. AI is unavailable in the private profile. We never read the CLI's stored credentials. | `ai::Secrets` keeps the API token in the platform store only, with no fallback to a file: the Keychain on macOS and iOS, the Credential Manager on Windows and the Secret Service on Linux (`ai::secrets::Keyring`); on Android it is sealed with AES-GCM under a key that never leaves the Android Keystore (`tarn_mobile_android::Keystore`, `Secrets.java`). `ApiToken`'s `Debug` never shows the value (`token_never_in_debug_output`). On Linux, iOS and Android (`tarn_nsh_shared::assistant`) a request leaves only on Send, a command or Group with Assistant, the chat lists every block a send carries with its size first, Settings › AI and the chat are hidden or refused in a private space, a burner tab and at Lockdown (`tabs::Model::assistant_origin` carries the page's own Shield level: `the_assistant_origin_carries_the_kind_and_the_sites_own_level`), the key typed into Settings › AI goes straight to the platform store, a Claude request without a stored key sends nothing and Ollama never gets the key (`claude_needs_a_stored_key_and_sends_it_only_to_anthropic`, `ollama_answers_on_loopback_without_the_key`), and a build for neither phone has no store and sends nothing; turning the switch off, deleting a profile or clearing its data drops every window's chat. macOS and Windows the assistant column (`crates/app/src/assistant.rs`) sends only on Send, names every block a send carries with its size above the question field, passes the active page's effective Shield level (per-site setting included) with each send, drops the chat when the profile, its data or its AI switch goes, and shows no chat in a private space, burner tab or Lockdown; Settings › AI stores the key through `ai::secrets::Keyring` only.. The core rules in `browser_core::assistant`: no chat in a private space, burner tab, Lockdown or with the profile's AI switch off (`private_burner_and_lockdown_get_no_session`), a send from any of them, from another profile or with the switch off is refused and drops every pill, and a pill whose page went to Lockdown since it was added, or whose address does not parse, is dropped, also after the user removed it, and the answers given while it or a refused send's pills were attached are never sent again (`a_refused_send_forgets_answers_given_while_its_pills_were_attached`, `a_removed_pill_whose_page_went_to_lockdown_still_forgets_its_answers`, `a_send_from_where_the_assistant_is_not_allowed_is_refused_and_drops_the_pills`, `a_send_drops_pills_whose_page_went_to_lockdown_since_they_were_added`, `a_pill_without_a_readable_address_counts_as_lockdown`, `answers_given_while_a_pill_now_in_lockdown_was_attached_are_never_sent_again`), nothing is sent without a send event and every block it would carry is listed with its size (`the_view_lists_every_block_that_would_be_sent`), each block and the whole request are capped (`pills_are_capped_each_and_with_history_in_total`). Local models implement `ai::LocalModel` and run only through `ai::local::stream`, the one place that can make the `local::Checked` token their `respond` takes, after their availability check: `engine::foundation_models::FoundationModel` (macOS and iOS, the `foundation-models` feature) calls only `SystemLanguageModel.default` and takes no transport; `ai::Ollama` is available only when Ollama on loopback answers `/api/show` for the model and reports no remote host, and a `-cloud` or `:cloud` name is refused before anything is asked (`cloud_models_are_never_local`, `an_ollama_that_does_not_answer_needs_setup_and_gets_no_question`). An unavailable model answers `AiError::Unavailable` with its reason instead of another model answering; `ai::local::route` never sends a local choice to the cloud (`a_local_choice_never_routes_to_the_cloud`). A selection or another tab reaches the assistant only by the user's choice: the selection menu has no assistant entry where `tabs::Model::assistant_menu` refuses the page (AI off, private space, burner, Lockdown), the tab picker lists only the current space's other web tabs the assistant may read and never wakes a sleeping one to read it (`the_tab_picker_lists_other_web_tabs_the_assistant_may_read_and_wakes_none`, `a_selection_and_a_loaded_tab_reach_the_assistant_and_a_sleeping_tab_is_never_read` on Linux and mobile), and a send still checks every pill's page level. Commands run on the system's on-device model when it is available and the cloud was chosen; with a local choice that cannot answer the chat says why and asks no cloud, and every answer names the model that gave it (`ai::local::answer`: `commands_stay_on_the_device_when_it_can_answer_and_say_who_answered`; `commands_answer_on_the_device_and_name_it_while_questions_go_where_chosen`). | @@ -18,7 +18,7 @@ settings per client are in `cryptography.md`; the actors, components and externa | S6 | High | Dangerous schemes and untrusted URL sources | Allowlist `http`, `https`, `about:blank`, `blob`. `data:` not at top level. `file:` only by explicit user action. `javascript:` rejected in the command bar and on paste. External schemes prompt each time. URLs from other apps, drops and sync pass the same policy. | `nav_policy::decide` with table test; applied to typed input, Open File (`load_file` is the only load that reaches `file:`, decided as `Source::FileOpen` through `nav_policy::file_open`, which also admits only the user's Back, Forward and Reload onto a file that view itself opened, never a restored history; an opened page loads `file:` subresources and frames only from its own folder, or only itself when that folder is a root, a mounted volume's top or holds the home folder, with symlinks resolved and `file:` URLs naming a host refused before any lookup (macOS WebKit's read-access grant and `nav_policy::file_subresource_allowed` for frames, Chromium's request filter (not yet verified at runtime that CEF hands it `file:` subresources; macOS opens files in WebKit), iOS's grant, Android's `shouldInterceptRequest`; Linux gap in `docs/nsh-plan.md` §4), so its images and styles load, and file pages cannot read other files with scripts; the address shows `File:` and the file's name; iOS and Android copy the picked file into a folder of its own under a staging directory cleared at launch), command-line URLs, restored tabs and session snapshots, main-frame navigations, redirects and popups. A page's external-scheme request shows a banner naming the origin of the frame that started it ("A page" when opaque or while a main-frame load is in flight, so a server redirect is never credited to the page or frame that linked to it), only in its own tab, until that tab's next commit or close; while it shows, further requests are dropped, and "Open" ignores clicks for 700 ms after it, or any banner above it, appears, and again when the window becomes active. Links other apps send (the default-browser case, `shared::open_urls` through GPUI's `on_open_urls`) pass `decide(ExternalApp)`, at most 10 in 10 s across the app (the rest are dropped with a toast), and load as a page's link (`WebView::load_link` with no opener), so S10 refuses a local target or any redirect hop into the local network with its usual notice; typing the address opens it. A loopback link (`localhost`, 127.0.0.0/8, `::1`) opens as typed while Settings › Privacy › Open localhost links from other apps is on (the default), since developers open local servers from terminals and editors; the accepted risk is that a link from a remote sender (a mail) can then reach a service on this computer, as a typed address could. Off, it gets the notice. Other local addresses always get it. The notice offers Open Anyway, which loads the address as the user's own navigation. Chromium tabs do the same: their `load_link` sets no shell mark, also for a load held until the view is ready, so `on_before_browse` credits the page (a Chromium integration test is not written yet); such a load is not a user's, so it does not bridge WebKit's cookies first and the site may open signed out in Chromium. Open: public names that resolve to private addresses (`nip.io`-style) are not recognised. | | S19 | High | Sync storage is read or tampered with | Client-side authenticated encryption; remote data validated as untrusted input; secrets and cookies never synced. | Not built. | | S7 | Medium | TLS downgrade or click-through | WebKit's default trust evaluation, never custom acceptance, and no bypass at any level. Chromium tabs cancel certificate errors and turn Chrome's override off, so its certificate page has no way through. | No custom trust handling exists. Plain-HTTP page navigations into an HTTPS-only site are blocked (a URL with an explicit port loads when the view was built HTTPS-only, because `make-https` leaves ports alone; Chromium tabs, which have no per-level view, upgrade such a link without a port and refuse one with a port unless the page being left is HTTPS-only). | -| S8 | Medium | Local data at rest | File permissions and FileVault (documented). Private profile in memory only. Wipe covers data store, history, kept page text, protected-site hosts (at most 200 a profile, the busiest kept, since a page can choose the hosts it is upgraded to), favicons, site zoom levels, muted sites, downloads list and saved `interaction_state`. No URLs in logs. | DB `0600` in `0700` dir; private profile uses in-memory DB. On Windows the data folder takes Local AppData's user-only access list; a portable Tarn gives its `Data` folder a protected one for the current user, SYSTEM and Administrators at start unless it already has one (`engine::restrict_to_user`), and shows a storage warning whenever that fails, as on FAT and exFAT drives or a folder another account owns. `secure_delete` is on and clearing history, deleting a profile's data, deleting a profile or deleting a space truncates the WAL, so deleted rows are not left in the files. "Delete everything" removes WebKit's public website data types; WebKit-private state such as its HSTS host list is not covered. A Lockdown profile uses a non-persistent WebKit store and empties its own persistent store whenever the profile is opened at that level (`crates/app/tests/lockdown.rs`); a store it shares from another profile ("Share data") stays with that profile, which keeps using it, while the profile that owns a shared store empties it for both when it moves into Lockdown; a request still in flight at the switch can set a cookie after the wipe, which the next Lockdown launch removes. Chromium has one profile, owned by one Tarn profile: deleting that profile's website data, deleting the profile or moving it into Lockdown clears cookies, HTTP cache and sign-ins through CEF, keeps Chromium closed until the next launch, and deletes everything under `Chromium/` once CEF is gone, at quit or before CEF starts at the next launch; a profile at Lockdown at launch or quit loses its Chromium folder and ownership before CEF starts. Chrome's disk cache is kept inside that folder. Per-site Clear Site Data and a site set to Lockdown remove the site's Chromium cookies (host, parent domains and subdomains), the storage of its origins on default ports and of open tabs on that host, and the whole HTTP cache; storage of sibling subdomains and session storage stay. Per-site zoom (`site_zoom`, host and factor per profile) is cleared with history, never written for a Lockdown page, and kept in memory for the private profile; the downloads list can be cleared from the library. Lockdown still records history and tabs for session restore, and a per-site Lockdown override uses the profile's store; the private space keeps nothing. The panic file `last-panic.txt` keeps the panic's location and backtrace and only a literal (`&'static str`) message; a formatted one, which may carry a page address, is left out (`lib.rs::record_panics`, tested). A burner tab (`Model::open_burner`) is a hidden private-store space with its own profile at Strict, so its WebKit store is a non-persistent one of its own, never shared with the private space or another burner, and never Chromium; it records no history, site icons or downloads rows (`Core::keeps_records`), refuses pop-ups and pinning, and leaving it, closing its tab or its window deletes every row of its profile (spaces, tabs, zoom, permissions, counters and the rest of `PROFILE_TABLES`), closes a peek opened from it and drops its data store (`Model::burn`); the emptied profile row stays in memory until the last window closes, so its id is not reused while a late download still names it. A window's Undo (`browser_core::undo::Stack`) keeps in memory only, and only for the window's life, the serial of a reopen-stack entry, a Clean Up record (tab and group ids and positions) or a sidebar move; a close, Clean Up or move in a private space or a burner tab adds nothing (`Stack::push`, tested), and a reopen-stack entry is the same one Reopen Closed Tab already keeps. Shortcut tips (`browser_core::hints`) count per profile in `feature_hints` (a command's name, how often its tip showed and when), a profile table, so export, Delete everything and deleting the profile cover it (`feature_hints_count_per_profile_and_go_with_the_profile_and_its_reset`); a private space or a burner tab shows no tip and counts nothing. Snippets (`browser_core::snippets`, name and text, at most 16 KiB each) live per profile in `snippets`, a profile table, so export, Delete everything and deleting the profile cover them (`snippets_are_checked_per_profile_and_go_with_the_profile_and_its_reset`); a private space or burner tab has a profile of its own and so no snippets. Notes (`browser_core::notes`, a title of at most 200 characters and text of at most 64 KiB, 1000 a profile, without control, bidi or zero-width characters: `store::is_invisible`) live per profile in `notes`, a profile table, so export, Delete everything and deleting the profile cover them (`notes_are_clean_capped_per_profile_and_go_with_the_profile_and_its_reset`); `Store::save_note` refuses a private profile, which private spaces and burner tabs use, so nothing of theirs is written (`notes_are_never_written_for_a_private_profile_and_stop_at_the_cap`). Notes are never synced. | +| S8 | Medium | Local data at rest | File permissions and FileVault (documented). Private profile in memory only. Wipe covers data store, history, kept page text, protected-site hosts (at most 200 a profile, the busiest kept, since a page can choose the hosts it is upgraded to), favicons, site zoom levels, muted sites, downloads list and saved `interaction_state`. No URLs in logs. | DB `0600` in `0700` dir; private profile uses in-memory DB. On Windows the data folder takes Local AppData's user-only access list; a portable Tarn gives its `Data` folder a protected one for the current user, SYSTEM and Administrators at start unless it already has one (`engine::restrict_to_user`), and shows a storage warning whenever that fails, as on FAT and exFAT drives or a folder another account owns. `secure_delete` is on and clearing history, deleting a profile's data, deleting a profile or deleting a space truncates the WAL, so deleted rows are not left in the files. "Delete everything" removes WebKit's public website data types; WebKit-private state such as its HSTS host list is not covered. A Lockdown profile uses a non-persistent WebKit store and empties its own persistent store whenever the profile is opened at that level (`crates/app/tests/lockdown.rs`); a store it shares from another profile ("Share data") stays with that profile, which keeps using it, while the profile that owns a shared store empties it for both when it moves into Lockdown; a request still in flight at the switch can set a cookie after the wipe, which the next Lockdown launch removes. Chromium has one profile, owned by one Tarn profile: deleting that profile's website data, deleting the profile or moving it into Lockdown clears cookies, HTTP cache and sign-ins through CEF, keeps Chromium closed until the next launch, and deletes everything under `Chromium/` once CEF is gone, at quit or before CEF starts at the next launch; a profile at Lockdown at launch or quit loses its Chromium folder and ownership before CEF starts. Chrome's disk cache is kept inside that folder. Per-site Clear Site Data and a site set to Lockdown remove the site's Chromium cookies (host, parent domains and subdomains), the storage of its origins on default ports and of open tabs on that host, and the whole HTTP cache; storage of sibling subdomains and session storage stay. Per-site zoom (`site_zoom`, host and factor per profile) is cleared with history, never written for a Lockdown page, and kept in memory for the private profile; the downloads list can be cleared from the library. Lockdown still records history and tabs for session restore, and a per-site Lockdown override uses the profile's store; the private space keeps nothing. The panic file `last-panic.txt` keeps the panic's location and backtrace and only a literal (`&'static str`) message; a formatted one, which may carry a page address, is left out (`lib.rs::record_panics`, tested). A burner tab (`Model::open_burner`) is a hidden private-store space with its own profile at Strict, so its WebKit store is a non-persistent one of its own, never shared with the private space or another burner, and never Chromium; it records no history, site icons or downloads rows (`Core::keeps_records`), refuses pop-ups and pinning, and leaving it, closing its tab or its window deletes every row of its profile (spaces, tabs, zoom, permissions, counters and the rest of `PROFILE_TABLES`), closes a peek opened from it and drops its data store (`Model::burn`); the emptied profile row stays in memory until the last window closes, so its id is not reused while a late download still names it. A window's Undo (`browser_core::undo::Stack`) keeps in memory only, and only for the window's life, the serial of a reopen-stack entry, a Clean Up record (tab and group ids and positions) or a sidebar move; a close, Clean Up or move in a private space or a burner tab adds nothing (`Stack::push`, tested), and a reopen-stack entry is the same one Reopen Closed Tab already keeps. Shortcut tips (`browser_core::hints`) count per profile in `feature_hints` (a command's name, how often its tip showed and when), a profile table, so export, Delete everything and deleting the profile cover it (`feature_hints_count_per_profile_and_go_with_the_profile_and_its_reset`); a private space or a burner tab shows no tip and counts nothing. Snippets (`browser_core::snippets`, name and text, at most 16 KiB each) live per profile in `snippets`, a profile table, so export, Delete everything and deleting the profile cover them (`snippets_are_checked_per_profile_and_go_with_the_profile_and_its_reset`); a private space or burner tab has a profile of its own and so no snippets. Notes (`browser_core::notes`, a title of at most 200 characters and text of at most 64 KiB, 1000 a profile, without control, bidi or zero-width characters: `store::is_invisible`) live per profile in `notes`, a profile table, so export, Delete everything and deleting the profile cover them (`notes_are_clean_capped_per_profile_and_go_with_the_profile_and_its_reset`); `Store::save_note` refuses a private profile, which private spaces and burner tabs use, so nothing of theirs is written (`notes_are_never_written_for_a_private_profile_and_stop_at_the_cap`). Notes are never synced. Assistant chats (`browser_core::assistant::Session::save`, the turns and the addresses of content attached to them, at most 1 MiB a chat and 200 a profile, without control, bidi or zero-width characters) live per profile in `chats`, a profile table, so export, Delete everything and deleting the profile cover them (`chats_are_clean_capped_per_profile_and_go_with_the_profile_and_its_reset`); `Store::save_chat` refuses a private profile and a session never exists in a private space, a burner tab or under Lockdown. A restored chat keeps its sources as removed pills, so a send still forgets what a site now in Lockdown gave it (`a_chat_is_saved_and_restored_with_its_sources`), and a forgotten answer's text is replaced before the chat is saved again (`answers_from_a_site_now_in_lockdown_lose_their_text_before_a_save`); opening a saved chat forgets what a site now in Lockdown gave it and saves it at once, so a chat saved before its site moved to Lockdown keeps that text only until it is next opened or sent; Copy and Insert into Page are not offered on a removed answer. Exports for the share sheet (Shield card, notes on iOS and Android) are written to a `0700` temporary folder, and each export removes the earlier ones of the same run; the last one stays until the system clears its temporary folder. | | S9 | Medium | Cross-profile leaks through shell features | Favicons, suggestions, permissions, downloads, extensions and AI context keyed by profile. Favicons are fetched by the tab's own web view, not by the shell. | Schema keys rows by profile; suggestions query one profile. A link peek (⇧-click) uses the opener's profile data store and Shield rules and moves only into a tab of that profile. A space rule (`space_rules`, a host or `*.host`) opens a new tab of a matching URL in the ruled space, so in its profile: only for argv and macOS open-URL requests (after `nav_policy` `ExternalApp`), command-bar new tabs and pop-ups from a link the user activated (`target=_blank`, ⌘-click; WebKit's `LinkActivated`) already allowed by `nav_policy` and the pop-up rules, never for a script's `window.open`, which keeps its opener for sign-in and payment flows, and never for a navigation inside a tab. The routed tab is a fresh shell load without the opener, so the page cannot script it, but a page with a user gesture can open a ruled host in the other profile with that profile's cookies. A link from another app keeps its S10 link-load check in the ruled space. Nothing is routed out of a private space or burner tab, and neither is ever a target. Shortcut tip counters are read and written for the current space's profile only (`hints::Throttle`). Notes are read and edited for the current space's profile only; another profile's id edits or deletes nothing, and a note reaches the assistant only as `notes::as_pill` (`Pill::Note`), which `assistant` admits from the session's own profile. | | S10 | Medium | Public sites attacking localhost or LAN devices | Content rule blocks requests to loopback and private address ranges unless the top-level page is itself local. Web Inspector only in the dev profile or by toggle. | Rules generated in `shield::rules`, including userinfo, IPv4-mapped IPv6, trailing-dot, CGNAT (100.64/10) and IPv6 link-local (fe80::/10) forms; each host pattern ends at the path or a numeric port, so `127.example.com` or `localhost:x@evil.com` as the top page does not lift the block, and a top page with credentials or an IPv6 form embedding IPv4 (`::ffff:`, NAT64) never counts as local. A Shift-clicked link is loaded by the shell as a peek, so it gets the same public-to-private check before `PeekLink` is emitted. The peek loads with `WebView::load_link`, which is not a user navigation: the first URL and every redirect hop get the check, judged from the opener's origin until the peek has a page (`crates/app/tests/redirects.rs` covers the user's own loads across redirects). `*.localhost` top pages count as local and rely on the resolver answering loopback for them. Rules compile asynchronously; a WebKit view holds its first load (or session restore) until its level's built-in list is attached, and if that list fails to compile the view loads nothing and shows the error. Chromium tabs get no rule lists; `engine::request_filter` checks each request with `shield::rules::is_local`, which accepts the same forms, and treats the top page as local only when both the main frame's URL and Chromium's first-party site for the request are local, so a local page just left cannot exempt the next page's first requests; a request filter that has no Shield snapshot yet cancels everything. WebSocket handshakes from Chromium tabs never reach that filter, so a public page in Chromium can still open a WebSocket to a local address (open). At Strict, Chromium tabs drop the cross-origin `Referer` header but the next page's `document.referrer` still names the page left (open). Web Inspector is enabled only with Settings › Developer on or in a developer profile (in Chromium tabs, only then does the page menu keep Chrome's Inspect); the local-server probe connects only to 127.0.0.1 on a fixed list of dev ports with a 300 ms timeout. JSON documents are read from the client world with a size cap and parsed with depth, node and text limits (`devkit::json_view`). Both engines also refuse a script-started main-frame navigation from a public page into a local address (`nav_policy::into_private_network`); a navigation the user started (typed, a click in Chromium, or the shell's back, forward or reload) keeps through its redirects. Back, forward and reload count as the user's only when the shell started them, never by navigation type, so a script's `location.reload()` or `history.go()` that a server redirects into the local network is refused. The page left is judged by its origin: a `blob:` page by its inner origin, a WebKit page without a committed origin (a new popup, `about:blank`, `data:`) by the origin of the frame that started the navigation, and anything opaque or without an http(s) origin as public. A back, forward or reload with nothing to go to does not count, nor does the reload after a page's process ends, since a page can end its own process. In WebKit a clicked link and WebKit's own swipe back from a public page into the local network are refused too, since WebKit reports them like a script's; the user types the address, or presses Open Anyway on the notice, which names the address. A link in an assistant answer to a local or home-network host is refused (`browser_core::assistant::links::classify`, not yet in any client). | A page may also not send the top frame or a new window from a public origin to a private address (WebKit `decide_policy`, `create_web_view` and Chromium `on_before_browse`); typed addresses still load. If the built-in rule list fails to compile, a banner says the protection is off. | S20 | High | Tampered or hostile filter lists | Bundle signed by a separate CI key and verified in the app; size caps per file kind and in total; last good bundle kept. Lists are data only: network rules, plain CSS selectors and domains, never scriptlets or code. On Windows, list element hiding is a `