diff --git a/crates/agent-chat/src/seat.rs b/crates/agent-chat/src/seat.rs index 05e696e7..41e0f52d 100644 --- a/crates/agent-chat/src/seat.rs +++ b/crates/agent-chat/src/seat.rs @@ -20,6 +20,10 @@ pub trait ChatWorkspace: 'static { /// Foreground and background terminals; none once the workspace closed. fn terminals(&self, cx: &App) -> Option>; fn connections(&self, cx: &App) -> Vec; + /// Metadata of this seat's original live workspace, independent of visible tabs. + fn workspace_description(&self, _cx: &App) -> Option { + None + } /// Whether saved connections can be opened in this window. fn opens_connections(&self, cx: &App) -> bool; /// Calls `changed` whenever the workspace's membership or placement diff --git a/crates/agent-chat/src/thread.rs b/crates/agent-chat/src/thread.rs index 287deebf..79b6b094 100644 --- a/crates/agent-chat/src/thread.rs +++ b/crates/agent-chat/src/thread.rs @@ -201,8 +201,10 @@ impl AgentThread { pub fn context(&mut self, cx: &App) -> String { self.offer_tools(cx); let input = self::tool_runtime::resolution::Resolution::observe(self.deps.seat(), cx); + let attachments = self.composer.default_attachments(); + let workspace = self.deps.seat().workspace_description(cx); self.tools - .context(&input, self.composer.default_attachments(), cx) + .context(&input, attachments, workspace.as_ref(), cx) } pub fn offline_servers(&mut self, cx: &App) -> Vec<(ServerDescriptor, ConnectionSummary)> { diff --git a/crates/agent-chat/src/thread/connection_wait.rs b/crates/agent-chat/src/thread/connection_wait.rs index 2a98e752..53546585 100644 --- a/crates/agent-chat/src/thread/connection_wait.rs +++ b/crates/agent-chat/src/thread/connection_wait.rs @@ -20,14 +20,6 @@ pub(super) enum ConnectionWaitError { ConnectFailed, #[error("Connecting to the server timed out.")] Timeout, - #[error( - "The server is waiting for the user to sign in; ask them to finish signing in, then call list_terminals." - )] - VisiblePromptTimeout, - #[error( - "The server is waiting for the user to sign in from the chat or unlock the vault; ask them to, then call open_terminal again." - )] - HiddenPromptTimeout, } impl ConnectionWaitError { pub(super) fn into_failure(self) -> nocterm_ai::ToolFailure { @@ -135,20 +127,58 @@ impl WaitTarget { } } -/// One finite waiter owns timing and promotion decisions for its original receipt. +/// One waiter owns timing and promotion decisions for its original receipt. +/// Machine work has a finite deadline; an outstanding human sign-in question does not. pub(in crate::thread) struct ConnectionWaitOperation { target: WaitTarget, - started: Instant, shown: bool, - waiting: bool, +} + +const CONNECT_LIMIT: Duration = Duration::from_secs(60); +const CONNECT_POLL: Duration = Duration::from_millis(150); +const SIGN_IN_POLL: Duration = Duration::from_millis(500); + +/// The current stretch of machine work. Each human answer starts a fresh stretch. +enum WaitPhase { + Connecting { deadline: Instant }, + SigningIn, +} + +impl WaitPhase { + fn connecting(now: Instant) -> Self { + Self::Connecting { + deadline: now + CONNECT_LIMIT, + } + } + + fn poll_interval(&self) -> Duration { + match self { + Self::Connecting { .. } => CONNECT_POLL, + Self::SigningIn => SIGN_IN_POLL, + } + } + + fn observe(&mut self, status: TerminalStatus, now: Instant) { + match status { + TerminalStatus::AwaitingVault | TerminalStatus::AwaitingUser => { + *self = Self::SigningIn; + } + TerminalStatus::Connecting if matches!(self, Self::SigningIn) => { + *self = Self::connecting(now); + } + _ => {} + } + } + + fn expired(&self, now: Instant) -> bool { + matches!(self, Self::Connecting { deadline } if now >= *deadline) + } } impl ConnectionWaitOperation { pub(in crate::thread) fn new(target: WaitTarget) -> Self { Self { target, - started: Instant::now(), shown: false, - waiting: false, } } pub(in crate::thread) async fn run( @@ -156,10 +186,9 @@ impl ConnectionWaitOperation { thread: &WeakEntity, cx: &mut AsyncApp, ) -> Result { + let mut phase = WaitPhase::connecting(cx.background_executor().now()); let result = loop { - cx.background_executor() - .timer(Duration::from_millis(150)) - .await; + cx.background_executor().timer(phase.poll_interval()).await; let step = thread.update(cx, |thread, cx| { thread.poll_connection_wait(&self.target, cx) }); @@ -168,7 +197,7 @@ impl ConnectionWaitOperation { Ok(Err(error)) => break Err(error), Err(_) => break Err(ConnectionWaitError::ChatClosed), }; - if let Some(result) = self.advance(step, cx) { + if let Some(result) = self.advance(step, &mut phase, cx) { break result; } }; @@ -184,14 +213,20 @@ impl ConnectionWaitOperation { bool, nocterm_ai::context::TerminalDescriptor, ), + phase: &mut WaitPhase, cx: &mut AsyncApp, ) -> Option> { + let now = cx.background_executor().now(); + if let Some(status) = step.0 { + phase.observe(status, now); + } match step { (Some(TerminalStatus::Connected), _, descriptor) => { return Some(Ok(serde_json::json!({ "terminal": descriptor }))); } - (_, true, _) => self.waiting = true, - (Some(TerminalStatus::AwaitingUser), false, _) if !self.shown => { + (Some(TerminalStatus::AwaitingUser | TerminalStatus::AwaitingVault), false, _) + if !self.shown => + { self.shown = true; let seat = self.target.seat.clone(); let item = self.target.expected.item(); @@ -204,19 +239,8 @@ impl ConnectionWaitOperation { } _ => {} } - let limit = if self.shown || self.waiting { - Duration::from_secs(180) - } else { - Duration::from_secs(60) - }; - (self.started.elapsed() >= limit).then(|| { - Err(if self.shown { - ConnectionWaitError::VisiblePromptTimeout - } else if self.waiting { - ConnectionWaitError::HiddenPromptTimeout - } else { - ConnectionWaitError::Timeout - }) - }) + phase + .expired(now) + .then_some(Err(ConnectionWaitError::Timeout)) } } diff --git a/crates/agent-chat/src/thread/queue.rs b/crates/agent-chat/src/thread/queue.rs index 2706eab8..dc811677 100644 --- a/crates/agent-chat/src/thread/queue.rs +++ b/crates/agent-chat/src/thread/queue.rs @@ -336,6 +336,7 @@ impl AgentThread { if self.deps.seat().id() != target.seat().id() || self.registration().as_ref().map(|value| value.id) != target.registration() || !self.session.session_current(target.ticket()) + || self.session.stopped() || !self.session.accepts_updates() || !self.deps.enabled(cx) { diff --git a/crates/agent-chat/src/thread/tool_runtime.rs b/crates/agent-chat/src/thread/tool_runtime.rs index a9140176..67af1877 100644 --- a/crates/agent-chat/src/thread/tool_runtime.rs +++ b/crates/agent-chat/src/thread/tool_runtime.rs @@ -270,9 +270,10 @@ impl ToolRuntime { &mut self, input: &resolution::Resolution, defaults: &[Attachment], + workspace: Option<&nocterm_ai::context::WorkspaceDescriptor>, cx: &gpui::App, ) -> String { - self.turn.context(input, defaults, cx) + self.turn.context(input, defaults, workspace, cx) } /// Tells the chat's bridge what it offers the agent: the file tools only while an attached /// terminal takes them. The bridge tells a connected agent when that changes. diff --git a/crates/agent-chat/src/thread/tool_runtime/turn_context.rs b/crates/agent-chat/src/thread/tool_runtime/turn_context.rs index 65bf1243..1a42d3fc 100644 --- a/crates/agent-chat/src/thread/tool_runtime/turn_context.rs +++ b/crates/agent-chat/src/thread/tool_runtime/turn_context.rs @@ -197,6 +197,7 @@ impl TurnContext { &mut self, input: &super::resolution::Resolution, defaults: &[Attachment], + workspace: Option<&nocterm_ai::context::WorkspaceDescriptor>, cx: &App, ) -> String { let terminals: Vec<_> = self @@ -209,7 +210,7 @@ impl TurnContext { .into_iter() .map(|(server, _)| server) .collect(); - nocterm_ai::context::context_block(&terminals, &servers) + nocterm_ai::context::context_block_with_workspace(&terminals, &servers, workspace) } /// A human description of what `call` acts on, for its approval card. pub(super) fn describe_target( diff --git a/crates/agent/src/panel.rs b/crates/agent/src/panel.rs index 3860def9..75d79ae4 100644 --- a/crates/agent/src/panel.rs +++ b/crates/agent/src/panel.rs @@ -528,13 +528,20 @@ impl AgentPanel { impl AgentPanel { pub(super) fn render_menu(&mut self, window: &Window, cx: &mut Context) -> AnyElement { let kind = self.menus.current().cloned(); + let value = self.menus.query(cx); + let query = if kind == Some(MenuKind::Context) { + value.trim().to_lowercase() + } else { + value.to_lowercase() + }; let attachment = matches!(kind, Some(MenuKind::Context)).then(|| match self.current() { Some(thread) if chat_servers::takes_servers(thread.read(cx)) => { - chat_servers::ChatServersRenderer::render_menu(&thread, cx) + chat_servers::ChatServersRenderer::render_menu(&thread, &query, cx) } thread => attach::AttachmentMenuRenderer::render_attach_menu( thread, self.host.workspace().clone(), + &query, cx, ), }); @@ -542,7 +549,7 @@ impl AgentPanel { kind, self.current(), self.menus.query_input(), - self.menus.query(cx).to_lowercase(), + query, self.host.window_agents(cx), self.last_agent(cx), self.focus.clone(), diff --git a/crates/agent/src/panel/attach.rs b/crates/agent/src/panel/attach.rs index 872ed2d7..7b94b8d3 100644 --- a/crates/agent/src/panel/attach.rs +++ b/crates/agent/src/panel/attach.rs @@ -67,6 +67,7 @@ impl AttachmentMenuRenderer { pub(super) fn render_attach_menu( thread: Option>, workspace: gpui_kit::WeakEntity, + query: &str, cx: &mut Context, ) -> AnyElement { let (Some(thread), Some(workspace)) = (thread, workspace.upgrade()) else { @@ -89,7 +90,7 @@ impl AttachmentMenuRenderer { seat.opens_connections(cx) .then(|| SavedServerOpen::Workspace(seat.clone())) }; - let rows = Self::active_rows(&terminals, &summaries, &thread, cx); + let rows = Self::active_rows(&terminals, &summaries, &thread, query, cx); let mut sessions: HashMap> = HashMap::new(); for entry in &terminals { if let Some(profile) = entry @@ -101,21 +102,26 @@ impl AttachmentMenuRenderer { sessions.entry(profile).or_default().push(entry); } } - let mut menu = - v_flex() - .w_full() - .gap(px(2.)) - .child(super::local_attachment::LocalAttachment::render( - &thread, - workspace.downgrade(), - cx, - )); + let local = servers::matches_query("Local terminal", query); + let saved_rows = servers::server_rows(&summaries, query); + let empty = !local && rows.is_empty() && saved_rows.is_empty(); + let mut menu = v_flex().w_full().gap(px(2.)); + if local { + menu = menu.child(super::local_attachment::LocalAttachment::render( + &thread, + workspace.downgrade(), + cx, + )); + } + if empty { + menu = menu.child(heading("No matching servers or terminals", cx)); + } if !rows.is_empty() { menu = menu.child(heading("Active sessions", cx)).children(rows); } - if !summaries.is_empty() { + if !saved_rows.is_empty() { menu = menu.child(heading("Saved servers", cx)); - for row in servers::server_rows(&summaries) { + for row in saved_rows { menu = menu.child(match row { servers::ServerRow::Folder(group) => Self::folder_row(group, &thread, cx), servers::ServerRow::Server { summary, nested } => Self::server_row( @@ -138,6 +144,7 @@ impl AttachmentMenuRenderer { terminals: &[TerminalEntry], summaries: &[ConnectionSummary], thread: &Entity, + query: &str, cx: &mut Context, ) -> Vec { let seat = thread.read(cx).workspace_seat().clone(); @@ -159,7 +166,9 @@ impl AttachmentMenuRenderer { continue; } } - rows.push(Self::terminal_row(entry, thread, seat.clone(), cx)); + if servers::matches_query(&entry.title, query) { + rows.push(Self::terminal_row(entry, thread, seat.clone(), cx)); + } } rows } diff --git a/crates/agent/src/panel/chat_servers.rs b/crates/agent/src/panel/chat_servers.rs index b7cbcebf..157ee347 100644 --- a/crates/agent/src/panel/chat_servers.rs +++ b/crates/agent/src/panel/chat_servers.rs @@ -77,6 +77,7 @@ impl ChatServersRenderer { /// The attach menu of a chat whose agent takes servers. pub(super) fn render_menu( thread: &Entity, + query: &str, cx: &mut Context, ) -> AnyElement { let servers = offered(thread.read(cx)); @@ -95,7 +96,30 @@ impl ChatServersRenderer { ), ); } - for (index, server) in servers.into_iter().enumerate() { + let had_servers = !servers.is_empty(); + let mut matches = servers + .into_iter() + .enumerate() + .filter(|(_, server)| { + super::servers::matches_query(&server.option.name, query) + || server + .option + .description + .as_deref() + .is_some_and(|address| super::servers::matches_query(address, query)) + }) + .peekable(); + if had_servers && matches.peek().is_none() { + menu = menu.child( + div() + .px_2() + .py_1() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("No matching servers"), + ); + } + for (index, server) in matches { menu = menu.child(Self::row(thread, index, server, busy, cx)); } menu.into_any_element() diff --git a/crates/agent/src/panel/composer.rs b/crates/agent/src/panel/composer.rs index 13043f36..d9aae241 100644 --- a/crates/agent/src/panel/composer.rs +++ b/crates/agent/src/panel/composer.rs @@ -409,12 +409,13 @@ impl AgentPanel { &mut self, kind: MenuKind, open: bool, + window: &mut Window, cx: &mut Context, ) { if open { - self.menus.open(kind); - } else { - self.menus.close_if_same(&kind); + self.menus.open_with_window(kind, window, cx); + } else if self.menus.close_if_same(&kind) && kind == MenuKind::Context { + self.focus_composer(window, cx); } cx.notify(); } diff --git a/crates/agent/src/panel/local_attachment.rs b/crates/agent/src/panel/local_attachment.rs index 5f8eb695..c76a65cf 100644 --- a/crates/agent/src/panel/local_attachment.rs +++ b/crates/agent/src/panel/local_attachment.rs @@ -114,6 +114,7 @@ impl LocalAttachment { if let Some(entry) = Self::terminal(original.read(cx), cx) { owner.update(cx, |panel, cx| { panel.on_attachment_selected(origin, Attachment::Terminal(entry.item), cx); + panel.focus_composer(window, cx); }); } else { owner.update(cx, |panel, cx| { @@ -121,6 +122,7 @@ impl LocalAttachment { "Could not open a local terminal. Try opening it from the terminal menu." .into(), )); + panel.focus_composer(window, cx); cx.notify(); }); } diff --git a/crates/agent/src/panel/menu.rs b/crates/agent/src/panel/menu.rs index 3753c33b..09138932 100644 --- a/crates/agent/src/panel/menu.rs +++ b/crates/agent/src/panel/menu.rs @@ -155,6 +155,7 @@ impl ConfigMenuRenderer { let panel = cx.weak_entity(); let content_panel = panel.clone(); let open = menus.current() == Some(&kind); + let attachment_focus = (kind == MenuKind::Context).then(|| menus.attachment_focus(cx)); Popover::new(id) .anchor(anchor) .p_1() @@ -162,9 +163,12 @@ impl ConfigMenuRenderer { .trigger(trigger) .trigger_style(gpui_kit::StyleRefinement::default().min_w_0().max_w_full()) .open(open) - .on_open_change(move |open, _, cx| { + .when_some(attachment_focus, |popover, focus| { + popover.track_focus(&focus) + }) + .on_open_change(move |open, window, cx| { let _ = panel.update(cx, |this, cx| { - this.on_menu_open_changed(kind.clone(), *open, cx); + this.on_menu_open_changed(kind.clone(), *open, window, cx); }); }) .content(move |_, window, cx| { @@ -177,12 +181,15 @@ impl ConfigMenuRenderer { impl ConfigMenuRenderer { pub(super) fn render_menu( - mut frame: MenuFrame, + frame: MenuFrame, window: &gpui_kit::Window, cx: &mut Context, ) -> gpui_kit::AnyElement { let kind = frame.kind.clone(); let heading = Self::menu_heading(kind.as_ref(), frame.thread.as_ref(), cx); + if kind == Some(MenuKind::Context) { + return Self::attachment_frame(heading, frame, cx); + } let mut menu = ConfigMenuRenderer::frame(heading, cx); match kind { Some(MenuKind::Agents) => { @@ -194,14 +201,6 @@ impl ConfigMenuRenderer { cx, )); } - Some(MenuKind::Context) => { - menu = menu.child( - frame - .attachment - .take() - .unwrap_or_else(|| div().into_any_element()), - ) - } Some(MenuKind::Config(id)) => { if let Some(thread) = frame.thread.clone() { let options = thread.read(cx).config_options(); @@ -223,13 +222,46 @@ impl ConfigMenuRenderer { Some(MenuKind::Modes) => { menu = menu.children(Self::mode_choices(frame.thread.as_ref(), cx)) } - Some(MenuKind::Usage) | None => {} + Some(MenuKind::Context | MenuKind::Usage) | None => {} } menu.test_support().into_any_element() } } impl ConfigMenuRenderer { + fn attachment_frame( + heading: String, + frame: MenuFrame, + cx: &Context, + ) -> gpui_kit::AnyElement { + v_flex() + .w(rems(18.)) + .max_h(rems(18.)) + .gap_1() + .child( + div() + .id("agent-menu-heading") + .test_support() + .flex_shrink_0() + .px_2() + .py_1() + .text_xs() + .font_semibold() + .text_color(cx.theme().muted_foreground) + .child(heading), + ) + .child(div().flex_shrink_0().child(frame.query_input)) + .child( + v_flex() + .id("agent-picker") + .test_support() + .min_h_0() + .overflow_y_scroll() + .child(frame.attachment.unwrap_or_else(|| div().into_any_element())), + ) + .into_any_element() + } + fn menu_heading( kind: Option<&MenuKind>, thread: Option<&gpui_kit::Entity>, diff --git a/crates/agent/src/panel/menu_view.rs b/crates/agent/src/panel/menu_view.rs index 2eaa2ee5..54c537de 100644 --- a/crates/agent/src/panel/menu_view.rs +++ b/crates/agent/src/panel/menu_view.rs @@ -1,7 +1,8 @@ //! Configuration/search controls, usage-card lifetimes and one cancellable clipboard export. use super::{AgentPanel, MenuKind}; use gpui_kit::{ - App, AppContext as _, Context, Entity, FocusHandle, SharedString, Subscription, Window, + App, AppContext as _, Context, Entity, FocusHandle, Focusable, SharedString, Subscription, + Window, component::{ Sizable as _, input::{Input, InputEvent, InputState}, @@ -12,6 +13,7 @@ pub(super) struct MenuView { menu: Option, usage_focus: FocusHandle, search: Entity, + attachment_search: Entity, _bindings: Vec, copy: Option>, } @@ -22,6 +24,8 @@ impl MenuView { cx: &mut Context, ) -> Self { let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search models…")); + let attachment_search = + cx.new(|cx| InputState::new(window, cx).placeholder("Search servers and terminals…")); let usage_focus = cx.focus_handle(); let bindings = vec![ cx.subscribe(&search, |panel, _, event, cx| { @@ -29,6 +33,11 @@ impl MenuView { panel.on_config_query_changed(cx); } }), + cx.subscribe(&attachment_search, |panel, _, event, cx| { + if matches!(event, InputEvent::Change) { + panel.on_config_query_changed(cx); + } + }), cx.on_focus_out(&usage_focus, window, |panel, _, _, cx| { panel.on_usage_dismiss_requested(cx); }), @@ -40,6 +49,7 @@ impl MenuView { menu: None, usage_focus, search, + attachment_search, _bindings: bindings, copy: None, } @@ -86,10 +96,34 @@ impl MenuView { pub(super) fn usage_contains_focus(&self, window: &Window, cx: &App) -> bool { self.usage_focus.contains_focused(window, cx) } + pub(super) fn open_with_window(&mut self, kind: MenuKind, window: &mut Window, cx: &mut App) { + if kind == MenuKind::Context && !self.is_open(&kind) { + self.clear_attachment_query(window, cx); + } + self.open(kind); + } + fn clear_attachment_query(&self, window: &mut Window, cx: &mut App) { + if !self.attachment_search.read(cx).value().is_empty() { + self.attachment_search + .update(cx, |input, cx| input.set_value("", window, cx)); + } + } + pub(super) fn attachment_focus(&self, cx: &App) -> FocusHandle { + self.attachment_search.read(cx).focus_handle(cx) + } pub(super) fn query(&self, cx: &App) -> SharedString { + if self.is_open(&MenuKind::Context) { + return self.attachment_search.read(cx).value(); + } self.search.read(cx).value() } pub(super) fn query_input(&self) -> Input { - Input::new(&self.search).small() + if self.is_open(&MenuKind::Context) { + Input::new(&self.attachment_search) + .id("attachment-query") + .small() + } else { + Input::new(&self.search).small() + } } } diff --git a/crates/agent/src/panel/servers.rs b/crates/agent/src/panel/servers.rs index 9ee5f3c8..245654d2 100644 --- a/crates/agent/src/panel/servers.rs +++ b/crates/agent/src/panel/servers.rs @@ -16,9 +16,22 @@ pub(super) enum ServerRow<'a> { } /// The rows for `summaries`, folders and servers sorted by name. -pub(super) fn server_rows(summaries: &[ConnectionSummary]) -> Vec> { +pub(super) fn server_rows<'a>( + summaries: &'a [ConnectionSummary], + query: &str, +) -> Vec> { let key = |name: &str| (name.to_lowercase(), name.to_owned()); - let mut servers: Vec<&ConnectionSummary> = summaries.iter().collect(); + let mut servers: Vec<&ConnectionSummary> = summaries + .iter() + .filter(|summary| { + matches_query(summary.name.as_ref(), query) + || matches_query(&summary.target.host, query) + || summary + .group + .as_ref() + .is_some_and(|group| matches_query(group, query)) + }) + .collect(); servers.sort_by_cached_key(|summary| { ( summary.group.as_deref().map(key), @@ -43,6 +56,20 @@ pub(super) fn server_rows(summaries: &[ConnectionSummary]) -> Vec> rows } +/// Match a normalized user query against a displayed name or address. +pub(super) fn matches_query(label: &str, query: &str) -> bool { + if query.is_empty() { + return true; + } + if label.is_ascii() && query.is_ascii() { + return label + .as_bytes() + .windows(query.len()) + .any(|part| part.eq_ignore_ascii_case(query.as_bytes())); + } + label.to_lowercase().contains(query) +} + #[cfg(test)] mod tests { use super::*; @@ -71,7 +98,7 @@ mod tests { summary("ai-server", Some("homelab")), summary("backup", None), ]; - let rows: Vec = server_rows(&summaries) + let rows: Vec = server_rows(&summaries, "") .into_iter() .map(|row| match row { ServerRow::Folder(name) => format!("[{name}]"), @@ -93,4 +120,24 @@ mod tests { ] ); } + + #[test] + fn search_keeps_matching_servers_in_their_folders() { + let mut summaries = [ + summary("API", Some("Homelab")), + summary("Database", Some("Homelab")), + summary("Backup", None), + ]; + summaries[2].target.host = "storage.example.test".into(); + let rows = server_rows(&summaries, "api"); + assert!(matches!(rows.as_slice(), [ + ServerRow::Folder("Homelab"), + ServerRow::Server { summary, nested: true } + ] if summary.name.as_ref() == "API")); + assert_eq!(server_rows(&summaries, "homelab").len(), 3); + assert!(matches!(server_rows(&summaries, "storage").as_slice(), [ + ServerRow::Server { summary, nested: false } + ] if summary.name.as_ref() == "Backup")); + assert!(server_rows(&summaries, "unknown").is_empty()); + } } diff --git a/crates/agent/src/panel/tests/chat_servers.rs b/crates/agent/src/panel/tests/chat_servers.rs index 101a9515..d96f6b0c 100644 --- a/crates/agent/src/panel/tests/chat_servers.rs +++ b/crates/agent/src/panel/tests/chat_servers.rs @@ -61,3 +61,23 @@ fn the_attach_menu_of_an_agent_that_runs_elsewhere_lists_the_chats_servers( let request = f.commands.config.requests().pop().expect("a choice"); assert_eq!(request.setting, ConfigSetting::Boolean(false)); } + +#[gpui_kit::test] +fn attachment_search_keeps_the_hub_servers_original_choice_identity(cx: &mut TestAppContext) { + let f = fixture(cx); + hub_chat(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.click("agent-attach-context", cx); + window.input("BUILD.EXAMPLE", cx); + window.render_frame(cx); + assert!(window.try_find(("attach-server", 0usize)).is_none()); + assert!(window.try_find(("attach-server", 1usize)).is_some()); + window.click(("attach-server", 1usize), cx); + }) + .unwrap(); + cx.run_until_parked(); + let request = f.commands.config.requests().pop().expect("a choice"); + assert_eq!(request.config.as_str(), "server:build"); + assert_eq!(request.setting, ConfigSetting::Boolean(false)); +} diff --git a/crates/agent/src/panel/tests/composer/menu_stability.rs b/crates/agent/src/panel/tests/composer/menu_stability.rs index 4ae2e1b5..56ae4c74 100644 --- a/crates/agent/src/panel/tests/composer/menu_stability.rs +++ b/crates/agent/src/panel/tests/composer/menu_stability.rs @@ -236,3 +236,58 @@ fn reopening_the_attachment_picker_starts_at_the_top(cx: &mut TestAppContext) { }) .unwrap(); } + +#[gpui_kit::test] +fn attachment_search_takes_focus_filters_and_restores_the_draft(cx: &mut TestAppContext) { + let f = fixture(cx); + many_servers(&f, cx); + new_chat(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.focus(&f.panel.read(cx).composer_focus(cx), cx); + window.input("draft", cx); + window.click("agent-attach-context", cx); + assert!(window.try_find("attachment-query").is_some()); + window.input("SERVER-10", cx); + window.render_frame(cx); + assert!(window.try_find("attach-connection-server-00").is_none()); + assert!(window.try_find(ROW).is_some()); + assert_eq!(f.panel.read(cx).composer_text(cx).as_ref(), "draft"); + window.click(ROW, cx); + let thread = f.panel.read(cx).current().unwrap(); + assert!( + thread + .read(cx) + .composer() + .attachments() + .contains(&Attachment::Connection("server-10".into())) + ); + window.press("escape", cx); + window.render_frame(cx); + assert!(window.try_find("agent-picker").is_none()); + window.input(" continued", cx); + window.render_frame(cx); + assert_eq!( + f.panel.read(cx).composer_text(cx).as_ref(), + "draft continued" + ); + window.click("agent-attach-context", cx); + assert!(window.try_find("attach-connection-server-00").is_some()); + window.input("nothing matches", cx); + window.render_frame(cx); + assert!( + window + .try_find("No matching servers or terminals") + .is_some() + ); + window.click("agent-attach-context", cx); + window.render_frame(cx); + window.input("!", cx); + window.render_frame(cx); + assert_eq!( + f.panel.read(cx).composer_text(cx).as_ref(), + "draft continued!" + ); + }) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/seat_binding.rs b/crates/agent/src/panel/tests/seat_binding.rs index b423ed96..8d071c7d 100644 --- a/crates/agent/src/panel/tests/seat_binding.rs +++ b/crates/agent/src/panel/tests/seat_binding.rs @@ -150,6 +150,43 @@ fn chats_keep_their_workspace_terminals_while_another_workspace_is_active(cx: &m .unwrap(); } +#[gpui_kit::test] +fn workspace_ai_context_reads_live_original_metadata_not_selected_workspace( + cx: &mut TestAppContext, +) { + let f = fixture(cx); + cx.update_window(f.handle, |_, window, cx| { + let first = nocterm_project_model::ProjectId::from_bytes([1; 16]); + let (seat, surface, outer) = project_seat(&f, first, window, cx); + surface.set_ai_description("First", "original workspace hint", cx); + let second = nocterm_project_model::ProjectId::from_bytes([2; 16]); + let (other, other_surface, _) = project_seat(&f, second, window, cx); + other_surface.set_ai_description("Second", "unrelated workspace hint", cx); + assert_eq!( + seat.workspace_description(cx).unwrap().description, + "original workspace hint" + ); + assert_eq!( + other.workspace_description(cx).unwrap().description, + "unrelated workspace hint" + ); + surface.set_ai_description("First", "edited workspace hint", cx); + assert_eq!( + seat.workspace_description(cx).unwrap().description, + "edited workspace hint" + ); + f.workspace.update(cx, |workspace, cx| { + let index = workspace + .items(cx) + .position(|item| item.item_id() == outer.entity_id()) + .unwrap(); + workspace.close_item(index, window, cx); + }); + assert!(seat.workspace_description(cx).is_none()); + }) + .unwrap(); +} + #[gpui_kit::test] fn simultaneous_account_sources_filter_foreign_terminals_and_relogin_cannot_reclaim_old_authority( cx: &mut TestAppContext, diff --git a/crates/agent/src/panel/tests/servers.rs b/crates/agent/src/panel/tests/servers.rs index 63b83daf..61e098cc 100644 --- a/crates/agent/src/panel/tests/servers.rs +++ b/crates/agent/src/panel/tests/servers.rs @@ -254,7 +254,7 @@ fn a_background_session_can_be_shown_in_a_tab(cx: &mut TestAppContext) { } #[gpui_kit::test] -fn a_locked_vault_is_unlocked_from_the_chat_without_a_tab(cx: &mut TestAppContext) { +fn a_locked_vault_is_unlocked_from_the_chat_even_after_a_long_wait(cx: &mut TestAppContext) { let f = fixture(cx); let directory = install(&f, cx); directory.sign_in.vault_locked().set(true); @@ -266,24 +266,7 @@ fn a_locked_vault_is_unlocked_from_the_chat_without_a_tab(cx: &mut TestAppContex thread.offline_servers(cx)[0].0.server_id.clone() }) }); - let (respond, mut response) = oneshot::channel(); - cx.update(|cx| { - thread.update(cx, |thread, _| { - let registration = thread.registration().as_ref().unwrap().id; - f.calls - .try_send(BridgeCall { - arguments: None, - display_token: None, - registration_id: registration, - call: nocterm_ai::TerminalCall::OpenTerminal(nocterm_ai::OpenTerminal { - server_id: server, - }), - respond, - }) - .unwrap(); - }) - }); - cx.run_until_parked(); + let mut response = queue_server_open(&f, &thread, &server, cx); cx.update_window(f.handle, |_, window, cx| { window.render_frame(cx); if thread.read(cx).has_pending_approvals() { @@ -294,6 +277,12 @@ fn a_locked_vault_is_unlocked_from_the_chat_without_a_tab(cx: &mut TestAppContex cx.executor().advance_clock(Duration::from_secs(1)); cx.run_until_parked(); assert!(response.try_recv().unwrap().is_none(), "still signing in"); + cx.executor().advance_clock(Duration::from_secs(240)); + cx.run_until_parked(); + assert!( + response.try_recv().unwrap().is_none(), + "the original vault wait survives" + ); let unlocks = Rc::new(Cell::new(0)); let counter = unlocks.clone(); cx.update_window(f.handle, |_, window, cx| { @@ -338,7 +327,7 @@ fn a_locked_vault_is_unlocked_from_the_chat_without_a_tab(cx: &mut TestAppContex } #[gpui_kit::test] -fn a_password_is_typed_in_the_chat_without_a_tab(cx: &mut TestAppContext) { +fn a_delayed_password_answer_gets_a_fresh_connection_deadline(cx: &mut TestAppContext) { let f = fixture(cx); let directory = install(&f, cx); directory.sign_in.asks().set(true); @@ -350,24 +339,7 @@ fn a_password_is_typed_in_the_chat_without_a_tab(cx: &mut TestAppContext) { thread.offline_servers(cx)[0].0.server_id.clone() }) }); - let (respond, mut response) = oneshot::channel(); - cx.update(|cx| { - thread.update(cx, |thread, _| { - let registration = thread.registration().as_ref().unwrap().id; - f.calls - .try_send(BridgeCall { - arguments: None, - display_token: None, - registration_id: registration, - call: nocterm_ai::TerminalCall::OpenTerminal(nocterm_ai::OpenTerminal { - server_id: server, - }), - respond, - }) - .unwrap(); - }) - }); - cx.run_until_parked(); + let mut response = queue_server_open(&f, &thread, &server, cx); cx.update_window(f.handle, |_, window, cx| { window.render_frame(cx); if thread.read(cx).has_pending_approvals() { @@ -378,6 +350,14 @@ fn a_password_is_typed_in_the_chat_without_a_tab(cx: &mut TestAppContext) { cx.executor().advance_clock(Duration::from_secs(1)); cx.run_until_parked(); assert!(response.try_recv().unwrap().is_none(), "still signing in"); + cx.executor().advance_clock(Duration::from_secs(240)); + cx.run_until_parked(); + assert!( + response.try_recv().unwrap().is_none(), + "the password prompt is still pending" + ); + let access = directory.accesses.borrow()[0].clone(); + access.link().connecting().set(true); cx.update_window(f.handle, |_, window, cx| { assert!(!thread.read(cx).sign_in_waits()[0].vault()); assert_eq!( @@ -402,6 +382,19 @@ fn a_password_is_typed_in_the_chat_without_a_tab(cx: &mut TestAppContext) { .unwrap(); cx.executor().advance_clock(Duration::from_secs(1)); cx.run_until_parked(); + assert!( + response.try_recv().unwrap().is_none(), + "still connecting after the answer" + ); + cx.executor().advance_clock(Duration::from_secs(50)); + cx.run_until_parked(); + assert!( + response.try_recv().unwrap().is_none(), + "the answer started a fresh network budget" + ); + access.link().connecting().set(false); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); assert_eq!(*directory.sign_in.answers().borrow(), ["hunter2"]); let answer = response.try_recv().unwrap().unwrap().unwrap(); assert!(answer["terminal"]["id"].is_string()); @@ -411,6 +404,63 @@ fn a_password_is_typed_in_the_chat_without_a_tab(cx: &mut TestAppContext) { }); } +#[gpui_kit::test] +fn a_stalled_connection_after_sign_in_still_times_out(cx: &mut TestAppContext) { + let f = fixture(cx); + let directory = install(&f, cx); + directory.sign_in.asks().set(true); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + let server = cx.update(|cx| { + thread.update(cx, |thread, cx| { + thread.attach(Attachment::Group("prod".into()), cx); + thread.offline_servers(cx)[0].0.server_id.clone() + }) + }); + let mut response = queue_server_open(&f, &thread, &server, cx); + cx.update_window(f.handle, |_, window, cx| { + window.render_frame(cx); + window.click(("tool-Allow for this server", 0usize), cx); + }) + .unwrap(); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + let access = directory.accesses.borrow()[0].clone(); + access.link().connecting().set(true); + directory.sign_in.asks().set(false); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + assert!(response.try_recv().unwrap().is_none()); + cx.executor().advance_clock(Duration::from_secs(61)); + cx.run_until_parked(); + let error = response.try_recv().unwrap().unwrap().unwrap_err(); + assert!( + error + .message() + .contains("Connecting to the server timed out.") + ); + let item = directory.background.borrow()[0]; + cx.update(|cx| { + assert!(!f.workspace.read(cx).is_background(item, cx)); + assert!(thread.read(cx).sign_in_waits().is_empty()); + }); +} + +#[gpui_kit::test] +fn stopping_the_chat_cancels_the_sign_in_wait(cx: &mut TestAppContext) { + let f = fixture(cx); + let directory = show_hidden_sign_in(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + cx.update(|cx| thread.update(cx, |thread, cx| thread.stop(cx))); + cx.executor().advance_clock(Duration::from_secs(1)); + cx.run_until_parked(); + let item = directory.background.borrow()[0]; + cx.update(|cx| { + assert!(!f.workspace.read(cx).is_background(item, cx)); + assert!(thread.read(cx).sign_in_waits().is_empty()); + }); +} + #[gpui_kit::test] fn rows_attached_through_a_folder_do_not_toggle_on_their_own(cx: &mut TestAppContext) { let f = fixture(cx); diff --git a/crates/agent/src/panel/tests/servers/workspaces.rs b/crates/agent/src/panel/tests/servers/workspaces.rs index 1e1e4b0e..6d699193 100644 --- a/crates/agent/src/panel/tests/servers/workspaces.rs +++ b/crates/agent/src/panel/tests/servers/workspaces.rs @@ -42,6 +42,36 @@ fn replace_project(f: &Fixture, source: ProjectSurfaceReceipt, window: &mut Wind super::super::seat_binding::project_seat(f, project, window, cx); } +#[gpui_kit::test] +fn workspace_chat_context_includes_its_own_description_even_without_terminals( + cx: &mut TestAppContext, +) { + let f = fixture(cx); + let project = nocterm_project_model::ProjectId::from_bytes([1; 16]); + let surface = cx + .update_window(f.handle, |_, window, cx| { + let (_, surface, _) = super::super::seat_binding::project_seat(&f, project, window, cx); + surface.set_ai_description("Build workspace", "original-staging-hint", cx); + surface + }) + .unwrap(); + cx.run_until_parked(); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + cx.update_window(f.handle, |_, window, cx| { + let other = nocterm_project_model::ProjectId::from_bytes([2; 16]); + let (_, other_surface, _) = super::super::seat_binding::project_seat(&f, other, window, cx); + other_surface.set_ai_description("Unrelated", "foreign-workspace-hint", cx); + surface.set_ai_description("Build workspace", "edited-staging-hint", cx); + let payload = thread.update(cx, |thread, cx| thread.context(cx)); + assert!(payload.contains("Build workspace")); + assert!(payload.contains("edited-staging-hint")); + assert!(!payload.contains("original-staging-hint")); + assert!(!payload.contains("foreign-workspace-hint")); + }) + .unwrap(); +} + #[gpui_kit::test] fn a_workspace_chat_can_attach_and_open_an_additional_saved_server(cx: &mut TestAppContext) { let f = fixture(cx); diff --git a/crates/agent/src/panel/tests/terminal_fixture.rs b/crates/agent/src/panel/tests/terminal_fixture.rs index 8540fe1c..3e58be40 100644 --- a/crates/agent/src/panel/tests/terminal_fixture.rs +++ b/crates/agent/src/panel/tests/terminal_fixture.rs @@ -20,6 +20,7 @@ pub(super) struct Link { epoch: std::cell::Cell, remote: std::cell::Cell, closed: std::cell::Cell, + connecting: std::cell::Cell, /// Reconnecting fails, leaving it closed. unreachable: std::cell::Cell, reconnects: std::cell::Cell, @@ -103,6 +104,8 @@ impl TerminalState for Access { TerminalStatus::AwaitingVault } else if self.sign_in.asks.get() { TerminalStatus::AwaitingUser + } else if self.link.connecting.get() { + TerminalStatus::Connecting } else { TerminalStatus::Connected }, @@ -370,6 +373,9 @@ impl Link { pub(super) fn closed(&self) -> &std::cell::Cell { &self.closed } + pub(super) fn connecting(&self) -> &std::cell::Cell { + &self.connecting + } pub(super) fn unreachable(&self) -> &std::cell::Cell { &self.unreachable } diff --git a/crates/agent/src/workspace_seat.rs b/crates/agent/src/workspace_seat.rs index 2f7d9c95..d50c24e3 100644 --- a/crates/agent/src/workspace_seat.rs +++ b/crates/agent/src/workspace_seat.rs @@ -115,6 +115,20 @@ impl ChatWorkspace for WorkspaceSeat { .map(|directory| directory.connections(cx)) .unwrap_or_default() } + fn workspace_description(&self, cx: &App) -> Option { + if !self.current() { + return None; + } + let metadata = self + .workspace + .upgrade()? + .read(cx) + .context_ai_description(self.source, cx)?; + Some(nocterm_ai::context::WorkspaceDescriptor { + name: metadata.name.to_string(), + description: metadata.description.to_string(), + }) + } fn opens_connections(&self, cx: &App) -> bool { self.terminals(cx).is_some() && self.workspace.upgrade().is_some_and(|workspace| { diff --git a/crates/ai/src/context.rs b/crates/ai/src/context.rs index 1c505700..7d1bdaa6 100644 --- a/crates/ai/src/context.rs +++ b/crates/ai/src/context.rs @@ -39,6 +39,14 @@ pub struct ServerDescriptor { pub user: String, } +/// AI-facing metadata of the chat's original workspace, not an execution capability. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct WorkspaceDescriptor { + pub name: String, + pub description: String, +} + /// Short ids handed to agents instead of internal ones. pub struct OpaqueIds { ids: BTreeMap, @@ -82,6 +90,14 @@ pub const TERMINAL_RULES: &str = "Reach the user's terminals and servers only th /// The terminals and offline servers of a chat, as JSON between delimiters /// the agent can recognize. User-editable text is filtered for secrets. pub fn context_block(terminals: &[TerminalDescriptor], servers: &[ServerDescriptor]) -> String { + context_block_with_workspace(terminals, servers, None) +} + +pub fn context_block_with_workspace( + terminals: &[TerminalDescriptor], + servers: &[ServerDescriptor], + workspace: Option<&WorkspaceDescriptor>, +) -> String { let safe: Vec<_> = terminals .iter() .cloned() @@ -116,10 +132,16 @@ pub fn context_block(terminals: &[TerminalDescriptor], servers: &[ServerDescript }) .collect(); let files = safe.iter().any(|terminal| terminal.file_tools); - let json = if servers.is_empty() && !files { + let json = if servers.is_empty() && !files && workspace.is_none() { serde_json::to_string(&safe) } else { let mut context = serde_json::json!({ "terminals": safe }); + if let Some(workspace) = workspace { + context["workspace"] = serde_json::json!(WorkspaceDescriptor { + name: crate::redact::redact(&workspace.name), + description: crate::redact::redact(&workspace.description), + }); + } if !servers.is_empty() { context["offline_servers"] = serde_json::json!(servers); context["note"] = serde_json::json!( diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rs index 9016a61c..2c485e5e 100644 --- a/crates/ai/src/tests.rs +++ b/crates/ai/src/tests.rs @@ -219,6 +219,24 @@ fn explicit_descriptor_payload_filters_user_metadata_and_has_no_credentials() { assert_eq!(ids.get("actual-sensitive-entity-id"), "t1"); assert_eq!(ids.resolve("t1"), Some("actual-sensitive-entity-id")); } +#[test] +fn workspace_metadata_is_sent_without_terminals_and_redacts_user_text() { + use crate::context::{WorkspaceDescriptor, context_block_with_workspace}; + let descriptor = WorkspaceDescriptor { + name: "CI workspace".into(), + description: "Build scripts here; password=marker-private ".into(), + }; + let payload = context_block_with_workspace(&[], &[], Some(&descriptor)); + assert!(payload.contains("CI workspace")); + assert!(payload.contains("Build scripts here")); + assert!(!payload.contains("marker-private")); + assert_eq!(payload.matches("").count(), 1); + assert_eq!( + context_block_with_workspace(&[], &[], None), + context_block(&[], &[]) + ); +} + #[test] fn redacts_keys_tokens_assignments_and_error_payload() { let text = "-----BEGIN OPENSSH PRIVATE KEY-----\nmarker\n-----END OPENSSH PRIVATE KEY----- sk-abcdefgh123 ghp_abcdefgh123 password=marker-secret"; diff --git a/crates/connections-io/src/repository/tests.rs b/crates/connections-io/src/repository/tests.rs index 40e0088d..ac91def9 100644 --- a/crates/connections-io/src/repository/tests.rs +++ b/crates/connections-io/src/repository/tests.rs @@ -17,6 +17,7 @@ fn profile() -> Profile { id: ProfileId::from_bytes([7; 16]), name: "Build".into(), description: "notes".into(), + notes: String::new(), target: Target::new("tester", "build.test", 22), options: Default::default(), auth: Auth::Auto, diff --git a/crates/connections-model/src/draft.rs b/crates/connections-model/src/draft.rs index 7b98c48e..a86a2fbb 100644 --- a/crates/connections-model/src/draft.rs +++ b/crates/connections-model/src/draft.rs @@ -26,6 +26,7 @@ pub enum ValidationField { Launch, Session, Description, + Notes, IconColor, Country, JumpHosts, @@ -57,8 +58,10 @@ pub enum ProfileValidationError { IconColor(String), #[error("`{0}` is not a two-letter country code such as DE.")] Country(String), - #[error("Description must be at most 16384 bytes.")] + #[error("AI description must be at most 16384 bytes.")] Description, + #[error("Notes must be at most 16384 bytes.")] + Notes, } impl ProfileValidationError { pub fn field(&self) -> ValidationField { @@ -74,6 +77,7 @@ impl ProfileValidationError { Self::IconColor(_) => ValidationField::IconColor, Self::Country(_) => ValidationField::Country, Self::Description => ValidationField::Description, + Self::Notes => ValidationField::Notes, } } } @@ -82,6 +86,7 @@ pub struct MetadataDraft { pub name: String, pub group: String, pub description: String, + pub notes: String, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct EndpointDraft { @@ -139,6 +144,7 @@ pub struct EditorDefaults { pub struct ValidatedProfile { pub name: String, pub description: String, + pub notes: String, pub group: Option, pub target: Target, pub auth: Auth, @@ -157,6 +163,7 @@ impl ValidatedProfile { id, name: self.name, description: self.description, + notes: self.notes, options: self.options, target: self.target, auth: self.auth, @@ -183,9 +190,13 @@ impl ProfileDraft { if self.metadata.description.len() > 16384 { return Err(ProfileValidationError::Description); } + if self.metadata.notes.len() > 16384 { + return Err(ProfileValidationError::Notes); + } Ok(ValidatedProfile { name: optional(&self.metadata.name).unwrap_or_else(|| target.host.clone()), description: self.metadata.description.trim().to_owned(), + notes: self.metadata.notes.trim().to_owned(), group: optional(&self.metadata.group), target, auth, diff --git a/crates/connections-model/src/draft/tests.rs b/crates/connections-model/src/draft/tests.rs index 53a3c996..8cbff34f 100644 --- a/crates/connections-model/src/draft/tests.rs +++ b/crates/connections-model/src/draft/tests.rs @@ -144,6 +144,21 @@ fn appearance_precedes_description_and_description_limit_counts_bytes() { assert_eq!(profile.country.as_deref(), Some("de")); assert_eq!(profile.description.len(), 16384); } +#[test] +fn notes_and_ai_description_are_independent_and_bounded() { + let mut draft = draft(); + draft.metadata.description = "Deployment context".into(); + draft.metadata.notes = " Operator reference\nSecond line ".into(); + let profile = draft.validate(&defaults()).unwrap(); + assert_eq!(profile.description, "Deployment context"); + assert_eq!(profile.notes, "Operator reference\nSecond line"); + draft.metadata.notes = "é".repeat(8193); + assert!(matches!( + draft.validate(&defaults()), + Err(ProfileValidationError::Notes) + )); +} + #[test] fn disabled_launch_ignores_hidden_json_but_preserves_starting_directory() { let mut draft = draft(); diff --git a/crates/connections-model/src/jump_route/tests.rs b/crates/connections-model/src/jump_route/tests.rs index e6660b0e..44717413 100644 --- a/crates/connections-model/src/jump_route/tests.rs +++ b/crates/connections-model/src/jump_route/tests.rs @@ -5,6 +5,7 @@ use nocterm_session::CredentialId; fn profile(name: &str, host: &str, jumps: Vec) -> Profile { Profile { description: String::new(), + notes: String::new(), options: Default::default(), id: profile_id_for(name), name: name.to_owned(), diff --git a/crates/connections-model/src/profile_authority/tests.rs b/crates/connections-model/src/profile_authority/tests.rs index 8701e081..abdf81e1 100644 --- a/crates/connections-model/src/profile_authority/tests.rs +++ b/crates/connections-model/src/profile_authority/tests.rs @@ -5,6 +5,7 @@ fn profile() -> Profile { id: ProfileId::from_bytes([1; 16]), name: "host".into(), description: String::new(), + notes: String::new(), target: Target::new("root", "host", 22), auth: Default::default(), options: Default::default(), diff --git a/crates/connections-model/src/profiles.rs b/crates/connections-model/src/profiles.rs index d7b7dbe6..22651044 100644 --- a/crates/connections-model/src/profiles.rs +++ b/crates/connections-model/src/profiles.rs @@ -34,8 +34,12 @@ impl fmt::Display for ProfileId { /// A saved connection. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Profile { + /// Existing AI-shared description; retain its persisted field name. #[serde(default, skip_serializing_if = "String::is_empty")] pub description: String, + /// Human notes, never projected into agent context. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub notes: String, #[serde( default, skip_serializing_if = "nocterm_session::SessionOptions::is_default" diff --git a/crates/connections-model/src/profiles/tests.rs b/crates/connections-model/src/profiles/tests.rs index f1b470b6..521059a6 100644 --- a/crates/connections-model/src/profiles/tests.rs +++ b/crates/connections-model/src/profiles/tests.rs @@ -7,6 +7,7 @@ mod snapshots; fn profile(name: &str, host: &str, group: Option<&str>) -> Profile { Profile { description: String::new(), + notes: String::new(), options: Default::default(), id: crate::test_support::profile_id_for(name), name: name.to_owned(), @@ -34,6 +35,18 @@ fn recent(host: &str, profile: Option, last_used: u64) -> Recent { } } +#[test] +fn connection_notes_round_trip_and_old_profiles_keep_their_ai_description() { + let mut original = profile("server", "example.test", None); + original.description = "Existing agent context".into(); + let old = toml::to_string(&original).unwrap(); + assert!(!old.contains("notes")); + assert_eq!(toml::from_str::(&old).unwrap(), original); + original.notes = "Personal notes".into(); + let decoded: Profile = toml::from_str(&toml::to_string(&original).unwrap()).unwrap(); + assert_eq!(decoded, original); +} + #[test] fn profiles_read_from_hand_written_toml() { let text = r#" diff --git a/crates/connections-model/src/replica/tests.rs b/crates/connections-model/src/replica/tests.rs index 2dafa144..ff26954f 100644 --- a/crates/connections-model/src/replica/tests.rs +++ b/crates/connections-model/src/replica/tests.rs @@ -8,6 +8,7 @@ fn profile(name: &str) -> Profile { id: profile_id_for("shared"), name: name.into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "host", 22), auth: Auth::Password, diff --git a/crates/connections-store/src/connections/tests.rs b/crates/connections-store/src/connections/tests.rs index 7d29947d..014af625 100644 --- a/crates/connections-store/src/connections/tests.rs +++ b/crates/connections-store/src/connections/tests.rs @@ -23,6 +23,7 @@ fn profile(name: &str) -> Profile { id: nocterm_connections_model::test_support::profile_id_for(name), name: name.into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "host", 22), auth: Auth::Password, diff --git a/crates/connections-store/src/facts/tests.rs b/crates/connections-store/src/facts/tests.rs index 4d2af950..ef446ebd 100644 --- a/crates/connections-store/src/facts/tests.rs +++ b/crates/connections-store/src/facts/tests.rs @@ -56,6 +56,7 @@ fn profile() -> Profile { id: nocterm_connections_model::profiles::ProfileId::from_bytes([1; 16]), name: "host".into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "example.com", 22), auth: Default::default(), diff --git a/crates/connections-store/src/publication/capture/tests.rs b/crates/connections-store/src/publication/capture/tests.rs index c41c0a67..89866ae6 100644 --- a/crates/connections-store/src/publication/capture/tests.rs +++ b/crates/connections-store/src/publication/capture/tests.rs @@ -12,6 +12,7 @@ fn profile() -> Profile { id: ProfileId::from_bytes([1; 16]), name: "Captured".into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "host", 22), auth: Auth::Password, diff --git a/crates/connections-store/src/replication/tests.rs b/crates/connections-store/src/replication/tests.rs index 8dfb3fbf..c77b06a5 100644 --- a/crates/connections-store/src/replication/tests.rs +++ b/crates/connections-store/src/replication/tests.rs @@ -19,6 +19,7 @@ fn profile(name: &str) -> Profile { id: profile_id_for(name), name: name.into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", format!("{name}.example"), 22), auth: Auth::Password, diff --git a/crates/connections/src/directory/tests.rs b/crates/connections/src/directory/tests.rs index 3ee3facf..90908dbb 100644 --- a/crates/connections/src/directory/tests.rs +++ b/crates/connections/src/directory/tests.rs @@ -10,6 +10,7 @@ use nocterm_connections_model::profiles::{ProfileId, Recent}; fn profile(name: &str) -> Profile { Profile { description: String::new(), + notes: String::new(), options: Default::default(), id: nocterm_connections_model::test_support::profile_id_for(name), name: name.into(), @@ -89,6 +90,8 @@ async fn empty_center_reconnect_uses_normal_directory_and_current_profile( }) .unwrap(); let mut server = profile("Saved name"); + server.description = "Shared server context".into(); + server.notes = "Human-only marker".into(); let connections = installed.connections().clone(); connections .update(cx, |connections, cx| { @@ -120,6 +123,9 @@ async fn empty_center_reconnect_uses_normal_directory_and_current_profile( assert_eq!(recent.len(), 1); assert_eq!(recent[0].id, expected[0].id); assert_eq!(recent[0].name, "Current name"); + assert_eq!(expected[0].description, "Shared server context"); + assert_eq!(recent[0].description, "Shared server context"); + assert!(!format!("{:?}", expected[0]).contains("Human-only marker")); assert_eq!(recent[0].target.host, "203.0.113.9"); assert!(recent[0].icon.is_some()); window.render_frame(cx); diff --git a/crates/connections/src/editor.rs b/crates/connections/src/editor.rs index d9df9ee2..3162ce42 100644 --- a/crates/connections/src/editor.rs +++ b/crates/connections/src/editor.rs @@ -271,9 +271,10 @@ impl ConnectionEditor { fn confirm(&mut self, window: &mut Window, cx: &mut Context) { let address = self.jump_hosts.address().read(cx).focus_handle(cx); let description = self.connection.description().read(cx).focus_handle(cx); + let notes = self.connection.notes().read(cx).focus_handle(cx); if address.contains_focused(window, cx) { self.add_jump_address(window, cx); - } else if !description.contains_focused(window, cx) { + } else if !description.contains_focused(window, cx) && !notes.contains_focused(window, cx) { self.save(true, window, cx); } } @@ -507,9 +508,12 @@ impl ConnectionEditor { }; let focus = input .map(|input| input.read(cx).focus_handle(cx)) - .or_else(|| { - matches!(error.field, ValidationField::Description) - .then(|| self.connection.description().read(cx).focus_handle(cx)) + .or_else(|| match error.field { + ValidationField::Description => { + Some(self.connection.description().read(cx).focus_handle(cx)) + } + ValidationField::Notes => Some(self.connection.notes().read(cx).focus_handle(cx)), + _ => None, }); if let Some(focus) = focus { self.focus_after_render(section, focus, window, cx); diff --git a/crates/connections/src/editor/connection.rs b/crates/connections/src/editor/connection.rs index 6f37c995..f16eaad5 100644 --- a/crates/connections/src/editor/connection.rs +++ b/crates/connections/src/editor/connection.rs @@ -10,6 +10,7 @@ use nocterm_session::DEFAULT_PORT; pub(super) struct ConnectionFields { name: Entity, description: Entity, + notes: Entity, host: Entity, port: Entity, user: Entity, @@ -61,6 +62,10 @@ impl ConnectionFields { TextareaState::new(window, cx) .default_value(profile.map(|p| p.description.clone()).unwrap_or_default()) }); + let notes = cx.new(|cx| { + TextareaState::new(window, cx) + .default_value(profile.map(|p| p.notes.clone()).unwrap_or_default()) + }); let subscriptions = [&name, &host, &port, &user, &group] .into_iter() .map(|input| watch(input, window, cx)) @@ -68,6 +73,7 @@ impl ConnectionFields { Self { name, description, + notes, host, port, user, @@ -90,12 +96,16 @@ impl ConnectionFields { pub(super) fn description(&self) -> &Entity { &self.description } + pub(super) fn notes(&self) -> &Entity { + &self.notes + } pub(super) fn snapshot(&self, cx: &App) -> (MetadataDraft, EndpointDraft) { ( MetadataDraft { name: text(&self.name, cx), group: text(&self.group, cx), description: self.description.read(cx).value().to_string(), + notes: self.notes.read(cx).value().to_string(), }, EndpointDraft { host: text(&self.host, cx), @@ -173,21 +183,38 @@ impl ConnectionFields { ), form::section( "Notes", - [form::stacked_row( - "Description", - "Shared with AI agents when this connection is attached. Avoid secrets.", - div() - .id("editor-description") - .test_support() - .h(description_height) - .child( - Textarea::new(&self.description) - .h(description_height) - .aria_label("Connection description"), - ), - None, - cx, - )], + [ + form::stacked_row( + "Notes", + "Personal reference; not included in AI context. Do not store secrets here.", + div() + .id("editor-notes") + .test_support() + .h(description_height) + .child( + Textarea::new(&self.notes) + .h(description_height) + .aria_label("Connection notes"), + ), + None, + cx, + ), + form::stacked_row( + "AI description", + "Shared with AI agents when this connection is attached. Avoid secrets.", + div() + .id("editor-description") + .test_support() + .h(description_height) + .child( + Textarea::new(&self.description) + .h(description_height) + .aria_label("Connection AI description"), + ), + None, + cx, + ), + ], cx, ), ] diff --git a/crates/connections/src/editor/tests.rs b/crates/connections/src/editor/tests.rs index 8e8c7602..33fbf569 100644 --- a/crates/connections/src/editor/tests.rs +++ b/crates/connections/src/editor/tests.rs @@ -88,6 +88,10 @@ fn sections_keep_drafts_and_multiline_description_enter_does_not_submit(cx: &mut cx, ); window.render_frame(cx); + window.click("editor-notes", cx); + window.input("Human-only note", cx); + window.press("enter", cx); + window.input("second note", cx); window.click("editor-description", cx); window.input("first line", cx); window.press("enter", cx); @@ -134,6 +138,7 @@ fn sections_keep_drafts_and_multiline_description_enter_does_not_submit(cx: &mut let profile = connections.read(cx).profiles(cx).iter().next().unwrap(); assert_eq!(profile.target.host, "draft.test"); assert_eq!(profile.description, "first line\nsecond line"); + assert_eq!(profile.notes, "Human-only note\nsecond note"); assert_eq!(profile.auth, Auth::Password); assert_eq!( profile.launch.as_ref().unwrap().program.as_deref(), diff --git a/crates/connections/src/editor/tests/appearance.rs b/crates/connections/src/editor/tests/appearance.rs index 241c5348..b601b5c0 100644 --- a/crates/connections/src/editor/tests/appearance.rs +++ b/crates/connections/src/editor/tests/appearance.rs @@ -33,9 +33,11 @@ fn dialog_and_icon_fade_paint_without_an_ambient_settings_alias(cx: &mut TestApp quads.iter().filter(|q| q.background.as_solid()==Some(expected)).map(|q| q.bounds).collect::>(), quads.iter().filter(|q| q.bounds.intersects(&dialog)).take(10).map(|q| (q.bounds,q.background)).collect::>() ); + let viewport = window.find("editor-section-content").bounds(); + let icon = window.find("editor-icon-auto").bounds(); window.scroll( "editor-section-content", - gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(-800.))), + gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), viewport.center().y - icon.center().y)), cx, ); window.render_frame(cx); diff --git a/crates/connections/src/panel/tests.rs b/crates/connections/src/panel/tests.rs index 1e4a008f..6cc109a5 100644 --- a/crates/connections/src/panel/tests.rs +++ b/crates/connections/src/panel/tests.rs @@ -48,6 +48,7 @@ fn native_drag_moves_to_collapsed_folder_root_and_remembered_empty_folder(cx: &m group: Some(group.into()), target: nocterm_session::Target::new("ci", name, 22), description: String::new(), + notes: String::new(), options: Default::default(), auth: Default::default(), credential: None, @@ -221,6 +222,7 @@ fn gp(name: &str, group: Option<&str>) -> Profile { group: group.map(Into::into), target: nocterm_session::Target::new("ci", name, 22), description: String::new(), + notes: String::new(), options: Default::default(), auth: Default::default(), credential: None, diff --git a/crates/connections/src/panel/tests/list.rs b/crates/connections/src/panel/tests/list.rs index fa8e6137..02de8de1 100644 --- a/crates/connections/src/panel/tests/list.rs +++ b/crates/connections/src/panel/tests/list.rs @@ -9,6 +9,7 @@ fn profile(index: usize) -> Profile { group: Some("Work".into()), target: nocterm_session::Target::new("ci", "host", 22), description: "A saved host".into(), + notes: String::new(), options: Default::default(), auth: Default::default(), credential: None, diff --git a/crates/connections/src/panel/tests/reorder.rs b/crates/connections/src/panel/tests/reorder.rs index f459fdee..b3bf810e 100644 --- a/crates/connections/src/panel/tests/reorder.rs +++ b/crates/connections/src/panel/tests/reorder.rs @@ -10,6 +10,7 @@ fn dropping_on_a_row_places_the_connection_above_it(cx: &mut TestAppContext) { group: group.map(Into::into), target: nocterm_session::Target::new("ci", name, 22), description: String::new(), + notes: String::new(), options: Default::default(), auth: Default::default(), credential: None, diff --git a/crates/connections/src/probe_sources/tests.rs b/crates/connections/src/probe_sources/tests.rs index f7dbd086..a8970679 100644 --- a/crates/connections/src/probe_sources/tests.rs +++ b/crates/connections/src/probe_sources/tests.rs @@ -48,6 +48,7 @@ impl Scene { id: nocterm_connections_model::test_support::profile_id_for("source"), name: "source".into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "example.com", 22), auth: Default::default(), diff --git a/crates/connections/src/session_intents/tests.rs b/crates/connections/src/session_intents/tests.rs index 54c5abe6..1b566ca5 100644 --- a/crates/connections/src/session_intents/tests.rs +++ b/crates/connections/src/session_intents/tests.rs @@ -8,6 +8,7 @@ fn saved_profile_keeps_description_and_session_overrides_when_opened() { ), name: "Legacy build".into(), description: "Windows-1251 machine\nUses a private proxy".into(), + notes: String::new(), target: nocterm_session::Target::new("ci", "build.example", 22), auth: nocterm_session::Auth::Auto, group: None, @@ -43,6 +44,7 @@ fn saved(name: &str, host: &str) -> Profile { id: nocterm_connections_model::test_support::profile_id_for(name), name: name.into(), description: String::new(), + notes: String::new(), target: nocterm_session::Target::new("ops", host, 22), auth: nocterm_session::Auth::Password, group: None, diff --git a/crates/hub-io/src/vault.rs b/crates/hub-io/src/vault.rs index d5b221f7..99a7ac2b 100644 --- a/crates/hub-io/src/vault.rs +++ b/crates/hub-io/src/vault.rs @@ -226,6 +226,10 @@ impl VaultAccess for HubVault { self.run(move |ledger| async move { ledger.get(id, binding).await }) } + fn reveal_password(&self, id: CredentialId) -> VaultFuture { + self.run(move |ledger| async move { ledger.reveal_password(id).await }) + } + fn put( &self, id: Option, diff --git a/crates/hub-io/src/vault/ledger.rs b/crates/hub-io/src/vault/ledger.rs index 9d641402..a1c4adc6 100644 --- a/crates/hub-io/src/vault/ledger.rs +++ b/crates/hub-io/src/vault/ledger.rs @@ -227,6 +227,17 @@ impl Ledger { Ok(record.secret) } + pub(super) async fn reveal_password(&self, id: CredentialId) -> Result { + let _operation = self.access.operation().await?; + let keys = self.keys()?; + self.sync(&keys).await?; + let record = self.record(&keys, &id.to_string())?; + if !record.binding.can_reveal_password() { + return Err(VaultError::Unsupported); + } + Ok(record.secret) + } + /// Renames the record `id` and binds it as `binding` while its secret stays. pub(super) async fn update( &self, diff --git a/crates/hub-io/src/vault/tests.rs b/crates/hub-io/src/vault/tests.rs index fff53df8..ae3a9b78 100644 --- a/crates/hub-io/src/vault/tests.rs +++ b/crates/hub-io/src/vault/tests.rs @@ -134,3 +134,45 @@ async fn the_vault_locks_itself_after_a_quiet_period() { .unwrap(); assert_eq!(vault.status(), VaultStatus::Locked); } + +#[tokio::test(flavor = "multi_thread")] +async fn management_reveals_an_unbound_password_but_not_a_private_key() { + let (vault, _hub, _dir) = vault(); + let id = vault + .put( + None, + "Password".into(), + CredentialBinding::password([]), + Secret::new("synthetic password"), + ) + .await + .unwrap(); + let key = vault + .put( + None, + "Key".into(), + CredentialBinding::PrivateKey { + public_key: "ssh-ed25519 synthetic".into(), + }, + Secret::new("synthetic key"), + ) + .await + .unwrap(); + assert_eq!( + vault.reveal_password(id).await.unwrap().expose(), + "synthetic password" + ); + assert!(matches!( + vault.reveal_password(key).await, + Err(VaultError::Unsupported) + )); + assert!(matches!( + vault.get(id, binding()).await, + Err(VaultError::Binding) + )); + vault.lock(); + assert!(matches!( + vault.reveal_password(id).await, + Err(VaultError::Locked) + )); +} diff --git a/crates/hub-io/tests/hub/account.rs b/crates/hub-io/tests/hub/account.rs index 50bcea2b..b0a2cc0c 100644 --- a/crates/hub-io/tests/hub/account.rs +++ b/crates/hub-io/tests/hub/account.rs @@ -170,6 +170,10 @@ fn a_credential_kept_on_one_device_is_read_on_another() { ); let secret = block_on(vault.get(id, binding)).unwrap(); assert_eq!(secret.expose(), "hunter2"); + let revealed = block_on(vault.reveal_password(id)).unwrap(); + assert_eq!(revealed.expose(), "hunter2"); + vault.lock(); + assert!(block_on(vault.reveal_password(id)).is_err()); block_on(first.account(&hub).vault().delete(id)).unwrap(); } @@ -236,6 +240,7 @@ fn a_profile_saved_on_one_device_is_read_on_another() { id: profile_id_for(&name), name: name.clone(), description: String::new(), + notes: String::new(), options: Default::default(), target: nocterm_session::Target::new("ci", "live.example", 22), auth: Auth::Password, diff --git a/crates/hub-io/tests/hub/replica_performance.rs b/crates/hub-io/tests/hub/replica_performance.rs index 82282fbf..aa87fc45 100644 --- a/crates/hub-io/tests/hub/replica_performance.rs +++ b/crates/hub-io/tests/hub/replica_performance.rs @@ -13,6 +13,7 @@ fn profile(name: String) -> Profile { id: profile_id_for(&name), name, description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "initial.example", 22), auth: Auth::Password, diff --git a/crates/plugins-ui/src/lib.rs b/crates/plugins-ui/src/lib.rs index b1b95c64..d226f153 100644 --- a/crates/plugins-ui/src/lib.rs +++ b/crates/plugins-ui/src/lib.rs @@ -14,7 +14,8 @@ //! the application implements, and the install row: **Install plugin…**, **Open plugins //! folder** and the plugin files found there, through the `PluginsFolder` port. The page draws //! the section in parts (`UserPart`): its rows in the plugin list, the selected plugin's detail -//! beside it, and the switch, install, folder and consent below. One switch turns a user plugin +//! beside it, and a header with the restart policy and Add plugin action. Package selection and +//! consent live in one modal, with folder reads requested only while it is open. One switch turns a user plugin //! on (enabled and allowed in windows) or off (disabled, its place kept). A held run (safe //! mode, or not allowed) lists none; its install row opens the folder and says what to do //! first. @@ -69,7 +70,7 @@ pub fn settings_page( .with_icon(IconName::Plug) } -/// The lazy Plugins page with a User section below the system plugins, which stay unchanged. +/// The lazy Plugins page with built-in and external plugins and a modal installer. pub fn settings_page_with_user_plugins( catalog: Arc, toggles: Rc, diff --git a/crates/plugins-ui/src/page.rs b/crates/plugins-ui/src/page.rs index d02531d2..c5d56a10 100644 --- a/crates/plugins-ui/src/page.rs +++ b/crates/plugins-ui/src/page.rs @@ -86,7 +86,7 @@ impl PluginsPage { page } - /// Adds the User section below the system plugins. + /// Adds the external plugin list, details and installation action. pub fn with_user_plugins( mut self, session: crate::UserSession, diff --git a/crates/plugins-ui/src/user.rs b/crates/plugins-ui/src/user.rs index 2f087043..11125b38 100644 --- a/crates/plugins-ui/src/user.rs +++ b/crates/plugins-ui/src/user.rs @@ -8,6 +8,7 @@ mod consent; mod consent_view; mod folder; +mod install_view; mod part_view; mod port; mod removal; diff --git a/crates/plugins-ui/src/user/consent_view.rs b/crates/plugins-ui/src/user/consent_view.rs index 2e94215a..c9497f70 100644 --- a/crates/plugins-ui/src/user/consent_view.rs +++ b/crates/plugins-ui/src/user/consent_view.rs @@ -5,6 +5,7 @@ use gpui_kit::{ component::{ ActiveTheme as _, Disableable as _, Sizable as _, StyledExt as _, button::{Button, ButtonVariants as _}, + dialog::Confirm, h_flex, switch::Switch, v_flex, @@ -47,10 +48,6 @@ pub(super) fn consent_dialog( .test_support() .w_full() .gap_2() - .p_4() - .border_1() - .border_color(cx.theme().border) - .rounded(cx.theme().radius) .child(div().text_lg().font_semibold().child(title)) .child(fact( "Publisher", @@ -179,12 +176,37 @@ fn answer( .gap_2() .pt_2() .child( - Button::new("user-consent-deny") - .small() - .primary() + // The styled Button installs its own keyed focus handle during render, replacing + // a supplied track_focus. Keep the initial Deny focus on its container, where + // the focus remains in the Dialog action path (including Escape). + div() + .id("user-consent-default") + .test_support() .track_focus(section.deny_focus()) - .label("Deny") - .on_click(cx.listener(|section, _, _, cx| section.deny(cx))), + .tab_index(0) + .tab_stop(false) + .rounded(cx.theme().radius) + .border_1() + .border_color(cx.theme().background.opacity(0.)) + .focus({ + let ring = cx.theme().ring; + move |style| style.border_color(ring) + }) + .on_action(cx.listener(|section, _: &Confirm, window, cx| { + if section.deny_focus().is_focused(window) { + section.close_install_dialog(window, cx); + cx.stop_propagation(); + } + })) + .child( + Button::new("user-consent-deny") + .small() + .primary() + .label("Deny") + .on_click(cx.listener(|section, _, window, cx| { + section.close_install_dialog(window, cx); + })), + ), ) .child( Button::new("user-consent-accept") diff --git a/crates/plugins-ui/src/user/folder.rs b/crates/plugins-ui/src/user/folder.rs index 1f010c0e..282f3128 100644 --- a/crates/plugins-ui/src/user/folder.rs +++ b/crates/plugins-ui/src/user/folder.rs @@ -4,7 +4,7 @@ use std::{path::PathBuf, sync::Arc}; -use gpui_kit::SharedString; +use gpui_kit::{SharedString, Task}; use nocterm_core::error::SharedCause; /// Most files of the folder the section lists. @@ -38,6 +38,8 @@ pub(super) struct FolderState { folder: Arc, found: Vec, error: Option, + task: Option>, + generation: u64, } impl FolderState { @@ -46,6 +48,8 @@ impl FolderState { folder, found: Vec::new(), error: None, + task: None, + generation: 0, } } @@ -61,6 +65,34 @@ impl FolderState { self.folder.clone() } + pub(super) fn busy(&self) -> bool { + self.task.is_some() + } + + pub(super) fn start(&mut self, task: Task<()>) { + self.task = Some(task); + } + + pub(super) fn generation(&self) -> u64 { + self.generation + } + + /// Releases the one in-flight task, indicating whether the result still belongs to + /// the current installer. + pub(super) fn settled(&mut self, generation: u64) -> bool { + self.task = None; + generation == self.generation + } + + /// Closing invalidates the projection and any pending delivery. Keep the task slot until + /// the synchronous port call settles: dropping its awaiting task cannot stop an already + /// running filesystem operation. + pub(super) fn close(&mut self) { + self.generation = self.generation.wrapping_add(1); + self.found.clear(); + self.error = None; + } + /// What a listing found, or why it failed. pub(super) fn listed(&mut self, listed: Result, FolderError>) { match listed { diff --git a/crates/plugins-ui/src/user/install_view.rs b/crates/plugins-ui/src/user/install_view.rs new file mode 100644 index 00000000..ca20edaf --- /dev/null +++ b/crates/plugins-ui/src/user/install_view.rs @@ -0,0 +1,229 @@ +//! Package sources and the consent in the modal installation flow. + +use gpui_kit::{ + AnyElement, Context, IntoElement, SharedString, TestSupportExt as _, + component::{ + ActiveTheme as _, Disableable as _, Sizable as _, StyledExt as _, + button::{Button, ButtonVariants as _}, + h_flex, v_flex, + }, + div, + prelude::*, +}; +use nocterm_ui::form; + +use super::{consent_view::consent_dialog, section::UserPluginsSection}; + +pub(super) fn body( + section: &UserPluginsSection, + cx: &mut Context, +) -> AnyElement { + let loaded = section.loaded(); + let content = if let Some(consent) = section.consent() { + consent_dialog(section, consent, cx) + } else { + v_flex() + .gap_3() + .child(form::note( + "External plugins come from files. Their publishers are not verified; \ + review the permissions before installing.", + cx, + )) + .child(install_row(section, loaded, cx)) + .children(dev_banner(section, cx)) + .children(folder_listing(section, loaded, cx)) + .child( + h_flex().justify_end().child( + Button::new("user-install-cancel") + .small() + .label("Cancel") + .on_click(cx.listener(|section, _, window, cx| { + section.close_install_dialog(window, cx); + })), + ), + ) + .into_any_element() + }; + v_flex() + .id("user-install-dialog") + .test_support() + .w_full() + .gap_3() + .child(content) + .children(section.notice().cloned().map(|notice| { + div() + .id("user-notice") + .aria_label(notice.clone()) + .test_support() + .child(if section.busy() { + form::note(notice, cx) + } else { + form::error_text(notice, cx) + }) + })) + .into_any_element() +} + +/// Install a plugin from a file and open the plugins folder. In a run that holds the plugins the +/// folder still opens, and the install button says what to do first. +fn install_row( + section: &UserPluginsSection, + loaded: bool, + cx: &mut Context, +) -> AnyElement { + let install = Button::new("user-install") + .small() + .primary() + .label("Choose plugin file…") + .disabled(!loaded || section.busy()) + .on_click(cx.listener(|section, _, window, cx| { + section.choose_file(window, cx); + })); + v_flex() + .gap_1() + .child( + h_flex() + .id("user-install-row") + .test_support() + .gap_2() + .child(install) + .child( + Button::new("user-open-folder") + .small() + .ghost() + .label("Open plugins folder") + .disabled(section.folder().busy()) + .on_click(cx.listener(|section, _, _, cx| section.open_folder(cx))), + ), + ) + .when(section.folder().busy(), |row| { + row.child(form::note("Reading plugins folder…", cx)) + }) + .when(!loaded, |row| { + row.child( + div() + .id("user-install-held") + .aria_label( + "Allow external plugins in Plugins settings and restart Nocterm to install plugins.", + ) + .test_support() + .child(form::note( + "Allow external plugins in Plugins settings and restart Nocterm to install plugins. \ + Files you put in the plugins folder are offered here after restart.", + cx, + )), + ) + }) + .children( + section + .folder() + .error() + .cloned() + .map(|error| { + div() + .id("user-folder-error") + .aria_label(error.clone()) + .test_support() + .child(form::error_text(error, cx)) + }), + ) + .into_any_element() +} + +/// The plugin files in the plugins folder, each with a button that installs it through the +/// consent. Shown only in a run that loads user plugins. +fn folder_listing( + section: &UserPluginsSection, + loaded: bool, + cx: &mut Context, +) -> Option { + let found = section.folder().found(); + if !loaded || found.is_empty() { + return None; + } + let rows = found.iter().enumerate().map(|(index, path)| { + let name = path.file_name().map_or_else( + || path.to_string_lossy().into_owned(), + |name| name.to_string_lossy().into_owned(), + ); + let location = path.to_string_lossy().into_owned(); + h_flex() + .id(("user-folder-file", index)) + .aria_label(SharedString::from(name.clone())) + .test_support() + .w_full() + .gap_2() + .child(div().flex_1().min_w_0().truncate().text_sm().child(name)) + .child( + Button::new(("user-folder-install", index)) + .small() + .outline() + .label("Review…") + .disabled(section.busy()) + .on_click(cx.listener(move |section, _, window, cx| { + section.begin_install(&location, window, cx); + })), + ) + .into_any_element() + }); + Some( + v_flex() + .id("user-folder") + .aria_label("In your plugins folder") + .test_support() + .w_full() + .gap_1() + .child( + div() + .text_sm() + .font_semibold() + .child("In your plugins folder"), + ) + .children(rows) + .into_any_element(), + ) +} + +/// The banner of a developer session: the plugin and settings are not saved, and one button +/// loads the file under test through the same consent as any other package. +fn dev_banner( + section: &UserPluginsSection, + cx: &mut Context, +) -> Option { + let location = section.dev_location(cx)?; + let name = std::path::Path::new(&location).file_name().map_or_else( + || location.clone(), + |name| name.to_string_lossy().into_owned(), + ); + Some( + v_flex() + .id("user-dev") + .aria_label("Developer session") + .test_support() + .w_full() + .gap_1() + .p_3() + .border_1() + .border_color(cx.theme().border) + .rounded(cx.theme().radius) + .child( + div() + .text_sm() + .font_semibold() + .child("Developer session \u{2014} the plugin and settings are not saved"), + ) + .child( + div().child( + Button::new("user-dev-load") + .small() + .outline() + .label(format!("Load {name}")) + .disabled(section.busy()) + .on_click(cx.listener(move |section, _, window, cx| { + section.begin_install(&location, window, cx); + })), + ), + ) + .into_any_element(), + ) +} diff --git a/crates/plugins-ui/src/user/section.rs b/crates/plugins-ui/src/user/section.rs index a8f378eb..448001ce 100644 --- a/crates/plugins-ui/src/user/section.rs +++ b/crates/plugins-ui/src/user/section.rs @@ -4,8 +4,8 @@ use std::rc::Rc; use gpui_kit::{ - App, AppContext as _, Context, Entity, FocusHandle, PathPromptOptions, Render, SharedString, - Subscription, Task, Window, + App, AppContext as _, Context, Entity, FocusHandle, ParentElement, PathPromptOptions, Render, + SharedString, Subscription, Task, Window, component::WindowExt as _, px, }; use nocterm_plugin_model::PluginId; use nocterm_ui::{FormFrame, FormScope, PluginSettingsDirectory, PluginSettingsForm}; @@ -30,6 +30,7 @@ pub struct UserPluginsSection { selected_fingerprint: Option, form: Option>, consent: Option, + install_dialog_open: bool, /// Why the last action was refused. notice: Option, /// Which folded lists of the detail the user opened. @@ -66,7 +67,7 @@ impl UserPluginsSection { let _ = weak.update(cx, |_, cx| cx.notify()); }), )); - let section = Self { + Self { session, switch, directory, @@ -75,15 +76,14 @@ impl UserPluginsSection { selected_fingerprint: None, form: None, consent: None, + install_dialog_open: false, notice: None, unfolded: Unfolded::default(), deny_focus: cx.focus_handle(), _subscriptions: subscriptions, operation: None, generation: 0, - }; - section.refresh_folder(cx); - section + } } pub(super) fn folder(&self) -> &FolderState { @@ -91,42 +91,67 @@ impl UserPluginsSection { } /// Lists the plugins folder again, when this run can install from it. - pub(super) fn refresh_folder(&self, cx: &mut Context) { - if !self.session.is_loaded() { + pub(super) fn refresh_folder(&mut self, cx: &mut Context) { + if !self.install_dialog_open || !self.loaded() || self.folder.busy() { return; } + let generation = self.folder.generation(); let folder = self.folder.port(); let listed = cx .background_executor() .spawn(async move { folder.packages() }); - cx.spawn(async move |section, cx| { + self.folder.start(cx.spawn(async move |section, cx| { let listed = listed.await; let _ = section.update(cx, |section, cx| { - section.folder.listed(listed); - cx.notify(); + if section.folder_delivery(generation, cx) { + section.folder.listed(listed); + cx.notify(); + } }); - }) - .detach(); + })); } /// Creates the plugins folder if needed and opens it in the file manager. pub(super) fn open_folder(&mut self, cx: &mut Context) { + if !self.install_dialog_open || self.folder.busy() { + return; + } + let generation = self.folder.generation(); let folder = self.folder.port(); let prepared = cx .background_executor() .spawn(async move { folder.prepare() }); - cx.spawn(async move |section, cx| { + self.folder.start(cx.spawn(async move |section, cx| { let prepared = prepared.await; let _ = section.update(cx, |section, cx| { + if !section.folder_delivery(generation, cx) { + return; + } match prepared { - Ok(path) => cx.open_with_system(&path), + Ok(path) => { + cx.open_with_system(&path); + section.refresh_folder(cx); + } Err(error) => section.folder.failed(&error), } cx.notify(); }); - }) - .detach(); - self.refresh_folder(cx); + })); + cx.notify(); + } + + /// A late result from a dismissed installer is not delivered. If it reopened while + /// the port was busy, coalesce those opens into one new scan after the old task settles. + fn folder_delivery(&mut self, generation: u64, cx: &mut Context) -> bool { + let current = self.folder.settled(generation); + if !self.install_dialog_open { + return false; + } + if !current { + self.refresh_folder(cx); + cx.notify(); + } + current } /// Why this run did not load the plugins, or `None` when it did. @@ -235,33 +260,101 @@ impl UserPluginsSection { self.rows(cx).iter().any(|row| &row.id == plugin) } + pub(super) fn busy(&self) -> bool { + self.operation.is_some() + } + + pub(super) fn install_dialog_open(&self) -> bool { + self.install_dialog_open + } + + /// The installation flow has a single modal, from the source picker to consent. + pub(super) fn open_install_dialog(&mut self, window: &mut Window, cx: &mut Context) { + if self.install_dialog_open || self.busy() { + return; + } + self.install_dialog_open = true; + self.notice = None; + let section = cx.entity(); + let body = cx.new(|cx| super::UserPartView::new(section, super::UserPart::Install, cx)); + let dismiss = cx.weak_entity(); + window.open_dialog(cx, move |dialog, _, _| { + let dismiss = dismiss.clone(); + dialog + .title("Add plugin") + .w(px(560.)) + // Enter never grants permission to install a package. + .on_ok(|_, _, _| false) + .on_close(move |_, _, cx| { + let _ = dismiss.update(cx, |section, cx| section.dismiss_install(cx)); + }) + .child(body.clone()) + }); + self.refresh_folder(cx); + cx.notify(); + } + + pub(super) fn close_install_dialog(&mut self, window: &mut Window, cx: &mut Context) { + if self.install_dialog_open { + self.dismiss_install(cx); + window.close_dialog(cx); + } + } + + /// Closing the dialog cancels pending selection/inspection but never an accepted install. + fn dismiss_install(&mut self, cx: &mut Context) { + if !self.install_dialog_open { + return; + } + self.install_dialog_open = false; + self.consent = None; + self.notice = None; + self.folder.close(); + self.generation = self.generation.wrapping_add(1); + self.operation = None; + cx.notify(); + } + /// Asks the user for a package file, then starts the install from it. pub(super) fn choose_file(&mut self, window: &mut Window, cx: &mut Context) { + if !self.install_dialog_open || !self.loaded() || self.busy() || self.consent.is_some() { + return; + } let picked = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None, }); - cx.spawn_in(window, async move |this, cx| { - if let Ok(Ok(Some(paths))) = picked.await - && let Some(path) = paths.first() - { - let location = path.to_string_lossy().into_owned(); - let _ = this.update_in(cx, |section, window, cx| { - section.begin_install(&location, window, cx); - }); - } - }) - .detach(); + self.generation = self.generation.wrapping_add(1); + let generation = self.generation; + self.notice = Some("Choosing plugin file…".into()); + self.operation = Some(cx.spawn_in(window, async move |this, cx| { + let picked = picked.await; + let _ = this.update_in(cx, |section, window, cx| { + if section.generation != generation { + return; + } + section.operation = None; + section.notice = None; + if let Ok(Ok(Some(paths))) = picked + && let Some(path) = paths.first() + { + section.begin_install(&path.to_string_lossy(), window, cx); + } + cx.notify(); + }); + })); + cx.notify(); } /// Reads the package at `location` and, when it is acceptable, opens the consent. Nothing is /// stored until the user accepts. pub fn begin_install(&mut self, location: &str, window: &mut Window, cx: &mut Context) { - if self.operation.is_some() { + if self.busy() || self.consent.is_some() || !self.loaded() { return; } + self.open_install_dialog(window, cx); self.notice = None; let Some(manager) = self.session.loaded() else { return; @@ -316,6 +409,9 @@ impl UserPluginsSection { }; let result = manager.install(request, cx); self.consent = None; + self.install_dialog_open = false; + self.folder.close(); + window.close_dialog(cx); self.notice = Some("Installing plugin…".into()); self.generation = self.generation.wrapping_add(1); let generation = self.generation; @@ -333,20 +429,12 @@ impl UserPluginsSection { } Err(error) => section.notice = Some(describe(&error).into()), } - section.refresh_folder(cx); cx.notify(); }); })); cx.notify(); } - pub(super) fn deny(&mut self, cx: &mut Context) { - self.consent = None; - self.generation = self.generation.wrapping_add(1); - self.operation = None; - cx.notify(); - } - /// Shows `plugin` in the detail, first sending what was typed into the previous form. The /// page hears of it ([`UserSelected`]) and lets go of its own selection. pub fn select(&mut self, plugin: &PluginId, window: &mut Window, cx: &mut Context) { @@ -474,7 +562,7 @@ impl UserPluginsSection { cx: &mut Context, action: impl FnOnce(&dyn UserPlugins, &mut App) -> Task>, ) { - if self.operation.is_some() { + if self.busy() || self.install_dialog_open { return; } let Some(manager) = self.session.loaded().cloned() else { diff --git a/crates/plugins-ui/src/user/section_view.rs b/crates/plugins-ui/src/user/section_view.rs index d815222b..73066203 100644 --- a/crates/plugins-ui/src/user/section_view.rs +++ b/crates/plugins-ui/src/user/section_view.rs @@ -1,4 +1,4 @@ -//! How the User section looks: the head (the switch, install and the folder, the consent), the +//! How the User section looks: the header with the permission switch and add action, the //! rows of the installed plugins and the detail of the selected one. The Plugins page draws each //! part in its place ([`UserPart`]); on its own the section draws them one under the other. @@ -18,7 +18,7 @@ use nocterm_plugin_model::PluginId; use nocterm_ui::{IconName, form}; use super::{ - consent_view::consent_dialog, + install_view, port::{RowState, UserPluginRow, describe}, section::{FoldedList, UserPluginsSection}, switch_view, @@ -32,8 +32,10 @@ const FOLDED_LINES: usize = 3; /// A part of the section that the Plugins page draws in its own place. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum UserPart { - /// Above the plugin list: the switch, install and the plugins folder, notices, the consent. + /// Above the plugin list: the permission switch, notices and the add action. Head, + /// Inside the installation dialog: the package sources and consent. + Install, /// In the plugin list: one row per installed plugin, each marked External. Rows, /// Beside the list: the selected plugin and the audit log. @@ -64,6 +66,7 @@ pub(super) fn part( ) -> AnyElement { let drawn = match part { UserPart::Head => Some(head(section, cx)), + UserPart::Install => Some(install_view::body(section, cx)), UserPart::Rows => rows(section, cx), UserPart::Detail => selected_detail(section, cx), }; @@ -71,201 +74,58 @@ pub(super) fn part( } fn head(section: &UserPluginsSection, cx: &mut Context) -> AnyElement { - let loaded = section.loaded(); v_flex() .id("user-plugins-head") .test_support() .w_full() .gap_2() - .child(form::page_header( - "External plugins", - Some( - "Plugins you install from a file. Their publishers are not verified, and they \ - can only do what you allow here." - .into(), - ), - cx, - )) - .children(switch_view::switch_row(section, cx)) - .children(switch_view::explanation(section, cx)) - .child(install_row(section, loaded, cx)) - .children(folder_listing(section, loaded, cx)) - .children(dev_banner(section, cx)) - .children( - section - .notice() - .cloned() - .or_else(|| section.manager_error(cx)) - .map(|notice| { - div() - .id("user-notice") - .aria_label(notice.clone()) - .test_support() - .child(form::error_text(notice.clone(), cx)) - }), - ) - .children( - section - .consent() - .filter(|_| loaded) - .map(|consent| consent_dialog(section, consent, cx)), - ) - .into_any_element() -} - -/// Install a plugin from a file and open the plugins folder. In a run that holds the plugins the -/// folder still opens, and the install button says what to do first. -fn install_row( - section: &UserPluginsSection, - loaded: bool, - cx: &mut Context, -) -> AnyElement { - let install = Button::new("user-install") - .small() - .outline() - .label("Install plugin…") - .disabled(!loaded || section.consent().is_some()) - .on_click(cx.listener(|section, _, window, cx| { - section.choose_file(window, cx); - })); - v_flex() - .gap_1() .child( h_flex() - .id("user-install-row") - .test_support() - .gap_2() - .child(install) + .w_full() + .items_center() + .justify_between() + .gap_3() + .child(div().flex_1().min_w_0().child(form::page_header( + "Plugins", + Some("Manage built-in and external plugins.".into()), + cx, + ))) .child( - Button::new("user-open-folder") + Button::new("user-add-plugin") .small() - .ghost() - .label("Open plugins folder") - .on_click(cx.listener(|section, _, _, cx| section.open_folder(cx))), + .primary() + .icon(IconName::Plus) + .label("Add plugin…") + .disabled(section.busy() || section.install_dialog_open()) + .on_click(cx.listener(|section, _, window, cx| { + section.open_install_dialog(window, cx); + })), ), ) - .when(!loaded, |row| { - row.child( - div() - .id("user-install-held") - .aria_label( - "Allow external plugins above and restart Nocterm to install plugins.", - ) - .test_support() - .child(form::note( - "Allow external plugins above and restart Nocterm to install plugins. \ - Files you put in the plugins folder are offered here then.", - cx, - )), + .children(switch_view::switch_row(section, cx)) + .children(switch_view::explanation(section, cx)) + .when(!section.install_dialog_open(), |head| { + head.children( + section + .notice() + .cloned() + .or_else(|| section.manager_error(cx)) + .map(|notice| { + div() + .id("user-notice") + .aria_label(notice.clone()) + .test_support() + .child(if section.busy() { + form::note(notice, cx) + } else { + form::error_text(notice, cx) + }) + }), ) }) - .children( - section - .folder() - .error() - .cloned() - .map(|error| form::error_text(error, cx)), - ) .into_any_element() } -/// The plugin files in the plugins folder, each with a button that installs it through the -/// consent. Shown only in a run that loads user plugins. -fn folder_listing( - section: &UserPluginsSection, - loaded: bool, - cx: &mut Context, -) -> Option { - let found = section.folder().found(); - if !loaded || found.is_empty() || section.consent().is_some() { - return None; - } - let rows = found.iter().enumerate().map(|(index, path)| { - let name = path.file_name().map_or_else( - || path.to_string_lossy().into_owned(), - |name| name.to_string_lossy().into_owned(), - ); - let location = path.to_string_lossy().into_owned(); - h_flex() - .id(("user-folder-file", index)) - .aria_label(SharedString::from(name.clone())) - .test_support() - .w_full() - .gap_2() - .child(div().flex_1().min_w_0().truncate().text_sm().child(name)) - .child( - Button::new(("user-folder-install", index)) - .small() - .outline() - .label("Install…") - .on_click(cx.listener(move |section, _, window, cx| { - section.begin_install(&location, window, cx); - })), - ) - .into_any_element() - }); - Some( - v_flex() - .id("user-folder") - .aria_label("In your plugins folder") - .test_support() - .w_full() - .gap_1() - .child( - div() - .text_sm() - .font_semibold() - .child("In your plugins folder"), - ) - .children(rows) - .into_any_element(), - ) -} - -/// The banner of a developer session: the plugin and settings are not saved, and one button -/// loads the file under test through the same consent as any other package. -fn dev_banner( - section: &UserPluginsSection, - cx: &mut Context, -) -> Option { - let location = section.dev_location(cx)?; - let name = std::path::Path::new(&location).file_name().map_or_else( - || location.clone(), - |name| name.to_string_lossy().into_owned(), - ); - Some( - v_flex() - .id("user-dev") - .aria_label("Developer session") - .test_support() - .w_full() - .gap_1() - .p_3() - .border_1() - .border_color(cx.theme().border) - .rounded(cx.theme().radius) - .child( - div() - .text_sm() - .font_semibold() - .child("Developer session \u{2014} the plugin and settings are not saved"), - ) - .child( - div().child( - Button::new("user-dev-load") - .small() - .outline() - .label(format!("Load {name}")) - .disabled(section.consent().is_some()) - .on_click(cx.listener(move |section, _, window, cx| { - section.begin_install(&location, window, cx); - })), - ), - ) - .into_any_element(), - ) -} - /// The rows of the installed plugins, in a run that loads them. fn rows(section: &UserPluginsSection, cx: &mut Context) -> Option { if !section.loaded() { diff --git a/crates/plugins-ui/src/user/tests.rs b/crates/plugins-ui/src/user/tests.rs index 5e1af9b3..b4c3f63f 100644 --- a/crates/plugins-ui/src/user/tests.rs +++ b/crates/plugins-ui/src/user/tests.rs @@ -243,6 +243,7 @@ struct Fixture { struct FakeFolder { files: std::sync::Mutex>, prepared: std::sync::atomic::AtomicUsize, + listed: std::sync::atomic::AtomicUsize, } /// The folder of a test cannot be made: opening it in a file manager is the platform's. @@ -258,6 +259,8 @@ impl PluginsFolder for FakeFolder { } fn packages(&self) -> Result, FolderError> { + self.listed + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); Ok(self.files.lock().unwrap().clone()) } } @@ -747,6 +750,9 @@ fn a_developer_session_offers_its_file_and_the_consent_says_dev(cx: &mut TestApp ); fixture.plugins.dev.replace(Some("/work/clock.wasm".into())); fixture.section.update(cx, |_, cx| cx.notify()); + frame(&fixture, cx, |window, cx| { + window.click("user-add-plugin", cx) + }); frame(&fixture, cx, |window, cx| { assert_eq!(window.find("user-dev").label(), Some("Developer session")); assert_eq!( diff --git a/crates/plugins-ui/src/user/tests/page.rs b/crates/plugins-ui/src/user/tests/page.rs index 28ad66c1..5d84e98b 100644 --- a/crates/plugins-ui/src/user/tests/page.rs +++ b/crates/plugins-ui/src/user/tests/page.rs @@ -5,10 +5,12 @@ use crate::{ PluginsPage, tests::{FakeToggles, catalog}, }; +use gpui_kit::component::WindowExt as _; /// The page with the built-in plugins of the crate's fixture and one external plugin. fn open_page(cx: &mut TestAppContext) -> gpui_kit::AnyWindowHandle { cx.update(|cx| { + cx.set_reduce_motion(true); gpui_kit::init(cx); let store = nocterm_store::SettingsConfig::in_memory(Default::default()).install(cx); nocterm_ui::init(nocterm_ui::DesignTokens::builtin(), store, cx); @@ -91,3 +93,26 @@ fn external_plugins_share_the_list_and_one_plugin_is_selected_at_a_time(cx: &mut assert!(window.try_find("user-plugin-detail").is_none()); }); } + +#[gpui_kit::test] +fn the_add_action_opens_a_modal_instead_of_inline_install_controls(cx: &mut TestAppContext) { + let window = open_page(cx); + draw(window, cx, |window, cx| { + assert!(window.try_find("user-install").is_none()); + assert!(window.try_find("user-open-folder").is_none()); + assert!(window.try_find("user-install-dialog").is_none()); + window.click("user-add-plugin", cx); + }); + draw(window, cx, |window, cx| { + assert!(window.has_active_dialog(cx)); + assert!(window.try_find("user-install-dialog").is_some()); + assert!(window.try_find("user-install").is_some()); + assert!(window.try_find("user-open-folder").is_some()); + window.click("user-install-cancel", cx); + }); + draw(window, cx, |window, cx| { + assert!(!window.has_active_dialog(cx)); + assert!(window.try_find("user-install-dialog").is_none()); + assert_eq!(window.find("plugin-detail").label(), Some("Tools")); + }); +} diff --git a/crates/plugins-ui/src/user/tests/switch.rs b/crates/plugins-ui/src/user/tests/switch.rs index 1f05bfda..f0b6b6a4 100644 --- a/crates/plugins-ui/src/user/tests/switch.rs +++ b/crates/plugins-ui/src/user/tests/switch.rs @@ -1,6 +1,13 @@ //! The switch that allows user plugins at the next start, and the held run. use super::*; +use gpui_kit::component::WindowExt as _; + +fn open_install(fixture: &Fixture, cx: &mut TestAppContext) { + frame(fixture, cx, |window, cx| { + window.click("user-add-plugin", cx) + }); +} #[gpui_kit::test] fn a_run_that_is_not_allowed_shows_the_switch_why_and_the_folder_but_no_list_or_install( @@ -21,6 +28,11 @@ fn a_run_that_is_not_allowed_shows_the_switch_why_and_the_folder_but_no_list_or_ .starts_with("External plugins are off") ); assert!(window.try_find("user-plugins-restart").is_none()); + assert!(window.try_find("user-install-dialog").is_none()); + }); + open_install(&fixture, cx); + frame(&fixture, cx, |window, cx| { + assert!(window.has_active_dialog(cx)); assert!( window.try_find("user-install-held").is_some(), "says what to do first" @@ -52,6 +64,9 @@ fn a_run_whose_table_does_not_read_says_why_before_any_click(cx: &mut TestAppCon assert!(!label.contains("External plugins are off"), "{label}"); assert_eq!(window.find("user-plugins-allowed").checked(), Some(false)); assert!(window.try_find("user-plugins-restart").is_none()); + }); + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { assert!( window.try_find("user-install-held").is_some(), "says what to do first" @@ -79,6 +94,9 @@ fn a_safe_mode_run_says_so_and_the_switch_only_stores_the_next_start(cx: &mut Te frame(&fixture, cx, |window, _| { assert_eq!(window.find("user-plugins-allowed").checked(), Some(true)); assert!(window.try_find("user-plugin-list").is_none()); + }); + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { assert!( window.try_find("user-install-held").is_some(), "says what to do first" @@ -122,6 +140,9 @@ fn switching_off_a_loaded_run_keeps_the_list_and_asks_for_a_restart(cx: &mut Tes Some("Restart Nocterm to stop loading external plugins.") ); assert!(window.try_find("user-plugin-row:user-acme-clock").is_some()); + }); + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { assert!(window.try_find("user-install").is_some()); assert!(window.try_find("user-install-held").is_none()); }); @@ -158,6 +179,9 @@ fn a_developer_session_has_no_switch(cx: &mut TestAppContext) { frame(&fixture, cx, |window, _| { assert!(window.try_find("user-plugins-allowed").is_none()); assert!(window.try_find("user-plugins-restart").is_none()); + }); + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { assert!(window.try_find("user-dev-load").is_some()); }); } @@ -165,6 +189,7 @@ fn a_developer_session_has_no_switch(cx: &mut TestAppContext) { #[gpui_kit::test] fn the_plugins_folder_is_made_in_a_held_run_too_and_a_failure_says_why(cx: &mut TestAppContext) { let fixture = open_held(HeldBy::NotAllowed, false, cx); + open_install(&fixture, cx); frame(&fixture, cx, |window, cx| { window.click("user-open-folder", cx) }); @@ -176,20 +201,20 @@ fn the_plugins_folder_is_made_in_a_held_run_too_and_a_failure_says_why(cx: &mut .load(std::sync::atomic::Ordering::SeqCst), 1 ); - let text = fixture - .section - .read_with(cx, |section, _| section.folder().error().cloned()); - assert_eq!( - text.as_deref(), - Some("The plugins folder could not be opened: read-only file system") - ); + frame(&fixture, cx, |window, _| { + assert_eq!( + window.find("user-folder-error").label(), + Some("The plugins folder could not be opened: read-only file system") + ); + }); } #[gpui_kit::test] fn a_file_in_the_plugins_folder_installs_through_the_consent(cx: &mut TestAppContext) { let fixture = open(vec![], Ok(candidate()), cx); - cx.run_until_parked(); + open_install(&fixture, cx); frame(&fixture, cx, |window, cx| { + assert!(window.has_active_dialog(cx)); assert!(window.try_find("user-install").is_some()); assert!(window.try_find("user-install-held").is_none()); assert!(window.try_find("user-folder").is_some()); @@ -212,3 +237,91 @@ fn a_file_in_the_plugins_folder_installs_through_the_consent(cx: &mut TestAppCon assert!(window.try_find("user-folder").is_none()); }); } + +#[gpui_kit::test] +fn escape_cancels_consent_and_reopening_starts_with_the_package_sources(cx: &mut TestAppContext) { + let fixture = open(vec![], Ok(candidate()), cx); + open_install(&fixture, cx); + frame(&fixture, cx, |window, cx| { + window.click(("user-folder-install", 0usize), cx); + }); + frame(&fixture, cx, |window, cx| { + assert!(window.try_find("user-consent").is_some()); + window.press("escape", cx); + }); + frame(&fixture, cx, |window, cx| { + assert!(!window.has_active_dialog(cx)); + assert!(window.try_find("user-consent").is_none()); + }); + cx.executor().advance_clock(Duration::from_millis(751)); + assert!(fixture.plugins.calls().is_empty()); + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { + assert!(window.try_find("user-consent").is_none()); + assert!(window.try_find("user-folder").is_some()); + }); +} + +#[gpui_kit::test] +fn folder_discovery_runs_on_open_not_on_settings_render(cx: &mut TestAppContext) { + use std::sync::atomic::Ordering; + let fixture = open(vec![], Ok(candidate()), cx); + frame(&fixture, cx, |window, _| { + assert!(window.try_find("user-folder").is_none()); + }); + frame(&fixture, cx, |_, _| {}); + assert_eq!(fixture.folder.listed.load(Ordering::SeqCst), 0); + + open_install(&fixture, cx); + frame(&fixture, cx, |window, _| { + assert!(window.try_find("user-folder").is_some()); + }); + frame(&fixture, cx, |window, cx| { + window.click("user-install-cancel", cx); + }); + assert_eq!(fixture.folder.listed.load(Ordering::SeqCst), 1); +} + +#[gpui_kit::test] +fn rapid_reopens_coalesce_behind_the_already_admitted_folder_read(cx: &mut TestAppContext) { + use std::sync::atomic::Ordering; + let fixture = open(vec![], Ok(candidate()), cx); + // Dispatch several open/close actions without draining the background executor. + cx.update_window(fixture.window, |_, window, cx| { + window.click("user-add-plugin", cx); + window.click("user-install-cancel", cx); + window.click("user-add-plugin", cx); + window.click("user-install-cancel", cx); + window.click("user-add-plugin", cx); + window.render_frame(cx); + assert!(window.has_active_dialog(cx)); + assert!(window.try_find("user-folder").is_none()); + }) + .unwrap(); + assert_eq!(fixture.folder.listed.load(Ordering::SeqCst), 0); + + frame(&fixture, cx, |window, _| { + assert_eq!( + window.find(("user-folder-file", 0usize)).label(), + Some("weather.wasm") + ); + }); + // One admitted read settles after its dialog closes, one refresh belongs to + // the final dialog; intermediate opens never start another operation. + assert_eq!(fixture.folder.listed.load(Ordering::SeqCst), 2); +} + +#[gpui_kit::test] +fn enter_on_the_default_consent_answer_does_not_install(cx: &mut TestAppContext) { + let fixture = open(vec![], Ok(candidate()), cx); + begin(&fixture, cx); + cx.executor().advance_clock(Duration::from_millis(751)); + frame(&fixture, cx, |window, cx| { + assert_eq!(window.find("user-consent-state").label(), Some("ready")); + window.press("enter", cx); + }); + frame(&fixture, cx, |window, cx| { + assert!(!window.has_active_dialog(cx)); + }); + assert!(fixture.plugins.calls().is_empty()); +} diff --git a/crates/plugins-ui/src/view.rs b/crates/plugins-ui/src/view.rs index ed8e1120..33157ebd 100644 --- a/crates/plugins-ui/src/view.rs +++ b/crates/plugins-ui/src/view.rs @@ -33,11 +33,11 @@ pub(crate) fn page(page: &PluginsPage, cx: &mut Context) -> impl In .track_focus(&page_focus(page, cx)) .w_full() .gap_6() - .child(plugins(rows, external_rows(page, cx), selected, cx)) .children(external_head(page, cx)) + .child(plugins(rows, external_rows(page, cx), selected, cx)) } -/// The external plugins' head: the switch, install and the plugins folder, the consent. +/// Page header: policy switch, notices and the action that opens the installation dialog. fn external_head(page: &PluginsPage, _: &mut Context) -> Option { page.user() .map(|user| gpui_kit::AnyView::from(user.head().clone()).into_any_element()) diff --git a/crates/project-model/src/catalog_state.rs b/crates/project-model/src/catalog_state.rs index 4a472391..c04b8178 100644 --- a/crates/project-model/src/catalog_state.rs +++ b/crates/project-model/src/catalog_state.rs @@ -1,4 +1,4 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use crate::{Catalog, CatalogError, ProjectDefinition, ProjectId}; @@ -18,6 +18,7 @@ pub struct CatalogState { catalog: Catalog, generation: u64, stamps: BTreeMap, + temporary: BTreeSet, } impl CatalogState { @@ -30,6 +31,7 @@ impl CatalogState { catalog, generation, stamps, + temporary: BTreeSet::new(), } } @@ -37,10 +39,28 @@ impl CatalogState { &self.catalog } - pub fn into_catalog(self) -> Catalog { + /// Durable snapshots exclude session-only workspace definitions, including on shutdown. + pub fn into_catalog(mut self) -> Catalog { + for id in self.temporary { + let _ = self.catalog.remove(id); + } self.catalog } + pub fn is_temporary(&self, id: ProjectId) -> bool { + self.temporary.contains(&id) + } + + pub fn save_temporary( + &mut self, + candidate: ProjectDefinition, + ) -> Result { + let id = candidate.id(); + let stamp = self.save(candidate, None)?; + self.temporary.insert(id); + Ok(stamp) + } + pub fn generation(&self) -> u64 { self.generation } @@ -88,6 +108,7 @@ impl CatalogState { let generation = self.next_generation()?; self.catalog.remove(id)?; self.stamps.remove(&id); + self.temporary.remove(&id); self.generation = generation; Ok(()) } diff --git a/crates/project-model/src/definition.rs b/crates/project-model/src/definition.rs index c2c991af..0bbd983b 100644 --- a/crates/project-model/src/definition.rs +++ b/crates/project-model/src/definition.rs @@ -166,6 +166,8 @@ impl ProjectSource { pub struct ProjectDraft { pub id: ProjectId, pub name: String, + #[serde(skip_serializing_if = "String::is_empty")] + pub ai_description: String, pub target: ProjectTarget, pub source: ProjectSource, /// Supplied Unix timestamp; the domain never reads a clock. @@ -184,6 +186,8 @@ enum SavedDraft { struct CurrentDraft { id: ProjectId, name: String, + #[serde(default)] + ai_description: String, target: ProjectTarget, source: ProjectSource, updated: u64, @@ -196,6 +200,8 @@ struct CurrentDraft { struct LegacyDraft { id: ProjectId, name: String, + #[serde(default)] + ai_description: String, host: HostLocator, root: RootPath, source: ProjectSource, @@ -210,6 +216,7 @@ impl<'de> Deserialize<'de> for ProjectDraft { SavedDraft::Current(saved) => Self { id: saved.id, name: saved.name, + ai_description: saved.ai_description, target: saved.target, source: saved.source, updated: saved.updated, @@ -217,6 +224,7 @@ impl<'de> Deserialize<'de> for ProjectDraft { SavedDraft::Legacy(saved) => Self { id: saved.id, name: saved.name, + ai_description: saved.ai_description, target: ProjectTarget::HostFolder { host: saved.host, root: saved.root, @@ -250,6 +258,10 @@ impl ProjectDefinition { &self.0.name } + pub fn ai_description(&self) -> &str { + &self.0.ai_description + } + pub fn target(&self) -> &ProjectTarget { &self.0.target } @@ -278,6 +290,9 @@ impl TryFrom for ProjectDefinition { if !valid_text(&draft.name, 128) { return Err(ProjectValidationError::InvalidName); } + if draft.ai_description.len() > 16384 { + return Err(ProjectValidationError::InvalidAiDescription); + } draft.target.validate()?; draft.source.validate()?; Ok(Self(draft)) diff --git a/crates/project-model/src/error.rs b/crates/project-model/src/error.rs index 680e8d15..44572cf8 100644 --- a/crates/project-model/src/error.rs +++ b/crates/project-model/src/error.rs @@ -8,6 +8,8 @@ use crate::ProjectId; pub enum ProjectValidationError { #[error("choose a non-empty project name of at most 128 bytes")] InvalidName, + #[error("AI description must be at most 16384 bytes")] + InvalidAiDescription, #[error("choose an unambiguous absolute POSIX project directory")] InvalidRoot, #[error("the project host or jump route is invalid")] diff --git a/crates/project-model/tests/behavior/catalog_state.rs b/crates/project-model/tests/behavior/catalog_state.rs index caa64ef1..57a2ba49 100644 --- a/crates/project-model/tests/behavior/catalog_state.rs +++ b/crates/project-model/tests/behavior/catalog_state.rs @@ -94,3 +94,23 @@ fn exact_ssh_route_changes_invalidate_only_the_affected_source_stamp() { assert_ne!(state.stamp(project(1)).unwrap(), first); assert_eq!(state.stamp(project(2)).unwrap(), retained); } + +#[test] +fn temporary_workspaces_are_live_but_never_in_durable_catalogs() { + let original = definition(1); + let temporary = definition(2); + let mut state = CatalogState::new(Catalog::new(vec![original.clone()]).unwrap(), 0); + state.save_temporary(temporary.clone()).unwrap(); + let mut draft = temporary.to_draft(); + draft.name = "Renamed temporary workspace".into(); + let edited = ProjectDefinition::try_from(draft).unwrap(); + state.save(edited.clone(), Some(&temporary)).unwrap(); + assert_eq!(state.catalog().get(edited.id()), Some(&edited)); + assert!(state.is_temporary(edited.id())); + let disk = state.clone().into_catalog(); + assert_eq!(disk.iter().collect::>(), vec![&original]); + state.remove(&edited).unwrap(); + state.save(edited.clone(), None).unwrap(); + assert!(!state.is_temporary(edited.id())); + assert_eq!(state.into_catalog().get(edited.id()), Some(&edited)); +} diff --git a/crates/project-model/tests/behavior/targets.rs b/crates/project-model/tests/behavior/targets.rs index efa39288..b0134b0d 100644 --- a/crates/project-model/tests/behavior/targets.rs +++ b/crates/project-model/tests/behavior/targets.rs @@ -7,11 +7,35 @@ fn version_one_folder_catalog_migrates_without_changing_identity_or_route() { let catalog = Catalog::decode(&serde_json::to_vec(&wire).unwrap()).unwrap(); let saved = catalog.get(project(1)).unwrap(); assert_eq!(saved.host_folder().unwrap().1.as_str(), "/old folder"); + assert_eq!(saved.ai_description(), ""); let updated: serde_json::Value = serde_json::from_slice(&catalog.encode().unwrap()).unwrap(); assert_eq!(updated["version"], 2); assert!(updated["projects"][0].get("host").is_none()); assert_eq!(updated["projects"][0]["target"]["kind"], "host_folder"); } +#[test] +fn workspace_ai_description_round_trips_and_rejects_oversize_input() { + let original = definition(1); + let mut draft = original.to_draft(); + draft.ai_description = "Application context\nStaging environment".into(); + let described = ProjectDefinition::try_from(draft.clone()).unwrap(); + let encoded = Catalog::new(vec![described.clone()]) + .unwrap() + .encode() + .unwrap(); + let catalog = Catalog::decode(&encoded).unwrap(); + assert_eq!(catalog.get(original.id()), Some(&described)); + assert_eq!( + described.ai_description(), + "Application context\nStaging environment" + ); + draft.ai_description = "é".repeat(8193); + assert!(matches!( + ProjectDefinition::try_from(draft), + Err(ProjectValidationError::InvalidAiDescription) + )); +} + #[test] fn unknown_provider_keeps_opaque_reference_and_history_identity_through_unrelated_edits() { let reference = ProviderResourceRef::new( diff --git a/crates/project-model/tests/support/mod.rs b/crates/project-model/tests/support/mod.rs index fd0e2960..5142d51a 100644 --- a/crates/project-model/tests/support/mod.rs +++ b/crates/project-model/tests/support/mod.rs @@ -8,6 +8,7 @@ pub(crate) fn definition(value: u8) -> ProjectDefinition { ProjectDraft { id: project(value), name: "Example".into(), + ai_description: String::new(), target: ProjectTarget::HostFolder { host: HostLocator::Local, root: RootPath::parse("/home/user/project").unwrap(), diff --git a/crates/project-service/src/catalog.rs b/crates/project-service/src/catalog.rs index 4058ca58..c5544bbc 100644 --- a/crates/project-service/src/catalog.rs +++ b/crates/project-service/src/catalog.rs @@ -138,33 +138,85 @@ impl ProjectCatalog { self.metadata.new_identity().map_err(Into::into) } - pub(crate) fn save( + pub(crate) fn is_temporary(&self, project: ProjectId, cx: &App) -> bool { + self.state.read(cx).visible().is_temporary(project) + } + + pub(crate) fn save_temporary( &mut self, project: ProjectDefinition, - expected: Option, cx: &mut Context, - ) -> Task> { + ) -> Result { + self.check_open(cx)?; let id = project.id(); let owner = self.identity; - self.edit( + self.edit_memory( move |state| { - state - .save(project, expected.as_ref()) - .map(|stamp| ProjectBinding { - project: id, - stamp, - owner, - }) + state.save_temporary(project).map(|stamp| ProjectBinding { + project: id, + stamp, + owner, + }) }, cx, ) } + fn edit_memory( + &mut self, + edit: impl FnOnce(&mut CatalogState) -> Result, + cx: &mut Context, + ) -> Result { + let mut result = None; + self.state.update(cx, |state, cx| { + state.update_immediate_checked( + |state| { + result = Some(edit(state).map_err(StoreError::edit)?); + Ok(()) + }, + cx, + ) + })?; + result.ok_or(ProjectsError::Interrupted) + } + + pub(crate) fn save( + &mut self, + project: ProjectDefinition, + expected: Option, + cx: &mut Context, + ) -> Task> { + let id = project.id(); + let owner = self.identity; + let edit = move |state: &mut CatalogState| { + state + .save(project, expected.as_ref()) + .map(|stamp| ProjectBinding { + project: id, + stamp, + owner, + }) + }; + if self.is_temporary(id, cx) { + return Task::ready( + self.check_open(cx) + .and_then(|()| self.edit_memory(edit, cx)), + ); + } + self.edit(edit, cx) + } + pub(crate) fn remove( &mut self, expected: ProjectDefinition, cx: &mut Context, ) -> Task> { + if self.is_temporary(expected.id(), cx) { + return Task::ready( + self.check_open(cx) + .and_then(|()| self.edit_memory(move |state| state.remove(&expected), cx)), + ); + } self.edit(move |state| state.remove(&expected), cx) } @@ -177,6 +229,9 @@ impl ProjectCatalog { if let Err(error) = self.check_binding(binding, cx) { return Task::ready(Err(error)); } + if self.is_temporary(expected.id(), cx) { + return self.remove(expected, cx); + } self.edit( move |state| { if state.stamp(expected.id()) != Some(binding.stamp) { diff --git a/crates/project-service/src/installation.rs b/crates/project-service/src/installation.rs index 849ed1a8..2b14ae46 100644 --- a/crates/project-service/src/installation.rs +++ b/crates/project-service/src/installation.rs @@ -141,6 +141,23 @@ impl ProjectsHandle { self.0.read(cx).catalog.read(cx).check_binding(binding, cx) } + /// Session-only workspace definitions use the same checked catalog and claims. + pub fn save_temporary( + &self, + project: ProjectDefinition, + cx: &mut App, + ) -> Result { + self.0 + .read(cx) + .catalog + .clone() + .update(cx, |catalog, cx| catalog.save_temporary(project, cx)) + } + + pub fn is_temporary(&self, project: ProjectId, cx: &App) -> bool { + self.0.read(cx).catalog.read(cx).is_temporary(project, cx) + } + pub fn save( &self, project: ProjectDefinition, diff --git a/crates/project-service/src/lib.rs b/crates/project-service/src/lib.rs index fe638969..faaf953b 100644 --- a/crates/project-service/src/lib.rs +++ b/crates/project-service/src/lib.rs @@ -1,6 +1,6 @@ //! Retained workspace catalog, original window claims and setup admission. //! -//! Owns: durable checked catalog edits, source generations and duplicate-window +//! Owns: durable and temporary checked catalog edits, source generations and duplicate-window //! focus requests, captured setup lifecycle, prepared-resource save retry and //! cancellation/cleanup admission and non-destructive environment job admission. //! Does not own: native sessions, processes, @@ -9,7 +9,7 @@ //! and ShutdownCoordinator, captured ProjectPreparation and HostExec. //! Ports provided: ProjectsHandle, WorkspaceSetup, EnvironmentOperation and RemovalOperation. //! Settings section: none. Globals: none. -//! Invariants: failed writes retain the committed catalog; stale original +//! Invariants: temporary definitions never reach durable catalog snapshots; failed writes retain the committed catalog; stale original //! definition/window receipts never retarget a pending connection action; setup //! shutdown freezes admission and cleanup never deletes attached resources or a //! resource whose catalog publication succeeded. Environment jobs retain exact captured diff --git a/crates/project-service/tests/behavior/publication.rs b/crates/project-service/tests/behavior/publication.rs index 8f7f1ab3..38a76887 100644 --- a/crates/project-service/tests/behavior/publication.rs +++ b/crates/project-service/tests/behavior/publication.rs @@ -310,3 +310,39 @@ fn publication_observation_is_driven_by_commit_even_when_the_caller_drops_its_ta assert!(changed.load(Ordering::SeqCst) > before); drop(subscription); } + +#[gpui::test] +async fn temporary_definitions_require_no_disk_write_and_are_excluded_from_later_writes( + cx: &mut gpui::TestAppContext, +) { + let (writer, release, writes) = gated_writer().into_parts(); + let handle = install( + PreparedProjects::loaded(Ok(None), true), + writer, + &ShutdownCoordinator::default(), + cx, + ); + let temporary = definition(1); + let binding = cx.update(|cx| handle.save_temporary(temporary.clone(), cx).unwrap()); + let mut draft = temporary.to_draft(); + draft.name = "Temporary edit".into(); + let edited = ProjectDefinition::try_from(draft).unwrap(); + cx.update(|cx| handle.save(edited.clone(), Some(temporary), cx)) + .await + .unwrap(); + assert!(writes.lock().unwrap().is_empty()); + let persistent = definition(2); + let save = cx.update(|cx| handle.save(persistent.clone(), None, cx)); + cx.run_until_parked(); + assert_eq!( + writes.lock().unwrap()[0].iter().collect::>(), + vec![&persistent] + ); + release.send(Ok(())).unwrap(); + save.await.unwrap(); + cx.update(|cx| { + handle.check_binding(binding, cx).unwrap(); + assert_eq!(handle.catalog(cx).get(project(1)), Some(&edited)); + assert!(handle.is_temporary(project(1), cx)); + }); +} diff --git a/crates/project-service/tests/support/mod.rs b/crates/project-service/tests/support/mod.rs index 475a696d..0d2333a1 100644 --- a/crates/project-service/tests/support/mod.rs +++ b/crates/project-service/tests/support/mod.rs @@ -12,6 +12,7 @@ pub(crate) fn definition(value: u8) -> ProjectDefinition { ProjectDefinition::try_from(ProjectDraft { id: project(value), name: "Project".into(), + ai_description: String::new(), target: ProjectTarget::HostFolder { host: HostLocator::Local, root: RootPath::parse("/srv/project").unwrap(), diff --git a/crates/project-storage/tests/catalog.rs b/crates/project-storage/tests/catalog.rs index d487aad2..937733aa 100644 --- a/crates/project-storage/tests/catalog.rs +++ b/crates/project-storage/tests/catalog.rs @@ -12,6 +12,7 @@ fn catalog(value: u8) -> Catalog { ProjectDefinition::try_from(ProjectDraft { id: ProjectId::from_bytes([value; 16]), name: "Project".into(), + ai_description: String::new(), target: ProjectTarget::HostFolder { host: HostLocator::Local, root: RootPath::parse("/srv/project").unwrap(), diff --git a/crates/projects/src/context.rs b/crates/projects/src/context.rs index 04e88275..81b7ccfe 100644 --- a/crates/projects/src/context.rs +++ b/crates/projects/src/context.rs @@ -191,7 +191,7 @@ pub(crate) fn capture_host( Err(refusal.unwrap_or(ProjectParentError::Disconnected)) } -fn capture( +pub(crate) fn capture( caps: &TerminalCapabilities, cx: &App, ) -> Result { diff --git a/crates/projects/src/editor/controls.rs b/crates/projects/src/editor/controls.rs index 6bb27434..69d410a2 100644 --- a/crates/projects/src/editor/controls.rs +++ b/crates/projects/src/editor/controls.rs @@ -7,11 +7,12 @@ use gpui_kit::{ base::TestSupportExt as _, component::{ ActiveTheme as _, StyledExt as _, - input::{Input, InputEvent, InputState}, + input::{Input, InputEvent, InputState, Textarea, TextareaState}, v_flex, }, div, prelude::*, + px, }; use nocterm_project_model::{ ProjectDefinition, ProjectDraft, ProjectId, ProjectIdentity, ProjectSource, ProjectTarget, @@ -25,6 +26,7 @@ pub(super) struct ProjectControls { original: Option, metadata: ProjectMetadata, name: Entity, + ai_description: Entity, path: Entity, options: Option>, source: Option, @@ -55,6 +57,7 @@ impl ProjectControls { source: ProjectSource::Manual, }, name, + ai_description: cx.new(|cx| TextareaState::new(window, cx)), path, options: Some(options), source: Some(source.clone()), @@ -81,6 +84,9 @@ impl ProjectControls { input.set_value(crate::location::label(original.target()), window, cx); input }); + let ai_description = cx.new(|cx| { + TextareaState::new(window, cx).default_value(original.ai_description().to_owned()) + }); Self { metadata: ProjectMetadata { id: original.id(), @@ -89,6 +95,7 @@ impl ProjectControls { }, original: Some(original), name, + ai_description, path, options: None, source: None, @@ -197,6 +204,14 @@ impl ProjectControls { }) }) .collect(); + let description_changed = changed.clone(); + subscriptions.push( + cx.subscribe(&self.ai_description, move |_, event: &InputEvent, cx| { + if matches!(event, InputEvent::Change) { + description_changed(cx); + } + }), + ); if let Some(options) = &self.options { subscriptions .push(cx.subscribe(options, move |_, _: &WorkspaceDraftChanged, cx| changed(cx))); @@ -249,6 +264,7 @@ impl ProjectControls { Ok(ProjectDraft { id: self.metadata.id, name: self.name.read(cx).value().trim().to_owned(), + ai_description: self.ai_description.read(cx).value().trim().to_owned(), target, source: self.metadata.source.clone(), updated: timestamp, @@ -259,8 +275,9 @@ impl ProjectControls { &self, pending: bool, step: WizardStep, - _cx: &App, + cx: &App, ) -> impl IntoElement + use<> { + let muted = cx.theme().muted_foreground; v_flex() .gap_3() .when( @@ -297,5 +314,28 @@ impl ProjectControls { )), ) }) + .when( + self.original.is_some() || step == WizardStep::Project, + |form| { + form.child( + v_flex() + .gap_1() + .child(div().text_sm().font_medium().child("AI description")) + .child( + div().text_xs().text_color(muted).child( + "Shared with AI agents in this workspace. Avoid secrets.", + ), + ) + .child( + div().id("project-ai-description").test_support().child( + Textarea::new(&self.ai_description) + .h(px(96.)) + .aria_label("Workspace AI description") + .disabled(pending), + ), + ), + ) + }, + ) } } diff --git a/crates/projects/src/lib.rs b/crates/projects/src/lib.rs index d65a6496..230b0f4d 100644 --- a/crates/projects/src/lib.rs +++ b/crates/projects/src/lib.rs @@ -1,6 +1,6 @@ //! Workspace creation and presentation across explicit installed providers. //! -//! Owns: saved workspace library, three-mode native creation controls, shared +//! Owns: saved and temporary workspace library, three-mode native creation controls, shared //! directory-picker consumption, image search/version draft owners, Workspaces settings controls, observed environment //! settings with explicit tool changes, explicit Keep/Stop/Delete removal controls, //! and one outer Item with inner terminal tabs. @@ -33,6 +33,7 @@ pub mod plugin; mod progress; mod removal; mod settings_page; +mod temporary; pub use settings_page::settings_page; mod view; @@ -78,6 +79,37 @@ pub fn register( workspace.register_action(|workspace, _: &ToggleProjects, window, cx| { workspace.toggle_panel(&plugin::WORKSPACES.id, window, cx); }); + let create_installed = installed.clone(); + workspace.register_action( + move |workspace, action: &nocterm_workspace::CreateWorkspaceFromTab, window, cx| { + if let Err(error) = + temporary::create(&create_installed, action.item, workspace, window, cx) + { + nocterm_ui::notice::error( + window, + cx, + "project-create", + "Could not create workspace", + error.to_string(), + ); + } + }, + ); + let edit_installed = installed.clone(); + workspace.register_action( + move |workspace, action: &nocterm_workspace::EditWorkspaceFromTab, window, cx| { + if let Err(error) = temporary::edit(&edit_installed, action.item, workspace, window, cx) + { + nocterm_ui::notice::error( + window, + cx, + "project-edit", + "Could not edit workspace", + error.to_string(), + ); + } + }, + ); workspace.register_action(move |workspace, _: &NewProject, window, cx| { match context::capture_current(workspace, &installed, window, cx) { Ok(source) => { diff --git a/crates/projects/src/opening.rs b/crates/projects/src/opening.rs index 3218270b..71521de4 100644 --- a/crates/projects/src/opening.rs +++ b/crates/projects/src/opening.rs @@ -28,7 +28,38 @@ pub(crate) fn open( if let Some(intent) = ProjectOpenIntent::capture(installed, project, window.window_handle().window_id(), cx)? { - intent.publish(workspace, window, cx)?; + intent.publish(None, workspace, window, cx)?; + } + Ok(()) +} + +/// For a context-menu creation the clicked source is authoritative, even if another tab is focused. +pub(crate) struct CapturedParent { + source: nocterm_workspace_ports::ProjectCreationSource, + session: std::rc::Rc, +} + +impl CapturedParent { + pub(crate) fn new( + source: nocterm_workspace_ports::ProjectCreationSource, + session: std::rc::Rc, + ) -> Self { + Self { source, session } + } +} + +pub(crate) fn open_captured( + installed: &Installed, + project: ProjectId, + parent: CapturedParent, + workspace: &mut Workspace, + window: &mut Window, + cx: &mut Context, +) -> Result<(), ProjectOpenError> { + if let Some(intent) = + ProjectOpenIntent::capture(installed, project, window.window_handle().window_id(), cx)? + { + intent.publish(Some(parent), workspace, window, cx)?; } Ok(()) } @@ -72,6 +103,7 @@ impl ProjectOpenIntent { } fn publish( self, + captured: Option, workspace: &mut Workspace, window: &mut Window, cx: &mut Context, @@ -89,7 +121,7 @@ impl ProjectOpenIntent { return Err(error.into()); } }; - let (presentation, lifetime) = match self.presentation(workspace, window, cx) { + let (presentation, lifetime) = match self.presentation(captured, workspace, window, cx) { Ok(presentation) => presentation, Err(error) => { self.installed.model().release_claim(self.claim, cx)?; @@ -123,10 +155,22 @@ impl ProjectOpenIntent { } fn presentation( &self, + captured: Option, workspace: &Workspace, window: &Window, cx: &mut App, ) -> Result<(ProjectPresentation, ProjectLifetime), ProjectOpenError> { + if let Some(captured) = captured { + let parent_item = captured.source.expected().map(|expected| expected.item()); + return Ok(( + ProjectPresentation::new( + self.definition.clone(), + Some(captured.source.parent().clone()), + parent_item, + ), + ProjectLifetime::new(self.claim, Ok(captured.session)), + )); + } let host = crate::location::host(self.definition.target()); let source = host .as_ref() diff --git a/crates/projects/src/temporary.rs b/crates/projects/src/temporary.rs new file mode 100644 index 00000000..ab5590d1 --- /dev/null +++ b/crates/projects/src/temporary.rs @@ -0,0 +1,107 @@ +//! A temporary workspace derives its location and ordinary launch from the clicked tab. +use crate::{Installed, ProjectOpenError, ProjectView, context, opening}; +use gpui_kit::{Context, EntityId, Window}; +use nocterm_project_model::{ + ProjectDefinition, ProjectDraft, ProjectSource, ProjectTarget, RootPath, +}; +use nocterm_workspace::Workspace; +use nocterm_workspace_ports::ProjectParentError; + +pub(crate) fn create( + installed: &Installed, + item: EntityId, + workspace: &mut Workspace, + window: &mut Window, + cx: &mut Context, +) -> Result<(), ProjectOpenError> { + let item = workspace + .general_item(item, cx) + .ok_or(ProjectParentError::UnavailableParent)?; + let capabilities = item + .terminal_capabilities(cx) + .ok_or(ProjectParentError::UnavailableParent)?; + let source = context::capture(&capabilities, cx)?; + let expected = source.expected().ok_or(ProjectParentError::StaleSession)?; + let cwd = source + .cwd() + .and_then(|path| path.to_str()) + .ok_or(nocterm_project_model::ProjectValidationError::InvalidRoot)?; + let root = RootPath::parse(cwd)?; + let name: String = root + .as_str() + .rsplit('/') + .find(|part| !part.trim().is_empty()) + .unwrap_or("Workspace") + .chars() + .scan(0, |bytes, ch| { + *bytes += ch.len_utf8(); + (*bytes <= 128).then_some(ch) + }) + .collect(); + let identity = installed.model().new_identity(cx)?; + let definition = ProjectDefinition::try_from(ProjectDraft { + id: identity.id, + name, + target: ProjectTarget::HostFolder { + host: source.parent().host().clone(), + root, + }, + source: ProjectSource::Manual, + ai_description: String::new(), + updated: identity.created, + })?; + let session = installed.terminals().capture( + item.view(), + expected, + capabilities, + definition.target(), + cx, + )?; + installed.model().save_temporary(definition.clone(), cx)?; + let result = opening::open_captured( + installed, + definition.id(), + opening::CapturedParent::new(source, session), + workspace, + window, + cx, + ); + if result.is_err() { + // Failed surface admission must not leave an unused temporary definition. + installed.model().remove(definition, cx).detach(); + } + result +} + +pub(crate) fn edit( + installed: &Installed, + item: EntityId, + workspace: &mut Workspace, + window: &mut Window, + cx: &mut Context, +) -> Result<(), ProjectOpenError> { + let view = workspace + .general_item(item, cx) + .and_then(|item| item.view().downcast::().ok()) + .ok_or(ProjectOpenError::Removed)?; + let definition = installed + .catalog(cx) + .get(view.read(cx).project()) + .cloned() + .ok_or(ProjectOpenError::Removed)?; + // The environment controls read the shell; open them after the action's + // mutable workspace lease has ended, retaining the exact clicked item. + let installed = installed.clone(); + let workspace = cx.weak_entity(); + window.defer(cx, move |window, cx| { + let Some(shell) = workspace.upgrade() else { + return; + }; + if shell.read(cx).general_item(item, cx).is_some() + && installed.catalog(cx).get(definition.id()) == Some(&definition) + { + crate::editor::edit(installed, definition, workspace, window, cx); + } + }); + Ok(()) +} diff --git a/crates/projects/src/tests/creation.rs b/crates/projects/src/tests/creation.rs index 3388bb38..0be1f7fe 100644 --- a/crates/projects/src/tests/creation.rs +++ b/crates/projects/src/tests/creation.rs @@ -12,6 +12,13 @@ fn creation_keeps_the_original_server_and_folder_after_another_connection_is_sel window.click("project-new", cx); window.render_frame(cx); fill(window, "project-name", "Original project", cx); + reveal_form(window, "project-ai-description", cx); + fill( + window, + "project-ai-description", + "Build and deploy project", + cx, + ); assert!(window.try_find("project-form-server").is_some()); }) .unwrap(); @@ -25,6 +32,7 @@ fn creation_keeps_the_original_server_and_folder_after_another_connection_is_sel cx.update(|cx| { let saved = rig.installed.catalog(cx).iter().next().unwrap(); assert_eq!(saved.name(), "Original project"); + assert_eq!(saved.ai_description(), "Build and deploy project"); assert_eq!(saved.host_folder().unwrap().0, &a); assert_eq!( saved.host_folder().unwrap().1.as_str(), diff --git a/crates/projects/src/tests/library.rs b/crates/projects/src/tests/library.rs index c8e8f928..1e7703bf 100644 --- a/crates/projects/src/tests/library.rs +++ b/crates/projects/src/tests/library.rs @@ -251,6 +251,13 @@ fn renaming_saved_metadata_updates_the_open_tab_without_replacing_its_scope( window.click("project-edit-01010101010101010101010101010101", cx); window.render_frame(cx); fill(window, "project-name", "Renamed live tab", cx); + reveal_form(window, "project-ai-description", cx); + fill( + window, + "project-ai-description", + "Workspace build commands", + cx, + ); window.click("project-save", cx); }) .unwrap(); @@ -262,6 +269,14 @@ fn renaming_saved_metadata_updates_the_open_tab_without_replacing_its_scope( "Renamed live tab" ); assert_eq!(workspace.context_source(cx), source); + assert_eq!( + workspace + .context_ai_description(source, cx) + .unwrap() + .description + .as_ref(), + "Workspace build commands" + ); assert_eq!( workspace.selected_context(cx), ContextId::Project(definition(1).id()) diff --git a/crates/projects/src/tests/support.rs b/crates/projects/src/tests/support.rs index dc59c40d..7d045f75 100644 --- a/crates/projects/src/tests/support.rs +++ b/crates/projects/src/tests/support.rs @@ -21,6 +21,7 @@ pub(super) fn definition(value: u8) -> ProjectDefinition { ProjectDefinition::try_from(ProjectDraft { id: ProjectId::from_bytes([value; 16]), name: format!("Workspace {value}"), + ai_description: String::new(), target: ProjectTarget::HostFolder { host: HostLocator::Local, root: RootPath::parse(format!("/srv/project-{value}")).unwrap(), @@ -330,7 +331,10 @@ pub(super) fn wizard_field(window: &mut gpui_kit::Window, id: &str, cx: &mut App if window.try_find("project-wizard-steps").is_none() { return; } - let project = matches!(id, "project-name" | "project-path" | "project-git"); + let project = matches!( + id, + "project-name" | "project-path" | "project-git" | "project-ai-description" + ); let tools = id.starts_with("project-language") || id.starts_with("project-version"); let connection = id.starts_with("project-mode") || id.starts_with("project-image") diff --git a/crates/projects/src/tests/terminals.rs b/crates/projects/src/tests/terminals.rs index 4c8c0927..3454f011 100644 --- a/crates/projects/src/tests/terminals.rs +++ b/crates/projects/src/tests/terminals.rs @@ -575,3 +575,97 @@ fn opening_a_local_folder_without_a_general_terminal_uses_the_existing_resolver( assert_eq!(terminals.resolutions(), vec![HostLocator::Local]); assert_eq!(terminals.attempts().len(), 1); } + +fn click_tab_command( + f: &FolderFixture, + item: gpui_kit::EntityId, + label: &str, + cx: &mut TestAppContext, +) { + cx.update_window(f.rig.window, |_, window, cx| { + window.render_frame(cx); + window.right_click(("tab-title", item.as_u64()), cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.rig.window, |_, window, cx| { + window.render_frame(cx); + let ix = (0usize..32) + .find(|ix| { + window + .within("popup-menu") + .try_find(*ix) + .is_some_and(|row| row.label() == Some(label)) + }) + .expect("tab menu command"); + window.within("popup-menu").click(ix, cx); + }) + .unwrap(); + cx.run_until_parked(); +} + +#[gpui_kit::test] +fn temporary_workspace_from_tab_retains_source_and_uses_edited_root_for_new_terminals( + cx: &mut TestAppContext, +) { + let f = FolderFixture::new(cx); + let other = f + .rig + .parent(remote(Some("server-b"), "b.example"), "Other server", cx); + click_tab_command(&f, f.parent.item.entity_id(), "Create workspace", cx); + let (id, outer) = cx.update(|cx| { + let workspace = f.rig.workspace.read(cx); + let ContextId::Project(id) = workspace.selected_context(cx) else { + panic!("expected workspace") + }; + assert!(f.rig.model.is_temporary(id, cx)); + let definition = f.rig.model.catalog(cx).get(id).unwrap(); + assert_eq!( + definition.host_folder().unwrap().0, + &remote(Some("server-a"), "a.example") + ); + assert_eq!( + definition.host_folder().unwrap().1.as_str(), + "/srv/original-folder" + ); + (id, workspace.active_item(cx).unwrap().item_id()) + }); + assert_eq!(f.terminals.attempts().len(), 1); + click_tab_command(&f, outer, "Workspace settings", cx); + cx.update_window(f.rig.window, |_, window, cx| { + window.render_frame(cx); + window.within("dialog").click("project-path", cx); + window.press("ctrl-a", cx); + window.input("/srv/changed", cx); + window.within("dialog").click("project-save", cx); + }) + .unwrap(); + cx.run_until_parked(); + cx.update_window(f.rig.window, |_, window, cx| { + window.render_frame(cx); + window.click("project-terminal-new", cx); + assert_eq!( + f.rig + .model + .catalog(cx) + .get(id) + .unwrap() + .host_folder() + .unwrap() + .1 + .as_str(), + "/srv/changed" + ); + assert!( + f.rig + .workspace + .read(cx) + .general_item(other.item.entity_id(), cx) + .is_some() + ); + }) + .unwrap(); + assert_eq!(f.terminals.attempts().len(), 2); + assert_eq!(f.terminals.attempts()[1].1.as_str(), "/srv/changed"); + assert!(f.terminals.resolutions().is_empty()); +} diff --git a/crates/projects/src/view.rs b/crates/projects/src/view.rs index ec476d20..28ea9f90 100644 --- a/crates/projects/src/view.rs +++ b/crates/projects/src/view.rs @@ -124,6 +124,11 @@ impl ProjectView { cx: &mut Context, ) -> Self { surface.set_monitor_target(presentation.definition.target().clone(), cx); + surface.set_ai_description( + presentation.definition.name(), + presentation.definition.ai_description(), + cx, + ); let subscriptions = Self::subscribe(&installed, &surface, &workspace, window, cx); Self { installed, @@ -338,15 +343,32 @@ impl ProjectView { pub(crate) fn refresh(&mut self, window: &mut Window, cx: &mut Context) { if let Some(definition) = self.installed.catalog(cx).get(self.project()) { if definition.target() != self.presentation.definition.target() { - self.presentation.parent_item = None; - self.lifetime.retry(Err( - nocterm_workspace_ports::ProjectParentError::WrongHost.into() - )); + // Folder-only edits on the same original host keep the captured launch, + // and affect future terminals without modifying an already running shell. + match ( + self.presentation.definition.host_folder(), + definition.host_folder(), + ) { + (Some((previous, _)), Some((host, root))) if previous == host => { + self.lifetime.update_root(root.clone()); + } + _ => { + self.presentation.parent_item = None; + self.lifetime.retry(Err( + nocterm_workspace_ports::ProjectParentError::WrongHost.into(), + )); + } + } } self.presentation.definition = definition.clone(); } self.surface .set_monitor_target(self.presentation.definition.target().clone(), cx); + self.surface.set_ai_description( + self.presentation.definition.name(), + self.presentation.definition.ai_description(), + cx, + ); if let Some(root) = crate::location::root(self.presentation.definition.target()) { self.surface.set_root(root, cx); } @@ -428,6 +450,17 @@ impl ProjectView { .border_b_1() .border_color(theme.border) .child(self.presentation.caption(icon, cx)) + .when( + self.installed.model().is_temporary(self.project(), cx), + |header| { + header.child( + div() + .text_xs() + .text_color(theme.muted_foreground) + .child("Temporary"), + ) + }, + ) .child( Button::new("project-terminal-new") .ghost() diff --git a/crates/projects/src/view/lifetime.rs b/crates/projects/src/view/lifetime.rs index 5399f3a4..fee3ef02 100644 --- a/crates/projects/src/view/lifetime.rs +++ b/crates/projects/src/view/lifetime.rs @@ -41,6 +41,12 @@ impl ProjectLifetime { } self.session.clone() } + pub(crate) fn update_root(&mut self, root: nocterm_project_model::RootPath) { + if let Ok(session) = &self.session { + self.session = Ok(session.with_root(root)); + self.error = None; + } + } pub(crate) fn failed(&mut self, error: ProjectOpenError) { self.error = Some(error); } diff --git a/crates/ssh/src/auth.rs b/crates/ssh/src/auth.rs index d8af9f2c..7e0fc91b 100644 --- a/crates/ssh/src/auth.rs +++ b/crates/ssh/src/auth.rs @@ -39,12 +39,22 @@ const MAX_KEY_OFFERS: usize = 4; /// Times the user may mistype one secret. const MAX_SECRET_ATTEMPTS: usize = 3; +/// A dead unauthenticated handle is not a rejected credential. Its question +/// cannot be answered on another connection; the verified link may ask anew. +#[derive(Debug, thiserror::Error)] +pub(crate) enum AuthError { + #[error("The server closed the SSH connection while waiting for sign-in.")] + ExpiredPrompt, + #[error(transparent)] + Session(#[from] SessionError), +} + pub(crate) async fn authenticate( handle: &mut Handle, login: &Login<'_>, config: &SshConfig, driver: &SessionDriver, -) -> Result<(), SessionError> { +) -> Result<(), AuthError> { let mut authenticator = Authenticator { handle, login, @@ -70,7 +80,7 @@ struct Authenticator<'a> { } impl<'a> Authenticator<'a> { - async fn run(&mut self, config: &SshConfig) -> Result<(), SessionError> { + async fn run(&mut self, config: &SshConfig) -> Result<(), AuthError> { // Asking for no authentication is how a client learns what the host // accepts; a few hosts really do let the user in right here. let probe = self.handle.authenticate_none(self.user()).await; @@ -102,7 +112,8 @@ impl<'a> Authenticator<'a> { "{}@{} accepted an authentication factor, but sign-in is incomplete. {remaining}", self.user(), self.login.target().host - ))); + )) + .into()); } if let Some(message) = key_required_message(public_key_only, self.login.auth(), self.rejected_key) @@ -111,12 +122,14 @@ impl<'a> Authenticator<'a> { "{}@{} {message}", self.user(), self.login.target().host - ))); + )) + .into()); } Err(SessionError::AuthenticationFailed { user: self.user().to_owned(), host: self.login.target().host.clone(), - }) + } + .into()) } fn user(&self) -> &'a str { @@ -219,7 +232,7 @@ impl<'a> Authenticator<'a> { Ok(false) } - async fn try_default_keys(&mut self, config: &SshConfig) -> Result { + async fn try_default_keys(&mut self, config: &SshConfig) -> Result { let Some(directory) = &config.identity_dir else { return Ok(false); }; @@ -233,7 +246,7 @@ impl<'a> Authenticator<'a> { /// Offers one private key file. `explicit` is set for a key the user /// chose, whose absence is worth a warning. - async fn try_key_file(&mut self, path: &Path, explicit: bool) -> Result { + async fn try_key_file(&mut self, path: &Path, explicit: bool) -> Result { if !self.may_offer_key() { return Ok(false); } @@ -254,7 +267,7 @@ impl<'a> Authenticator<'a> { { return Ok(false); } - let Some(key) = self.unlock(path, text).await else { + let Some(key) = self.unlock(path, text).await? else { return Ok(false); }; let public = key.public_key().key_data().clone(); @@ -273,7 +286,7 @@ impl<'a> Authenticator<'a> { .. }) ); - self.succeeded(result) + Ok(self.succeeded(result)?) } /// Offers the key the profile keeps in the vault. The terminal answers @@ -283,7 +296,7 @@ impl<'a> Authenticator<'a> { &mut self, credential: CredentialId, public_key: &str, - ) -> Result { + ) -> Result { if !self.may_offer_key() { return Ok(false); } @@ -299,7 +312,7 @@ impl<'a> Authenticator<'a> { credential, public_key: public_key.to_owned(), }) - .await + .await? else { return Ok(false); }; @@ -319,8 +332,9 @@ impl<'a> Authenticator<'a> { }, _ => None, }; - self.offer_vault_key(named.key_data().clone(), key, hash) - .await + Ok(self + .offer_vault_key(named.key_data().clone(), key, hash) + .await?) } /// Offers `key` the profile keeps in the vault. @@ -345,33 +359,40 @@ impl<'a> Authenticator<'a> { /// Decodes a private key, asking for its passphrase if it has one. /// `None` means the key cannot be used. - async fn unlock(&self, path: &Path, text: Arc>>) -> Option { + async fn unlock( + &self, + path: &Path, + text: Arc>>, + ) -> Result, AuthError> { match decode(text.clone(), None).await { - Ok(key) => return Some(key), + Ok(key) => return Ok(Some(key)), Err(russh::keys::Error::KeyIsEncrypted) => {} Err(error) => { tracing::warn!(key = %path.display(), %error, "unusable private key"); - return None; + return Ok(None); } } for attempt in 0..MAX_SECRET_ATTEMPTS { // Dismissing the prompt skips this key, not the whole sign-in. - let passphrase = self + let Some(passphrase) = self .ask(SecretRequest::KeyPassphrase { path: path.to_owned(), retry: attempt > 0, }) - .await?; + .await? + else { + return Ok(None); + }; if let Ok(key) = decode(text.clone(), Some(passphrase)).await { - return Some(key); + return Ok(Some(key)); } } - None + Ok(None) } /// The methods that need the user at the keyboard. - async fn try_typed_secrets(&mut self) -> Result { + async fn try_typed_secrets(&mut self) -> Result { let mut passwords = 0; let mut conversations = 0; @@ -382,12 +403,13 @@ impl<'a> Authenticator<'a> { retry: passwords > 0, }; passwords += 1; - let password = self.ask(request).await.ok_or(SessionError::Cancelled)?; + let password = self.ask(request).await?.ok_or(SessionError::Cancelled)?; let result = self .handle .authenticate_password(self.user(), password.expose()) .await; - if self.succeeded(result)? { + let result = self.after_prompt(result)?; + if self.succeeded(Ok(result))? { return Ok(true); } } else if self.offers(MethodKind::KeyboardInteractive) @@ -405,7 +427,7 @@ impl<'a> Authenticator<'a> { /// Keyboard-interactive: the host asks questions in its own words until /// it is satisfied (one-time codes, PAM password prompts). - async fn converse(&mut self) -> Result { + async fn converse(&mut self) -> Result { let mut response = self .handle .authenticate_keyboard_interactive_start(self.user(), None) @@ -436,28 +458,42 @@ impl<'a> Authenticator<'a> { }, echo: prompt.echo, }; - let answer = self.ask(request).await.ok_or(SessionError::Cancelled)?; + let answer = self.ask(request).await?.ok_or(SessionError::Cancelled)?; answers.push(answer.expose().to_owned()); } - response = self + let result = self .handle .authenticate_keyboard_interactive_respond(answers) - .await - .map_err(lost)?; + .await; + response = self.after_prompt(result)?; } } } } - async fn ask(&self, request: SecretRequest) -> Option { - self.driver + async fn ask(&self, request: SecretRequest) -> Result, AuthError> { + let answer = self + .driver .ask(|reply| Prompt::Secret { request, hop: self.login.hop(), reply, }) .await - .flatten() + .flatten(); + if answer.is_some() && self.handle.is_closed() { + return Err(AuthError::ExpiredPrompt); + } + Ok(answer) + } + + /// The protocol can close between accepting a reply and sending it. + /// Retry only the link, never the old answer. + fn after_prompt(&self, result: Result) -> Result { + if matches!(&result, Err(russh::Error::SendError)) && self.handle.is_closed() { + return Err(AuthError::ExpiredPrompt); + } + result.map_err(|error| lost(error).into()) } } diff --git a/crates/ssh/src/connection.rs b/crates/ssh/src/connection.rs index 2d194b97..3297b6b3 100644 --- a/crates/ssh/src/connection.rs +++ b/crates/ssh/src/connection.rs @@ -71,17 +71,16 @@ async fn session( fs_requests: FsRequests, exec_requests: ExecRequests, ) -> CloseReason { - let observed = Arc::new(Mutex::new(Observed::default())); let mut size = request.size; // Until the shell runs, the only commands that matter are a new size to // start it with and the user giving up. let established = tokio::select! { () = driver.closed() => return CloseReason::ClosedByUser, - result = route::establish(config, request, relay, driver, &observed) => result, + result = route::establish(config, request, relay, driver) => result, () = closed_while_connecting(driver, &mut size) => return CloseReason::ClosedByUser, }; - let (handle, route) = match established { + let (handle, route, observed) = match established { Ok(established) => established, Err(error) => return CloseReason::Failed(error), }; diff --git a/crates/ssh/src/route.rs b/crates/ssh/src/route.rs index 8f909b02..288fc96b 100644 --- a/crates/ssh/src/route.rs +++ b/crates/ssh/src/route.rs @@ -117,11 +117,10 @@ pub(crate) async fn establish( request: &ConnectRequest, relay: Option>, driver: &SessionDriver, - observed: &Arc>, -) -> Result<(Handle, Route), SessionError> { +) -> Result<(Handle, Route, Arc>), SessionError> { let mut route = Route::new(relay); - match extend(&mut route, config, request, driver, observed).await { - Ok(handle) => Ok((handle, route)), + match extend(&mut route, config, request, driver).await { + Ok((handle, observed)) => Ok((handle, route, observed)), Err(error) => { route.close().await; Err(error) @@ -134,20 +133,18 @@ async fn extend( config: &SshConfig, request: &ConnectRequest, driver: &SessionDriver, - observed: &Arc>, -) -> Result, SessionError> { +) -> Result<(Handle, Arc>), SessionError> { for (index, jump) in request.jumps.iter().enumerate() { let login = Login::jump(index, jump); - let hop_observed = Arc::new(Mutex::new(Observed::default())); - let handle = link(route, &login, config, request, driver, &hop_observed).await?; + let (handle, observed) = link(route, &login, config, request, driver).await?; route.hops.push(Hop { handle, - observed: hop_observed, + observed, target: jump.target.clone(), }); } let login = Login::destination(request); - link(route, &login, config, request, driver, observed).await + link(route, &login, config, request, driver).await } /// One step: reach the host, verify its key, sign in. @@ -157,39 +154,49 @@ async fn link( config: &SshConfig, request: &ConnectRequest, driver: &SessionDriver, - observed: &Arc>, -) -> Result, SessionError> { +) -> Result<(Handle, Arc>), SessionError> { let own = |error| match login.hop() { Some(hop) => at_hop(hop.index, &hop.target, error), None => error, }; - let host_keys = login::load_host_keys(config, login.target()) - .await - .map_err(own)?; - driver - .emit(Event::Connecting(ConnectStage::Connecting { - hop: login.hop().map(|hop| hop.index), - })) - .await; - let mut handle = reach(route, login, &host_keys, request, observed, driver) - .await - .map_err(|fault| match fault { - Fault::Own(error) => own(error), - Fault::Forward(error) => forward_fault(route, error), - })?; - login::verify_host(&handle, login, host_keys, driver, observed) - .await - .map_err(own)?; + // A server can expire its pending authentication while the user is answering. + // Reopen this same route step once, with fresh observations and verification. + // The expired question is discarded; authentication asks its new questions. + let mut retried = false; + loop { + let observed = Arc::new(Mutex::new(Observed::default())); + let host_keys = login::load_host_keys(config, login.target()) + .await + .map_err(own)?; + driver + .emit(Event::Connecting(ConnectStage::Connecting { + hop: login.hop().map(|hop| hop.index), + })) + .await; + let mut handle = reach(route, login, &host_keys, request, &observed, driver) + .await + .map_err(|fault| match fault { + Fault::Own(error) => own(error), + Fault::Forward(error) => forward_fault(route, error), + })?; + login::verify_host(&handle, login, host_keys, driver, &observed) + .await + .map_err(own)?; - driver - .emit(Event::Connecting(ConnectStage::Authenticating { - hop: login.hop().map(|hop| hop.index), - })) - .await; - auth::authenticate(&mut handle, login, config, driver) - .await - .map_err(own)?; - Ok(handle) + driver + .emit(Event::Connecting(ConnectStage::Authenticating { + hop: login.hop().map(|hop| hop.index), + })) + .await; + match auth::authenticate(&mut handle, login, config, driver).await { + Ok(()) => return Ok((handle, observed)), + Err(auth::AuthError::ExpiredPrompt) if !retried => retried = true, + Err(auth::AuthError::Session(error)) => return Err(own(error)), + Err(error @ auth::AuthError::ExpiredPrompt) => { + return Err(own(SessionError::ConnectionLost(error.to_string()))); + } + } + } } /// Opens the stream to the host and runs the handshake over it. diff --git a/crates/ssh/tests/authentication_grace.rs b/crates/ssh/tests/authentication_grace.rs new file mode 100644 index 00000000..346e09e4 --- /dev/null +++ b/crates/ssh/tests/authentication_grace.rs @@ -0,0 +1,193 @@ +//! A server that expires its unauthenticated transport between asking and receiving a password. +use nocterm_session::{ + Auth, ConnectRequest, Event, HostKeyDecision, Prompt, PtySize, Secret, SecretRequest, Target, + Transport, +}; +use nocterm_ssh::{SshConfig, SshTransport}; +use russh::{ + Channel, ChannelId, Disconnect, MethodKind, MethodSet, Pty, + server::{self, ChannelOpenHandle, Msg, Session}, +}; +use std::{ + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; +use tokio::{sync::oneshot, time::timeout}; + +struct Server(Arc); + +impl server::Handler for Server { + type Error = russh::Error; + + async fn auth_none(&mut self, _: &str) -> Result { + Ok(server::Auth::reject()) + } + + async fn auth_password( + &mut self, + _: &str, + password: &str, + ) -> Result { + self.0.fetch_add(1, Ordering::Relaxed); + Ok(if password == "fresh answer" { + server::Auth::Accept + } else { + server::Auth::reject() + }) + } + + async fn channel_open_session( + &mut self, + _: Channel, + reply: ChannelOpenHandle, + _: &mut Session, + ) -> Result<(), Self::Error> { + reply.accept().await; + Ok(()) + } + + async fn pty_request( + &mut self, + channel: ChannelId, + _: &str, + _: u32, + _: u32, + _: u32, + _: u32, + _: &[(Pty, u32)], + session: &mut Session, + ) -> Result<(), Self::Error> { + session.channel_success(channel)?; + Ok(()) + } + + async fn shell_request( + &mut self, + channel: ChannelId, + session: &mut Session, + ) -> Result<(), Self::Error> { + session.channel_success(channel)?; + Ok(()) + } +} + +async fn password_question( + session: &nocterm_session::Session, +) -> nocterm_session::Reply> { + timeout(Duration::from_secs(5), async { + loop { + match session.next_event().await.unwrap() { + Event::Prompt(Prompt::UnknownHostKey { reply, .. }) => { + reply.send(HostKeyDecision::AcceptOnce); + } + Event::Prompt(Prompt::Secret { + request: SecretRequest::Password { retry: false, .. }, + reply, + .. + }) => return reply, + Event::Closed(reason) => panic!("closed before asking for a password: {reason:?}"), + Event::Prompt(prompt) => panic!("unexpected prompt: {prompt:?}"), + _ => {} + } + } + }) + .await + .unwrap() +} + +fn password_server_config() -> Arc { + let key = nocterm_ssh_keys::KeyMaterial::ed25519_from_seed(&[42; 32], "").unwrap(); + Arc::new(server::Config { + keys: vec![russh::keys::PrivateKey::from_openssh(key.to_secret().expose()).unwrap()], + methods: MethodSet::from([MethodKind::Password].as_slice()), + auth_rejection_time: Duration::ZERO, + ..Default::default() + }) +} + +#[tokio::test] +async fn an_expired_password_question_reopens_the_link_and_asks_afresh() { + let dir = tempfile::tempdir().unwrap(); + let config = password_server_config(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = attempts.clone(); + let (first, first_handle) = oneshot::channel(); + let (finished, first_finished) = oneshot::channel(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let running = server::run_stream(config.clone(), stream, Server(observed.clone())) + .await + .unwrap(); + first.send(running.handle()).ok().unwrap(); + let _ = running.await; + finished.send(()).unwrap(); + + let (stream, _) = listener.accept().await.unwrap(); + let _ = server::run_stream(config, stream, Server(observed)) + .await + .unwrap() + .await; + }); + let transport = SshTransport::new(SshConfig { + known_hosts: dir.path().join("known_hosts"), + ..Default::default() + }) + .unwrap(); + let session = transport.open(ConnectRequest { + target: Target::new("test", "127.0.0.1", port), + auth: Auth::Password, + launch: Default::default(), + proxy: Default::default(), + term: "xterm".into(), + size: PtySize::default(), + connect_timeout: Duration::from_secs(5), + keepalive_interval: None, + jumps: Vec::new(), + }); + let expired = password_question(&session).await; + let handle = first_handle.await.unwrap(); + handle + .disconnect( + Disconnect::ByApplication, + "sign-in expired".into(), + "en".into(), + ) + .await + .unwrap(); + timeout(Duration::from_secs(5), first_finished) + .await + .unwrap() + .unwrap(); + // The server's end has closed; allow the independent client runtime to + // process its disconnect before the user's answer arrives. + tokio::time::sleep(Duration::from_millis(100)).await; + expired.send(Some(Secret::new("expired answer"))); + + let fresh = password_question(&session).await; + assert_eq!( + attempts.load(Ordering::Relaxed), + 0, + "expired answer was not replayed" + ); + fresh.send(Some(Secret::new("fresh answer"))); + timeout(Duration::from_secs(5), async { + loop { + match session.next_event().await.unwrap() { + Event::Connected => break, + Event::Closed(reason) => panic!("reopened link failed: {reason:?}"), + Event::Prompt(prompt) => panic!("unexpected prompt: {prompt:?}"), + _ => {} + } + } + }) + .await + .unwrap(); + assert_eq!(attempts.load(Ordering::Relaxed), 1); + session.close(); + server.abort(); +} diff --git a/crates/terminal/src/project.rs b/crates/terminal/src/project.rs index b2b48575..344fc71d 100644 --- a/crates/terminal/src/project.rs +++ b/crates/terminal/src/project.rs @@ -112,6 +112,14 @@ impl ProjectTerminalOpen for ProjectTerminals { } } impl ProjectTerminalSession for FolderSession { + fn with_root(&self, root: RootPath) -> Rc { + Rc::new(Self { + installed: self.installed.clone(), + spec: self.spec.clone(), + local: self.local, + root, + }) + } fn open( &self, target: ProjectTerminalTarget, diff --git a/crates/vault-store/src/access.rs b/crates/vault-store/src/access.rs index 3a95c77a..2d21ed57 100644 --- a/crates/vault-store/src/access.rs +++ b/crates/vault-store/src/access.rs @@ -58,6 +58,9 @@ impl VaultAccess for VaultService { fn get(&self, id: CredentialId, binding: CredentialBinding) -> VaultFuture { VaultService::get(self, id, binding) } + fn reveal_password(&self, id: CredentialId) -> VaultFuture { + VaultService::reveal_password(self, id) + } fn put( &self, id: Option, diff --git a/crates/vault-store/src/backend.rs b/crates/vault-store/src/backend.rs index 90fd1f88..c001cd2a 100644 --- a/crates/vault-store/src/backend.rs +++ b/crates/vault-store/src/backend.rs @@ -61,6 +61,9 @@ impl Vault { pub fn get(&self, id: CredentialId, binding: &CredentialBinding) -> Result { self.state.get(id, binding) } + pub fn reveal_password(&self, id: CredentialId) -> Result { + self.state.reveal_password(id) + } pub fn put( &mut self, id: Option, diff --git a/crates/vault-store/src/tests/status.rs b/crates/vault-store/src/tests/status.rs index 99ad6ef0..7d8a5dd9 100644 --- a/crates/vault-store/src/tests/status.rs +++ b/crates/vault-store/src/tests/status.rs @@ -109,3 +109,26 @@ fn a_missing_vault_reports_missing() { VaultService::new(directory.path().join("vault"), Duration::from_secs(60)).unwrap(); assert_eq!(service.status(), VaultStatus::Missing); } + +#[test] +fn management_can_reveal_an_unbound_password_only_while_unlocked() { + let directory = tempfile::tempdir().unwrap(); + let service = locked_vault(&directory); + block_on(service.unlock(Secret::new(MASTER))).unwrap(); + let id = block_on(service.put( + None, + "named password".into(), + nocterm_vault::CredentialBinding::password([]), + Secret::new("synthetic password"), + )) + .unwrap(); + assert_eq!( + block_on(service.reveal_password(id)).unwrap().expose(), + "synthetic password" + ); + service.lock(); + assert!(matches!( + block_on(service.reveal_password(id)), + Err(VaultError::Locked | VaultError::Cancelled) + )); +} diff --git a/crates/vault-store/src/worker.rs b/crates/vault-store/src/worker.rs index 3af2c357..c274f892 100644 --- a/crates/vault-store/src/worker.rs +++ b/crates/vault-store/src/worker.rs @@ -303,6 +303,9 @@ impl VaultService { pub fn get(&self, id: CredentialId, binding: CredentialBinding) -> VaultFuture { self.request(move |vault| vault.get(id, &binding)) } + pub fn reveal_password(&self, id: CredentialId) -> VaultFuture { + self.request(move |vault| vault.reveal_password(id)) + } pub fn put( &self, id: Option, diff --git a/crates/vault-ui/src/credentials_tab.rs b/crates/vault-ui/src/credentials_tab.rs index fc1477a8..95e22c61 100644 --- a/crates/vault-ui/src/credentials_tab.rs +++ b/crates/vault-ui/src/credentials_tab.rs @@ -23,7 +23,9 @@ use nocterm_vault::{CredentialBinding, CredentialInfo, VaultAccess, VaultFuture} use std::sync::Arc; mod catalog; +mod reveal; use catalog::{Catalog, RenameFocus}; +use reveal::Reveal; pub(crate) struct CredentialsTab { service: Arc, @@ -35,6 +37,7 @@ pub(crate) struct CredentialsTab { /// What the list is narrowed to: a name or a server. query: Entity, renaming: Option, + reveal: Reveal, _subscriptions: Vec, } @@ -56,7 +59,8 @@ impl CredentialsTab { let subscriptions = vec![cx.subscribe(&query, |this, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { let rename = this.rename_focus(cx); - if this.catalog.search(&input.read(cx).value(), rename) { + let hidden = this.hide_password(); + if this.catalog.search(&input.read(cx).value(), rename) || hidden { cx.notify(); } } @@ -69,12 +73,16 @@ impl CredentialsTab { message: None, query, renaming: None, + reveal: Reveal::Hidden, _subscriptions: subscriptions, } } /// Reads the records again. pub(crate) fn refresh(&mut self, cx: &mut Context) { + if self.hide_password() { + cx.notify(); + } let generation = self.generation; let future = self.service.list(); cx.spawn(async move |this, cx| { @@ -85,6 +93,7 @@ impl CredentialsTab { } match result { Ok(records) => { + this.hide_password(); let rename = this.rename_focus(cx); this.catalog.replace(records, rename); } @@ -99,6 +108,7 @@ impl CredentialsTab { /// Forgets what the vault showed and every draft: it locked or the page closed. pub(crate) fn clear(&mut self, window: &mut Window, cx: &mut Context) { self.generation = self.generation.wrapping_add(1); + self.hide_password(); self.catalog.clear(); self.busy = false; self.message = None; @@ -108,6 +118,80 @@ impl CredentialsTab { cx.notify(); } + /// Drops both the plaintext and any outstanding delivery before the tab is hidden. + pub(crate) fn dismiss_password(&mut self, cx: &mut Context) { + if self.hide_password() { + cx.notify(); + } + } + + pub(crate) fn vault_changed(&mut self, cx: &mut Context) { + if !self.service.is_unlocked() || self.reveal.is_stale(self.service.revision()) { + self.dismiss_password(cx); + } + } + + fn hide_password(&mut self) -> bool { + let Some(id) = self.reveal.id() else { + return false; + }; + self.reveal = Reveal::Hidden; + self.catalog.remeasure(id); + true + } + + fn toggle_password(&mut self, id: CredentialId, cx: &mut Context) { + let was_selected = self.reveal.id() == Some(id); + let hidden = self.hide_password(); + if was_selected + || self.busy + || !self.service.is_unlocked() + || !self + .catalog + .record(id) + .is_some_and(|record| record.binding.can_reveal_password()) + { + if hidden { + cx.notify(); + } + return; + } + let revision = self.service.revision(); + let future = self.service.reveal_password(id); + self.message = None; + let task = cx.spawn(async move |this, cx| { + let result = future.await; + let _ = this.update(cx, |this, cx| { + if this.reveal.id() != Some(id) || this.reveal.is_stale(revision) { + return; + } + if !this.service.is_unlocked() || revision != this.service.revision() { + this.dismiss_password(cx); + return; + } + this.reveal = match result { + Ok(secret) => Reveal::Shown { + id, + revision, + secret, + }, + Err(error) => { + this.message = Some((error.to_string().into(), true)); + Reveal::Hidden + } + }; + this.catalog.remeasure(id); + cx.notify(); + }); + }); + self.reveal = Reveal::Pending { + id, + revision, + _task: task, + }; + cx.notify(); + } + fn rename_focus(&self, cx: &gpui_kit::App) -> Option { self.renaming .as_ref() @@ -171,6 +255,7 @@ impl CredentialsTab { } fn operation(&mut self, future: VaultFuture<()>, cx: &mut Context) { + self.hide_password(); self.busy = true; self.message = None; let generation = self.generation; @@ -245,17 +330,69 @@ impl CredentialsTab { .text_color(theme.muted_foreground) .child(crate::credential_row::describe(record)), ) + .when_some( + self.reveal.secret(id).filter(|_| { + self.service.is_unlocked() + && !self.reveal.is_stale(self.service.revision()) + }), + |column, secret| { + column.child( + div() + .id(("vault-revealed-password", index)) + .test_support() + .w_full() + .min_w_0() + .max_w_full() + .max_h(rems(6.)) + .overflow_x_scroll() + .overflow_y_scroll() + .rounded(theme.radius) + .bg(theme.muted) + .p_2() + .text_sm() + .font_family(theme.mono_font_family.clone()) + .whitespace_nowrap() + .child(secret.expose().to_owned()), + ) + }, + ) .when(shared, |column| { column.child(h_flex().flex_wrap().gap_1().children(detach)) }), ) - .child(self.actions(index, id, cx)) + .child(self.actions(index, record, cx)) .into_any_element() } - /// Rename, copy the ID and delete. - fn actions(&self, index: usize, id: CredentialId, cx: &mut Context) -> AnyElement { + /// Reveal a password, rename, copy the ID and delete. + fn actions(&self, index: usize, record: &CredentialInfo, cx: &mut Context) -> AnyElement { + let id = record.id; + let selected = self.reveal.id() == Some(id); + let pending = self.reveal.is_pending(id); h_flex() + .when(record.binding.can_reveal_password(), |row| { + row.child( + Button::new(("vault-reveal-password", index)) + .small() + .ghost() + .icon(if pending { + IconName::LoaderCircle + } else if selected { + IconName::EyeOff + } else { + IconName::Eye + }) + .tooltip(if pending { + "Retrieving password… Click to cancel" + } else if selected { + "Hide password" + } else { + "Show password" + }) + .disabled(self.busy) + .on_click(cx.listener(move |this, _, _, cx| this.toggle_password(id, cx))), + ) + }) .child( Button::new(("vault-rename", index)) .small() @@ -329,7 +466,13 @@ impl CredentialsTab { impl Render for CredentialsTab { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { - if !self.service.is_unlocked() { + let unlocked = self.service.is_unlocked(); + if !unlocked + || (self.reveal.id().is_some() && self.reveal.is_stale(self.service.revision())) + { + self.hide_password(); + } + if !unlocked { return form::section( "Saved credentials", [form::note( diff --git a/crates/vault-ui/src/credentials_tab/catalog.rs b/crates/vault-ui/src/credentials_tab/catalog.rs index 5ffaab90..0ccd1547 100644 --- a/crates/vault-ui/src/credentials_tab/catalog.rs +++ b/crates/vault-ui/src/credentials_tab/catalog.rs @@ -115,6 +115,12 @@ impl Catalog { self.scroll.clone() } + pub(super) fn remeasure(&self, id: CredentialId) { + if let Some(index) = self.position(id) { + self.scroll.remeasure_items(index..index + 1); + } + } + pub(super) fn rename_focus(&self, id: CredentialId, focus: Option) { if let Some(index) = self.position(id) { let top = self.scroll.logical_scroll_top(); diff --git a/crates/vault-ui/src/credentials_tab/reveal.rs b/crates/vault-ui/src/credentials_tab/reveal.rs new file mode 100644 index 00000000..e89eac6f --- /dev/null +++ b/crates/vault-ui/src/credentials_tab/reveal.rs @@ -0,0 +1,54 @@ +//! A single explicitly revealed secret, tied to the current vault status revision. +//! Replacing or hiding the reveal drops the pending delivery task or zeroizing secret. +use gpui_kit::Task; +use nocterm_session::{CredentialId, Secret}; + +#[derive(Default)] +pub(super) enum Reveal { + #[default] + Hidden, + Pending { + id: CredentialId, + revision: u64, + _task: Task<()>, + }, + Shown { + id: CredentialId, + revision: u64, + secret: Secret, + }, +} + +impl Reveal { + pub(super) fn id(&self) -> Option { + match self { + Self::Hidden => None, + Self::Pending { id, .. } | Self::Shown { id, .. } => Some(*id), + } + } + + pub(super) fn is_pending(&self, id: CredentialId) -> bool { + matches!(self, Self::Pending { id: pending, .. } if *pending == id) + } + + pub(super) fn is_stale(&self, revision: u64) -> bool { + match self { + Self::Hidden => false, + Self::Pending { + revision: captured, .. + } + | Self::Shown { + revision: captured, .. + } => *captured != revision, + } + } + + pub(super) fn secret(&self, id: CredentialId) -> Option<&Secret> { + match self { + Self::Shown { + id: shown, secret, .. + } if *shown == id => Some(secret), + _ => None, + } + } +} diff --git a/crates/vault-ui/src/lib.rs b/crates/vault-ui/src/lib.rs index 5d0fab0b..f33efef2 100644 --- a/crates/vault-ui/src/lib.rs +++ b/crates/vault-ui/src/lib.rs @@ -1,6 +1,6 @@ //! Vault settings and authentication views with explicit lifecycle dependencies. //! Unlock prompt facts and scan progress remain private to their original masked-control owner. -//! Owns: settings page, private masked form controls, unlock dialog and credential presentation, including the group a credential belongs to and its read-only state; the Credentials tab, where credentials are searched, a password is added under a name in a dialog, a credential renamed or deleted and a shared password detached from a server. +//! Owns: settings page, private masked form controls, unlock dialog and credential presentation, including the group a credential belongs to and its read-only state; the Credentials tab, where credentials are searched, a password is added under a name in a dialog, a credential renamed or deleted, a shared password detached from a server, and one password revealed on demand while unlocked. //! Does not own: encrypted format, persistence, workers or native authentication. //! Ports used: supplied VaultAccess and SettingsHandle. Ports provided: CredentialStore, SettingsPageSpec. //! Settings: vault. Globals: none. Invariants: hidden/locked pages clear secrets. diff --git a/crates/vault-ui/src/tests/credentials_tab.rs b/crates/vault-ui/src/tests/credentials_tab.rs index 85d0b053..6295b2d4 100644 --- a/crates/vault-ui/src/tests/credentials_tab.rs +++ b/crates/vault-ui/src/tests/credentials_tab.rs @@ -45,6 +45,13 @@ fn a_password_added_under_a_name_signs_in_to_no_server_until_one_chooses_it( assert!(window.try_find(("vault-rename", 0usize)).is_some()); }) .unwrap(); + toggle_reveal(handle, 0, cx); + assert!( + revealed(handle, 0, cx), + "an unattached password is still viewable" + ); + toggle_reveal(handle, 0, cx); + assert!(!revealed(handle, 0, cx)); } #[gpui_kit::test] @@ -254,3 +261,113 @@ fn measure_search_in_large_credentials_tab(cx: &mut TestAppContext) { ) .unwrap(); } + +fn toggle_reveal(handle: gpui_kit::AnyWindowHandle, index: usize, cx: &mut TestAppContext) { + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window.click(("vault-reveal-password", index), cx); + }) + .unwrap(); + drain(cx); +} + +fn revealed(handle: gpui_kit::AnyWindowHandle, index: usize, cx: &mut TestAppContext) -> bool { + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + window + .try_find(("vault-revealed-password", index)) + .is_some_and(|row| row.visible()) + }) + .unwrap() +} + +#[gpui_kit::test] +fn only_the_explicitly_selected_password_is_revealed_and_private_keys_have_no_eye( + cx: &mut TestAppContext, +) { + let (handle, service) = unlocked_on_credentials(cx); + seed_credentials(&service, 2); + block_on(service.put( + None, + "SSH key".into(), + CredentialBinding::PrivateKey { + public_key: "ssh-ed25519 synthetic".into(), + }, + Secret::new("synthetic test key"), + )) + .unwrap(); + click(handle, "vault-refresh", cx); + drain(cx); + assert!(!revealed(handle, 0, cx)); + cx.update_window(handle, |_, window, cx| { + window.render_frame(cx); + assert!(window.try_find(("vault-rename", 2usize)).is_some()); + assert!(window.try_find(("vault-reveal-password", 2usize)).is_none()); + }) + .unwrap(); + toggle_reveal(handle, 0, cx); + assert!(revealed(handle, 0, cx)); + toggle_reveal(handle, 1, cx); + assert!(!revealed(handle, 0, cx)); + assert!(revealed(handle, 1, cx)); + toggle_reveal(handle, 1, cx); + assert!(!revealed(handle, 1, cx)); +} + +#[gpui_kit::test] +fn a_revealed_password_is_forgotten_on_search_tab_change_or_page_deactivation( + cx: &mut TestAppContext, +) { + let (handle, view, service) = setup(cx); + block_on(service.create(Secret::new("master password"))).unwrap(); + seed_credentials(&service, 1); + drain(cx); + tab(handle, 1, cx); + toggle_reveal(handle, 0, cx); + assert!(revealed(handle, 0, cx)); + type_field(handle, "vault-search", "synthetic", cx); + assert!(!revealed(handle, 0, cx)); + toggle_reveal(handle, 0, cx); + assert!(revealed(handle, 0, cx)); + tab(handle, 0, cx); + tab(handle, 1, cx); + assert!(!revealed(handle, 0, cx)); + toggle_reveal(handle, 0, cx); + assert!(revealed(handle, 0, cx)); + cx.update_window(handle, |_, window, cx| { + view.update(cx, |view, cx| SettingsPage::on_deactivate(view, window, cx)); + }) + .unwrap(); + assert!(!revealed(handle, 0, cx)); + assert!(service.is_unlocked()); +} + +#[gpui_kit::test] +fn a_pending_reveal_cannot_reappear_after_hiding_or_locking_and_unlocking(cx: &mut TestAppContext) { + use nocterm_vault::testing::{Gate, VaultOperation}; + let (handle, service) = unlocked_on_credentials(cx); + seed_credentials(&service, 1); + click(handle, "vault-refresh", cx); + drain(cx); + let gate = Gate::pending(); + service.hold_next(VaultOperation::RevealPassword, gate.clone()); + toggle_reveal(handle, 0, cx); + assert!(!revealed(handle, 0, cx)); + toggle_reveal(handle, 0, cx); + gate.release(); + drain(cx); + assert!(!revealed(handle, 0, cx)); + let gate = Gate::pending(); + service.hold_next(VaultOperation::RevealPassword, gate.clone()); + toggle_reveal(handle, 0, cx); + service.lock(); + block_on(service.unlock(Secret::new("master password"))).unwrap(); + gate.release(); + drain(cx); + assert!(!revealed(handle, 0, cx)); + toggle_reveal(handle, 0, cx); + assert!(revealed(handle, 0, cx)); + service.lock(); + drain(cx); + assert!(!revealed(handle, 0, cx)); +} diff --git a/crates/vault-ui/src/view.rs b/crates/vault-ui/src/view.rs index 6ffa16c8..5da1f716 100644 --- a/crates/vault-ui/src/view.rs +++ b/crates/vault-ui/src/view.rs @@ -131,6 +131,8 @@ impl VaultView { } /// Follows the vault locking or unlocking, by this page or any other path. fn status_changed(&mut self, window: &mut Window, cx: &mut Context) { + self.credentials + .update(cx, |credentials, cx| credentials.vault_changed(cx)); let unlocked = self.service.is_unlocked(); if unlocked == self.unlocked { return; @@ -261,7 +263,9 @@ impl VaultView { if self.tab == tab { return; } - // Master passwords never wait in a hidden tab. + // Passwords never wait in a hidden tab. + self.credentials + .update(cx, |credentials, cx| credentials.dismiss_password(cx)); self.form.clear_passwords(window, cx); self.message = None; self.tab = tab; @@ -283,6 +287,8 @@ impl SettingsPage for VaultView { if self.device_busy { self.lock(window, cx); } + self.credentials + .update(cx, |credentials, cx| credentials.dismiss_password(cx)); self.form.clear_passwords(window, cx); } fn on_close(&mut self, window: &mut Window, cx: &mut Context) { diff --git a/crates/vault/src/access.rs b/crates/vault/src/access.rs index ce33835e..7b7d516d 100644 --- a/crates/vault/src/access.rs +++ b/crates/vault/src/access.rs @@ -29,6 +29,10 @@ pub trait VaultAccess: Send + Sync + 'static { fn change_password(&self, password: Secret) -> VaultFuture<()>; fn list(&self) -> VaultFuture>; fn get(&self, id: CredentialId, binding: CredentialBinding) -> VaultFuture; + /// Management view only: reads a password or key passphrase by ID from an unlocked + /// vault, including passwords not attached to a server. Never returns an SSH private key + /// or changes the authentication binding checked by `get`. + fn reveal_password(&self, id: CredentialId) -> VaultFuture; fn put( &self, id: Option, diff --git a/crates/vault/src/model.rs b/crates/vault/src/model.rs index 10475181..04f912f6 100644 --- a/crates/vault/src/model.rs +++ b/crates/vault/src/model.rs @@ -135,6 +135,11 @@ impl CredentialBinding { } } + /// The management view may reveal passwords and key passphrases, never private keys. + pub fn can_reveal_password(&self) -> bool { + matches!(self, Self::Password { .. } | Self::KeyPassphrase { .. }) + } + /// The addresses a password answers; none for any other record. pub fn targets(&self) -> &[Target] { match self { diff --git a/crates/vault/src/state.rs b/crates/vault/src/state.rs index 2cd38c3c..d72ef05a 100644 --- a/crates/vault/src/state.rs +++ b/crates/vault/src/state.rs @@ -208,17 +208,28 @@ impl VaultState { .collect()) } pub fn get(&self, id: CredentialId, binding: &CredentialBinding) -> Result { - let record = self - .state()? - .records - .iter() - .find(|record| record.info.id == id) - .ok_or(VaultError::NotFound)?; + let record = self.record(id)?; if !record.info.binding.answers(binding) { return Err(VaultError::Binding); } Ok(record.secret.clone()) } + pub fn reveal_password(&self, id: CredentialId) -> Result { + let record = self.record(id)?; + if !record.info.binding.can_reveal_password() { + return Err(VaultError::Unsupported); + } + Ok(record.secret.clone()) + } + + fn record(&self, id: CredentialId) -> Result<&Record, VaultError> { + self.state()? + .records + .iter() + .find(|record| record.info.id == id) + .ok_or(VaultError::NotFound) + } + pub fn prepare_put( &self, id: CredentialId, diff --git a/crates/vault/src/state/tests.rs b/crates/vault/src/state/tests.rs index 3c4ac41d..3f3f810d 100644 --- a/crates/vault/src/state/tests.rs +++ b/crates/vault/src/state/tests.rs @@ -251,3 +251,57 @@ fn a_key_record_answers_only_for_the_same_public_half() { Err(VaultError::Binding) )); } + +#[test] +fn password_reveal_does_not_weaken_authentication_binding_or_expose_private_keys() { + let mut state = state(); + let ids = [ + CredentialId::from_bytes([21; 16]), + CredentialId::from_bytes([22; 16]), + CredentialId::from_bytes([23; 16]), + ]; + for (index, binding) in [ + CredentialBinding::password([]), + CredentialBinding::KeyPassphrase { + path: "/key".into(), + }, + private_key("ssh-ed25519 synthetic"), + ] + .into_iter() + .enumerate() + { + let candidate = state + .prepare_put( + ids[index], + "synthetic credential".into(), + binding, + Secret::new("test password"), + SealNonces::new([30 + index as u8; 24], [34 + index as u8; 24]), + ) + .unwrap(); + state.accept_write(candidate); + } + for id in &ids[..2] { + assert_eq!( + state.reveal_password(*id).unwrap().expose(), + "test password" + ); + } + assert!(matches!( + state.get(ids[0], &binding()), + Err(VaultError::Binding) + )); + assert!(matches!( + state.get(ids[0], &CredentialBinding::password([])), + Err(VaultError::Binding) + )); + assert!(matches!( + state.reveal_password(ids[2]), + Err(VaultError::Unsupported) + )); + state.lock(); + assert!(matches!( + state.reveal_password(ids[0]), + Err(VaultError::Locked) + )); +} diff --git a/crates/vault/src/testing.rs b/crates/vault/src/testing.rs index 52d4abdd..9938d83a 100644 --- a/crates/vault/src/testing.rs +++ b/crates/vault/src/testing.rs @@ -18,6 +18,7 @@ pub enum VaultOperation { Unlock, ChangePassword, List, + RevealPassword, Delete, } @@ -288,6 +289,22 @@ impl VaultAccess for ScriptedVaultAccess { Ok(secret.clone()) }) } + fn reveal_password(&self, id: CredentialId) -> VaultFuture { + self.gated_request(VaultOperation::RevealPassword, move |memory| { + if memory.status != VaultStatus::Unlocked { + return Err(VaultError::Locked); + } + let (info, secret) = memory + .records + .iter() + .find(|(info, _)| info.id == id) + .ok_or(VaultError::NotFound)?; + if !info.binding.can_reveal_password() { + return Err(VaultError::Unsupported); + } + Ok(secret.clone()) + }) + } fn put( &self, id: Option, diff --git a/crates/workspace-ports/src/project_terminal.rs b/crates/workspace-ports/src/project_terminal.rs index c6f40f81..de53a572 100644 --- a/crates/workspace-ports/src/project_terminal.rs +++ b/crates/workspace-ports/src/project_terminal.rs @@ -1,7 +1,7 @@ //! Captured original terminal destinations and provider contracts below the shell. use crate::{ExpectedSession, TerminalCapabilities}; use gpui::{AnyEntity, AnyView, App, Entity, Window}; -use nocterm_project_model::ProjectTarget; +use nocterm_project_model::{ProjectTarget, RootPath}; use std::rc::Rc; mod error; @@ -55,6 +55,9 @@ pub trait ProjectTerminalOpen: 'static { /// A captured connection launch configuration, independent of parent tab lifetime. pub trait ProjectTerminalSession: 'static { + /// Change only the starting folder, retaining the original connection launch. + fn with_root(&self, root: RootPath) -> Rc; + fn open( &self, target: ProjectTerminalTarget, diff --git a/crates/workspace/src/actions.rs b/crates/workspace/src/actions.rs index 996a8281..e7d5762b 100644 --- a/crates/workspace/src/actions.rs +++ b/crates/workspace/src/actions.rs @@ -167,3 +167,17 @@ pub fn request_sign_in(window: &mut gpui_kit::Window, cx: &mut gpui_kit::App) { window.dispatch_action(action, cx); } } + +/// Create a temporary workspace from the original terminal tab, not the focused tab. +#[derive(Clone, Debug, PartialEq, gpui_kit::Action)] +#[action(namespace = workspace, no_json)] +pub struct CreateWorkspaceFromTab { + pub item: gpui_kit::EntityId, +} + +/// Edit the definition of the original outer workspace tab. +#[derive(Clone, Debug, PartialEq, gpui_kit::Action)] +#[action(namespace = workspace, no_json)] +pub struct EditWorkspaceFromTab { + pub item: gpui_kit::EntityId, +} diff --git a/crates/workspace/src/dock_item.rs b/crates/workspace/src/dock_item.rs index 280e0377..6aded989 100644 --- a/crates/workspace/src/dock_item.rs +++ b/crates/workspace/src/dock_item.rs @@ -10,7 +10,7 @@ use gpui_kit::{ component::{ ActiveTheme as _, Disableable as _, Icon, Sizable as _, Theme, button::{Button, ButtonVariants as _}, - dock::{BasePanel, Panel, PanelControl, PanelEvent}, + dock::{BasePanel, DragPanel, Panel, PanelControl, PanelEvent}, h_flex, input::{Input, InputEvent, InputState}, menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem}, @@ -167,6 +167,74 @@ impl DockItem { cx.notify(); } } + fn alias_title( + &self, + selection: Option, + cx: &mut Context, + ) -> impl IntoElement + use<> { + div() + .id("tab-alias") + .test_support() + .relative() + .min_w_8() + .overflow_hidden() + .child( + div() + .whitespace_nowrap() + .text_ellipsis() + // The committed title still determines the layout while editing. + // Typing and cancelling cannot resize the tab or move its neighbours. + .when(self.editing.is_some(), |label| label.invisible()) + .child( + self.alias + .clone() + .unwrap_or_else(|| self.item.tab_title(cx)), + ), + ) + .when_some(self.editing.clone(), |label, input| { + label.child( + div() + .absolute() + .inset_0() + .key_context("TabAlias") + .child( + Input::new(&input) + .xsmall() + .aria_label("Tab name") + .appearance(false) + .p_0() + .size_full() + .text_sm(), + ) + .on_key_down(cx.listener( + |this, event: &gpui_kit::KeyDownEvent, window, cx| { + if event.keystroke.key == "escape" { + cx.stop_propagation(); + this.finish_alias(false, true, window, cx); + } + }, + )), + ) + }) + .when(self.editing.is_none(), |label| { + label.on_click(cx.listener( + move |this, event: &gpui_kit::ClickEvent, window, cx| { + if event.click_count() == 2 + && selection.is_some_and(|selection| { + this.workspace.upgrade().is_some_and(|workspace| { + workspace.read(cx).accepts_context_selection(selection, cx) + }) + }) + { + cx.stop_propagation(); + if let Some(selection) = selection { + this.start_alias(selection, window, cx); + } + } + }, + )) + }) + } } impl Focusable for DockItem { fn focus_handle(&self, cx: &App) -> FocusHandle { @@ -296,7 +364,48 @@ impl Panel for DockItem { let color = GROUP_COLORS[self.group_color? % GROUP_PALETTE]; Some(color(cx.theme())) } - #[expect(clippy::too_many_lines, reason = "predates the limit")] + fn on_tab_drop( + &mut self, + drag: &DragPanel, + window: &mut Window, + cx: &mut Context, + ) -> bool { + if self.group_color.is_none() { + return false; + } + let target = self.item.item_id(); + let Some(workspace) = self.workspace.upgrade() else { + return false; + }; + let surface = workspace.read(cx); + if surface.source() != self.source + || !surface.accepts_context_selection(surface.selection(), cx) + || surface + .content() + .group_drop_source(drag, target, cx) + .is_none() + { + return false; + } + let selection = surface.selection(); + let drag = drag.clone(); + // Joining can update this DockItem's group badge. Do so after the + // toolkit has released its mutable borrow of the drop target. + window.defer(cx, move |window, cx| { + workspace.update(cx, |surface, cx| { + if !surface.accepts_context_selection(selection, cx) { + return; + } + if let Some(id) = surface.content().group_drop_source(&drag, target, cx) { + surface.content_mut().group_tab_with(id, target, window, cx); + surface.activate_item_by_id(id, window, cx); + cx.notify(); + } + }); + }); + true + } + fn title(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let icon_color = match self.item.tab_state(cx) { TabState::Idle => cx.theme().muted_foreground, @@ -322,47 +431,7 @@ impl Panel for DockItem { .small() .text_color(icon_color), ) - .child(match &self.editing { - Some(input) => div() - .key_context("TabAlias") - .w(rems(cx.design().layout.tab_max_width - 3.0)) - .child(Input::new(input).small()) - .on_key_down( - cx.listener(|this, event: &gpui_kit::KeyDownEvent, window, cx| { - if event.keystroke.key == "escape" { - cx.stop_propagation(); - this.finish_alias(false, true, window, cx); - } - }), - ) - .into_any_element(), - None => div() - .id("tab-alias") - .min_w_0() - .text_ellipsis() - .child( - self.alias - .clone() - .unwrap_or_else(|| self.item.tab_title(cx)), - ) - .on_click( - cx.listener(move |this, event: &gpui_kit::ClickEvent, window, cx| { - if event.click_count() == 2 - && selection.is_some_and(|selection| { - this.workspace.upgrade().is_some_and(|workspace| { - workspace.read(cx).accepts_context_selection(selection, cx) - }) - }) - { - cx.stop_propagation(); - if let Some(selection) = selection { - this.start_alias(selection, window, cx); - } - } - }), - ) - .into_any_element(), - }) + .child(self.alias_title(selection, cx)) .child( Button::new(("close-tab", id.as_u64())) .ghost() @@ -380,72 +449,89 @@ impl Panel for DockItem { }); }), ) - .context_menu(move |mut menu, window, cx| { - use crate::workspace::TabCloseScope; - let selection = menu_workspace.upgrade().and_then(|workspace| { - let workspace = workspace.read(cx); - (workspace.source() == source).then(|| workspace.selection()) - }); - for (label, scope) in [ - ("Close Tab", TabCloseScope::Current), - ("Close Other Tabs in Pane", TabCloseScope::Others), - ("Close Tabs to the Left", TabCloseScope::Left), - ("Close Tabs to the Right", TabCloseScope::Right), - ("Close All Tabs", TabCloseScope::All), - ] { - let disabled = menu_workspace.upgrade().is_none_or(|workspace| { - workspace - .read(cx) - .content() - .tabs_to_close(id, scope, cx) - .is_empty() - }); - let workspace = menu_workspace.clone(); - menu = menu.item(PopupMenuItem::new(label).disabled(disabled).on_click( - move |_, window, cx| { - let _ = workspace.update(cx, |workspace, cx| { - if selection.is_some_and(|selection| { - workspace.accepts_context_selection(selection, cx) - }) { - workspace.close_tabs(id, scope, window, cx); - } - }); - }, - )); - } - menu = menu.separator(); - for (label, placement) in [ - ( - "Split Vertically — Right", - gpui_kit::component::Placement::Right, - ), - ( - "Split Horizontally — Below", - gpui_kit::component::Placement::Bottom, - ), - ] { - let workspace = menu_workspace.clone(); - let disabled = workspace.upgrade().is_none_or(|workspace| { - !workspace.read(cx).content().can_split_item(id, cx) - }); - menu = menu.item(PopupMenuItem::new(label).disabled(disabled).on_click( - move |_, window, cx| { - let _ = workspace.update(cx, |workspace, cx| { - if selection.is_some_and(|selection| { - workspace.accepts_context_selection(selection, cx) - }) { - workspace.split_item(id, placement, window, cx); - } - }); - }, - )); - } - group_menu(menu.separator(), id, &menu_workspace, selection, window, cx) - .separator() - .menu("Settings", Box::new(crate::OpenSettings)) + .context_menu(move |menu, window, cx| { + tab_menu(menu, id, source, &menu_workspace, window, cx) }) } } +/// Build the context menu only on demand, with the original tab identity. +fn tab_menu( + mut menu: PopupMenu, + id: EntityId, + source: ProjectSurfaceReceipt, + menu_workspace: &WeakEntity, + window: &mut Window, + cx: &mut Context, +) -> PopupMenu { + use crate::workspace::TabCloseScope; + let selection = menu_workspace.upgrade().and_then(|workspace| { + let workspace = workspace.read(cx); + (workspace.source() == source).then(|| workspace.selection()) + }); + for (label, scope) in [ + ("Close Tab", TabCloseScope::Current), + ("Close Other Tabs in Pane", TabCloseScope::Others), + ("Close Tabs to the Left", TabCloseScope::Left), + ("Close Tabs to the Right", TabCloseScope::Right), + ("Close All Tabs", TabCloseScope::All), + ] { + let disabled = menu_workspace.upgrade().is_none_or(|workspace| { + workspace + .read(cx) + .content() + .tabs_to_close(id, scope, cx) + .is_empty() + }); + let workspace = menu_workspace.clone(); + menu = menu.item(PopupMenuItem::new(label).disabled(disabled).on_click( + move |_, window, cx| { + let _ = workspace.update(cx, |workspace, cx| { + if selection + .is_some_and(|selection| workspace.accepts_context_selection(selection, cx)) + { + workspace.close_tabs(id, scope, window, cx); + } + }); + }, + )); + } + menu = menu.separator(); + for (label, placement) in [ + ( + "Split Vertically — Right", + gpui_kit::component::Placement::Right, + ), + ( + "Split Horizontally — Below", + gpui_kit::component::Placement::Bottom, + ), + ] { + let workspace = menu_workspace.clone(); + let disabled = workspace + .upgrade() + .is_none_or(|workspace| !workspace.read(cx).content().can_split_item(id, cx)); + menu = menu.item(PopupMenuItem::new(label).disabled(disabled).on_click( + move |_, window, cx| { + let _ = workspace.update(cx, |workspace, cx| { + if selection + .is_some_and(|selection| workspace.accepts_context_selection(selection, cx)) + { + workspace.split_item(id, placement, window, cx); + } + }); + }, + )); + } + menu = group_menu(menu.separator(), id, menu_workspace, selection, window, cx) + .separator() + .menu("Settings", Box::new(crate::OpenSettings)); + if let Some(surface) = menu_workspace.upgrade() + && let Some((label, action)) = surface.read(cx).workspace_tab_command(id, cx) + { + menu = menu.menu(label, action); + } + menu +} /// What the tab menu offers for groups of tabs. fn group_menu( mut menu: PopupMenu, diff --git a/crates/workspace/src/lib.rs b/crates/workspace/src/lib.rs index 9644830b..995e7de4 100644 --- a/crates/workspace/src/lib.rs +++ b/crates/workspace/src/lib.rs @@ -61,7 +61,7 @@ //! before calling the feature's close hook. Local directory synchronization reports typed //! capability refusals and preserves encoding causes through its LocalTerminal port. //! SurfaceSelection owns original source, expiring selection receipts and presentation lifecycle. -//! SurfaceState owns initial opening issuance, the starting folder and monitoring metadata. +//! SurfaceState owns initial opening issuance, the starting folder and inert monitoring/AI metadata. //! SurfaceContent owns foreground and off-dock membership and returns tab effects; //! the surface entity applies events and focus. Background promotion transfers the //! original TabEntry together with its subscriptions into the native dock. @@ -117,8 +117,9 @@ pub use workspace::{ LayoutChoice, LayoutEditError, LayoutSwitchError, MalformedLayouts, PanelEntry, PanelRegistration, PanelRequest, ProjectSurface, ProjectSurfaceEvent, ProjectSurfaceFactory, ProjectSurfaceReceipt, RegistrationError, SessionFactory, SessionSpec, TabCloseScope, TabPane, - TabSnapshot, ToolbarRegistration, WidgetRegistration, Workspace, WorkspaceEvent, ZoneAware, - admit_project_terminal, edit_layouts, legacy_layout_swapped, validate_project_terminal_target, + TabSnapshot, ToolbarRegistration, WidgetRegistration, Workspace, WorkspaceDescription, + WorkspaceEvent, ZoneAware, admit_project_terminal, edit_layouts, legacy_layout_swapped, + validate_project_terminal_target, }; /// The key context of the workspace, for keymap entries. diff --git a/crates/workspace/src/test_support/project_terminal.rs b/crates/workspace/src/test_support/project_terminal.rs index f200723a..c6f1dfbe 100644 --- a/crates/workspace/src/test_support/project_terminal.rs +++ b/crates/workspace/src/test_support/project_terminal.rs @@ -72,6 +72,11 @@ impl ProjectTerminalOpen for ProjectTerminalProbe { } } impl ProjectTerminalSession for ProjectTerminalProbe { + fn with_root(&self, root: RootPath) -> Rc { + let mut session = self.clone(); + session.root = Some(root); + Rc::new(session) + } fn open( &self, target: ProjectTerminalTarget, diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index 83d23919..87ef9488 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -34,7 +34,9 @@ mod project_terminal; pub(crate) use project_terminal::project_terminal_selection; pub use project_terminal::{admit_project_terminal, validate_project_terminal_target}; mod queries; -pub use project_surface::{ProjectSurface, ProjectSurfaceEvent, ProjectSurfaceFactory}; +pub use project_surface::{ + ProjectSurface, ProjectSurfaceEvent, ProjectSurfaceFactory, WorkspaceDescription, +}; pub(crate) mod surface; mod surfaces; mod tabs; diff --git a/crates/workspace/src/workspace/groups_tests.rs b/crates/workspace/src/workspace/groups_tests.rs index 05ac6b40..fbed2558 100644 --- a/crates/workspace/src/workspace/groups_tests.rs +++ b/crates/workspace/src/workspace/groups_tests.rs @@ -5,7 +5,11 @@ use std::sync::Arc; use gpui_kit::{ AnyWindowHandle, App, AppContext as _, Context, Entity, EntityId, EventEmitter, FocusHandle, - Focusable, TestAppContext, Window, component::Placement, div, prelude::*, + Focusable, TestAppContext, Window, + component::{Placement, WindowExt as _}, + div, + prelude::*, + test::TestWindowExt as _, }; use nocterm_session::{ExecError, ExecFuture, ExecOutput, ExecRequest, HostExec, Target}; @@ -238,3 +242,57 @@ fn a_program_joins_the_session_on_its_host_it_was_opened_from(cx: &mut TestAppCo "another host's program stands alone" ); } + +#[gpui_kit::test] +fn dropping_an_ordinary_tab_on_a_grouped_tab_joins_the_group(cx: &mut TestAppContext) { + let (window, workspace) = fixture(cx); + let [a, b, c, d] = open(cx, window, &workspace, 4)[..] else { + unreachable!() + }; + with(cx, window, &workspace, |ws, window, cx| { + ws.group_tab_with(b, a, window, cx); + }); + cx.update_window(window, |_, window, cx| { + crate::workspace::tests::drag_tab(window, d, b, cx); + }) + .unwrap(); + cx.run_until_parked(); + + assert_eq!(bars(cx, &workspace), [vec![a, b, d, c]]); + assert_eq!(color(cx, &workspace, a), color(cx, &workspace, d)); + assert_eq!(color(cx, &workspace, c), None); + workspace.read_with(cx, |ws, cx| { + assert_eq!(ws.tab_group_items(a, cx), [a, b, d]); + assert_eq!(ws.active_item(cx).unwrap().item_id(), d); + }); +} + +#[gpui_kit::test] +fn renaming_a_tab_does_not_move_its_neighbours_until_commit(cx: &mut TestAppContext) { + let (window, workspace) = fixture(cx); + let [first, second] = open(cx, window, &workspace, 2)[..] else { + unreachable!() + }; + let first = ("tab-title", first.as_u64()); + let second = ("tab-title", second.as_u64()); + cx.update_window(window, |_, window, cx| { + window.render_frame(cx); + let before = window.find(first).bounds(); + let neighbour = window.find(second).bounds(); + window.within(first).double_click("tab-alias", cx); + window.render_frame(cx); + assert!(window.focused_input(cx).is_some()); + assert_eq!(window.find(first).bounds(), before); + assert_eq!(window.find(second).bounds(), neighbour); + window.press("ctrl-a", cx); + window.input("A substantially longer connection title", cx); + window.render_frame(cx); + assert_eq!(window.find(first).bounds(), before); + assert_eq!(window.find(second).bounds(), neighbour); + window.press("escape", cx); + window.render_frame(cx); + assert_eq!(window.find(first).bounds(), before); + assert_eq!(window.find(second).bounds(), neighbour); + }) + .unwrap(); +} diff --git a/crates/workspace/src/workspace/native_terminal_tab_tests.rs b/crates/workspace/src/workspace/native_terminal_tab_tests.rs index d7a3454c..b19bd98a 100644 --- a/crates/workspace/src/workspace/native_terminal_tab_tests.rs +++ b/crates/workspace/src/workspace/native_terminal_tab_tests.rs @@ -588,3 +588,27 @@ fn deferred_find_is_cancelled_when_its_bottom_target_hides_before_delivery( assert_eq!(tab.read_with(cx, |tab, _| tab.closed.get()), 0); } } + +#[gpui_kit::test] +fn central_tab_admission_and_activation_restore_zoomed_bottom_dock(cx: &mut TestAppContext) { + let (window, ws, tabs) = open_three(cx, false); + let local = cx.update(|cx| tab(cx, "/local")); + with(cx, window, &ws, |ws, window, cx| { + ws.add_local_terminal(local.clone(), window, cx); + }); + zoom(cx, window, &ws, local.entity_id()); + cx.update(|cx| assert!(ws.read(cx).zoomed_pane(cx).is_some())); + with(cx, window, &ws, |ws, window, cx| { + assert!(ws.activate_item_by_id(tabs[0].entity_id(), window, cx)); + assert!(ws.zoomed_pane(cx).is_none()); + assert!(ws.dock_region_open(DockPlacement::Bottom, cx)); + }); + zoom(cx, window, &ws, local.entity_id()); + let new = cx.update(|cx| tab(cx, "/settings")); + with(cx, window, &ws, |ws, window, cx| { + ws.add_item(new.clone(), window, cx); + assert!(ws.zoomed_pane(cx).is_none()); + assert!(ws.dock_region_open(DockPlacement::Bottom, cx)); + assert_eq!(ws.active_item(cx).unwrap().item_id(), new.entity_id()); + }); +} diff --git a/crates/workspace/src/workspace/project_surface.rs b/crates/workspace/src/workspace/project_surface.rs index c55af7f9..bea117b8 100644 --- a/crates/workspace/src/workspace/project_surface.rs +++ b/crates/workspace/src/workspace/project_surface.rs @@ -14,6 +14,13 @@ pub enum ProjectSurfaceEvent { }, } +/// Inert AI-facing metadata of the original workspace, never session authority. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct WorkspaceDescription { + pub name: SharedString, + pub description: SharedString, +} + pub(super) struct ProjectPresentation { surface: ProjectSurface, _events: Subscription, @@ -87,6 +94,11 @@ impl ProjectSurface { self.entity .update(cx, |surface, cx| surface.set_monitor_target(target, cx)); } + pub fn set_ai_description(&self, name: &str, description: &str, cx: &mut App) { + self.entity.update(cx, |surface, _| { + surface.set_ai_description(name, description) + }); + } pub fn set_root(&self, root: RootPath, cx: &mut App) { self.entity .update(cx, |surface, cx| surface.set_root(root, cx)); diff --git a/crates/workspace/src/workspace/queries.rs b/crates/workspace/src/workspace/queries.rs index 61f1412f..4868feef 100644 --- a/crates/workspace/src/workspace/queries.rs +++ b/crates/workspace/src/workspace/queries.rs @@ -85,6 +85,19 @@ impl Workspace { .content() .terminals(cx)) } + /// Reads only metadata of the original live surface, even when it is hidden. + pub fn context_ai_description( + &self, + source: ProjectSurfaceReceipt, + cx: &App, + ) -> Option { + self.surfaces + .window() + .resolve(source, cx) + .ok()? + .read(cx) + .ai_description() + } pub fn selected_context(&self, cx: &App) -> nocterm_project_model::ContextId { self.context_source(cx).context() } diff --git a/crates/workspace/src/workspace/surface.rs b/crates/workspace/src/workspace/surface.rs index ee9a0f79..02a20492 100644 --- a/crates/workspace/src/workspace/surface.rs +++ b/crates/workspace/src/workspace/surface.rs @@ -99,6 +99,35 @@ impl TabSurface { self.emit_observation(WorkspaceEvent::SurfaceItemsChanged(source), cx); } } + pub(crate) fn workspace_tab_command( + &self, + id: EntityId, + cx: &App, + ) -> Option<(&'static str, Box)> { + if !self.selection.general() || !self.tabs().contains(id) { + return None; + } + if self.tabs().project(id).is_some() { + Some(( + "Workspace settings", + Box::new(crate::EditWorkspaceFromTab { item: id }), + )) + } else if self + .content + .item_handle(id)? + .terminal_capabilities(cx)? + .project_parent() + .is_some() + { + Some(( + "Create workspace", + Box::new(crate::CreateWorkspaceFromTab { item: id }), + )) + } else { + None + } + } + pub(crate) fn new_local_terminal_from( &mut self, id: EntityId, @@ -126,6 +155,12 @@ impl TabSurface { self.emit_observation(WorkspaceEvent::ActiveSessionChanged, cx); } } + pub(in crate::workspace) fn ai_description(&self) -> Option { + self.state.ai_description() + } + pub(in crate::workspace) fn set_ai_description(&mut self, name: &str, description: &str) { + self.state.set_ai_description(name, description); + } pub(in crate::workspace) fn root(&self) -> Option { self.state.root() } diff --git a/crates/workspace/src/workspace/surface/commands.rs b/crates/workspace/src/workspace/surface/commands.rs index 611cb621..55301056 100644 --- a/crates/workspace/src/workspace/surface/commands.rs +++ b/crates/workspace/src/workspace/surface/commands.rs @@ -6,6 +6,7 @@ pub(super) struct SurfaceState { initial_terminal: bool, root: Option, monitor_target: Option, + ai_description: Option, } impl SurfaceState { pub(super) fn monitor_target(&self) -> Option { @@ -18,6 +19,22 @@ impl SurfaceState { self.monitor_target = Some(target); true } + pub(super) fn ai_description(&self) -> Option { + self.ai_description.clone() + } + pub(super) fn set_ai_description(&mut self, name: &str, description: &str) { + if self + .ai_description + .as_ref() + .is_some_and(|old| old.name.as_ref() == name && old.description.as_ref() == description) + { + return; + } + self.ai_description = Some(crate::WorkspaceDescription { + name: name.to_owned().into(), + description: description.to_owned().into(), + }); + } pub(super) fn root(&self) -> Option { self.root.clone() } diff --git a/crates/workspace/src/workspace/surface/membership.rs b/crates/workspace/src/workspace/surface/membership.rs index 6dc0f63a..9123ba7b 100644 --- a/crates/workspace/src/workspace/surface/membership.rs +++ b/crates/workspace/src/workspace/surface/membership.rs @@ -260,6 +260,15 @@ impl SurfaceContent { ) -> Vec<(EntityId, SharedString)> { self.tabs().tab_groups_to_join(id, cx) } + pub(crate) fn group_drop_source( + &self, + drag: &gpui_kit::component::dock::DragPanel, + target: EntityId, + cx: &App, + ) -> Option { + self.tabs() + .group_drop_source(drag.panel(), drag.source(), target, cx) + } pub(crate) fn is_tab_grouped(&self, id: EntityId) -> bool { self.tabs().is_tab_grouped(id) } diff --git a/crates/workspace/src/workspace/tabs/groups.rs b/crates/workspace/src/workspace/tabs/groups.rs index b2bf8cb7..8e5458b2 100644 --- a/crates/workspace/src/workspace/tabs/groups.rs +++ b/crates/workspace/src/workspace/tabs/groups.rs @@ -32,6 +32,26 @@ impl Tabs { self.regroup(window, cx); } + /// Resolve a native drag only against this surface's live placement. + /// A member of an existing group still moves that group as a unit. + pub(in crate::workspace) fn group_drop_source( + &self, + panel: PanelId, + node: NodeId, + target: EntityId, + cx: &App, + ) -> Option { + if self.topology.locked(cx) + || !self.is_tab_grouped(target) + || self.groups.group_of(panel).is_some() + || self.topology.location(panel, cx)?.1 != node + { + return None; + } + let entry = self.item_for_panel(panel)?; + Some(entry.id()) + } + /// Puts the tab showing `item` in the group of the tab showing `other`, /// starting one when `other` is in none. pub(in crate::workspace) fn group_tab_with( diff --git a/crates/workspace/src/workspace/tabs/lifecycle.rs b/crates/workspace/src/workspace/tabs/lifecycle.rs index 449a93e2..f1b37b88 100644 --- a/crates/workspace/src/workspace/tabs/lifecycle.rs +++ b/crates/workspace/src/workspace/tabs/lifecycle.rs @@ -14,6 +14,9 @@ impl Tabs { return None; } let dock_item = entry.dock_item.clone(); + if placement == DockPlacement::Center { + self.topology.reveal_center(window, cx); + } self.entries.push(entry); let height = (placement == DockPlacement::Bottom).then(|| self.local.height(window, cx)); self.topology @@ -59,6 +62,14 @@ impl Tabs { let previous = self.active_central_id; let selected_local = self.local.selected() == Some(id); let panel = self.entries[index].panel(); + if self.topology.zoomed(cx).is_some() + && self + .topology + .location(panel, cx) + .is_some_and(|(placement, _)| placement == DockPlacement::Center) + { + self.topology.reveal_center(window, cx); + } let location = if focused || previous == Some(id) || selected_local { self.topology.location(panel, cx) } else { diff --git a/crates/workspace/src/workspace/tabs/selection.rs b/crates/workspace/src/workspace/tabs/selection.rs index c6b5efd3..e7636b13 100644 --- a/crates/workspace/src/workspace/tabs/selection.rs +++ b/crates/workspace/src/workspace/tabs/selection.rs @@ -37,6 +37,13 @@ impl Tabs { let panel = entry.panel(); let focus = entry.handle.focus_handle(cx); let local = entry.local.is_some(); + if self + .topology + .location(panel, cx) + .is_some_and(|(placement, _)| placement == DockPlacement::Center) + { + self.topology.reveal_center(window, cx); + } self.topology.select(panel, window, cx); self.last_command_id = Some(id); let mut events = self.mark_active(id); diff --git a/crates/workspace/src/workspace/tabs/topology.rs b/crates/workspace/src/workspace/tabs/topology.rs index 83f49db8..d7a0361f 100644 --- a/crates/workspace/src/workspace/tabs/topology.rs +++ b/crates/workspace/src/workspace/tabs/topology.rs @@ -39,6 +39,20 @@ impl DockTopology { pub(super) fn zoomed(&self, cx: &App) -> Option { self.dock.read(cx).zoomed_group() } + /// Central navigation must reveal the main pane without hiding the bottom dock. + pub(super) fn reveal_center(&self, window: &mut Window, cx: &mut App) { + let dock = self.dock.read(cx); + let Some(node) = dock.zoomed_group() else { + return; + }; + if dock + .layout(DockPlacement::Bottom) + .is_some_and(|tree| tree.find_node(node).is_some()) + { + self.dock + .update(cx, |dock, cx| dock.set_zoomed_out(window, cx)); + } + } pub(super) fn dump(&self, cx: &App) -> DockAreaState { self.dock.read(cx).dump(cx) } diff --git a/docs/AI_AGENTS.md b/docs/AI_AGENTS.md index e28f7bf0..3ed77b20 100644 --- a/docs/AI_AGENTS.md +++ b/docs/AI_AGENTS.md @@ -233,8 +233,9 @@ An attached server (directly or through its folder) gives the agent every open session of that server, whether you opened it or an agent did. A server without a session is listed to the agent as an *offline server*; the agent connects to it with the `open_terminal` tool, in the background, without opening a tab or -taking focus. If the connection needs you, the agent waits up to three -minutes; only a new host key moves the session into a tab so you can answer. +taking focus. If the connection needs you, the agent waits for your answer; +the connection deadline resumes with a fresh budget afterwards. A question +that cannot be answered in the chat moves the session into a tab. When the connection of an attached server's terminal drops, the agent's next call on it reconnects it in place and then goes ahead, and `open_terminal` reconnects a background session the chat opened instead of adding another; the @@ -246,7 +247,10 @@ A password, passphrase or one-time code is asked in the chat: the session stays in the background, you type the answer into the card and the agent continues. When the saved credential is in a locked vault, the card also offers **Unlock vault**: it opens the unlock dialog (master password or fingerprint) and the -saved secret then answers the sign-in. +saved secret then answers the sign-in. If the server expired its SSH connection +while waiting, Nocterm retries the same connection once, checks the host key +again and asks a fresh authentication question. It does not replay your old +answer. Stop or detach cancels the chat's wait. The agent receives explicit terminal descriptors: opaque terminal id, title, local/remote status, working directory when known, and selected connection diff --git a/docs/VAULT.md b/docs/VAULT.md index c50550a6..ce7bb2c0 100644 --- a/docs/VAULT.md +++ b/docs/VAULT.md @@ -36,7 +36,11 @@ A password is bound to the addresses it lists (`user@host:port`) and answers no one password can sign in to several servers. The **Credentials** tab of the Vault page lists what the vault keeps by name: **Add a password** saves one under a name for no server yet; the pencil renames any record; under a password, each server it signs in to has a cross that -detaches it; the bin deletes the record. In the connection editor, **Saved passwords** lists +detaches it; the bin deletes the record. The eye reveals the selected password while the +vault is unlocked, including passwords not yet attached to a server. Select the eye again +to hide it. Switching tabs, searching, refreshing, leaving the page or locking hides the +password. Key passphrases can be revealed too; private keys are never shown. +In the connection editor, **Saved passwords** lists the vault's passwords: choosing one signs the connection in with it and adds its address to the password when the connection is saved. A password of one address is stored as before (`"target"`), so older versions still read it; one shared by several or saved for none is @@ -99,8 +103,9 @@ bounded operation finishes. Domain secrets and KDF buffers use secrecy/zeroize; Debug output is redacted. Only encrypted revisions are retained for comparison. GPUI's password widget uses shared strings and undo storage. Inputs and undo history -are cleared on submission/lock, but the widget cannot guarantee erasure of every -previous allocation. This is not protection against a compromised running process, +are cleared on submission/lock. A revealed password is held by a zeroizing secret only +while shown, but GPUI's rendering copies and password widgets cannot guarantee erasure +of every previous allocation. This is not protection against a compromised running process, a debugger, OS swap or physical memory access. The application does not claim an independent cryptographic audit. Review of this implementation is separate from audit claims about the underlying RustCrypto primitives. diff --git a/docs/adr/0179-temporary-workspaces-from-terminal-tabs.md b/docs/adr/0179-temporary-workspaces-from-terminal-tabs.md new file mode 100644 index 00000000..8a9e94c0 --- /dev/null +++ b/docs/adr/0179-temporary-workspaces-from-terminal-tabs.md @@ -0,0 +1,42 @@ +# 0179. Terminal tabs can create session-only folder workspaces + +Status: accepted + +## Context + +A connected ordinary terminal already holds the exact connection configuration and +observed working directory. The saved workspace wizard is unnecessary for a +temporary folder scope, and the focused terminal may differ from a tab whose +context menu the user opened. + +## Decision + +Extend [0067](0067-project-tabs-with-inner-surfaces.md): a folder workspace can +also be temporary for the lifetime of the application. Its checked definition, +claims, admission and surface identity are the same as a saved workspace. +CatalogState marks temporary IDs and excludes those definitions from every +durable catalog snapshot, including shutdown. Memory-only edits use the existing +checked publication owner and refuse an outstanding durable edit rather than +overtake it. Closing its outer tab closes its sessions but leaves the definition +available in the current process; it is not restored from disk. + +A tab-context action names the exact original General Item. Projects checks +its connected parent receipt and observed absolute directory, and captures the +original session launch before opening the outer workspace. No current-tab or +different-host fallback is permitted. The workspace tab context opens the +existing definition editor. A same-host folder edit derives future terminal +launches with the new root from the original captured session, leaving existing +shells unchanged. A different host still invalidates the captured launch. + +## Alternatives + +A separate temporary tab implementation would duplicate context identity, +terminal placement, and lifetime rules. Saving and later deleting a definition +would leave temporary data on disk after a crash. Re-resolving a connection +after every directory edit could silently substitute different launch settings. + +## Consequences + +Temporary workspaces share all normal folder-workspace capabilities and limits, +including the bounded live catalog. Only persistent definitions are passed to +the repository. An unobserved directory must be reported rather than guessed. diff --git a/docs/adr/0180-descriptive-ai-context-is-bound-to-the-original-workspace.md b/docs/adr/0180-descriptive-ai-context-is-bound-to-the-original-workspace.md new file mode 100644 index 00000000..60a67219 --- /dev/null +++ b/docs/adr/0180-descriptive-ai-context-is-bound-to-the-original-workspace.md @@ -0,0 +1,44 @@ +# 0180. Descriptive AI context is bound to the original workspace + +Status: accepted + +## Context + +A saved connection's existing description reaches attached agents through the +connection directory. Users also need notes for themselves, and descriptive +context for a workspace rather than an individual connection. Chats retain their +original live surface independently of window selection. + +## Decision + +A profile retains the existing serialized `description` as AI-shared text; the +editor names that purpose explicitly. Human-only `notes` is a separate optional +persisted value and is absent from the connection directory's projections. +A workspace definition has an optional `ai_description`. Both new draft values +default to empty in existing documents and are bounded by byte length when edited. +Neither description grants execution or credential authority. + +The project feature projects its current name and AI description to the original +inner surface, alongside its other inert metadata. The chat seat reads that +projection through the exact live surface receipt when producing agent context. +A hidden live surface remains readable; a closed or replaced surface does not +redirect to another workspace. General has no workspace descriptor. + +The neutral AI context codec redacts this user text and escapes delimiter +characters just as it does connection descriptions. When present, workspace +metadata is included even with no attached terminals; the format for General +without workspace metadata does not change. + +## Alternatives + +Reusing a single connection text field for both notes and AI context would either +expose human notes to agents or remove existing agent context during migration. +Reading the selected workspace would misdescribe chats working in hidden +surfaces. Storing a copy inside chat history would create another stale authority. + +## Consequences + +Description and notes stay with their respective saved definitions; only explicitly +AI-facing text enters context. A bounded inert surface projection updates with the +definition and avoids per-render formatting or new I/O. Edits do not change project +identity, session authority or chat history ownership. diff --git a/docs/adr/0181-sign-in-waits-do-not-spend-connection-deadlines.md b/docs/adr/0181-sign-in-waits-do-not-spend-connection-deadlines.md new file mode 100644 index 00000000..cbe30fb7 --- /dev/null +++ b/docs/adr/0181-sign-in-waits-do-not-spend-connection-deadlines.md @@ -0,0 +1,55 @@ +# 0181. Sign-in waits do not spend connection deadlines + +Status: accepted + +## Context + +A chat's background connection or reconnect used a single absolute deadline: +60 seconds without a prompt, extended to 180 seconds once the user was asked to +sign in. Time spent entering a secret or unlocking the vault consumed that same +budget. The background session could be closed without completing the answer, +or before the transport had time to finish starting the shell after the answer. +Separately, an SSH server can close its unauthenticated transport while the +user is considering a question. + +## Decision + +- The chat's original connection-wait operation budgets a maximum of 60 seconds + per stretch of machine connection work. While the terminal reports a pending + user or vault question, the operation waits for human input. Leaving that + state resets the machine deadline. Transport failure, detachment, session + replacement, chat closure or Stop still terminate the original wait. +- The chat polls pending sign-in at 500 ms rather than the 150 ms connection + cadence. A prompt not expressible through the chat's existing sign-in port is + shown in the terminal tab, preserving its original receipt. +- If the SSH adapter observes that an unauthenticated link has closed when + accepting a secret answer, or the send fails because it closed, it may + establish that same route step once more. The new connection verifies its + host key again and asks its own authentication questions. It never replays + the old answer, including a keyboard-interactive code. Ordinary credential + rejection is not a reason to restart a link. The original session source + and cancellation continue to guard all work. + +This amends the sign-in timeout consequence in [0011](0011-chat-configuration.md) +and the finite operation timing in [0044](0044-private-thread-coordination.md). +The per-hop route and trust semantics of [0060](0060-ssh-jump-host-routes.md) +are unchanged. + +## Alternatives rejected + +- Extending one absolute deadline still charges time spent with the user + for the connection itself. +- Retrying the expired prompt against another SSH connection would replay + an answer without authority for its new authentication question. +- Repeated automatic reconnections would mask real connection failures and + increase work indefinitely. + +## Consequences + +A chat can remain waiting while its user enters a secret; there is no local +human-input countdown. Connection work remains bounded and the waiter retains +one original receipt and operation guard. MCP calls are limited by existing +bridge admission (one outstanding call per socket, four sockets per chat, +64 across the installation); cancellation continues checking original state. +A host that expires its sign-in grace period may require a fresh answer. +Ordinary connection attempts perform no additional handshake or caching. diff --git a/docs/adr/README.md b/docs/adr/README.md index ea0a8671..cef3ac18 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -64,7 +64,7 @@ acceptance; a later record supersedes an earlier one. | [0063](0063-agent-chats-below-the-panel.md) | Agent chats live in a service crate below the panel | | [0065](0065-retained-context-surfaces.md) | Context surfaces retain their native dock and original callback authority (whole-window selection superseded by0067) | | [0066](0066-scoped-chat-storage.md) | Scoped chat authority precedes payload discovery in versioned storage | -| [0067](0067-project-tabs-with-inner-surfaces.md) | Workspaces are outer connection tabs with independent inner terminal surfaces (footer order superseded in part by 0083) | +| [0067](0067-project-tabs-with-inner-surfaces.md) | Workspaces are outer connection tabs with independent inner terminal surfaces (footer order superseded in part by 0083; extended by 0179) | | [0069](0069-workspace-chat-launch-boundary.md) | Workspace chat scope preserves the existing local agent launch lifecycle | | [0070](0070-original-workspace-connection-recovery.md) | Workspace authentication belongs to its inner terminal | | [0071](0071-provider-workspace-locations.md) | Workspace locations retain provider identity and session authority | @@ -174,3 +174,6 @@ acceptance; a later record supersedes an earlier one. | [0176](0176-agent-previews-use-bounded-pixels.md) | Agent previews transport bounded pixels across the native display path, amending [0035](0035-injected-image-codecs.md) and [0169](0169-single-image-previews-reuse-the-inspection-decode.md) | | [0177](0177-attachment-batches-reuse-one-inspection-decode.md) | Attachment batches may reuse the final inspection decode, amending the selection scope of [0169](0169-single-image-previews-reuse-the-inspection-decode.md) | | [0178](0178-acp-budgets-inbound-and-outbound-lines-separately.md) | ACP reserves outbound line space for the Base64 expansion of an admitted image collection | +| [0179](0179-temporary-workspaces-from-terminal-tabs.md) | Terminal tabs can create session-only folder workspaces; same-host folder edits retain the captured launch (extends 0067) | +| [0180](0180-descriptive-ai-context-is-bound-to-the-original-workspace.md) | Descriptive AI context is bound to the original workspace | +| [0181](0181-sign-in-waits-do-not-spend-connection-deadlines.md) | Human sign-in waits pause connection deadlines; an expired SSH link can be verified and asked anew once | diff --git a/docs/architecture/adapter.md b/docs/architecture/adapter.md index 5ef6f085..6bc9bc13 100644 --- a/docs/architecture/adapter.md +++ b/docs/architecture/adapter.md @@ -168,7 +168,10 @@ first connection. Every hop verifies its own host key and completes authenticati before a forward is requested through it, with prompts tagged by their hop. The connection timeout applies per hop, a failure is attributed to its hop, routes over the limit are refused before any I/O, and closing the session closes the chain from the -destination outward. +destination outward. A link that expired while awaiting a secret answer can be +re-established once within the same route and source; the replacement verifies +host trust again and asks fresh questions, without replaying any answer +([ADR 0181](../adr/0181-sign-in-waits-do-not-spend-connection-deadlines.md)). Structured local commands through `HostExec::exec` start on a worker when their future is polled. The worker owns cleanup independently of output delivery or diff --git a/docs/architecture/domain.md b/docs/architecture/domain.md index 55296d7d..9664b398 100644 --- a/docs/architecture/domain.md +++ b/docs/architecture/domain.md @@ -12,7 +12,7 @@ features present them ([feature layer](feature.md)). ## Workspace folders `nocterm-project-model` owns stable workspace/context identities, checked names, -ordinary host folders, provider resource envelopes and the versioned catalog. +ordinary host folders, bounded optional AI description, provider resource envelopes and the versioned catalog. Provider references have independent schema versions and bounded inert data; unknown providers retain their references and history without acquiring a session. Import provenance grants no execution authority. Existing catalogs migrate to @@ -57,7 +57,9 @@ facts and nested `ProfileDraft` validation. Collection transitions preserve checked edit expectations, remembered folders, user ordering, credential matching and recent deduplication. Native identifiers, timestamps and editor user/home defaults are supplied through values or narrow ports. Validation -preserves typed credential, JSON, launch and session-option causes. +preserves typed credential, JSON, launch and session-option causes. Human notes and the existing +AI-shared description are separate persisted profile fields; both editor values have a 16 KiB limit. +Human notes never enter the connection directory projection or agent context. Profile encoding errors retain original typed TOML serializer causes through foundation `SharedError`; clones share the native diagnostic. Checked conflict classification and both 64 KiB mutation/profile limits remain domain rules. @@ -337,8 +339,11 @@ UI/service and native authentication contracts without workers or filesystem I/O `nocterm-vault-ui` receives an explicit `Arc`. Profiles store opaque IDs constructed from supplied bytes in `nocterm-session`. Authentication uses only matching password/key-passphrase bindings (`CredentialBinding::answers`): a password answers -the addresses it lists, so a password saved under a name may sign in to several servers, and -`VaultAccess::update` renames a record or changes those addresses while its secret stays +the addresses it lists, so a password saved under a name may sign in to several servers. +The separate management read `VaultAccess::reveal_password` requires the vault to be unlocked +and permits passwords and key passphrases, including unbound passwords, never private keys; +it does not change the authentication binding rules. `VaultAccess::update` renames a record +or changes those addresses while its secret stays (`CredentialBinding::may_become`; a key or passphrase keeps its binding) ([ADR 0151](../adr/0151-a-saved-password-signs-in-to-the-servers-it-lists.md)). Remember commits after Connected and excludes MFA. A stored SSH key is the binding `PrivateKey { public_key }`, referenced from diff --git a/docs/architecture/feature.md b/docs/architecture/feature.md index 2dcf70b4..40293fcb 100644 --- a/docs/architecture/feature.md +++ b/docs/architecture/feature.md @@ -42,9 +42,13 @@ contributions also links to the editor with its first item selected. The page also holds the User section (`UserPluginsSection`). It states whether this run loaded the user plugins (`UserSession::{Loaded, Held(HeldBy)}`, with `HeldBy::{SafeMode, NotAllowed}`), shows the "Allow user plugins" switch, which stores the choice for the next start through the narrow -`UserPluginsSwitch` port, and, in a loaded run, the install button, consent, list, detail, -removal questions and audit log through the `UserPlugins` port. A held run shows the reason and -no list. The application implements both ports; the section keeps no storage +`UserPluginsSwitch` port, and, in a loaded run, the list, detail, removal questions and audit log +through the `UserPlugins` port. The header's Add plugin action opens a modal for package selection +and consent; folder discovery starts only while that modal is open. Closing it invalidates any +late result, and reopening coalesces into one fresh listing after an in-flight folder operation +settles. A held run shows the reason, +allows opening the plugin folder, but offers no install or list. The application implements both +ports; the section keeps no storage ([ADR 0093](../adr/0093-user-plugins-start-off-and-the-api-stays-compatible.md)). `nocterm-layout-ui` owns the editor of the status bar and the panels, one section of Appearance @@ -203,7 +207,7 @@ the sidebar. Quick destinations and deleted profiles are excluded. Selecting a recent server defers opening through the normal authentication path until the workspace borrow ends. Editor sections own their address/metadata, authentication, jump hosts, launch and appearance controls and subscriptions. They project one pure domain draft, with a scrollable -active form, multiline description and fixed footer; +active form, separate multiline notes and AI description, and fixed footer; typed validation selects the section containing the invalid field. The Jump Hosts section edits the ordered route from saved connections or `user@host[:port]` addresses and reports an unresolvable route when saving. Opening a connection @@ -424,6 +428,13 @@ The local image picker shares the discovered snapshot and retains up to 25 matches for its current query. The fixed shared header retains the original server. Image sources use a single full-width bounded result viewport. +A connected General terminal's context menu creates a temporary folder workspace +from that exact terminal's observed working directory and captured launch, even +if another tab is selected. The workspace tab's context menu opens its settings. +Same-host folder edits change the root for future terminals, not existing shells; +temporary definitions live only in the current application process +([ADR 0179](../adr/0179-temporary-workspaces-from-terminal-tabs.md)). + Projects retains Workspace for outer ProjectView admission, Panel/action registration, focused source capture, General Item enumeration and connection directory projections. Its ProjectTerminal contracts and context errors are @@ -500,8 +511,11 @@ owns its cancellable status subscription. The feature handles `workspace::UnlockVault` and `workspace::LockVault` application-wide, so the palette and a terminal's sign-in prompt can unlock the vault in a small dialog without opening Settings and without depending on the -vault feature. The credential list describes a key record by its fingerprint and never shows -or saves the secret. +vault feature. The credential list describes a private key by its fingerprint, never its +secret. An explicit eye button can reveal one password or key passphrase through the vault's +separate management read. Hiding it, leaving the tab or page, refreshing or locking drops the +zeroizing secret and cancels the pending delivery; a changed vault status revision also fences +late results. The Credentials tab owns the most recent credential metadata and prepares name and server search terms when the service supplies a list. It uses a bounded @@ -578,7 +592,9 @@ return snapshots and named effects rather than mutable state. Fixed prompt attac do not follow later composer defaults. Jobs retain their original executor identity; cancellation preserves bounded readable outcomes. Terminal sign-in waits retain their prompt epoch, reconnect cleanup retains its original receipt, and background cleanup -preserves terminals promoted into ordinary tabs. Existing document, configuration, +preserves terminals promoted into ordinary tabs. A human sign-in wait does not spend +the connection deadline: each stretch of machine work has a 60-second budget, and +prompt polling uses a slower cadence ([ADR 0181](../adr/0181-sign-in-waits-do-not-spend-connection-deadlines.md)). Existing document, configuration, composer and archive owners remain separate from these responsibilities. A private reconnect dispatch owner moves accepted calls and their original busy diff --git a/docs/architecture/service.md b/docs/architecture/service.md index 87087642..f9231ac0 100644 --- a/docs/architecture/service.md +++ b/docs/architecture/service.md @@ -53,11 +53,13 @@ streams use the ordinary retry interval until a subscription stays open for that ([ADR 0131](../adr/0131-one-container-watch-per-host-connection.md), [ADR 0171](../adr/0171-container-watches-recover-once-without-waiting.md)). -`nocterm-project-service` owns the durable workspace catalog and the +`nocterm-project-service` owns the checked workspace catalog (durable and session-only definitions) and the open-window registry used to focus an already opened workspace. It uses `Persisted` and the shared shutdown coordinator. Catalog bindings identify the original committed definition so an old callback cannot open a changed folder -([ADR 0067](../adr/0067-project-tabs-with-inner-surfaces.md)). +([ADR 0067](../adr/0067-project-tabs-with-inner-surfaces.md)). Temporary definitions +use checked memory-only publication and are excluded from durable snapshots +([ADR 0179](../adr/0179-temporary-workspaces-from-terminal-tabs.md)). Preparation jobs retain their original source, operation and prepared result independently of the creation view. A failed catalog publication can retry saving without creating another resource. Process execution stays behind the supplied @@ -124,7 +126,9 @@ not eager memory allocations or an aggregate disk quota. Workspace chat scope selects document ownership, history and the original tool seat. All scopes use the existing local ACP connector, workdir preparation, -terminal sign-in and configured sandbox settings. A workspace scope does not +terminal sign-in and configured sandbox settings. AI-facing workspace metadata is read from the +chat's original live surface when preparing context, independent of selected tabs, and is +redacted alongside connection descriptions. A workspace scope does not install another agent process or change provider authentication ([ADR 0069](../adr/0069-workspace-chat-launch-boundary.md)). diff --git a/docs/reference/actions.md b/docs/reference/actions.md index 32dead14..5b17c3f4 100644 --- a/docs/reference/actions.md +++ b/docs/reference/actions.md @@ -51,10 +51,12 @@ Derived from `actions!` declarations, `#[derive(Action)]` types and `assets/keym | `workspace::CloseTabsRight` | Close tabs to the right of the active tab in its pane. | | | `workspace::CloseWindow` | Close this window. | `ctrl-alt-w` (linux, windows; Workspace); `cmd-shift-w` (macos; Workspace) | | `workspace::CopyConnectionName` | Copy the displayed connection name or alias. | | +| `workspace::CreateWorkspaceFromTab` | Create a temporary workspace from the original terminal tab, not the focused tab. | | | `workspace::DefaultSessionSettings` | Edit default session options. | | | `workspace::DisconnectSession` | Disconnect the focused session. | | | `workspace::EditCopy` | Copy the current terminal selection. | | | `workspace::EditPaste` | Paste the clipboard into the focused terminal. | | +| `workspace::EditWorkspaceFromTab` | Edit the definition of the original outer workspace tab. | | | `workspace::Find` | Open terminal search. | `ctrl-shift-f` (linux, windows; Workspace); `cmd-f` (macos; Workspace) | | `workspace::FindNext` | Select the next search match. | `f3` (linux, windows; Workspace); `f3` (macos; Workspace) | | `workspace::FindNextSelection` | Search for the current terminal selection. | `ctrl-f3` (linux, windows; Workspace); `cmd-f3` (macos; Workspace) | diff --git a/src/bootstrap/credential_tests.rs b/src/bootstrap/credential_tests.rs index 4332b094..13bfbb17 100644 --- a/src/bootstrap/credential_tests.rs +++ b/src/bootstrap/credential_tests.rs @@ -11,6 +11,7 @@ fn history_profile(target: Target) -> nocterm_connections_model::profiles::Profi id: nocterm_connections_model::profiles::ProfileId::from_bytes([7; 16]), name: "History".into(), description: String::new(), + notes: String::new(), options: Default::default(), target, auth: Auth::Password, diff --git a/src/connection_setup/tests.rs b/src/connection_setup/tests.rs index 50c9b2a9..bee94690 100644 --- a/src/connection_setup/tests.rs +++ b/src/connection_setup/tests.rs @@ -49,6 +49,7 @@ fn profile(name: &str) -> Profile { id: nocterm_connections_model::test_support::profile_id_for(name), name: name.into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", "host", 22), auth: Auth::Password, diff --git a/src/gui_tests/hub_account.rs b/src/gui_tests/hub_account.rs index 8065bae9..b9e2213e 100644 --- a/src/gui_tests/hub_account.rs +++ b/src/gui_tests/hub_account.rs @@ -37,6 +37,7 @@ pub(super) fn profile(name: &str) -> Profile { id: profile_id_for(name), name: name.into(), description: String::new(), + notes: String::new(), options: Default::default(), target: Target::new("ci", format!("{name}.example"), 22), auth: Auth::Password, diff --git a/src/gui_tests/project_workspaces.rs b/src/gui_tests/project_workspaces.rs index daf087c7..bb9fbbed 100644 --- a/src/gui_tests/project_workspaces.rs +++ b/src/gui_tests/project_workspaces.rs @@ -251,6 +251,7 @@ fn definition(host: HostLocator) -> ProjectDefinition { ProjectDraft { id: ProjectId::from_bytes([1; 16]), name: "Test workspace".into(), + ai_description: String::new(), target: nocterm_project_model::ProjectTarget::HostFolder { host, root: RootPath::parse("/home/test/project").unwrap(), diff --git a/src/gui_tests/project_workspaces/reconnection.rs b/src/gui_tests/project_workspaces/reconnection.rs index 5b5db899..b78e4239 100644 --- a/src/gui_tests/project_workspaces/reconnection.rs +++ b/src/gui_tests/project_workspaces/reconnection.rs @@ -158,6 +158,7 @@ fn saved_server() -> nocterm_connections_model::profiles::Profile { id: ProfileId::from_bytes([9; 16]), name: "Original SSH server".into(), description: String::new(), + notes: String::new(), target: nocterm_session::Target::new("test", "destination.example", 22), auth: nocterm_session::Auth::Password, group: None, diff --git a/vendor/gpui-component/src/dock/panel.rs b/vendor/gpui-component/src/dock/panel.rs index 678f8cc6..61885c20 100644 --- a/vendor/gpui-component/src/dock/panel.rs +++ b/vendor/gpui-component/src/dock/panel.rs @@ -23,7 +23,7 @@ use gpui::{ AnyElement, AnyView, App, Context, Entity, FocusHandle, Hsla, IntoElement, SharedString, WeakEntity, Window, }; -use gpui_base::dock::{PanelId, PanelState, TabGroup}; +use gpui_base::dock::{DragPanel, PanelId, PanelState, TabGroup}; use rust_i18n::t; use crate::{button::Button, menu::PopupMenu}; @@ -95,6 +95,18 @@ pub trait Panel: gpui_base::dock::Panel { None } + /// Handle a panel dropped on the center of this tab, rather than performing + /// the ordinary native reorder. Hosts may implement their own tab grouping + /// semantics. Returning false leaves the native drop unchanged. + fn on_tab_drop( + &mut self, + drag: &DragPanel, + window: &mut Window, + cx: &mut Context, + ) -> bool { + false + } + /// An element pinned to the trailing end of the title bar. fn title_suffix( &mut self, @@ -177,6 +189,9 @@ pub trait PanelView: gpui_base::dock::PanelView { fn title(&self, window: &mut Window, cx: &mut App) -> AnyElement; fn title_style(&self, cx: &App) -> Option; fn tab_accent(&self, cx: &App) -> Option; + fn on_tab_drop(&self, _drag: &DragPanel, _window: &mut Window, _cx: &mut App) -> bool { + false + } fn title_suffix(&self, window: &mut Window, cx: &mut App) -> Option; fn toolbar_buttons(&self, window: &mut Window, cx: &mut App) -> Option>; fn menu_visible(&self, _cx: &App) -> bool { @@ -208,6 +223,10 @@ impl PanelView for Entity { self.read(cx).tab_accent(cx) } + fn on_tab_drop(&self, drag: &DragPanel, window: &mut Window, cx: &mut App) -> bool { + self.update(cx, |this, cx| this.on_tab_drop(drag, window, cx)) + } + fn title_suffix(&self, window: &mut Window, cx: &mut App) -> Option { self.update(cx, |this, cx| { this.title_suffix(window, cx) diff --git a/vendor/gpui-component/src/dock/tab_panel.rs b/vendor/gpui-component/src/dock/tab_panel.rs index 76fb32eb..2ffca136 100644 --- a/vendor/gpui-component/src/dock/tab_panel.rs +++ b/vendor/gpui-component/src/dock/tab_panel.rs @@ -385,6 +385,7 @@ impl TabGroupSkin { this.when_some(drag, |this, drag| { this.on_drag(drag, { let visual = visual.clone(); + let source = source.clone(); move |drag, offset, _, cx| { source.start( drag, @@ -397,22 +398,29 @@ impl TabGroupSkin { }) .when(droppable, |this| { this.drag_over::(|this, _, _, cx| { - this.rounded_l_none() - .border_l_2() - .border_r_0() - .border_color(cx.theme().drag_border) + // A color-only highlight leaves both the hit area and + // neighboring tabs where the user saw them before dragging. + this.bg(cx.theme().tokens.drop_target) }) .on_drop({ let group = Rc::clone(&context); + let target = panel.clone(); + let source = source.clone(); move |drag: &DragPanel, window, cx| { + if source.is_center(window.mouse_position()) + && PanelHandle::of(&target).is_some_and(|target| { + target.on_tab_drop(drag, window, cx) + }) + { + return; + } group.drop_panel(drag.clone(), Some(ix), true, window, cx); } }) .drag_over::(|this, _, _, cx| { - this.rounded_l_none() - .border_l_2() - .border_r_0() - .border_color(cx.theme().drag_border) + // A color-only highlight leaves both the hit area and + // neighboring tabs where the user saw them before dragging. + this.bg(cx.theme().tokens.drop_target) }) .on_drop({ let group = Rc::clone(&context); diff --git a/vendor/gpui-component/src/dock/tab_panel/drag_preview.rs b/vendor/gpui-component/src/dock/tab_panel/drag_preview.rs index f016b5eb..5f77bb18 100644 --- a/vendor/gpui-component/src/dock/tab_panel/drag_preview.rs +++ b/vendor/gpui-component/src/dock/tab_panel/drag_preview.rs @@ -9,7 +9,7 @@ use crate::{ }; use gpui::{ AnyElement, App, AppContext as _, Bounds, Context, Div, Entity, Hsla, InteractiveElement as _, - IntoElement, ParentElement as _, Pixels, Point, Render, Size, Stateful, Styled as _, TextStyle, + IntoElement, ParentElement as _, Pixels, Point, Render, Stateful, Styled as _, TextStyle, Window, div, prelude::FluentBuilder as _, px, }; use gpui_base::{ @@ -20,7 +20,7 @@ use std::{cell::RefCell, rc::Rc, sync::Arc}; #[derive(Clone)] struct Appearance { - size: Size, + bounds: Bounds, typography: TextStyle, } @@ -30,11 +30,20 @@ pub(super) struct PaintedSource(Rc>>); impl PaintedSource { pub fn capture(&self, bounds: Bounds, window: &Window) { *self.0.borrow_mut() = Some(Appearance { - size: bounds.size, + bounds, typography: window.text_style(), }); } + /// Reserve the outer quarters of a tab for native reordering. + pub fn is_center(&self, point: Point) -> bool { + self.0.borrow().as_ref().is_some_and(|appearance| { + let bounds = appearance.bounds; + let quarter = bounds.size.width / 4.; + point.x >= bounds.left() + quarter && point.x <= bounds.right() - quarter + }) + } + pub fn start( &self, drag: &DragPanel, @@ -49,7 +58,7 @@ impl PaintedSource { .clone() .expect("a dock drag source was painted"); drag.set_drag_offset(offset); - drag.set_preview_size(appearance.size); + drag.set_preview_size(appearance.bounds.size); let background = content.background(cx); cx.new(|_| DragPanelPreview { appearance, @@ -162,7 +171,7 @@ pub struct DragPanelPreview { impl Render for DragPanelPreview { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { - let size = self.appearance.size; + let size = self.appearance.bounds.size; let typography = &self.appearance.typography; let mut root = div() .id("drag-panel") diff --git a/vendor/gpui-component/src/dock/tab_panel/drag_preview/tests.rs b/vendor/gpui-component/src/dock/tab_panel/drag_preview/tests.rs index bd4dd080..5f0da760 100644 --- a/vendor/gpui-component/src/dock/tab_panel/drag_preview/tests.rs +++ b/vendor/gpui-component/src/dock/tab_panel/drag_preview/tests.rs @@ -274,3 +274,29 @@ fn native_single_panel_title_preview_preserves_actual_title_surface(cx: &mut Tes let (cx, captured) = fixture(cx, false, false, true); assert_native_preview(cx, captured, "dock-title-drag-source", false); } + +#[gpui::test] +fn dragging_over_a_floating_tab_preserves_its_drop_geometry(cx: &mut TestAppContext) { + let (cx, _) = fixture(cx, true, false, false); + let source = cx.debug_bounds("dock-tab-drag-source-0").unwrap(); + let target = cx.debug_bounds("dock-tab-drag-source-1").unwrap(); + let start = source.origin + point(px(18.), px(10.)); + cx.simulate_mouse_move(start, None, Modifiers::none()); + cx.simulate_mouse_down(start, MouseButton::Left, Modifiers::none()); + cx.simulate_mouse_move( + start + point(px(18.), px(0.)), + MouseButton::Left, + Modifiers::none(), + ); + cx.run_until_parked(); + cx.simulate_mouse_move(target.center(), MouseButton::Left, Modifiers::none()); + cx.run_until_parked(); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + cx.debug_bounds("dock-tab-drag-source-1").unwrap(), + target, + "a drop highlight must not resize the target under the cursor" + ); + cx.simulate_mouse_up(target.center(), MouseButton::Left, Modifiers::none()); + cx.run_until_parked(); +} diff --git a/vendor/patches/gpui-component/0017-stable-tab-drop-geometry.patch b/vendor/patches/gpui-component/0017-stable-tab-drop-geometry.patch new file mode 100644 index 00000000..d6e2590a --- /dev/null +++ b/vendor/patches/gpui-component/0017-stable-tab-drop-geometry.patch @@ -0,0 +1,63 @@ +diff --git a/src/dock/panel.rs b/src/dock/panel.rs +index 678f8cc615185f2dc977b1cced1feb062b3617a2..61885c20fa8a781ba017749621328ef6a0f0b94c 100644 +GIT binary patch +delta 478 +zcmZvYy-EX75QPb(ki?J_niM8*K!^dC-A*C3MX(YpyY(hJ`vbdkm%BI76p{x>d0)ap +zK?wLNHWn#TSn3lfcM%D}DbLLL&S931mDlIW%cfetP$Ie#OsRv_rrOwBj06WMK_Is( +z0wwdD0!W6A2@_&X3NnO_lLA_d9Vnq=QqZwr24blJmjrnYi%vrlxwJEFh +z{&($U8_+K(4ITKqHV3}BJw2@Xllx%_hgtVJ^|ERi`mlQI+*FVMVeO*KS7%^8dIx6N +WZFlVJ-EEV-c3_@*M=P)Ue*ObpD5T;5 + +delta 29 +lcmdnCma%&U@ + +diff --git a/src/dock/tab_panel.rs b/src/dock/tab_panel.rs +index 76fb32eb018ee786cf5474eaa749f805248b32ec..2ffca1364bb21390ff81084656ba6d89e2f59b70 100644 +GIT binary patch +delta 553 +zcmd5&JxT*X7$p)!3xkCsTF9rxW<}h@B84$wO$?&gXsOLQ>wei8*vu?56GK2SXYeb< +zI|On8!3$X02x70bowC`|3s}C#YrRcmwfaydI$^8Fcl +zY|eQ~?QK^7L5%W-KA!D#CG%(<( +zaVqZ{)L_^k13d__t29ESSsV))dzk_K9Q#zQ6=_^wnHCyd7U{FYv!W%-bc`07kTQu0 +zwe~l2$=?n1eR7c5Y>O@!)z{bP2@_nSw5Z*IkdYdAJ=HfDq{;{@lytYKb-qTazgTe` +zILiW#nT!&w*Hzbb^60J1#i$+zOh)c)PSSgO`rS$nJtYIn!XVNrb+c_WyjrK!U#4n1 +i@B7hqrW3y|;QnZVo=#Wk>U5jRhtL1%^~q<)DgOe_*TzNw + +delta 221 +zcmbPzmvQn9#tnS-lk5H2CO7!7Y!0=zW}3X-n3b<6zceo;H6=bLJ}*Bnb+V(0^dv7{ +zuB7~;l+>d5oOmOs$Yg6%PDTS5XS%5bYf4dKdi><|rYe&^I7m-E5X3rJ#$RpngjkNr +g3*4P2H~2VAHZWzGydj2da=q&v8ds%@B-jN(rIs`vQm!p&0~LY8@&J+2klczTL6g!UX(8vV0{}@HAd(QqpOLhrot~jM +zIzys_v_nkuG@6Pv#b)B7KS7{WjHg1o%Nyi4J79G3~>8+A`Um!Y%a +zNkUw6IipP}t|BIjy(NtChp~O_vKUlF&X(>lMzAY>g&FZkY$ZawfQJG5FDZPmH74V7 +z3X3VSj*HW}Q?FN3qngrUzR0nDh1H8}-Qv0Jbh7W(S9OoYq$Sjx9~t=JY5UpdOBzFlI2#i5t4|5>_i;y5#h}eku3)b~AcUeqs&)K-l8~i77`BHG2VIJ?zdoy3>&sQIp`|hn-8;nUMiB1z~=15Y>cxn`vGpie!5n7}< +zTB+H}F_}yzXlBUt;J#bnwp*1W8Ne~by5O8pL`4Ufa_m5?rgq(e(G~!}6dA0^DMEMR +z)q5to4O!iUWrA>thrM>t&C`2QnfN1OMG0~#a;DX&Y$y)BPxs{ey~X;nEGuF-gv{ua +zMOKLZpc`}`D@3mw1f4a{sip_(0WQo~#~R5Fhp9-|We%*JrRZBK8e|=Y%Y;r(bLHSjf=wve0$%J8+TZYsy5L*3+ +ez!O}lAWz3g3n0qL8fq_G-K)1-%QNvm<=GF7+nDkI + +delta 7 +OcmeASJnyl=Uj+aSsRI=N + +# End of generated Nocterm binary patch. diff --git a/vendor/patches/sources.json b/vendor/patches/sources.json index 05aaf067..11f87343 100644 --- a/vendor/patches/sources.json +++ b/vendor/patches/sources.json @@ -289,7 +289,8 @@ "vendor/patches/gpui-component/0013-prepare-tab-styles-on-demand.patch", "vendor/patches/gpui-component/0014-settle-switch-within-physical-pixel.patch", "vendor/patches/gpui-component/0015-prepare-button-styles-on-demand.patch", - "vendor/patches/gpui-component/0016-migrate-jiff.patch" + "vendor/patches/gpui-component/0016-migrate-jiff.patch", + "vendor/patches/gpui-component/0017-stable-tab-drop-geometry.patch" ], "omitted": [] }, diff --git a/xtask/baseline.toml b/xtask/baseline.toml index 05d5cbce..8645d83b 100644 --- a/xtask/baseline.toml +++ b/xtask/baseline.toml @@ -21,7 +21,7 @@ nocterm-themes = 1 nocterm-ui = 2 nocterm-vault-broker = 1 nocterm-vt = 2 -nocterm-workspace = 4 +nocterm-workspace = 3 [domain_dependencies]