You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by lu...@apache.org on 2026/10/13 06:18:44 UTC
(maka) branch feat/desktop-gpui-shell updated: feat(desktop-gpui): open the file paths a reply names
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-gpui-shell
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/desktop-gpui-shell by this push:
new f1f0b99fe7 feat(desktop-gpui): open the file paths a reply names
f1f0b99fe7 is described below
commit f1f0b99fe770110c956de3615a8103621a166aeb
Author: Xun Lu <lu...@apache.org>
AuthorDate: Tue Oct 13 10:09:01 2026 +0800
feat(desktop-gpui): open the file paths a reply names
A file a script writes is never an Artifact, so when a reply named its
deliverable as inline code, nothing in the window led to it. On a Host
on this machine, paths in a settled reply now open when clicked:
- Once a reply has finished streaming, one background pass checks its
inline code spans that are wholly a path (absolute, `~/`, or relative
to the task's folder) and its links to `file:` URLs or plain paths.
Those naming something that exists become links with the client's
own `maka-file:` scheme in a copy of the reply's Markdown, still drawn
as a code chip. Selection copies the path as shown; find searches the
reply's own text and maps its ranges onto the copy.
- A click decides again from the file there, symlinks resolved: nothing
there says so; text, source, an HTML page or an image previews in the
Files face with Show in Finder and Copy Path; a document on a fixed
list (Office, iWork, OpenDocument, PDF, CSV, RTF, EPUB) opens in the
default app; a folder, a bundle or anything else shows in Finder.
Nothing off the list is opened or launched, whatever the link says.
- A Host elsewhere gets nothing: its paths are not this machine's.
A finished call's note now reads "Details appear when this answer
finishes", in Desktop's word for a turn, and the model picker's busy
tooltip takes Desktop's wording.
Generated-by: Claude Code
---
apps/desktop-gpui/CHANGELOG.md | 3 +
apps/desktop-gpui/crates/app/src/find_tests.rs | 8 +-
apps/desktop-gpui/crates/app/src/lib.rs | 2 +
.../crates/app/src/reply_path_tests.rs | 219 ++++++++
apps/desktop-gpui/crates/app/src/tests.rs | 2 +-
apps/desktop-gpui/crates/app/src/workbar_tests.rs | 2 +-
.../crates/app/src/workbench/workbar.rs | 51 +-
.../desktop-gpui/crates/conversation/src/corpus.rs | 2 +-
.../crates/conversation/src/corpus/markdown.rs | 2 +-
apps/desktop-gpui/crates/conversation/src/lib.rs | 4 +
apps/desktop-gpui/crates/conversation/src/paths.rs | 581 +++++++++++++++++++++
apps/desktop-gpui/crates/conversation/src/rows.rs | 11 +-
apps/desktop-gpui/crates/conversation/src/tests.rs | 3 +-
.../crates/conversation/src/tests/find.rs | 8 +-
.../crates/conversation/src/tests/paths.rs | 222 ++++++++
apps/desktop-gpui/crates/conversation/src/view.rs | 193 ++++++-
.../crates/conversation/src/view/text_views.rs | 34 +-
apps/desktop-gpui/crates/files/src/desk.rs | 30 +-
apps/desktop-gpui/crates/files/src/lib.rs | 7 +-
apps/desktop-gpui/crates/files/src/local.rs | 201 +++++++
apps/desktop-gpui/crates/files/src/policy.rs | 127 ++++-
apps/desktop-gpui/crates/files/src/preview.rs | 219 +++++++-
apps/desktop-gpui/crates/files/src/read.rs | 2 +
apps/desktop-gpui/crates/files/src/view.rs | 197 +++++--
apps/desktop-gpui/crates/files/src/view_tests.rs | 203 ++++++-
.../crates/shared/src/copy/conversation.rs | 20 +-
apps/desktop-gpui/crates/shared/src/copy/files.rs | 33 +-
apps/desktop-gpui/crates/shared/src/links.rs | 24 +-
apps/desktop-gpui/docs/plan/phase-4-modules.md | 17 +-
29 files changed, 2284 insertions(+), 143 deletions(-)
diff --git a/apps/desktop-gpui/CHANGELOG.md b/apps/desktop-gpui/CHANGELOG.md
index faacb00ea2..e5480491b0 100644
--- a/apps/desktop-gpui/CHANGELOG.md
+++ b/apps/desktop-gpui/CHANGELOG.md
@@ -178,6 +178,9 @@ The version lives only in the workspace `Cargo.toml`. A release moves the
- Files (⌘P): the task's files, with a preview of each and its actions.
HTML pages show rendered or as source (no scripts or styles) and open in
the default app.
+ - On a Host on this machine, a file path a reply names opens when
+ clicked: previewed in Files, opened in the default app (documents
+ only), or shown in Finder.
- Trace: the task's trace, usage and context window, as Maka Desktop's
Inspector shows them.
- Terminal: terminals the Host runs for the task, drawn as Zed draws
diff --git a/apps/desktop-gpui/crates/app/src/find_tests.rs b/apps/desktop-gpui/crates/app/src/find_tests.rs
index 39b1239d43..66df08b4c7 100644
--- a/apps/desktop-gpui/crates/app/src/find_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/find_tests.rs
@@ -34,10 +34,16 @@ use serde_json::{Value, json};
/// Task `s1`'s `subscription.open`: one settled turn in its tail.
fn open_with_a_turn() -> Value {
+ open_with_reply("The **needle** is here.")
+}
+
+/// Task `s1`'s `subscription.open`: one settled turn in its tail, whose
+/// reply (item `t1-a`) is `reply`.
+pub(crate) fn open_with_reply(reply: &str) -> Value {
let rows = [
json!({"type": "user", "id": "t1", "turnId": "t1", "ts": 1, "text": "Where is the needle?"}),
json!({"type": "assistant", "id": "t1-a", "turnId": "t1", "ts": 2,
- "text": "The **needle** is here.", "contentOrder": ["text"], "modelId": "m"}),
+ "text": reply, "contentOrder": ["text"], "modelId": "m"}),
json!({"type": "turn_state", "id": "t1-end", "turnId": "t1", "ts": 3,
"status": "completed"}),
];
diff --git a/apps/desktop-gpui/crates/app/src/lib.rs b/apps/desktop-gpui/crates/app/src/lib.rs
index 1914288a89..60ab0c1803 100644
--- a/apps/desktop-gpui/crates/app/src/lib.rs
+++ b/apps/desktop-gpui/crates/app/src/lib.rs
@@ -280,6 +280,8 @@ mod host_switch_tests;
#[cfg(test)]
mod pet_tests;
#[cfg(test)]
+mod reply_path_tests;
+#[cfg(test)]
mod review_tests;
#[cfg(test)]
mod search_tests;
diff --git a/apps/desktop-gpui/crates/app/src/reply_path_tests.rs b/apps/desktop-gpui/crates/app/src/reply_path_tests.rs
new file mode 100644
index 0000000000..36b1ae2338
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/reply_path_tests.rs
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! Paths a reply names, in the window: on a Host on this machine a click
+//! on one goes to the Files face, which previews a Markdown file there and
+//! shows itself, or only shows a script in Finder, even through a link the
+//! agent wrote with the client's own scheme. The face's desk is stubbed:
+//! nothing opens or shows on the machine running the tests. On a Host
+//! elsewhere the same reply is text.
+
+// Tests write their scratch files, and the changes' read checks the task
+// folder on the blocking pool.
+#![allow(clippy::disallowed_methods)]
+
+use std::cell::RefCell;
+use std::path::{Path, PathBuf};
+use std::rc::Rc;
+use std::sync::Arc;
+
+use files::Desk;
+use gpui_kit::test::TestWindowExt as _;
+use gpui_kit::{App, ElementId, TestAppContext, point, px};
+use host_protocol::{AccessCredential, RemoteTransport};
+use workspace::{RemoteHost, RemoteHostProfile, WindowHost};
+
+use crate::chrome_tests::row;
+use crate::find_tests::open_with_reply;
+use crate::tests::{Harness, ScriptedHost, session, settle};
+use crate::workbar_tests::NoGit;
+
+/// A task folder holding `notes.md` and `run.command`, removed when
+/// dropped.
+struct Folder(PathBuf);
+
+impl Folder {
+ fn new() -> Self {
+ let folder =
+ std::env::temp_dir().join(format!("maka-app-reply-paths-{}", uuid_like())).join("demo");
+ std::fs::create_dir_all(&folder).expect("folder");
+ let folder = std::fs::canonicalize(folder).expect("canonical");
+ std::fs::write(folder.join("notes.md"), "# Notes\n\nReady.").expect("notes");
+ std::fs::write(folder.join("run.command"), "#!/bin/sh\n").expect("command");
+ Self(folder)
+ }
+
+ fn path(&self) -> &Path {
+ &self.0
+ }
+}
+
+impl Drop for Folder {
+ fn drop(&mut self) {
+ if let Some(parent) = self.0.parent() {
+ std::fs::remove_dir_all(parent).ok();
+ }
+ }
+}
+
+/// A name no other run uses.
+fn uuid_like() -> String {
+ let nanos = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock")
+ .as_nanos();
+ format!("{}-{nanos}", std::process::id())
+}
+
+/// What the Files face handed to the default app and to Finder.
+#[derive(Default)]
+struct DeskLog {
+ opened: RefCell<Vec<PathBuf>>,
+ revealed: RefCell<Vec<PathBuf>>,
+}
+
+/// The window on `window_host` with task `s1`, run in `folder`, selected;
+/// its one reply is `reply`.
+fn window_with_reply(
+ window_host: WindowHost,
+ folder: &Path,
+ reply: &str,
+ cx: &mut TestAppContext,
+) -> (Harness, Rc<DeskLog>) {
+ let path = folder.to_str().expect("utf-8");
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", path, "active")]);
+ transport.reply("subscription.open", Ok(open_with_reply(reply)));
+ cx.executor().allow_parking();
+ let harness = Harness::on_host(transport, window_host, cx);
+ let log = Rc::new(DeskLog::default());
+ let desk = {
+ let (opened, revealed) = (log.clone(), log.clone());
+ Desk::new(
+ Rc::new(|_: &str, cx: &mut App| cx.spawn(async |_| None)),
+ Rc::new(move |path: &Path, _: &mut App| opened.opened.borrow_mut().push(path.into())),
+ None,
+ )
+ .with_reveal(Rc::new(move |path: &Path, _: &mut App| {
+ revealed.revealed.borrow_mut().push(path.into());
+ }))
+ };
+ harness.workbench.update(cx, |workbench, cx| {
+ workbench.review_panel().update(cx, |panel, _| panel.set_git_runner(Arc::new(NoGit)));
+ workbench.files_view().update(cx, |files, _| files.set_desk(desk));
+ });
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ frames(&harness, cx);
+ (harness, log)
+}
+
+/// Lets the reply's check, its text view's parse and what a click set off
+/// land.
+fn frames(harness: &Harness, cx: &mut TestAppContext) {
+ for _ in 0..4 {
+ harness.with_window(cx, |_, _| {});
+ settle(cx);
+ }
+}
+
+fn reply_id() -> ElementId {
+ conversation::item_element_id("t1", &transcript_model::ItemKey::Text("t1-a".into()))
+}
+
+/// Clicks the start of the reply's first line.
+fn click_reply(harness: &Harness, cx: &mut TestAppContext) {
+ harness.with_window(cx, |window, cx| window.click_at(reply_id(), point(px(16.), px(10.)), cx));
+ frames(harness, cx);
+}
+
+/// The file on this machine the Files face previews.
+fn previewed(harness: &Harness, cx: &mut TestAppContext) -> Option<PathBuf> {
+ harness.workbench.read_with(cx, |workbench, cx| {
+ let files = workbench.files_view().read(cx);
+ files
+ .preview()
+ .and_then(|preview| preview.read(cx).source().local().map(|file| file.path.clone()))
+ })
+}
+
+/// Whether the panel shows, on the Files face.
+fn files_shown(harness: &Harness, cx: &mut TestAppContext) -> bool {
+ harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.workbar_shown(cx)
+ && workbench.strip_tabs(cx).iter().any(|(key, _, shown)| key == "files" && *shown)
+ })
+}
+
+fn remote_host() -> WindowHost {
+ let transport = RemoteTransport::tls("wss://box.example.com/runtime-host").expect("tls");
+ let profile =
+ RemoteHostProfile::new("box", "Box", &"a".repeat(64), transport).expect("profile");
+ let credential = AccessCredential::new("mrha_x").expect("credential");
+ WindowHost::Remote(RemoteHost::new(profile, credential))
+}
+
+/// A Markdown path in the task folder, relative as the agent wrote it,
+/// opens the Files face on a preview of the file there.
+#[gpui_kit::test]
+fn a_markdown_path_in_a_reply_previews_the_file_in_the_files_face(cx: &mut TestAppContext) {
+ let folder = Folder::new();
+ let (harness, log) =
+ window_with_reply(WindowHost::Local, folder.path(), "`notes.md` is ready.", cx);
+ assert!(!files_shown(&harness, cx));
+ click_reply(&harness, cx);
+ assert_eq!(previewed(&harness, cx), Some(folder.path().join("notes.md")));
+ assert!(files_shown(&harness, cx), "the face shows the preview");
+ let name = harness.with_window(cx, |window, _| {
+ window.try_find("files-preview-name").and_then(|name| name.label().map(str::to_owned))
+ });
+ assert_eq!(name.as_deref(), Some("notes.md"));
+ assert!(log.opened.borrow().is_empty() && log.revealed.borrow().is_empty());
+}
+
+/// A link the agent wrote with the client's own scheme to a script only
+/// shows the script in Finder: nothing runs, and the face stays as it was.
+#[gpui_kit::test]
+fn an_agent_written_link_to_a_script_only_shows_it_in_finder(cx: &mut TestAppContext) {
+ let folder = Folder::new();
+ let (harness, log) = window_with_reply(
+ WindowHost::Local,
+ folder.path(),
+ "[Run the setup script now](maka-file:run.command)",
+ cx,
+ );
+ click_reply(&harness, cx);
+ assert_eq!(*log.revealed.borrow(), [folder.path().join("run.command")]);
+ assert!(log.opened.borrow().is_empty(), "nothing is opened or launched");
+ assert_eq!(previewed(&harness, cx), None);
+ assert!(!files_shown(&harness, cx));
+ assert_eq!(cx.opened_url(), None);
+}
+
+/// On a Host elsewhere a path in a reply is text, even one that exists on
+/// this machine: a click does nothing.
+#[gpui_kit::test]
+fn a_remote_hosts_reply_names_no_path(cx: &mut TestAppContext) {
+ let folder = Folder::new();
+ let notes = folder.path().join("notes.md");
+ let reply = format!("`{}` is ready.", notes.display());
+ let (harness, log) = window_with_reply(remote_host(), folder.path(), &reply, cx);
+ click_reply(&harness, cx);
+ assert_eq!(previewed(&harness, cx), None);
+ assert!(!files_shown(&harness, cx));
+ assert!(log.opened.borrow().is_empty() && log.revealed.borrow().is_empty());
+}
diff --git a/apps/desktop-gpui/crates/app/src/tests.rs b/apps/desktop-gpui/crates/app/src/tests.rs
index 5d99e7321b..955bdf6c42 100644
--- a/apps/desktop-gpui/crates/app/src/tests.rs
+++ b/apps/desktop-gpui/crates/app/src/tests.rs
@@ -449,7 +449,7 @@ impl Harness {
}
/// The window on `window_host`, whose requests go to `transport`.
- fn on_host(
+ pub(crate) fn on_host(
transport: Arc<ScriptedHost>,
window_host: WindowHost,
cx: &mut TestAppContext,
diff --git a/apps/desktop-gpui/crates/app/src/workbar_tests.rs b/apps/desktop-gpui/crates/app/src/workbar_tests.rs
index 0b03acd4e5..bc5505249b 100644
--- a/apps/desktop-gpui/crates/app/src/workbar_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/workbar_tests.rs
@@ -46,7 +46,7 @@ use crate::tests::{EPOCH, Harness, ScriptedHost, artifact, frame, session, settl
/// Git that fails at once: the changes' face shows its failure, and no
/// read waits on a subprocess.
-struct NoGit;
+pub(crate) struct NoGit;
impl GitRunner for NoGit {
fn run(&self, _: &Path, _: &[String]) -> Boxed<Result<GitOutput, GitError>> {
diff --git a/apps/desktop-gpui/crates/app/src/workbench/workbar.rs b/apps/desktop-gpui/crates/app/src/workbench/workbar.rs
index ce7493fb9e..26f146d8ea 100644
--- a/apps/desktop-gpui/crates/app/src/workbench/workbar.rs
+++ b/apps/desktop-gpui/crates/app/src/workbench/workbar.rs
@@ -68,13 +68,20 @@
//! stays, as Desktop's are; a settled turn and a subagent's writeback read
//! them again. The trace is read while its face shows and refreshed from
//! the task's own signals while it stays.
+//!
+//! On a Host on this machine the paths the task's replies name are links
+//! (the conversation's, resolved under the home folder and the task's
+//! folder), and a click on one goes to the Files face, which opens the
+//! file, shows it in Finder, or previews it and is shown
+//! ([`files::FilesView::open_path`]).
use std::cell::Cell;
use std::collections::BTreeSet;
+use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
-use conversation::{ConversationEvent, ConversationViewEvent};
+use conversation::{ConversationEvent, ConversationViewEvent, LocalPaths};
use files::{FilesView, FilesViewEvent};
use gpui_kit::assets::IconName as AssetIcon;
use gpui_kit::component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
@@ -458,15 +465,19 @@ impl Workbench {
),
// Escape in the file list gives the conversation its place
// back: a maximized panel restored, else the panel hidden and
- // the composer focused.
+ // the composer focused. A file a reply names, previewed, shows.
cx.subscribe_in(&files, window, |this, _, event: &FilesViewEvent, window, cx| {
- if matches!(event, FilesViewEvent::Dismiss) {
- if this.workbar_maximized(cx) {
- this.set_workbar_maximized(false, window, cx);
- } else {
- this.set_workbar_open(false, window, cx);
- this.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ match event {
+ FilesViewEvent::Dismiss => {
+ if this.workbar_maximized(cx) {
+ this.set_workbar_maximized(false, window, cx);
+ } else {
+ this.set_workbar_open(false, window, cx);
+ this.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ }
}
+ FilesViewEvent::Show => this.show_files(window, cx),
+ _ => {}
}
}),
// Escape in the trace does what it does in the file list.
@@ -506,6 +517,15 @@ impl Workbench {
this.stage_side_quote(folded, turn_id.clone(), window, cx);
}
}
+ // A path a reply names, clicked: the Files face does
+ // what the file there now asks. Only a Host on this
+ // machine names paths here.
+ ConversationViewEvent::OpenPath { path } if !this.host.read(cx).is_remote() => {
+ let path = path.clone();
+ this.workbar
+ .files
+ .update(cx, |files, cx| files.open_path(path, window, cx));
+ }
_ => {}
},
),
@@ -1105,6 +1125,7 @@ impl Workbench {
/// it, and reads it if it is a different task (the panel only while it
/// shows).
pub(super) fn sync_review_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.sync_reply_paths(cx);
let remote = self.host.read(cx).is_remote();
let target = self.catalog.read(cx).selected_row().map(|row| {
if remote {
@@ -1132,6 +1153,20 @@ impl Workbench {
self.refresh_review(window, cx);
}
+ /// Hands the conversation where the paths its replies name lie: the
+ /// home folder and the selected task's folder (the context strip's)
+ /// on a Host on this machine; nowhere on a Host elsewhere, whose paths
+ /// are not this machine's.
+ fn sync_reply_paths(&mut self, cx: &mut Context<Self>) {
+ let paths = (!self.host.read(cx).is_remote()).then(|| {
+ let catalog = self.catalog.read(cx);
+ let folder =
+ catalog.selected_row().map(|row| PathBuf::from(row.workspace_path.as_ref()));
+ LocalPaths::new(std::env::home_dir(), folder)
+ });
+ self.conversation.update(cx, |view, cx| view.set_local_paths(paths, cx));
+ }
+
/// Whether the changes show: the panel shows, on its Changes face.
fn changes_shown(&self, cx: &App) -> bool {
self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Changes
diff --git a/apps/desktop-gpui/crates/conversation/src/corpus.rs b/apps/desktop-gpui/crates/conversation/src/corpus.rs
index 59e506051a..a86b19d4d8 100644
--- a/apps/desktop-gpui/crates/conversation/src/corpus.rs
+++ b/apps/desktop-gpui/crates/conversation/src/corpus.rs
@@ -44,7 +44,7 @@ use crate::rows::{
RowKey, cap_cut, hidden_tool, tool_detail_text, tool_name_text, tool_summary_cut,
};
-pub(crate) use markdown::VisibleText;
+pub(crate) use markdown::{VisibleText, parse_options};
/// Which text of a row a match is in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
diff --git a/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs b/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs
index c478f76e52..47c37d737f 100644
--- a/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs
+++ b/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs
@@ -87,7 +87,7 @@ impl VisibleText {
/// The parse options of gpui-kit's text view with its default extensions
/// (`MarkdownExtensions::parse_options`): GFM, inline and block math on.
-fn parse_options() -> ParseOptions {
+pub(crate) fn parse_options() -> ParseOptions {
let mut options = ParseOptions::gfm();
options.constructs.frontmatter = false;
options.constructs.math_text = true;
diff --git a/apps/desktop-gpui/crates/conversation/src/lib.rs b/apps/desktop-gpui/crates/conversation/src/lib.rs
index 6911f4dc52..f52cab434e 100644
--- a/apps/desktop-gpui/crates/conversation/src/lib.rs
+++ b/apps/desktop-gpui/crates/conversation/src/lib.rs
@@ -33,6 +33,8 @@
//! `Searchable`), which searches every held row, read from the model.
//! It also carries the task's terminal output for the `terminal` crate:
//! [`ConversationState::set_pty_interest`] and [`SessionPtyEvent`].
+//! On a Host on this machine, the file paths its replies name open on a
+//! click ([`LocalPaths`], [`ConversationViewEvent::OpenPath`]).
//! - [`Composer`] edits the draft and sends it, or stops the running turn,
//! through the same state; its [`QueuePlate`] lists the queued messages.
//!
@@ -49,6 +51,7 @@ mod composer;
mod corpus;
mod edits_card;
mod paging;
+mod paths;
mod queue;
mod quiet_json;
mod quotes;
@@ -65,6 +68,7 @@ pub use composer::{
Composer, ComposerAction, ModelChoice, PERMISSION_MODES, permission_mode_hint,
permission_mode_label, thinking_level_label,
};
+pub use paths::LocalPaths;
pub use queue::{CancelQueueEdit, QueuePlate, queue_entry_element_id};
pub use rows::{edits_element_id, footer_element_id, item_element_id};
pub use side_chat::{
diff --git a/apps/desktop-gpui/crates/conversation/src/paths.rs b/apps/desktop-gpui/crates/conversation/src/paths.rs
new file mode 100644
index 0000000000..83bd60b20c
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/paths.rs
@@ -0,0 +1,581 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! File paths in a reply that open on this machine: which spans name one,
+//! the reply's Markdown with each of them made a link, and where a click
+//! on one goes.
+//!
+//! The kit's text view draws inline code as text and offers no hook for a
+//! click on it; its Markdown plugins replace a node with an element of
+//! their own, which a find cannot paint inside and a selection takes
+//! whole. So once a reply has finished streaming, the view hands its text
+//! view a copy of the reply's Markdown ([`PathLinks`]) in which each
+//! qualifying span is a link with this client's own scheme ([`SCHEME`]):
+//! an inline code span `` `~/a.md` `` becomes
+//! `` [`~/a.md`](maka-file:/Users/me/a.md) ``, still a code chip, drawn in
+//! the link colour with the link's pointer and underline; a link to a
+//! `file:` URL or to a plain path keeps its text and takes the scheme for
+//! its address. The text drawn is the reply's own, so a selection copies
+//! the path as shown and Copy reply copies the reply as written; a find
+//! searches the reply's own Markdown and maps each match through
+//! [`PathLinks::map_range`] before the text view paints it.
+//!
+//! Only for a Host on this machine ([`LocalPaths`], from the shell; a Host
+//! elsewhere gets none and nothing is decorated), and only when the path
+//! exists, file or folder:
+//! - an inline code span whose whole content, trimmed, is one path:
+//! absolute (`/…`), in the home folder (`~/…`), or relative to the
+//! task's working folder; a trailing `:line` or `:line:col` may be
+//! dropped. A command such as `ls ~/Downloads` names no path that
+//! exists;
+//! - a link whose address is a `file:` URL or a plain path, resolved the
+//! same way.
+//!
+//! Not code blocks, not bare paths in prose, not code inside a link's
+//! text, not user messages. Existence is checked once per reply, when it
+//! has finished streaming, off the main thread ([`check`]).
+//!
+//! A click decides nothing from what the reply wrote: the view reads the
+//! path back out of the link, resolves it again and hands it to the shell
+//! ([`crate::ConversationViewEvent::OpenPath`]), which looks at the file
+//! as it is then. A link the agent wrote with this scheme goes the same
+//! way.
+
+use std::ops::Range;
+use std::path::{Path, PathBuf};
+
+use gpui_kit::SharedString;
+use markdown::mdast::Node;
+
+use crate::corpus::parse_options;
+
+/// The scheme of a link to a path on this machine: this client's own,
+/// never handed to the platform.
+pub(crate) const SCHEME: &str = "maka-file:";
+
+/// The most spans of one reply that are looked at.
+const MAX_SPANS: usize = 64;
+/// The longest path looked at, in bytes (macOS's `PATH_MAX`).
+const MAX_PATH_BYTES: usize = 1024;
+
+/// Where the paths a reply names lie on this machine: the home folder
+/// (`~/…`) and the task's working folder (a relative path), as the shell
+/// hands them to the view for a Host on this machine
+/// ([`crate::ConversationView::set_local_paths`]).
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct LocalPaths {
+ home: Option<PathBuf>,
+ folder: Option<PathBuf>,
+}
+
+impl LocalPaths {
+ pub fn new(home: Option<PathBuf>, folder: Option<PathBuf>) -> Self {
+ Self { home, folder }
+ }
+
+ /// The path `written` names, without looking at the disk: as it is
+ /// when absolute, in the home folder for `~/…`, else in the working
+ /// folder. `None` for an empty text, a URL (`scheme://…`), or a folder
+ /// this does not know.
+ pub(crate) fn resolve(&self, written: &str) -> Option<PathBuf> {
+ if written.is_empty()
+ || written.len() > MAX_PATH_BYTES
+ || written.contains(['\n', '\r', '\0'])
+ || url_scheme(written).is_some_and(|_| written.contains("://"))
+ {
+ return None;
+ }
+ if let Some(rest) = written.strip_prefix("~/") {
+ return self.home.as_ref().map(|home| home.join(rest));
+ }
+ let path = Path::new(written);
+ if path.is_absolute() {
+ return Some(path.to_path_buf());
+ }
+ self.folder.as_ref().filter(|folder| folder.is_absolute()).map(|folder| folder.join(path))
+ }
+}
+
+/// A settled reply's Markdown with each span that names an existing path
+/// on this machine made a link with [`SCHEME`], and the map from the
+/// reply's own Markdown to it.
+#[derive(Debug)]
+pub(crate) struct PathLinks {
+ text: SharedString,
+ /// What changed, in source order.
+ edits: Vec<Edit>,
+}
+
+/// `removed` bytes of the reply at `at` became `inserted` bytes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct Edit {
+ at: usize,
+ removed: usize,
+ inserted: usize,
+}
+
+impl PathLinks {
+ /// `source` with each of `changes` (a range of it and what replaces
+ /// it; in order, none overlapping) made.
+ fn new(source: &str, changes: Vec<(Range<usize>, String)>) -> Self {
+ let mut text = String::with_capacity(source.len() + changes.len() * 32);
+ let mut edits = Vec::with_capacity(changes.len());
+ let mut copied = 0;
+ for (range, inserted) in changes {
+ text.push_str(&source[copied..range.start]);
+ text.push_str(&inserted);
+ copied = range.end;
+ edits.push(Edit { at: range.start, removed: range.len(), inserted: inserted.len() });
+ }
+ text.push_str(&source[copied..]);
+ Self { text: text.into(), edits }
+ }
+
+ /// The Markdown the text view draws.
+ pub(crate) fn text(&self) -> &SharedString {
+ &self.text
+ }
+
+ /// `range` of the reply's own Markdown as a range of [`Self::text`]:
+ /// what was inserted where it starts comes before it, what was
+ /// inserted where it ends after it, so it never takes in a link's
+ /// markup on its edges.
+ pub(crate) fn map_range(&self, range: Range<usize>) -> Range<usize> {
+ let start = self.map(range.start, true);
+ let end = self.map(range.end, false).max(start);
+ start..end
+ }
+
+ fn map(&self, at: usize, start: bool) -> usize {
+ let mut mapped = at;
+ for edit in &self.edits {
+ let before = if edit.removed == 0 && edit.at == at {
+ start
+ } else {
+ edit.at + edit.removed <= at
+ };
+ if !before {
+ break;
+ }
+ mapped = (mapped + edit.inserted).saturating_sub(edit.removed);
+ }
+ mapped
+ }
+}
+
+/// The links of `source`, a settled reply, to the paths it names that
+/// exist on this machine under `paths`; `None` when it names none. Looks
+/// at the disk: run it off the main thread.
+pub(crate) fn check(source: &str, paths: &LocalPaths) -> Option<PathLinks> {
+ let mut changes = Vec::new();
+ for span in spans(source).into_iter().take(MAX_SPANS) {
+ match span {
+ Span::Code { range, content } => {
+ let Some(path) = existing(&spellings(content.trim()), paths) else { continue };
+ let Some(href) = href(&path) else { continue };
+ changes.push((range.start..range.start, "[".to_owned()));
+ changes.push((range.end..range.end, format!("]({href})")));
+ }
+ Span::Link { tail, address } => {
+ let Some(path) = existing(&link_spellings(&address), paths) else { continue };
+ let Some(href) = href(&path) else { continue };
+ changes.push((tail, format!("]({href})")));
+ }
+ }
+ }
+ changes.sort_by_key(|(range, _)| range.start);
+ (!changes.is_empty()).then(|| PathLinks::new(source, changes))
+}
+
+/// Whether `href` is a link to a path on this machine ([`SCHEME`]), in
+/// any case.
+pub(crate) fn is_path_link(href: &str) -> bool {
+ url_scheme(href).is_some_and(|scheme| format!("{scheme}:").eq_ignore_ascii_case(SCHEME))
+}
+
+/// The path a link with [`SCHEME`] names, decoded, as it was written: the
+/// view resolves it again (an agent may have written `~/…` or a relative
+/// one).
+pub(crate) fn link_path(href: &str) -> Option<String> {
+ if !is_path_link(href) {
+ return None;
+ }
+ decode(&href[SCHEME.len()..])
+}
+
+/// The first of `spellings` that names a path that exists.
+fn existing(spellings: &[String], paths: &LocalPaths) -> Option<PathBuf> {
+ spellings.iter().filter_map(|spelling| paths.resolve(spelling)).find(|path| path.exists())
+}
+
+/// The address of a link to `path`.
+fn href(path: &Path) -> Option<String> {
+ Some(format!("{SCHEME}{}", encode(path.to_str()?)))
+}
+
+/// A span of a reply that may name a path.
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum Span {
+ /// An inline code span: its source, backticks included, and its
+ /// content.
+ Code { range: Range<usize>, content: String },
+ /// A link: the source from the end of its text to its end (`](…)`),
+ /// and its address.
+ Link { tail: Range<usize>, address: String },
+}
+
+/// The spans of `source` that may name a path, in source order: inline
+/// code and inline links in the text the view draws.
+fn spans(source: &str) -> Vec<Span> {
+ let mut spans = Vec::new();
+ if let Ok(Node::Root(root)) = markdown::to_mdast(source, &parse_options()) {
+ blocks(source, &root.children, &mut spans);
+ }
+ spans
+}
+
+fn blocks(source: &str, nodes: &[Node], spans: &mut Vec<Span>) {
+ for node in nodes {
+ match node {
+ Node::Paragraph(_) | Node::Heading(_) => {
+ inlines(source, node.children().map_or(&[][..], Vec::as_slice), spans);
+ }
+ Node::Blockquote(_)
+ | Node::List(_)
+ | Node::ListItem(_)
+ | Node::FootnoteDefinition(_) => {
+ blocks(source, node.children().map_or(&[][..], Vec::as_slice), spans);
+ }
+ Node::Table(table) => {
+ for row in &table.children {
+ for cell in row.children().into_iter().flatten() {
+ inlines(source, cell.children().map_or(&[][..], Vec::as_slice), spans);
+ }
+ }
+ }
+ // Code blocks, math, HTML, rules and definitions.
+ _ => {}
+ }
+ }
+}
+
+fn inlines(source: &str, nodes: &[Node], spans: &mut Vec<Span>) {
+ for node in nodes {
+ let range = node.position().map(|position| position.start.offset..position.end.offset);
+ let Some(range) = range.filter(|range| range.end <= source.len()) else { continue };
+ match node {
+ // After a `!` the link it becomes would be an image.
+ Node::InlineCode(code) if !source[..range.start].ends_with('!') => {
+ spans.push(Span::Code { range, content: code.value.clone() });
+ }
+ // An inline link with text; not an autolink (`<…>`), whose
+ // text is its address. Code in its text is its own.
+ Node::Link(link) if source[range.clone()].starts_with('[') => {
+ let text_end = link.children.last().and_then(Node::position);
+ if let Some(text_end) = text_end.map(|position| position.end.offset)
+ && source[text_end..range.end].starts_with(']')
+ {
+ spans.push(Span::Link { tail: text_end..range.end, address: link.url.clone() });
+ }
+ }
+ Node::Emphasis(_) | Node::Strong(_) | Node::Delete(_) => {
+ inlines(source, node.children().map_or(&[][..], Vec::as_slice), spans);
+ }
+ // Reference links, images, inline math and HTML.
+ _ => {}
+ }
+ }
+}
+
+/// How a code span's path may be written: as it is, then without a
+/// trailing `:line` or `:line:col`.
+fn spellings(written: &str) -> Vec<String> {
+ let mut spellings = vec![written.to_owned()];
+ spellings.extend(without_line(written).map(str::to_owned));
+ spellings
+}
+
+/// `text` without a trailing `:line` or `:line:col`, when it ends so.
+fn without_line(text: &str) -> Option<&str> {
+ let number = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
+ let (rest, last) = text.rsplit_once(':')?;
+ if !number(last) {
+ return None;
+ }
+ let head = match rest.rsplit_once(':') {
+ Some((head, line)) if number(line) => head,
+ _ => rest,
+ };
+ (!head.is_empty()).then_some(head)
+}
+
+/// How a link's address may name a path: a `file:` URL's path; a plain
+/// path as written, decoded (`%20`), and without a `#fragment`, each also
+/// without a trailing `:line`. Any other URL names none.
+fn link_spellings(address: &str) -> Vec<String> {
+ if let Some(scheme) = url_scheme(address) {
+ if scheme.eq_ignore_ascii_case("file") {
+ return file_url_path(address).into_iter().collect();
+ }
+ return Vec::new();
+ }
+ if address.is_empty() || address.starts_with(['#', '?']) || address.starts_with("//") {
+ return Vec::new();
+ }
+ let mut written = vec![address.to_owned()];
+ written.extend(decode(address).filter(|decoded| decoded != address));
+ if let Some((path, _)) = address.split_once('#') {
+ written.push(path.to_owned());
+ written.extend(decode(path));
+ }
+ let mut spellings: Vec<String> = Vec::new();
+ for text in written {
+ for spelling in self::spellings(&text) {
+ if !spellings.contains(&spelling) {
+ spellings.push(spelling);
+ }
+ }
+ }
+ spellings
+}
+
+/// The path of a `file:` URL on this machine (no host, or `localhost`),
+/// decoded.
+fn file_url_path(url: &str) -> Option<String> {
+ let rest = &url["file:".len()..];
+ let rest = rest.split(['?', '#']).next().unwrap_or_default();
+ let path = match rest.strip_prefix("//") {
+ Some(after) => {
+ let (host, path) = after.split_at(after.find('/')?);
+ (host.is_empty() || host.eq_ignore_ascii_case("localhost")).then_some(path)?
+ }
+ None => rest,
+ };
+ path.starts_with('/').then(|| decode(path)).flatten()
+}
+
+/// The scheme `text` starts with (`https` of `https:…`), as RFC 3986 spells
+/// one: a letter, then letters, digits, `+`, `-` or `.`, then a colon.
+fn url_scheme(text: &str) -> Option<&str> {
+ let (scheme, _) = text.split_once(':')?;
+ let mut bytes = scheme.bytes();
+ let first = bytes.next()?;
+ (first.is_ascii_alphabetic()
+ && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')))
+ .then_some(scheme)
+}
+
+/// `path` percent-encoded for a link's address: letters, digits, `-._~`
+/// and `/` stay, every other byte is `%XX`, so the address holds nothing
+/// Markdown or a table reads as markup.
+fn encode(path: &str) -> String {
+ let mut encoded = String::with_capacity(path.len());
+ for byte in path.bytes() {
+ if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/') {
+ encoded.push(byte as char);
+ } else {
+ encoded.push_str(&format!("%{byte:02X}"));
+ }
+ }
+ encoded
+}
+
+/// `text` with each `%XX` decoded; `None` when an escape is broken or the
+/// bytes are not UTF-8.
+fn decode(text: &str) -> Option<String> {
+ let bytes = text.as_bytes();
+ let mut decoded = Vec::with_capacity(bytes.len());
+ let mut at = 0;
+ while at < bytes.len() {
+ if bytes[at] == b'%' {
+ let hex = text.get(at + 1..at + 3)?;
+ decoded.push(u8::from_str_radix(hex, 16).ok()?);
+ at += 3;
+ } else {
+ decoded.push(bytes[at]);
+ at += 1;
+ }
+ }
+ String::from_utf8(decoded).ok()
+}
+
+#[cfg(test)]
+#[allow(clippy::disallowed_methods)] // Tests write their scratch files.
+mod tests {
+ use super::*;
+
+ /// A scratch home with `Downloads/报告 final.docx`, and a task folder
+ /// with `notes.md` and `src/main.rs`.
+ struct Scratch {
+ root: PathBuf,
+ paths: LocalPaths,
+ }
+
+ impl Scratch {
+ fn new() -> Self {
+ let root =
+ std::env::temp_dir().join(format!("maka-paths-{}", uuid::Uuid::new_v4().simple()));
+ let (home, folder) = (root.join("home"), root.join("task"));
+ std::fs::create_dir_all(home.join("Downloads")).expect("home");
+ std::fs::create_dir_all(folder.join("src")).expect("folder");
+ std::fs::write(home.join("Downloads/报告 final.docx"), b"doc").expect("docx");
+ std::fs::write(folder.join("notes.md"), b"# Notes").expect("notes");
+ std::fs::write(folder.join("src/main.rs"), b"fn main() {}").expect("main");
+ Self { paths: LocalPaths::new(Some(home), Some(folder)), root }
+ }
+
+ fn task(&self, rest: &str) -> String {
+ self.root.join("task").join(rest).to_str().expect("utf-8").to_owned()
+ }
+
+ fn home(&self, rest: &str) -> String {
+ self.root.join("home").join(rest).to_str().expect("utf-8").to_owned()
+ }
+ }
+
+ impl Drop for Scratch {
+ fn drop(&mut self) {
+ std::fs::remove_dir_all(&self.root).ok();
+ }
+ }
+
+ /// The path each link of `text` names, in order.
+ fn linked(text: &str) -> Vec<String> {
+ let Ok(Node::Root(root)) = markdown::to_mdast(text, &parse_options()) else {
+ panic!("parse");
+ };
+ let mut found = Vec::new();
+ collect_links(&Node::Root(root), &mut found);
+ found
+ }
+
+ fn collect_links(node: &Node, found: &mut Vec<String>) {
+ if let Node::Link(link) = node {
+ found.push(link_path(&link.url).unwrap_or_else(|| format!("other: {}", link.url)));
+ }
+ for child in node.children().into_iter().flatten() {
+ collect_links(child, found);
+ }
+ }
+
+ #[test]
+ fn paths_resolve_absolute_in_the_home_or_in_the_task_folder() {
+ let paths = LocalPaths::new(Some("/Users/me".into()), Some("/work/task".into()));
+ assert_eq!(paths.resolve("/etc/hosts"), Some("/etc/hosts".into()));
+ assert_eq!(paths.resolve("~/Downloads/a.md"), Some("/Users/me/Downloads/a.md".into()));
+ assert_eq!(paths.resolve("src/main.rs"), Some("/work/task/src/main.rs".into()));
+ assert_eq!(paths.resolve("ls ~/Downloads"), Some("/work/task/ls ~/Downloads".into()));
+ for none in ["", "https://example.com/a.md", "file:///etc/hosts", "a\nb"] {
+ assert_eq!(paths.resolve(none), None, "{none:?}");
+ }
+ let elsewhere = LocalPaths::new(None, None);
+ assert_eq!(elsewhere.resolve("~/a.md"), None);
+ assert_eq!(elsewhere.resolve("a.md"), None);
+ }
+
+ #[test]
+ fn spans_that_name_existing_paths_become_links() {
+ let scratch = Scratch::new();
+ let absolute = scratch.task("notes.md");
+ let reply = format!(
+ "**交付文件**:`~/Downloads/报告 final.docx`\n\n\
+ See `{absolute}`, ` src/main.rs:12:3 `, and [the notes](notes.md \"Notes\").\n\n\
+ | file | |\n|---|---|\n| `src` | [plan](file://{absolute}) |\n"
+ );
+ let links = check(&reply, &scratch.paths).expect("links");
+ assert_eq!(
+ linked(links.text()),
+ [
+ scratch.home("Downloads/报告 final.docx"),
+ absolute.clone(),
+ scratch.task("src/main.rs"),
+ scratch.task("notes.md"),
+ scratch.task("src"),
+ absolute.clone(),
+ ]
+ );
+ assert!(
+ links.text().contains("[`~/Downloads/报告 final.docx`](maka-file:/"),
+ "the span stays a code chip: {}",
+ links.text()
+ );
+ }
+
+ #[test]
+ fn commands_missing_paths_urls_and_code_blocks_stay_text() {
+ let scratch = Scratch::new();
+ let reply = format!(
+ "Run `ls ~/Downloads`, open `missing/report.md` or `https://example.com/notes.md`.\n\n\
+ ```\n{}\n```\n\n\
+ A bare {} in prose, [a page](https://example.com), \
+ [`notes.md`](https://example.com/notes) and Done!`notes.md`\n",
+ scratch.task("notes.md"),
+ scratch.task("notes.md"),
+ );
+ assert!(check(&reply, &scratch.paths).is_none());
+ // A Host elsewhere: nothing resolves.
+ let relative = "Open `notes.md`.";
+ assert!(check(relative, &scratch.paths).is_some());
+ assert!(check(relative, &LocalPaths::default()).is_none());
+ }
+
+ #[test]
+ fn a_match_in_the_reply_maps_into_its_links() {
+ let scratch = Scratch::new();
+ let reply = "Read `notes.md` now, then [this](notes.md).";
+ let links = check(reply, &scratch.paths).expect("links");
+ let text = links.text().to_string();
+ let source_of = |word: &str| {
+ let start = reply.find(word).expect("word");
+ start..start + word.len()
+ };
+ for (word, expected) in [("notes", "notes"), ("Read", "Read"), ("now, then", "now, then")] {
+ let mapped = links.map_range(source_of(word));
+ assert_eq!(&text[mapped], expected, "{word}");
+ }
+ // A match that ends at the span's backtick takes in none of the
+ // link's markup on its edges.
+ let edge = source_of("Read ");
+ assert_eq!(&text[links.map_range(edge)], "Read ");
+ let this = reply.rfind("this").expect("this");
+ assert_eq!(&text[links.map_range(this..this + 4)], "this");
+ assert_eq!(&text[links.map_range(reply.len() - 1..reply.len())], ".");
+ }
+
+ #[test]
+ fn link_addresses_round_trip_and_other_schemes_are_not_paths() {
+ let path = "/Users/me/Downloads/麦当劳 (MCD) 100%|a#b.docx";
+ let href = href(Path::new(path)).expect("href");
+ assert!(href.bytes().all(|byte| byte.is_ascii_graphic()), "{href}");
+ assert!(!href.contains(['|', '(', ')', ' ', '#']));
+ assert_eq!(link_path(&href).as_deref(), Some(path));
+ assert_eq!(link_path("MAKA-FILE:~/a.md").as_deref(), Some("~/a.md"));
+ assert_eq!(link_path("maka-file:%zz"), None);
+ for other in ["https://example.com", "file:///etc/hosts", "maka-files:/x", "notes.md"] {
+ assert!(!is_path_link(other), "{other}");
+ }
+ assert_eq!(file_url_path("file:///a%20b/c.md#x").as_deref(), Some("/a b/c.md"));
+ assert_eq!(file_url_path("file://localhost/a.md").as_deref(), Some("/a.md"));
+ assert_eq!(file_url_path("file://server/a.md"), None);
+ assert_eq!(without_line("a.rs:12:3"), Some("a.rs"));
+ assert_eq!(without_line("a.rs:12"), Some("a.rs"));
+ assert_eq!(without_line("a.rs"), None);
+ assert_eq!(without_line(":12"), None);
+ }
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/rows.rs b/apps/desktop-gpui/crates/conversation/src/rows.rs
index e20b258ced..75818ee112 100644
--- a/apps/desktop-gpui/crates/conversation/src/rows.rs
+++ b/apps/desktop-gpui/crates/conversation/src/rows.rs
@@ -340,10 +340,11 @@ pub(crate) enum ToolNote {
/// The call runs, or waits on the user, and has produced nothing yet
/// (Maka Desktop's `noOutputYet`).
NoOutputYet,
- /// The call finished, and what it returned has not arrived: a live
- /// `tool_result` carries no content, and the Host announces the Turn's
- /// durable rows, which carry it, only when the Turn ends.
- OutputAtTurnEnd,
+ /// The call finished, and its arguments and what it returned have not
+ /// arrived: a live `tool_result` carries no content, and the Host
+ /// announces the Turn's durable rows, which carry them, only when the
+ /// Turn ends.
+ DetailsAtTurnEnd,
/// The call finished without output (Maka Desktop's `noOutput`).
NoOutput,
}
@@ -744,7 +745,7 @@ fn tool_note(tool: &ToolItem, waiting: bool) -> ToolNote {
_ if waiting => ToolNote::NoOutputYet,
ToolStatus::Running => ToolNote::NoOutputYet,
ToolStatus::Completed | ToolStatus::Errored if tool.result.is_none() => {
- ToolNote::OutputAtTurnEnd
+ ToolNote::DetailsAtTurnEnd
}
_ => ToolNote::NoOutput,
}
diff --git a/apps/desktop-gpui/crates/conversation/src/tests.rs b/apps/desktop-gpui/crates/conversation/src/tests.rs
index a47a2c8ae4..5cd78e75e4 100644
--- a/apps/desktop-gpui/crates/conversation/src/tests.rs
+++ b/apps/desktop-gpui/crates/conversation/src/tests.rs
@@ -1713,7 +1713,7 @@ fn calls_inside_a_code_cell_show_their_summary_and_then_their_output(cx: &mut Te
}
let exec = tool_row(&harness, EXEC, cx);
assert_eq!((exec.input, exec.output), (None, None));
- assert_eq!(exec.note, ToolNote::OutputAtTurnEnd, "finished, so not “no output yet”");
+ assert_eq!(exec.note, ToolNote::DetailsAtTurnEnd, "finished, so not “no output yet”");
assert!(card_shows(&harness, EXEC, "tool-note", cx));
let read = tool_row(&harness, NESTED_READ, cx);
assert!(read.input.expect("input").contains(SKILL_PATH));
@@ -1987,6 +1987,7 @@ mod edits;
mod find;
mod history;
mod links;
+mod paths;
mod pty;
mod queue;
mod reasoning;
diff --git a/apps/desktop-gpui/crates/conversation/src/tests/find.rs b/apps/desktop-gpui/crates/conversation/src/tests/find.rs
index 1768aaf21c..8e44bab4f5 100644
--- a/apps/desktop-gpui/crates/conversation/src/tests/find.rs
+++ b/apps/desktop-gpui/crates/conversation/src/tests/find.rs
@@ -131,7 +131,7 @@ pub(super) fn open_tail(tail: Value, with_composer: bool, cx: &mut TestAppContex
harness
}
-fn open_find(harness: &Harness, cx: &mut TestAppContext) {
+pub(super) fn open_find(harness: &Harness, cx: &mut TestAppContext) {
harness.with_window(cx, |window, cx| {
harness.view.update(cx, |view, cx| view.open_find(window, cx));
});
@@ -140,7 +140,7 @@ fn open_find(harness: &Harness, cx: &mut TestAppContext) {
/// Types `query` into the bar (replacing what is selected) and lets the
/// search finish.
-fn find(harness: &Harness, query: &str, cx: &mut TestAppContext) {
+pub(super) fn find(harness: &Harness, query: &str, cx: &mut TestAppContext) {
harness.with_window(cx, |window, cx| window.input(query, cx));
settle(cx);
harness.with_window(cx, |_, _| {});
@@ -160,7 +160,7 @@ fn label_of(harness: &Harness, id: &'static str, cx: &mut TestAppContext) -> Opt
})
}
-fn count(harness: &Harness, cx: &mut TestAppContext) -> Option<String> {
+pub(super) fn count(harness: &Harness, cx: &mut TestAppContext) -> Option<String> {
label_of(harness, "find-count", cx)
}
@@ -192,7 +192,7 @@ struct TranscriptMatchView {
range: Range<usize>,
}
-fn fills(cx: &mut TestAppContext) -> (Hsla, Hsla) {
+pub(super) fn fills(cx: &mut TestAppContext) -> (Hsla, Hsla) {
cx.update(|cx| {
let maka = cx.maka();
(maka.find_match, maka.find_match_active)
diff --git a/apps/desktop-gpui/crates/conversation/src/tests/paths.rs b/apps/desktop-gpui/crates/conversation/src/tests/paths.rs
new file mode 100644
index 0000000000..e67fbc4e73
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/tests/paths.rs
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! Paths a reply names open on this machine (`crate::paths`): once the
+//! reply has settled, a code span or a link naming a path that exists is a
+//! link with the client's own scheme, and a click on it asks the owner to
+//! open the path again resolved. A Host elsewhere, a user message, a reply
+//! still streaming and a span that names nothing there stay text. A find
+//! still matches inside a path and paints it in place.
+
+#![allow(clippy::disallowed_methods)] // Tests write their scratch files.
+
+use std::cell::RefCell;
+use std::rc::Rc;
+
+use gpui_kit::{point, px};
+
+use super::find::{count, fills, find, open_find, open_tail, page_of, reply, turn};
+use super::*;
+use crate::{ConversationViewEvent, LocalPaths};
+
+/// A task folder with `notes.md`, `src/` and `run.command`, removed when
+/// dropped.
+struct Scratch {
+ folder: PathBuf,
+}
+
+impl Scratch {
+ fn new() -> Self {
+ let folder = std::env::temp_dir()
+ .join(format!("maka-reply-paths-{}", uuid::Uuid::new_v4().simple()));
+ std::fs::create_dir_all(folder.join("src")).expect("folder");
+ std::fs::write(folder.join("notes.md"), b"# Notes").expect("notes");
+ std::fs::write(folder.join("run.command"), b"#!/bin/sh\n").expect("command");
+ Self { folder }
+ }
+
+ fn paths(&self) -> LocalPaths {
+ LocalPaths::new(None, Some(self.folder.clone()))
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ std::fs::remove_dir_all(&self.folder).ok();
+ }
+}
+
+/// The session open on turn `t1`, whose reply is `text`, with what its
+/// view asks of its owner recorded.
+fn open_reply(
+ text: &str,
+ cx: &mut TestAppContext,
+) -> (Harness, Rc<RefCell<Vec<ConversationViewEvent>>>) {
+ let rows = turn("t1", 1, "Where is it?", None, text);
+ let harness = open_tail(page_of(&rows, None), false, cx);
+ let events = Rc::new(RefCell::new(Vec::new()));
+ let recorded = events.clone();
+ cx.update(|cx| {
+ cx.subscribe(&harness.view, move |_, event: &ConversationViewEvent, _| {
+ recorded.borrow_mut().push(event.clone());
+ })
+ .detach();
+ });
+ (harness, events)
+}
+
+/// Hands the view where paths lie (`None`: a Host elsewhere) and lets the
+/// check and the text view's parse land.
+fn set_paths(harness: &Harness, paths: Option<LocalPaths>, cx: &mut TestAppContext) {
+ harness.view.update(cx, |view, cx| view.set_local_paths(paths, cx));
+ for _ in 0..3 {
+ settle(cx);
+ harness.with_window(cx, |_, _| {});
+ }
+}
+
+/// Clicks the start of the first line of `row`.
+fn click_start(harness: &Harness, row: &RowKey, cx: &mut TestAppContext) {
+ let id = row.element_id();
+ harness.with_window(cx, |window, cx| window.click_at(id, point(px(16.), px(10.)), cx));
+ settle(cx);
+}
+
+fn opened(events: &Rc<RefCell<Vec<ConversationViewEvent>>>) -> Vec<PathBuf> {
+ events
+ .borrow()
+ .iter()
+ .filter_map(|event| match event {
+ ConversationViewEvent::OpenPath { path } => Some(path.clone()),
+ _ => None,
+ })
+ .collect()
+}
+
+/// A path in a settled reply opens on a click, as the task folder
+/// resolves it; on a Host elsewhere the same reply is text again.
+#[gpui_kit::test]
+fn a_settled_reply_s_path_opens_on_a_click(cx: &mut TestAppContext) {
+ let scratch = Scratch::new();
+ let (harness, events) = open_reply("`notes.md` is ready.", cx);
+ let row = reply("t1");
+ click_start(&harness, &row, cx);
+ assert!(opened(&events).is_empty(), "nothing is a link before the view knows the paths");
+
+ set_paths(&harness, Some(scratch.paths()), cx);
+ assert!(harness.view.read_with(cx, |view, _| view.path_checked(&row)));
+ click_start(&harness, &row, cx);
+ assert_eq!(opened(&events), [scratch.folder.join("notes.md")]);
+ assert_eq!(cx.opened_url(), None, "the platform is handed nothing");
+
+ // A Host elsewhere: the path is text again, and a click does nothing.
+ set_paths(&harness, None, cx);
+ click_start(&harness, &row, cx);
+ assert_eq!(opened(&events).len(), 1);
+}
+
+/// Only paths that exist are links: a command, a missing file and a URL
+/// in code stay text.
+#[gpui_kit::test]
+fn a_span_naming_nothing_there_stays_text(cx: &mut TestAppContext) {
+ let scratch = Scratch::new();
+ for text in ["`ls ~/Downloads` lists it.", "`gone.md` is gone.", "`https://example.com`"] {
+ let (harness, events) = open_reply(text, cx);
+ set_paths(&harness, Some(scratch.paths()), cx);
+ let row = reply("t1");
+ let links = harness.view.read_with(cx, |view, _| {
+ let text = view.rows().iter().find_map(|found| match &found.body {
+ RowBody::Text { text, .. } if found.key == row => Some(text.clone()),
+ _ => None,
+ });
+ text.and_then(|text| view.path_links(&row, &text))
+ });
+ assert!(links.is_none(), "{text}");
+ click_start(&harness, &row, cx);
+ assert!(opened(&events).is_empty(), "{text}");
+ }
+}
+
+/// A link the agent wrote with the client's own scheme goes the same way
+/// as the client's: the owner is handed the path, resolved again, and
+/// decides what opens. A Host elsewhere is handed nothing, nor is the
+/// platform.
+#[gpui_kit::test]
+fn an_agent_written_path_link_goes_to_the_owner_only_here(cx: &mut TestAppContext) {
+ let scratch = Scratch::new();
+ let (harness, events) = open_reply("[Run the setup script now](maka-file:run.command)", cx);
+ let row = reply("t1");
+ click_start(&harness, &row, cx);
+ assert!(opened(&events).is_empty(), "a Host elsewhere");
+ assert_eq!(cx.opened_url(), None);
+
+ set_paths(&harness, Some(scratch.paths()), cx);
+ click_start(&harness, &row, cx);
+ assert_eq!(opened(&events), [scratch.folder.join("run.command")]);
+ assert_eq!(cx.opened_url(), None);
+}
+
+/// A user message is never checked, and a reply only once it has
+/// finished streaming.
+#[gpui_kit::test]
+fn a_user_message_and_a_streaming_reply_are_not_checked(cx: &mut TestAppContext) {
+ let scratch = Scratch::new();
+ let (harness, mut frames) = start_turn(cx);
+ harness.view.update(cx, |view, cx| view.set_local_paths(Some(scratch.paths()), cx));
+ harness.push(frames.delta("m1", 0, "Wrote `notes.md` and"), cx);
+ settle(cx);
+ harness.with_window(cx, |_, _| {});
+ let (streaming, user) = harness.view.read_with(cx, |view, _| {
+ let key = |pick: fn(&RowBody) -> bool| {
+ view.rows().iter().find(|row| pick(&row.body)).map(|row| row.key.clone())
+ };
+ (
+ key(|body| matches!(body, RowBody::Text { streaming: true, .. })),
+ key(|body| matches!(body, RowBody::User { .. })),
+ )
+ });
+ let (streaming, user) = (streaming.expect("a streaming reply"), user.expect("the prompt"));
+ harness.view.read_with(cx, |view, _| {
+ assert!(!view.path_checked(&streaming), "not while it streams");
+ assert!(!view.path_checked(&user), "never a user message");
+ });
+}
+
+/// A find matches inside a path that is a link, and paints the match on
+/// the text it draws.
+#[gpui_kit::test]
+fn find_matches_inside_a_path_link(cx: &mut TestAppContext) {
+ let scratch = Scratch::new();
+ let (harness, _) = open_reply("Open `notes.md` and `src` now.", cx);
+ set_paths(&harness, Some(scratch.paths()), cx);
+ let row = reply("t1");
+ assert!(harness.view.read_with(cx, |view, _| view.path_checked(&row)));
+ open_find(&harness, cx);
+ find(&harness, "notes", cx);
+ assert_eq!(count(&harness, cx).as_deref(), Some("1/1"));
+ let (_, active_fill) = fills(cx);
+ let highlights = harness.view.read_with(cx, |view, _| view.text_views().highlights(&row));
+ // "Open notes.md and src now.": `notes`, in the active fill.
+ assert_eq!(highlights, [(5..10, active_fill)]);
+ let shown = harness.view.read_with(cx, |view, cx| {
+ let state = view.text_views().get(&row).expect("laid out");
+ state.read(cx).rendered_text().as_str().to_owned()
+ });
+ assert_eq!(shown.trim_end(), "Open notes.md and src now.", "the text drawn is the reply's");
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/view.rs b/apps/desktop-gpui/crates/conversation/src/view.rs
index 7e56b06726..bf2ba9d075 100644
--- a/apps/desktop-gpui/crates/conversation/src/view.rs
+++ b/apps/desktop-gpui/crates/conversation/src/view.rs
@@ -26,6 +26,7 @@ mod landing;
mod text_views;
use std::collections::{HashMap, HashSet};
+use std::path::PathBuf;
use std::rc::Rc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -44,7 +45,7 @@ use gpui_kit::component::{
h_flex, v_flex,
};
use gpui_kit::{
- AnyElement, App, AppContext as _, Axis, ClipboardItem, Context, ElementId, Entity,
+ AnyElement, App, AppContext as _, Axis, ClickEvent, ClipboardItem, Context, ElementId, Entity,
EventEmitter, FocusHandle, Focusable, FontWeight, HighlightStyle, Hsla,
InteractiveElement as _, IntoElement, KeyBinding, ParentElement as _, Pixels, Render, Role,
ScrollHandle, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled as _,
@@ -58,6 +59,7 @@ use transcript_model::{ToolStatus, TurnViewStatus};
use crate::composer::{attachment_chip, attachment_kind_icon};
use crate::corpus::Field;
use crate::paging::{PageDirection, Paging};
+use crate::paths::{self, LocalPaths, PathLinks};
use crate::rows::{
FooterRow, GroupPlace, HistoryRow, ListEdit, PromptAnswers, PromptBody, PromptRow, Row,
RowBody, RowKey, RowOptions, SentAttachment, SentQuote, ThinkingRow, ToolDiff, ToolKind,
@@ -95,6 +97,10 @@ pub enum ConversationViewEvent {
/// chat: the transcript's context menu (Desktop's "Ask in side panel").
/// `turn_id` names the Turn whose replies hold the whole selection.
AskInSideChat { text: SharedString, turn_id: Option<SharedString> },
+ /// Open the file or folder at `path` on this machine: a click on a
+ /// path a reply names ([`crate::paths`]). Only on a Host on this
+ /// machine; the owner looks at what is there now.
+ OpenPath { path: PathBuf },
}
gpui_kit::actions!(
@@ -156,6 +162,29 @@ fn system_time_ms(_: &App) -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_millis() as u64)
}
+/// A reply's paths, checked once ([`paths::check`]).
+enum PathCheck {
+ /// Being checked, in this text.
+ Checking(SharedString),
+ /// Checked in this text: its links, when it names any path there.
+ Done(SharedString, Option<Rc<PathLinks>>),
+}
+
+impl PathCheck {
+ /// Whether it is (or is being) checked in `text`.
+ fn is_of(&self, text: &SharedString) -> bool {
+ match self {
+ Self::Checking(checked) | Self::Done(checked, _) => same_text(checked, text),
+ }
+ }
+}
+
+/// Whether two texts are the same: the rows reuse an unchanged string, so
+/// the same pointer says so at once.
+fn same_text(a: &SharedString, b: &SharedString) -> bool {
+ (a.as_ptr() == b.as_ptr() && a.len() == b.len()) || a == b
+}
+
/// What a turn footer reads off the clocks for one frame.
#[derive(Debug, Clone, Copy)]
struct FooterNow {
@@ -266,6 +295,14 @@ pub struct ConversationView {
/// Whether right-clicking the transcript offers "Ask in side chat":
/// the task's conversation does, a side chat's own does not.
side_chat_menu: bool,
+ /// Where the paths replies name lie on this machine; `None` for a
+ /// Host elsewhere, and then no path is a link ([`paths`]).
+ local_paths: Option<LocalPaths>,
+ /// Each settled reply's paths, checked once, by row: dropped with the
+ /// row, the session, or a change of `local_paths`.
+ path_checks: HashMap<RowKey, PathCheck>,
+ /// Counts those drops: a check started before one lands nowhere.
+ path_generation: u64,
_copied: Option<Task<()>>,
_spinner: Option<Task<()>>,
/// Redraws the live running turn's status line as its clock reaches
@@ -321,6 +358,9 @@ impl ConversationView {
text_views: TextViews::default(),
retry_countdown: None,
side_chat_menu: false,
+ local_paths: None,
+ path_checks: HashMap::new(),
+ path_generation: 0,
_copied: None,
_spinner: None,
_clock: None,
@@ -368,6 +408,12 @@ impl ConversationView {
self.find.reveal.row()
}
+ /// Whether reply row `key`'s paths are checked, or being checked.
+ #[cfg(test)]
+ pub(crate) fn path_checked(&self, key: &RowKey) -> bool {
+ self.path_checks.contains_key(key)
+ }
+
/// The matches row `key` paints.
#[cfg(test)]
pub(crate) fn find_marks(&self, key: &RowKey) -> Vec<find::Mark> {
@@ -419,6 +465,8 @@ impl ConversationView {
self.card_diffs.clear();
self.text_views.clear();
self.rows.clear();
+ self.path_checks.clear();
+ self.path_generation += 1;
}
self.options.locale = Locale::current(cx);
self.utc_offset = local_utc_offset();
@@ -491,9 +539,114 @@ impl ConversationView {
self.update_spinner(cx);
self.note_retry(cx);
self.update_clock(cx);
+ self.check_paths(cx);
cx.notify();
}
+ /// Makes the paths replies name links that open on this machine,
+ /// resolved under `paths`; `None` for a Host elsewhere, where no path
+ /// is a link. Every reply is checked again.
+ pub fn set_local_paths(&mut self, paths: Option<LocalPaths>, cx: &mut Context<Self>) {
+ if self.local_paths == paths {
+ return;
+ }
+ self.local_paths = paths;
+ self.path_checks.clear();
+ self.path_generation += 1;
+ self.check_paths(cx);
+ cx.notify();
+ }
+
+ /// Checks the paths of each reply that has finished streaming and was
+ /// not checked in its current text, all in one background pass; drops
+ /// the checks of rows gone. A reply is shown as it is until its check
+ /// lands.
+ fn check_paths(&mut self, cx: &mut Context<Self>) {
+ let Some(paths) = self.local_paths.clone() else { return };
+ let mut replies = HashSet::new();
+ let mut unchecked = Vec::new();
+ for row in &self.rows {
+ let RowBody::Text { text, streaming, .. } = &row.body else { continue };
+ replies.insert(&row.key);
+ let checked = self.path_checks.get(&row.key).is_some_and(|check| check.is_of(text));
+ if !*streaming && !checked {
+ unchecked.push((row.key.clone(), text.clone()));
+ }
+ }
+ self.path_checks.retain(|key, _| replies.contains(key));
+ if unchecked.is_empty() {
+ return;
+ }
+ for (key, text) in &unchecked {
+ self.path_checks.insert(key.clone(), PathCheck::Checking(text.clone()));
+ }
+ let generation = self.path_generation;
+ let check = cx.background_spawn(async move {
+ unchecked
+ .into_iter()
+ .map(|(key, text)| {
+ let links = paths::check(&text, &paths);
+ (key, text, links)
+ })
+ .collect::<Vec<_>>()
+ });
+ cx.spawn(async move |this, cx| {
+ let checked = check.await;
+ this.update(cx, |this, cx| this.take_path_checks(generation, checked, cx)).ok();
+ })
+ .detach();
+ }
+
+ /// Keeps what a check found for each reply still waiting for it in the
+ /// same text.
+ fn take_path_checks(
+ &mut self,
+ generation: u64,
+ checked: Vec<(RowKey, SharedString, Option<PathLinks>)>,
+ cx: &mut Context<Self>,
+ ) {
+ if generation != self.path_generation {
+ return;
+ }
+ let mut linked = false;
+ for (key, text, links) in checked {
+ let waiting = matches!(
+ self.path_checks.get(&key),
+ Some(PathCheck::Checking(pending)) if same_text(pending, &text)
+ );
+ if waiting {
+ linked |= links.is_some();
+ self.path_checks.insert(key, PathCheck::Done(text, links.map(Rc::new)));
+ }
+ }
+ if linked {
+ cx.notify();
+ }
+ }
+
+ /// The links reply row `key` shows `text` with, once its check found
+ /// any.
+ pub(crate) fn path_links(&self, key: &RowKey, text: &SharedString) -> Option<Rc<PathLinks>> {
+ match self.path_checks.get(key)? {
+ PathCheck::Done(checked, links) if same_text(checked, text) => links.clone(),
+ _ => None,
+ }
+ }
+
+ /// A click on a link with the paths' scheme: the path it names,
+ /// resolved again, goes to the owner. A Host elsewhere opens nothing,
+ /// nor does a right-click.
+ fn open_path_link(&mut self, href: &str, event: &ClickEvent, cx: &mut Context<Self>) {
+ if !shared::links::follows(event) {
+ return;
+ }
+ let Some(paths) = &self.local_paths else { return };
+ let Some(path) = paths::link_path(href).and_then(|written| paths.resolve(&written)) else {
+ return;
+ };
+ cx.emit(ConversationViewEvent::OpenPath { path });
+ }
+
/// Parses the diff of each open card that has one and has not been
/// parsed in its current form, and drops the Diffs of closed cards.
fn sync_card_diffs(&mut self, cx: &mut Context<Self>) {
@@ -1213,7 +1366,7 @@ fn render_row(
return div().into_any_element();
};
let (
- row,
+ (row, links),
detail_scroll,
card_diff,
spinner_turns,
@@ -1228,6 +1381,10 @@ fn render_row(
let this = this.read(cx);
let row = this.rows.get(ix).cloned();
let marks = row.as_ref().and_then(|row| this.find.marks.of(&row.key));
+ let links = row.as_ref().and_then(|row| match &row.body {
+ RowBody::Text { text, .. } => this.path_links(&row.key, text),
+ _ => None,
+ });
let (detail_scroll, card_diff) = match row.as_ref().map(|row| &row.body) {
Some(RowBody::Tool(tool)) => (
this.detail_scrolls.get(&tool.expansion_key).cloned(),
@@ -1236,7 +1393,7 @@ fn render_row(
_ => (None, None),
};
(
- row,
+ (row, links),
detail_scroll,
card_diff,
this.spinner_turns,
@@ -1273,8 +1430,10 @@ fn render_row(
}
RowBody::Text { text, interrupted, .. } => {
// The reply's text view, reached here so that the find bar's
- // matches paint in it and one can be revealed.
- let state = text_views.state(&row.key, &text, cx);
+ // matches paint in it and one can be revealed. Once its paths
+ // are checked it draws their links ([`paths`]).
+ let shown = links.as_ref().map_or_else(|| text.clone(), |links| links.text().clone());
+ let state = text_views.state(&row.key, &shown, links, cx);
let marks = find.marks.as_deref();
text_views.paint_marks(&row.key, marks, marks_revision, find.fills, cx);
if let Some(range) = find.reveal.pending(&row.key, Field::Body, find.now)
@@ -1282,7 +1441,7 @@ fn render_row(
{
find.reveal.clear();
}
- render_text(id.clone(), text, interrupted, Some(state), window, cx)
+ render_text(id.clone(), shown, interrupted, Some(state), Some(view.clone()), window, cx)
}
RowBody::Tool(tool) => render_tool(
tool,
@@ -1559,17 +1718,20 @@ pub fn assistant_text(
window: &Window,
cx: &App,
) -> AnyElement {
- render_text(id.into(), text.into(), false, None, window, cx)
+ render_text(id.into(), text.into(), false, None, None, window, cx)
}
/// Assistant text: plain markdown on the plate, no bubble, body 14/22. In
/// the transcript the view's state is the row's (`state`, see
-/// [`TextViews`]); elsewhere it is the element's own.
+/// [`TextViews`]); elsewhere it is the element's own. A link to a path on
+/// this machine goes to `view` ([`paths`]); any other link opens when it
+/// is a web or mail address.
fn render_text(
id: ElementId,
text: SharedString,
interrupted: bool,
state: Option<Entity<TextViewState>>,
+ view: Option<WeakEntity<ConversationView>>,
window: &Window,
cx: &App,
) -> AnyElement {
@@ -1577,14 +1739,21 @@ fn render_text(
.w_full()
.gap_1()
.when(!text.is_empty(), |this| {
- let view = match &state {
+ let text_view = match &state {
Some(state) => TextView::new(state),
None => TextView::markdown(id, text),
};
this.child(
- view.style(message_text_style(window, cx))
+ text_view
+ .style(message_text_style(window, cx))
.selectable(true)
- .on_link_click(|href, event, _, cx| follow_link(href, event, cx))
+ .on_link_click(move |href, event, _, cx| {
+ if !paths::is_path_link(href) {
+ follow_link(href, event, cx);
+ } else if let Some(view) = &view {
+ view.update(cx, |view, cx| view.open_path_link(href, event, cx)).ok();
+ }
+ })
.w_full()
.text_size(dp(BODY_SIZE))
.line_height(relative(BODY_LINE_HEIGHT))
@@ -1997,7 +2166,7 @@ fn tool_detail(
.child(
match tool.note {
ToolNote::NoOutputYet => copy::TOOL_NO_OUTPUT,
- ToolNote::OutputAtTurnEnd => copy::TOOL_OUTPUT_AT_TURN_END,
+ ToolNote::DetailsAtTurnEnd => copy::TOOL_DETAILS_AT_TURN_END,
ToolNote::NoOutput => copy::TOOL_OUTPUT_NONE,
}
.get(cx),
diff --git a/apps/desktop-gpui/crates/conversation/src/view/text_views.rs b/apps/desktop-gpui/crates/conversation/src/view/text_views.rs
index da78285c34..20ad0addf0 100644
--- a/apps/desktop-gpui/crates/conversation/src/view/text_views.rs
+++ b/apps/desktop-gpui/crates/conversation/src/view/text_views.rs
@@ -28,6 +28,10 @@
//! before, and a row's text reaches its state only when the row's string
//! changed (the rows reuse an unchanged string), as the keyed element
//! does.
+//!
+//! A reply whose paths are links draws a copy of its Markdown
+//! ([`PathLinks`]); the find's ranges, of the reply's own Markdown, are
+//! mapped onto the copy before they reach the kit.
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -42,6 +46,7 @@ use gpui_kit::{
use super::find::Mark;
use crate::corpus::Field;
+use crate::paths::PathLinks;
use crate::rows::RowKey;
/// The reply rows' text view states, shared with the row renderer.
@@ -59,6 +64,8 @@ struct Row {
state: Entity<TextViewState>,
/// The string last handed to `state`.
text: SharedString,
+ /// The reply's path links `text` is the Markdown of, when it is.
+ links: Option<Rc<PathLinks>>,
/// The last frame that laid the row out.
used: u64,
/// What the highlights were last painted from.
@@ -91,12 +98,14 @@ impl TextViews {
.size_0()
}
- /// The state of reply row `key`, showing `text`: made on first use,
+ /// The state of reply row `key`, showing `text` (the Markdown of
+ /// `links` when the reply's paths are links): made on first use,
/// handed the text when it changed.
pub(crate) fn state(
&self,
key: &RowKey,
text: &SharedString,
+ links: Option<Rc<PathLinks>>,
cx: &mut App,
) -> Entity<TextViewState> {
let frame = self.0.frame.get();
@@ -108,6 +117,7 @@ impl TextViews {
let same = row.text.as_ptr() == text.as_ptr() && row.text.len() == text.len();
(!same).then(|| {
row.text = text.clone();
+ row.links = links;
row.state.clone()
})
}
@@ -116,6 +126,7 @@ impl TextViews {
let row = Row {
state: state.clone(),
text: text.clone(),
+ links,
used: frame,
painted: None,
highlights: Vec::new(),
@@ -144,7 +155,9 @@ impl TextViews {
fills: (Hsla, Hsla),
cx: &mut App,
) {
- let Some(state) = self.0.rows.borrow().get(key).map(|row| row.state.clone()) else {
+ let Some((state, links)) =
+ self.0.rows.borrow().get(key).map(|row| (row.state.clone(), row.links.clone()))
+ else {
return;
};
let rendered = state.read(cx).rendered_text();
@@ -165,7 +178,8 @@ impl TextViews {
.flatten()
.filter(|mark| mark.field == Field::Body)
.filter_map(|mark| {
- let range = rendered.range_for_source(mark.range.clone())?;
+ let source = shown_source(links.as_deref(), mark.range.clone());
+ let range = rendered.range_for_source(source)?;
Some(RangeHighlight::new(range, if mark.active { fills.1 } else { fills.0 }))
})
.collect();
@@ -187,10 +201,13 @@ impl TextViews {
/// source, by the kit's `reveal_range`. Whether the request was taken:
/// not while the source waits for its parse.
pub(crate) fn reveal(&self, key: &RowKey, source: Range<usize>, cx: &mut App) -> bool {
- let Some(state) = self.0.rows.borrow().get(key).map(|row| row.state.clone()) else {
+ let Some((state, links)) =
+ self.0.rows.borrow().get(key).map(|row| (row.state.clone(), row.links.clone()))
+ else {
return false;
};
let rendered = state.read(cx).rendered_text();
+ let source = shown_source(links.as_deref(), source);
let Some(range) = rendered.range_for_source(source) else { return false };
state.update(cx, |state, cx| state.reveal_range(range, cx)).is_ok()
}
@@ -235,6 +252,15 @@ impl TextViews {
}
}
+/// `source`, a range of a reply's own Markdown, as a range of the Markdown
+/// its text view draws.
+fn shown_source(links: Option<&PathLinks>, source: Range<usize>) -> Range<usize> {
+ match links {
+ Some(links) => links.map_range(source),
+ None => source,
+ }
+}
+
/// A match to bring into view once its row is laid out: the reply rows
/// hand it to their text view, the other rows to a probe after the text
/// it is in. It lapses after a second, as the kit's reveal does, so it
diff --git a/apps/desktop-gpui/crates/files/src/desk.rs b/apps/desktop-gpui/crates/files/src/desk.rs
index f2b850cc86..2fa1ba543e 100644
--- a/apps/desktop-gpui/crates/files/src/desk.rs
+++ b/apps/desktop-gpui/crates/files/src/desk.rs
@@ -18,7 +18,9 @@
*/
//! Where a file leaves the window: a copy saved where the person chooses
-//! (the platform's save dialog), and a copy handed to the default app.
+//! (the platform's save dialog), a copy handed to the default app, and a
+//! file on this machine that a reply names shown in Finder or handed to
+//! the default app as it is.
//!
//! The protocol gives no path to an Artifact (Desktop's Show in Finder and
//! Open come from Electron main), so a file opened in the default app is a
@@ -50,7 +52,7 @@ const TEMP_DIRECTORY: &str = "artifacts";
/// How a saved copy's place is chosen: `suggested` is the name the dialog
/// fills in; `None` when the person cancels.
pub type ChooseSavePath = Rc<dyn Fn(&str, &mut App) -> Task<Option<PathBuf>>>;
-/// How a file is handed to the system's default app.
+/// How a file is handed to the system's default app, or shown in Finder.
pub type OpenFile = Rc<dyn Fn(&Path, &mut App)>;
/// The desktop the Files face saves to and opens with: the platform's
@@ -59,6 +61,7 @@ pub type OpenFile = Rc<dyn Fn(&Path, &mut App)>;
pub struct Desk {
choose_save_path: ChooseSavePath,
open: OpenFile,
+ reveal: OpenFile,
temp_dir: TempDir,
}
@@ -80,17 +83,29 @@ impl std::fmt::Debug for Desk {
impl Desk {
/// A desk that asks with `choose_save_path`, opens with `open`, and
/// writes the copies it opens under `temp_dir` (none: nothing opens).
+ /// It shows nothing in Finder until [`Self::with_reveal`] says how.
pub fn new(
choose_save_path: ChooseSavePath,
open: OpenFile,
temp_dir: Option<PathBuf>,
) -> Self {
- Self { choose_save_path, open, temp_dir: TempDir::Fixed(temp_dir) }
+ Self {
+ choose_save_path,
+ open,
+ reveal: Rc::new(|_, _| {}),
+ temp_dir: TempDir::Fixed(temp_dir),
+ }
+ }
+
+ /// Shows a file or folder in Finder with `reveal`.
+ pub fn with_reveal(mut self, reveal: OpenFile) -> Self {
+ self.reveal = reveal;
+ self
}
/// The platform's save dialog, opening in Downloads, the system's
- /// default app, and this launch's directory of copies when
- /// [`install_temp_files`] set it up.
+ /// default app, Finder (the platform's file manager), and this
+ /// launch's directory of copies when [`install_temp_files`] set it up.
pub fn system() -> Self {
let choose: ChooseSavePath = Rc::new(|suggested, cx| {
let directory = dirs::download_dir().or_else(dirs::home_dir).unwrap_or_default();
@@ -107,6 +122,7 @@ impl Desk {
Self {
choose_save_path: choose,
open: Rc::new(|path, cx| cx.open_with_system(path)),
+ reveal: Rc::new(|path, cx| cx.reveal_path(path)),
temp_dir: TempDir::System,
}
}
@@ -119,6 +135,10 @@ impl Desk {
(self.open)(path, cx);
}
+ pub(crate) fn reveal(&self, path: &Path, cx: &mut App) {
+ (self.reveal)(path, cx);
+ }
+
pub(crate) fn temp_dir(&self, cx: &App) -> Option<PathBuf> {
match &self.temp_dir {
TempDir::System => cx.try_global::<TempFiles>().map(|temp| temp.launch_dir.clone()),
diff --git a/apps/desktop-gpui/crates/files/src/lib.rs b/apps/desktop-gpui/crates/files/src/lib.rs
index 4e534ae4df..15358cadc7 100644
--- a/apps/desktop-gpui/crates/files/src/lib.rs
+++ b/apps/desktop-gpui/crates/files/src/lib.rs
@@ -34,9 +34,13 @@
//! ([`init`]).
//! - [`Desk`] is where a copy is saved and how one reaches the default app;
//! [`install_temp_files`] sets up the copies' directory at launch.
+//! - [`local`] decides what a click on a path a reply names does with the
+//! file on this machine ([`PathOpening`]); [`FilesView::open_path`]
+//! does it, previewing a [`LocalFile`] in the face.
mod desk;
mod list;
+pub mod local;
pub mod policy;
mod preview;
pub mod read;
@@ -46,7 +50,8 @@ use gpui_kit::{App, KeyBinding};
pub use desk::{ChooseSavePath, Desk, OpenFile, install_temp_files};
pub use list::{ArtifactList, ArtifactListEvent, ListLoad, POLL_INTERVAL};
-pub use preview::{ArtifactPreview, Body, ImageBody, PreviewEvent, TextBody};
+pub use local::{LocalFile, PathOpening};
+pub use preview::{ArtifactPreview, Body, ImageBody, PreviewEvent, PreviewSource, TextBody};
pub use view::{FilesView, FilesViewEvent, Notice};
/// Key context of the Files face, while anything in it has focus.
diff --git a/apps/desktop-gpui/crates/files/src/local.rs b/apps/desktop-gpui/crates/files/src/local.rs
new file mode 100644
index 0000000000..62ffc08624
--- /dev/null
+++ b/apps/desktop-gpui/crates/files/src/local.rs
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! A file on this machine that a reply names (the conversation's paths):
+//! what a click on it does, decided from the file as it is when clicked,
+//! never from what the reply wrote of it, and the reads the Files face's
+//! preview of it makes.
+//!
+//! The path is resolved to what it names, symlinks followed, and that
+//! decides ([`classify`]):
+//! - nothing there: the face says the file is no longer there;
+//! - a folder, a bundle such as an `.app` among them: shown in Finder;
+//! - a file the preview draws ([`policy::local_kind`]: Markdown, text,
+//! source, an HTML page, an image, within the preview's limits): the
+//! Files face previews it;
+//! - a document on [`policy::is_openable_document`]'s list: the default
+//! app opens it;
+//! - anything else (a script, a program, a kind this does not know):
+//! shown in Finder. Nothing off that list is opened or launched.
+//!
+//! [`policy::local_kind`]: crate::policy::local_kind
+//! [`policy::is_openable_document`]: crate::policy::is_openable_document
+
+use std::fs::File;
+use std::io::{self, Read as _};
+use std::path::{Path, PathBuf};
+use std::time::UNIX_EPOCH;
+
+use host_protocol::ArtifactKind;
+
+use crate::policy::{Format, is_openable_document, local_kind};
+
+/// What a click on a path does with the file there now.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum PathOpening {
+ /// Nothing is there.
+ Missing,
+ /// Show this folder or file in Finder, selected in its folder.
+ Reveal(PathBuf),
+ /// Hand this document to the default app.
+ OpenInDefaultApp(PathBuf),
+ /// Preview this file in the Files face.
+ Preview(LocalFile),
+}
+
+/// A file on this machine the Files face previews.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
+pub struct LocalFile {
+ /// Where it is, symlinks resolved.
+ pub path: PathBuf,
+ /// Its name, the last part of `path`.
+ pub name: String,
+ /// How it previews: `file` (text), `html` or `image`.
+ pub kind: ArtifactKind,
+ pub size_bytes: u64,
+ /// When it last changed, Unix milliseconds; 0 when the system does not
+ /// say.
+ pub modified_at: u64,
+}
+
+impl<'a> From<&'a LocalFile> for Format<'a> {
+ fn from(file: &'a LocalFile) -> Self {
+ Format::new(&file.kind, &file.name, None)
+ }
+}
+
+/// What a click on `path` does, from what is there now. Looks at the
+/// disk: run it off the main thread.
+pub fn classify(path: &Path) -> PathOpening {
+ let Ok(path) = std::fs::canonicalize(path) else { return PathOpening::Missing };
+ let Ok(metadata) = std::fs::metadata(&path) else { return PathOpening::Missing };
+ if !metadata.is_file() {
+ return PathOpening::Reveal(path);
+ }
+ let Some(name) = path.file_name().and_then(|name| name.to_str()).map(str::to_owned) else {
+ return PathOpening::Reveal(path);
+ };
+ if let Some(kind) = local_kind(&name, metadata.len()) {
+ let modified_at = metadata
+ .modified()
+ .ok()
+ .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
+ .map_or(0, |since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX));
+ return PathOpening::Preview(LocalFile {
+ path,
+ name,
+ kind,
+ size_bytes: metadata.len(),
+ modified_at,
+ });
+ }
+ if is_openable_document(&name) {
+ return PathOpening::OpenInDefaultApp(path);
+ }
+ PathOpening::Reveal(path)
+}
+
+/// The bytes of the file at `path`, at most `limit` of them; a file grown
+/// past `limit` since it was classified is an error. Blocking: run it off
+/// the main thread.
+pub(crate) fn read(path: &Path, limit: u64) -> io::Result<Vec<u8>> {
+ let mut bytes = Vec::new();
+ File::open(path)?.take(limit + 1).read_to_end(&mut bytes)?;
+ if bytes.len() as u64 > limit {
+ return Err(io::Error::new(io::ErrorKind::FileTooLarge, "larger than the preview reads"));
+ }
+ Ok(bytes)
+}
+
+#[cfg(test)]
+#[allow(clippy::disallowed_methods)] // Tests write their scratch files.
+mod tests {
+ use super::*;
+
+ fn scratch() -> PathBuf {
+ let root = std::env::temp_dir()
+ .join(format!("maka-files-local-{}", uuid::Uuid::new_v4().simple()));
+ std::fs::create_dir_all(&root).expect("scratch");
+ // Symlinks resolve to the real directory (`/var` is `/private/var`).
+ std::fs::canonicalize(&root).expect("canonical")
+ }
+
+ #[test]
+ fn a_path_is_decided_by_what_is_there() {
+ let root = scratch();
+ std::fs::write(root.join("report.docx"), b"PK").expect("docx");
+ std::fs::write(root.join("notes.md"), b"# Notes").expect("md");
+ std::fs::write(root.join("setup.command"), b"#!/bin/sh\n").expect("command");
+ std::fs::create_dir_all(root.join("Tool.app/Contents")).expect("app");
+ std::fs::create_dir_all(root.join("folder")).expect("folder");
+ assert_eq!(
+ classify(&root.join("report.docx")),
+ PathOpening::OpenInDefaultApp(root.join("report.docx"))
+ );
+ for revealed in ["setup.command", "Tool.app", "folder"] {
+ assert_eq!(
+ classify(&root.join(revealed)),
+ PathOpening::Reveal(root.join(revealed)),
+ "{revealed}"
+ );
+ }
+ let PathOpening::Preview(notes) = classify(&root.join("./notes.md")) else {
+ panic!("a preview");
+ };
+ assert_eq!((notes.path, notes.name.as_str()), (root.join("notes.md"), "notes.md"));
+ assert_eq!((notes.kind, notes.size_bytes), (ArtifactKind::File, 7));
+ assert!(notes.modified_at > 0);
+ assert_eq!(classify(&root.join("gone.docx")), PathOpening::Missing);
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ /// A symlink named like a document is decided by what it points at.
+ #[cfg(unix)]
+ #[test]
+ fn a_symlink_is_decided_by_its_target() {
+ let root = scratch();
+ std::fs::create_dir_all(root.join("folder")).expect("folder");
+ std::fs::write(root.join("tool"), b"\x7fELF").expect("tool");
+ std::fs::write(root.join("real.docx"), b"PK").expect("docx");
+ std::os::unix::fs::symlink(root.join("folder"), root.join("x.docx")).expect("link");
+ std::os::unix::fs::symlink(root.join("tool"), root.join("y.docx")).expect("link");
+ std::os::unix::fs::symlink(root.join("real.docx"), root.join("z.md")).expect("link");
+ std::os::unix::fs::symlink(root.join("nowhere"), root.join("w.docx")).expect("link");
+ assert_eq!(classify(&root.join("x.docx")), PathOpening::Reveal(root.join("folder")));
+ assert_eq!(classify(&root.join("y.docx")), PathOpening::Reveal(root.join("tool")));
+ assert_eq!(
+ classify(&root.join("z.md")),
+ PathOpening::OpenInDefaultApp(root.join("real.docx"))
+ );
+ assert_eq!(classify(&root.join("w.docx")), PathOpening::Missing);
+ std::fs::remove_dir_all(&root).ok();
+ }
+
+ #[test]
+ fn a_read_stops_at_its_limit() {
+ let root = scratch();
+ std::fs::write(root.join("a.txt"), b"12345").expect("a");
+ assert_eq!(read(&root.join("a.txt"), 5).expect("read"), b"12345");
+ assert!(read(&root.join("a.txt"), 4).is_err());
+ assert!(read(&root.join("gone.txt"), 4).is_err());
+ std::fs::remove_dir_all(&root).ok();
+ }
+}
diff --git a/apps/desktop-gpui/crates/files/src/policy.rs b/apps/desktop-gpui/crates/files/src/policy.rs
index a8ef941dc7..4ce0a4b3a7 100644
--- a/apps/desktop-gpui/crates/files/src/policy.rs
+++ b/apps/desktop-gpui/crates/files/src/policy.rs
@@ -20,8 +20,9 @@
//! What the Files face decides without the Host or a window: which
//! Artifacts a person sees and may delete, what a row says, the filter, the
//! list's keys, names made safe for the disk, formats told from bytes, the
-//! language of a file's source, UTF-8 read in pieces, and the tool results
-//! that announce new files. No GPUI, no I/O.
+//! language of a file's source, UTF-8 read in pieces, the tool results
+//! that announce new files, and which files on this machine that a reply
+//! names it previews or hands to the default app. No GPUI, no I/O.
use host_protocol::{ArtifactKind, ArtifactProjection, ArtifactSource};
use serde_json::Value;
@@ -253,19 +254,43 @@ fn extension(name: &str) -> Option<String> {
(!stem.is_empty() && !extension.is_empty()).then(|| extension.to_ascii_lowercase())
}
+/// What tells a file's format: its kind, its name and its media type. An
+/// Artifact's ([`ArtifactProjection`]), or a file on this machine's
+/// ([`crate::LocalFile`]), which has no media type.
+#[derive(Debug, Clone, Copy)]
+pub struct Format<'a> {
+ kind: &'a ArtifactKind,
+ name: &'a str,
+ mime_type: Option<&'a str>,
+}
+
+impl<'a> Format<'a> {
+ pub fn new(kind: &'a ArtifactKind, name: &'a str, mime_type: Option<&'a str>) -> Self {
+ Self { kind, name, mime_type }
+ }
+}
+
+impl<'a> From<&'a ArtifactProjection> for Format<'a> {
+ fn from(artifact: &'a ArtifactProjection) -> Self {
+ Self::new(&artifact.kind, &artifact.name, artifact.mime_type.as_deref())
+ }
+}
+
/// Whether the file is Markdown: by its name, as Desktop tells
/// (`.md`, `.markdown`), or by its media type.
-pub fn is_markdown(artifact: &ArtifactProjection) -> bool {
- matches!(extension(&artifact.name).as_deref(), Some("md" | "markdown"))
- || artifact.mime_type.as_deref().is_some_and(|mime| mime.starts_with("text/markdown"))
+pub fn is_markdown<'a>(file: impl Into<Format<'a>>) -> bool {
+ let file = file.into();
+ matches!(extension(file.name).as_deref(), Some("md" | "markdown"))
+ || file.mime_type.is_some_and(|mime| mime.starts_with("text/markdown"))
}
/// Whether the file is an HTML page: kind `html`, or a `file` whose source
/// language is HTML by its name or media type ([`source_language`]).
-pub fn is_html(artifact: &ArtifactProjection) -> bool {
- match artifact.kind {
+pub fn is_html<'a>(file: impl Into<Format<'a>>) -> bool {
+ let file = file.into();
+ match file.kind {
ArtifactKind::Html => true,
- ArtifactKind::File => source_language(artifact) == Some("html"),
+ ArtifactKind::File => source_language(file) == Some("html"),
_ => false,
}
}
@@ -318,6 +343,60 @@ pub fn renderable_html(html: &str) -> String {
kept
}
+/// The documents a click on a path in a reply hands to the default app
+/// (on this machine, by the file's own name, case aside): office files,
+/// PDFs, CSV, iWork, OpenDocument, RTF and EPUB. No other file there is
+/// ever opened or launched: a script or an application a reply names could
+/// run.
+pub fn is_openable_document(name: &str) -> bool {
+ matches!(
+ extension(name).as_deref(),
+ Some(
+ "docx"
+ | "doc"
+ | "xlsx"
+ | "xls"
+ | "pptx"
+ | "ppt"
+ | "pdf"
+ | "csv"
+ | "pages"
+ | "numbers"
+ | "key"
+ | "odt"
+ | "ods"
+ | "odp"
+ | "rtf"
+ | "epub"
+ )
+ )
+}
+
+/// How the Files face previews the file on this machine named `name`, of
+/// `size` bytes, that a reply names: an HTML page (`html`), a raster image
+/// or an SVG (`image`, at most [`IMAGE_PREVIEW_MAX_BYTES`]), or text
+/// (`file`: Markdown, plain text and logs, and source the highlighter knows
+/// by its extension); text and pages at most [`TEXT_PREVIEW_CEILING`], read
+/// whole. `None` for anything else, a CSV among it: it is a document.
+pub fn local_kind(name: &str, size: u64) -> Option<ArtifactKind> {
+ let extension = extension(name)?;
+ let image = matches!(
+ extension.as_str(),
+ "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "ico" | "svg"
+ );
+ if image {
+ return (size <= IMAGE_PREVIEW_MAX_BYTES).then_some(ArtifactKind::Image);
+ }
+ let file = Format::new(&ArtifactKind::File, name, None);
+ let kind = match source_language(file) {
+ Some("html") => ArtifactKind::Html,
+ Some(_) => ArtifactKind::File,
+ None if matches!(extension.as_str(), "txt" | "text" | "log") => ArtifactKind::File,
+ None => return None,
+ };
+ (size <= TEXT_PREVIEW_CEILING).then_some(kind)
+}
+
/// Whether text read from a file is binary: a NUL in its first 8 KB.
pub fn looks_binary(text: &str) -> bool {
text.as_bytes()[..text.len().min(8192)].contains(&0)
@@ -326,14 +405,15 @@ pub fn looks_binary(text: &str) -> bool {
/// The language the kit's highlighter knows the source by, from the
/// file's extension, else its media type; `None` for plain text. HTML
/// files are `html` whatever their name.
-pub fn source_language(artifact: &ArtifactProjection) -> Option<&'static str> {
- if artifact.kind == ArtifactKind::Html {
+pub fn source_language<'a>(file: impl Into<Format<'a>>) -> Option<&'static str> {
+ let file = file.into();
+ if *file.kind == ArtifactKind::Html {
return Some("html");
}
- if artifact.kind == ArtifactKind::Diff {
+ if *file.kind == ArtifactKind::Diff {
return Some("diff");
}
- let by_extension = extension(&artifact.name).and_then(|extension| {
+ let by_extension = extension(file.name).and_then(|extension| {
Some(match extension.as_str() {
"rs" => "rust",
"py" | "pyi" => "python",
@@ -368,7 +448,7 @@ pub fn source_language(artifact: &ArtifactProjection) -> Option<&'static str> {
})
});
by_extension.or_else(|| {
- let mime = artifact.mime_type.as_deref()?.split(';').next()?.trim().to_ascii_lowercase();
+ let mime = file.mime_type?.split(';').next()?.trim().to_ascii_lowercase();
Some(match mime.as_str() {
"text/html" => "html",
"application/json" => "json",
@@ -608,6 +688,27 @@ mod tests {
assert!(looks_binary("PK\u{3}\u{4}\0\0") && !looks_binary("plain"));
}
+ #[test]
+ fn a_file_on_this_machine_previews_opens_or_neither_by_its_name() {
+ let small = 1024;
+ assert_eq!(local_kind("Notes.MD", small), Some(ArtifactKind::File));
+ assert_eq!(local_kind("main.rs", small), Some(ArtifactKind::File));
+ assert_eq!(local_kind("build.log", small), Some(ArtifactKind::File));
+ assert_eq!(local_kind("report.HTML", small), Some(ArtifactKind::Html));
+ assert_eq!(local_kind("chart.png", small), Some(ArtifactKind::Image));
+ assert_eq!(local_kind("chart.png", IMAGE_PREVIEW_MAX_BYTES + 1), None);
+ assert_eq!(local_kind("huge.md", TEXT_PREVIEW_CEILING + 1), None);
+ for none in ["data.csv", "setup.command", "Makefile", "tool", "a.docx", ".md"] {
+ assert_eq!(local_kind(none, small), None, "{none}");
+ }
+ for document in ["报告.DOCX", "a.pdf", "t.csv", "k.key", "b.epub", "s.ODS"] {
+ assert!(is_openable_document(document), "{document}");
+ }
+ for other in ["setup.command", "Maka.app", "run.sh", "x", "notes.md", "a.docx.exe"] {
+ assert!(!is_openable_document(other), "{other}");
+ }
+ }
+
#[test]
fn hidden_elements_leave_the_page_before_it_renders() {
let page = "<html><head><TITLE>Report</TITLE><style>p{color:red}</style></head>\
diff --git a/apps/desktop-gpui/crates/files/src/preview.rs b/apps/desktop-gpui/crates/files/src/preview.rs
index 430bd62861..d6a1ae083e 100644
--- a/apps/desktop-gpui/crates/files/src/preview.rs
+++ b/apps/desktop-gpui/crates/files/src/preview.rs
@@ -52,7 +52,14 @@
//! to the face; a click shows it at its actual size, scrolling, and
//! another fits it again.
//! - A PDF is not read: it opens in the default app or is saved.
+//!
+//! A file on this machine that a reply names ([`PreviewSource::Local`],
+//! [`crate::local`]) previews the same way, read whole from the disk off
+//! the main thread instead of from the Host: text and pages up to
+//! [`TEXT_PREVIEW_CEILING`], images up to [`IMAGE_PREVIEW_MAX_BYTES`]. Its
+//! lines offer Show in Finder where an Artifact's offer Save As.
+use std::path::PathBuf;
use std::sync::Arc;
use gpui_kit::assets::IconName as AssetIcon;
@@ -79,9 +86,11 @@ use shared::theme::{
};
use workspace::HostSession;
+use crate::local::LocalFile;
use crate::policy::{
- HTML_RENDER_MAX_BYTES, IMAGE_PREVIEW_MAX_BYTES, ImageType, TEXT_PREVIEW_CEILING, Utf8Pieces,
- is_html, is_markdown, is_office_document, looks_binary, renderable_html, source_language,
+ Format, HTML_RENDER_MAX_BYTES, IMAGE_PREVIEW_MAX_BYTES, ImageType, TEXT_PREVIEW_CEILING,
+ Utf8Pieces, is_html, is_markdown, is_office_document, looks_binary, renderable_html,
+ source_language,
};
use crate::read::{self, ReadFailure};
use crate::{IMAGE_CONTEXT, ToggleImageSize};
@@ -93,6 +102,73 @@ use crate::{IMAGE_CONTEXT, ToggleImageSize};
pub enum PreviewEvent {
SaveAs,
OpenInDefaultApp,
+ /// Show the file on this machine in Finder.
+ Reveal,
+}
+
+/// Where the previewed file is.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum PreviewSource {
+ /// An Artifact the Host keeps for the task.
+ Artifact(ArtifactProjection),
+ /// A file on this machine that a reply names.
+ Local(LocalFile),
+}
+
+impl PreviewSource {
+ pub fn name(&self) -> &str {
+ match self {
+ Self::Artifact(artifact) => &artifact.name,
+ Self::Local(file) => &file.name,
+ }
+ }
+
+ pub fn kind(&self) -> &ArtifactKind {
+ match self {
+ Self::Artifact(artifact) => &artifact.kind,
+ Self::Local(file) => &file.kind,
+ }
+ }
+
+ pub fn size_bytes(&self) -> u64 {
+ match self {
+ Self::Artifact(artifact) => artifact.size_bytes,
+ Self::Local(file) => file.size_bytes,
+ }
+ }
+
+ /// Unix milliseconds: when the Artifact was made, when the file on
+ /// this machine last changed.
+ pub fn time(&self) -> u64 {
+ match self {
+ Self::Artifact(artifact) => artifact.created_at,
+ Self::Local(file) => file.modified_at,
+ }
+ }
+
+ pub fn artifact(&self) -> Option<&ArtifactProjection> {
+ match self {
+ Self::Artifact(artifact) => Some(artifact),
+ Self::Local(_) => None,
+ }
+ }
+
+ pub fn local(&self) -> Option<&LocalFile> {
+ match self {
+ Self::Local(file) => Some(file),
+ Self::Artifact(_) => None,
+ }
+ }
+}
+
+impl<'a> From<&'a PreviewSource> for Format<'a> {
+ fn from(source: &'a PreviewSource) -> Self {
+ match source {
+ PreviewSource::Artifact(artifact) => artifact.into(),
+ PreviewSource::Local(file) => file.into(),
+ }
+ }
}
/// What the preview shows.
@@ -144,10 +220,10 @@ enum RichFormat {
impl RichFormat {
/// An HTML page renders as one (whatever its name says), a Markdown
/// file as Markdown.
- fn of(artifact: &ArtifactProjection) -> Option<Self> {
- if is_html(artifact) {
+ fn of(file: Format<'_>) -> Option<Self> {
+ if is_html(file) {
Some(Self::Html)
- } else if is_markdown(artifact) {
+ } else if is_markdown(file) {
Some(Self::Markdown)
} else {
None
@@ -274,7 +350,7 @@ impl ImageBody {
/// and runs the actions.
pub struct ArtifactPreview {
host: Entity<HostSession>,
- artifact: ArtifactProjection,
+ source: PreviewSource,
body: Body,
/// The body's region: a Tab stop, and where focus goes as the preview
/// opens.
@@ -287,9 +363,7 @@ impl EventEmitter<PreviewEvent> for ArtifactPreview {}
impl std::fmt::Debug for ArtifactPreview {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("ArtifactPreview")
- .field("artifact", &self.artifact.id)
- .finish_non_exhaustive()
+ f.debug_struct("ArtifactPreview").field("source", &self.source).finish_non_exhaustive()
}
}
@@ -299,10 +373,29 @@ impl ArtifactPreview {
artifact: ArtifactProjection,
window: &mut Window,
cx: &mut Context<Self>,
+ ) -> Self {
+ Self::of(host, PreviewSource::Artifact(artifact), window, cx)
+ }
+
+ /// The preview of `file`, on this machine.
+ pub fn local(
+ host: Entity<HostSession>,
+ file: LocalFile,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ Self::of(host, PreviewSource::Local(file), window, cx)
+ }
+
+ fn of(
+ host: Entity<HostSession>,
+ source: PreviewSource,
+ window: &mut Window,
+ cx: &mut Context<Self>,
) -> Self {
let mut this = Self {
host,
- artifact,
+ source,
body: Body::Loading,
focus: cx.focus_handle().tab_stop(true),
scroll: ScrollHandle::new(),
@@ -312,8 +405,13 @@ impl ArtifactPreview {
this
}
- pub fn artifact(&self) -> &ArtifactProjection {
- &self.artifact
+ /// The Artifact previewed; `None` for a file on this machine.
+ pub fn artifact(&self) -> Option<&ArtifactProjection> {
+ self.source.artifact()
+ }
+
+ pub fn source(&self) -> &PreviewSource {
+ &self.source
}
pub fn body(&self) -> &Body {
@@ -346,7 +444,15 @@ impl ArtifactPreview {
}
fn read(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let artifact = &self.artifact;
+ let artifact = match &self.source {
+ PreviewSource::Artifact(artifact) => artifact,
+ PreviewSource::Local(file) => {
+ let path = file.path.clone();
+ let image = file.kind == ArtifactKind::Image;
+ self.read_local(path, image, window, cx);
+ return;
+ }
+ };
match artifact.kind {
ArtifactKind::Pdf => {
self.body = Body::Pdf;
@@ -408,6 +514,39 @@ impl ArtifactPreview {
}));
}
+ /// Reads the file at `path` on this machine whole, off the main thread:
+ /// an image's bytes, or text.
+ fn read_local(
+ &mut self,
+ path: PathBuf,
+ image: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.body = Body::Loading;
+ cx.notify();
+ let limit = if image { IMAGE_PREVIEW_MAX_BYTES } else { TEXT_PREVIEW_CEILING };
+ let read = cx.background_spawn(async move {
+ crate::local::read(&path, limit).map_err(|error| match error.kind() {
+ std::io::ErrorKind::FileTooLarge => ReadFailure::TooLarge,
+ _ => ReadFailure::Local(error.to_string().into()),
+ })
+ });
+ self._read = Some(cx.spawn_in(window, async move |this, cx| {
+ let bytes = read.await;
+ this.update_in(cx, |this, window, cx| {
+ if image {
+ this.show_image(bytes, cx);
+ } else {
+ let text = bytes
+ .map(|bytes| Start::Whole(String::from_utf8_lossy(&bytes).into_owned()));
+ this.show_text(text, window, cx);
+ }
+ })
+ .ok();
+ }));
+ }
+
fn show_image(&mut self, bytes: Result<Vec<u8>, ReadFailure>, cx: &mut Context<Self>) {
self._read = None;
self.body = match bytes {
@@ -449,13 +588,13 @@ impl ArtifactPreview {
return;
}
};
- if self.artifact.kind == ArtifactKind::File && looks_binary(pieces.text()) {
+ if *self.source.kind() == ArtifactKind::File && looks_binary(pieces.text()) {
self.body = Body::NotText;
cx.notify();
return;
}
let text: SharedString = pieces.text().to_owned().into();
- let language = source_language(&self.artifact);
+ let language = source_language(&self.source);
let editor = cx.new(|cx| {
let mut editor = EditorState::new(window, cx)
.language(language.unwrap_or("text"))
@@ -463,7 +602,7 @@ impl ArtifactPreview {
editor.set_readonly(true, cx);
editor
});
- let format = RichFormat::of(&self.artifact);
+ let format = RichFormat::of((&self.source).into());
let rich = format
.filter(|format| format.renders(next.is_none(), total))
.map(|format| rich_state(format, &text, cx));
@@ -480,7 +619,7 @@ impl ArtifactPreview {
rendered: rich.is_some(),
rich,
};
- if self.artifact.kind == ArtifactKind::Diff {
+ if *self.source.kind() == ArtifactKind::Diff {
body.diff = parse_diff(&body.text, body.next.is_none(), cx);
}
self.body = Body::Text(Box::new(body));
@@ -499,6 +638,8 @@ impl ArtifactPreview {
}
fn read_more(&mut self, to_end: bool, window: &mut Window, cx: &mut Context<Self>) {
+ let PreviewSource::Artifact(artifact) = &self.source else { return };
+ let (session, id) = (artifact.session_id.clone(), artifact.id.clone());
let Body::Text(body) = &mut self.body else { return };
let Some(offset) = body.next else { return };
if body.reading || body.at_ceiling() {
@@ -509,7 +650,6 @@ impl ArtifactPreview {
let total = body.total;
let mut budget = TEXT_PREVIEW_CEILING.saturating_sub(body.pieces.byte_count());
let requester = self.host.read(cx).requester();
- let (session, id) = (self.artifact.session_id.clone(), self.artifact.id.clone());
self._read = Some(cx.spawn_in(window, async move |this, cx| {
let mut bytes = Vec::new();
let mut next = Some(offset);
@@ -571,7 +711,7 @@ impl ArtifactPreview {
editor.set_value(text, window, cx);
editor.set_scroll_offset(offset, cx);
});
- if self.artifact.kind == ArtifactKind::Diff {
+ if *self.source.kind() == ArtifactKind::Diff {
let complete = body.next.is_none();
let text = body.text.clone();
body.diff = parse_diff(&text, complete, cx);
@@ -631,7 +771,7 @@ impl ArtifactPreview {
.readonly(true)
.appearance(false)
.bordered(false)
- .aria_label(copy::preview_named(locale, &self.artifact.name))
+ .aria_label(copy::preview_named(locale, self.source.name()))
.size_full()
.text_size(rems(CODE_TEXT_REMS))
.into_any_element(),
@@ -824,7 +964,12 @@ impl ArtifactPreview {
return self.render_line(copy::WHY_UNSUPPORTED, true, self.image_openable(image), cx);
};
let label = if image.actual_size { copy::IMAGE_ACTUAL } else { copy::IMAGE_FIT };
- let not_drawn: SharedString = copy::WHY_NOT_DRAWN.in_locale(locale).into();
+ let not_drawn = if self.source.local().is_some() {
+ copy::WHY_LOCAL_NOT_SHOWN
+ } else {
+ copy::WHY_NOT_DRAWN
+ };
+ let not_drawn: SharedString = not_drawn.in_locale(locale).into();
let fallback = move || {
div()
.p_4()
@@ -864,11 +1009,14 @@ impl ArtifactPreview {
}
}
+ /// Whether the image may go to the default app: an Artifact's raster
+ /// image. A file on this machine opens only when it is a document.
fn image_openable(&self, image: &ImageBody) -> bool {
- image.kind.is_some_and(ImageType::is_openable)
+ self.source.artifact().is_some() && image.kind.is_some_and(ImageType::is_openable)
}
- /// A line that says why nothing shows, with the actions that help.
+ /// A line that says why nothing shows, with the actions that help. A
+ /// file on this machine says it with the way to Finder.
fn render_line(
&self,
text: shared::copy::Text,
@@ -876,9 +1024,13 @@ impl ArtifactPreview {
open: bool,
cx: &mut Context<Self>,
) -> AnyElement {
+ let text = if self.source.local().is_some() { copy::WHY_LOCAL_NOT_SHOWN } else { text };
self.render_why(text.get(cx).into(), None, save, open, cx)
}
+ /// The line, its retry when trying again could help, and `open` and
+ /// `save`: for a file on this machine, Show in Finder takes Save As's
+ /// place.
fn render_why(
&self,
text: SharedString,
@@ -888,6 +1040,7 @@ impl ArtifactPreview {
cx: &mut Context<Self>,
) -> AnyElement {
let retry = failure.is_some_and(retryable);
+ let local = self.source.local().is_some();
let line = if failure.is_some() {
StatusLine::error("files-why", text)
} else {
@@ -924,12 +1077,19 @@ impl ArtifactPreview {
})),
)
})
- .when(save, |this| {
+ .when(save && !local, |this| {
this.child(
quiet_button(Button::new("files-body-save"), cx)
.label(copy::SAVE_AS.get(cx))
.on_click(cx.listener(|_, _, _, cx| cx.emit(PreviewEvent::SaveAs))),
)
+ })
+ .when(save && local, |this| {
+ this.child(
+ quiet_button(Button::new("files-body-reveal"), cx)
+ .label(copy::REVEAL.get(cx))
+ .on_click(cx.listener(|_, _, _, cx| cx.emit(PreviewEvent::Reveal))),
+ )
}),
)
.into_any_element()
@@ -1057,6 +1217,7 @@ pub(crate) fn why(failure: &ReadFailure, locale: Locale) -> String {
ReadFailure::Unexpected => copy::WHY_UNEXPECTED,
ReadFailure::Changed => copy::WHY_CHANGED,
ReadFailure::TooLarge => copy::WHY_TOO_LARGE,
+ ReadFailure::Local(message) => return copy::why_local_read_failed(locale, message),
};
text.in_locale(locale).to_owned()
}
@@ -1080,7 +1241,13 @@ impl Render for ArtifactPreview {
Body::NotText => self.render_line(copy::WHY_NOT_TEXT, true, false, cx),
Body::UnknownKind => self.render_line(copy::WHY_UNKNOWN_KIND, true, false, cx),
Body::Failed(failure) => {
- let text = why(failure, locale).into();
+ // A file on this machine too large to read is found in
+ // Finder, not saved.
+ let text = if self.source.local().is_some() && saving_helps(failure) {
+ copy::WHY_LOCAL_NOT_SHOWN.in_locale(locale).into()
+ } else {
+ why(failure, locale).into()
+ };
self.render_why(text, Some(failure), saving_helps(failure), false, cx)
}
};
@@ -1090,7 +1257,7 @@ impl Render for ArtifactPreview {
.id("files-preview")
.test_support()
.role(Role::Region)
- .aria_label(copy::preview_named(locale, &self.artifact.name))
+ .aria_label(copy::preview_named(locale, self.source.name()))
.size_full()
.min_h_0()
.when(body_icon, |this| {
diff --git a/apps/desktop-gpui/crates/files/src/read.rs b/apps/desktop-gpui/crates/files/src/read.rs
index 9f4e80d63a..d3a42732f7 100644
--- a/apps/desktop-gpui/crates/files/src/read.rs
+++ b/apps/desktop-gpui/crates/files/src/read.rs
@@ -61,6 +61,8 @@ pub enum ReadFailure {
Changed,
/// The file is larger than this read takes.
TooLarge,
+ /// A file on this machine could not be read: the system's words.
+ Local(Arc<str>),
}
impl From<HostRequestError> for ReadFailure {
diff --git a/apps/desktop-gpui/crates/files/src/view.rs b/apps/desktop-gpui/crates/files/src/view.rs
index 08c4759959..8a1dd47277 100644
--- a/apps/desktop-gpui/crates/files/src/view.rs
+++ b/apps/desktop-gpui/crates/files/src/view.rs
@@ -32,9 +32,17 @@
//! the window leaves out, which the browser then runs as Desktop's frame
//! would, from a copy holding the page's bytes alone. Any other `file`, and
//! an SVG (an image whose default app may be a browser that runs it), could
-//! run code it does not announce. There is no Show in Finder: the protocol
-//! gives no path.
+//! run code it does not announce. An Artifact has no Show in Finder: the
+//! protocol gives no path.
+//!
+//! A click on a path a reply names comes here too ([`FilesView::open_path`],
+//! [`crate::local`]): the file there now shows in Finder, opens in the
+//! default app, or previews in the face, which the window then shows
+//! ([`FilesViewEvent::Show`]). Such a preview's menu holds Copy (text),
+//! Show in Finder, Copy Path, and Open in Default App for an HTML page,
+//! which opens the page itself; never Save As or Delete.
+use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
@@ -70,11 +78,12 @@ use workspace::HostSession;
use crate::desk::{Desk, write_saved_copy, write_temp_copy};
use crate::list::{ArtifactList, ArtifactListEvent, ListLoad};
+use crate::local::{LocalFile, PathOpening, classify};
use crate::policy::{
COPY_MAX_BYTES, ImageType, ListAction, ListKey, is_html, is_pdf, is_user_deletable,
list_action, matches_filter, row_summary, safe_file_name,
};
-use crate::preview::{ArtifactPreview, Body, PreviewEvent, why};
+use crate::preview::{ArtifactPreview, Body, PreviewEvent, PreviewSource, why};
use crate::read::{self, ReadFailure};
use crate::{
Back, FILES_CONTEXT, LIST_CONTEXT, OpenSelected, SelectFirst, SelectLast, SelectNext,
@@ -94,6 +103,9 @@ const MENU_WIDTH_REMS: f32 = 13.;
pub enum FilesViewEvent {
/// Escape in the list: the panel gives the conversation its place.
Dismiss,
+ /// A file on this machine opened in the preview: the window shows the
+ /// face.
+ Show,
}
/// What an action ended with, as the toast said it.
@@ -112,6 +124,10 @@ enum FileAction {
Save,
Open,
Delete,
+ /// Show a file on this machine in Finder.
+ Reveal,
+ /// Copy a file on this machine's path.
+ CopyPath,
}
/// The rows the list draws: the visible files the filter keeps, by their
@@ -140,6 +156,9 @@ pub struct FilesView {
desk: Desk,
/// The action under way; one at a time.
action: Option<(FileAction, Task<()>)>,
+ /// A click on a path a reply names, while what is there is looked at;
+ /// a later click replaces it.
+ opening: Option<Task<()>>,
notice: Option<Notice>,
/// The wall clock, read when the list changes, never in `render`.
clock: Rc<dyn Fn() -> u64>,
@@ -203,6 +222,7 @@ impl FilesView {
menu: MenuSlot::new(MenuPlacement::BelowEnd),
desk: Desk::system(),
action: None,
+ opening: None,
notice: None,
clock,
listed_at,
@@ -309,15 +329,15 @@ impl FilesView {
}
/// The list moved on: the clock is read again, the selection stays on
- /// its file or goes to the first, and a preview whose file is gone
- /// closes.
+ /// its file or goes to the first, and the preview of an Artifact that
+ /// is gone closes.
fn follow_list(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.listed_at = ((self.clock)(), shared::time::local_utc_offset());
- if let Some((preview, _)) = &self.preview {
- let id = preview.read(cx).artifact().id.clone();
- if self.find(&id, cx).is_none() {
- self.back(window, cx);
- }
+ let previewed = self.previewed(cx).map(|artifact| artifact.id);
+ if let Some(id) = previewed
+ && self.find(&id, cx).is_none()
+ {
+ self.back(window, cx);
}
self.keep_selection_in_filter(cx);
cx.notify();
@@ -358,16 +378,64 @@ impl FilesView {
self.selected = Some(id.to_owned().into());
let host = self.list.read(cx).host().clone();
let preview = cx.new(|cx| ArtifactPreview::new(host, artifact, window, cx));
+ self.show_preview(preview, window, cx);
+ }
+
+ /// Does what a click on `path`, a path a reply names on this machine,
+ /// asks, by what is there now ([`classify`], off the main thread): a
+ /// notice when nothing is; Finder for a folder or a file that neither
+ /// previews nor is a document; the default app for a document; else
+ /// the preview, and the window is asked to show the face. A later
+ /// click replaces one still being looked at.
+ pub fn open_path(&mut self, path: PathBuf, window: &mut Window, cx: &mut Context<Self>) {
+ let opening = cx.background_spawn(async move { classify(&path) });
+ self.opening = Some(cx.spawn_in(window, async move |this, cx| {
+ let opening = opening.await;
+ this.update_in(cx, |this, window, cx| {
+ this.opening = None;
+ match opening {
+ PathOpening::Missing => {
+ let title = copy::FILE_GONE.get(cx).to_owned();
+ this.say(Notice { ok: false, title, detail: None }, window, cx);
+ }
+ PathOpening::Reveal(path) => this.desk.reveal(&path, cx),
+ PathOpening::OpenInDefaultApp(path) => this.desk.open(&path, cx),
+ PathOpening::Preview(file) => {
+ this.open_local_preview(file, window, cx);
+ cx.emit(FilesViewEvent::Show);
+ }
+ }
+ })
+ .ok();
+ }));
+ }
+
+ /// Opens `file`, on this machine, in the preview, which takes the
+ /// focus.
+ fn open_local_preview(&mut self, file: LocalFile, window: &mut Window, cx: &mut Context<Self>) {
+ let host = self.list.read(cx).host().clone();
+ let preview = cx.new(|cx| ArtifactPreview::local(host, file, window, cx));
+ self.show_preview(preview, window, cx);
+ }
+
+ fn show_preview(
+ &mut self,
+ preview: Entity<ArtifactPreview>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
let subscription =
cx.subscribe_in(&preview, window, |this, _, event: &PreviewEvent, window, cx| {
match event {
PreviewEvent::SaveAs => this.save_as(window, cx),
PreviewEvent::OpenInDefaultApp => this.open_in_default_app(window, cx),
+ PreviewEvent::Reveal => this.reveal(cx),
}
});
preview.read(cx).focus_handle().clone().focus(window, cx);
self.preview = Some((preview, subscription));
self.menu = MenuSlot::new(MenuPlacement::BelowEnd);
+ self.action = None;
cx.notify();
}
@@ -391,15 +459,31 @@ impl FilesView {
// The actions.
+ /// The Artifact previewed.
fn previewed(&self, cx: &App) -> Option<ArtifactProjection> {
- self.preview().map(|preview| preview.read(cx).artifact().clone())
+ self.preview().and_then(|preview| preview.read(cx).artifact().cloned())
+ }
+
+ /// The file on this machine previewed.
+ fn previewed_local(&self, cx: &App) -> Option<LocalFile> {
+ self.preview().and_then(|preview| preview.read(cx).source().local().cloned())
}
/// Whether the previewed file offers `action`.
fn offers(&self, action: FileAction, cx: &App) -> bool {
let Some(preview) = self.preview() else { return false };
let preview = preview.read(cx);
- let artifact = preview.artifact();
+ let artifact = match preview.source() {
+ PreviewSource::Artifact(artifact) => artifact,
+ PreviewSource::Local(file) => {
+ return match action {
+ FileAction::Copy => matches!(preview.body(), Body::Text(_)),
+ FileAction::Open => is_html(file),
+ FileAction::Reveal | FileAction::CopyPath => true,
+ FileAction::Save | FileAction::Delete => false,
+ };
+ }
+ };
match action {
FileAction::Copy => match artifact.kind {
ArtifactKind::Diff | ArtifactKind::Html => true,
@@ -418,6 +502,7 @@ impl FilesView {
_ => is_html(artifact),
},
FileAction::Delete => is_user_deletable(artifact),
+ FileAction::Reveal | FileAction::CopyPath => false,
}
}
@@ -459,8 +544,18 @@ impl FilesView {
}
/// Copies the file's text: what the preview holds when it is whole,
- /// else read from the Host, up to [`COPY_MAX_BYTES`].
+ /// else read from the Host, up to [`COPY_MAX_BYTES`]. A file on this
+ /// machine is held whole.
pub fn copy(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(file) = self.previewed_local(cx) {
+ let whole = self.preview().and_then(|preview| preview.read(cx).complete_text());
+ if let Some(text) = whole.filter(|_| self.offers(FileAction::Copy, cx)) {
+ cx.write_to_clipboard(ClipboardItem::new_string(text.to_string()));
+ let title = copy::about(copy::COPIED, Locale::current(cx), &file.name);
+ self.say(Notice { ok: true, title, detail: None }, window, cx);
+ }
+ return;
+ }
self.start(
FileAction::Copy,
|this, window, cx| {
@@ -573,10 +668,32 @@ impl FilesView {
);
}
+ /// Shows the file on this machine previewed in Finder.
+ pub fn reveal(&mut self, cx: &mut Context<Self>) {
+ if let Some(file) = self.previewed_local(cx) {
+ self.desk.reveal(&file.path, cx);
+ }
+ }
+
+ /// Copies the path of the file on this machine previewed.
+ pub fn copy_path(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let Some(file) = self.previewed_local(cx) else { return };
+ cx.write_to_clipboard(ClipboardItem::new_string(file.path.display().to_string()));
+ let title = copy::about(copy::PATH_COPIED, Locale::current(cx), &file.name);
+ self.say(Notice { ok: true, title, detail: None }, window, cx);
+ }
+
/// Writes a copy of a PDF, a raster image or an HTML page under the
/// app's cache and hands it to the default app. A PDF's or an image's
/// extension comes from its bytes, a page's is `html` whatever its name.
+ /// An HTML page on this machine opens as it is, beside its files.
pub fn open_in_default_app(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(file) = self.previewed_local(cx) {
+ if self.offers(FileAction::Open, cx) {
+ self.desk.open(&file.path, cx);
+ }
+ return;
+ }
self.start(
FileAction::Open,
|this, window, cx| {
@@ -744,12 +861,30 @@ impl FilesView {
Self::copy,
));
}
- entries.push(item(
- "files-save",
- copy::SAVE_AS.get(cx),
- Icon::new(AssetIcon::Download),
- Self::save_as,
- ));
+ if self.offers(FileAction::Save, cx) {
+ entries.push(item(
+ "files-save",
+ copy::SAVE_AS.get(cx),
+ Icon::new(AssetIcon::Download),
+ Self::save_as,
+ ));
+ }
+ if self.offers(FileAction::Reveal, cx) {
+ entries.push(item(
+ "files-reveal",
+ copy::REVEAL.get(cx),
+ Icon::new(MakaIcon::Folder),
+ |this, _, cx| this.reveal(cx),
+ ));
+ }
+ if self.offers(FileAction::CopyPath, cx) {
+ entries.push(item(
+ "files-copy-path",
+ copy::COPY_PATH.get(cx),
+ Icon::new(MakaIcon::Copy),
+ Self::copy_path,
+ ));
+ }
if self.offers(FileAction::Open, cx) {
entries.push(item(
"files-open",
@@ -865,7 +1000,7 @@ impl FilesView {
match load {
ListLoad::Loading => line("files-loading", copy::LOADING.get(cx).into(), cx),
ListLoad::Failed(_) => div().into_any_element(),
- _ => empty_state(cx),
+ _ => empty_state(!list.host().read(cx).is_remote(), cx),
}
} else if shown == 0 {
line("files-no-matches", copy::NO_MATCHES.get(cx).into(), cx)
@@ -1044,8 +1179,9 @@ impl FilesView {
) -> AnyElement {
let maka = cx.maka();
let locale = Locale::current(cx);
- let artifact = preview.read(cx).artifact().clone();
- let kind = match artifact.kind {
+ let source = preview.read(cx).source().clone();
+ let name = source.name().to_owned();
+ let kind = match source.kind() {
ArtifactKind::File => copy::KIND_FILE.get(cx),
ArtifactKind::Diff => copy::KIND_DIFF.get(cx),
ArtifactKind::Html => copy::KIND_HTML.get(cx),
@@ -1054,13 +1190,13 @@ impl FilesView {
_ => copy::KIND_FILE.get(cx),
};
let (now, offset) = self.listed_at;
- let size = file_size(locale, artifact.size_bytes);
- let when = shared::time::compact_timestamp(locale, artifact.created_at, now, offset);
+ let size = file_size(locale, source.size_bytes());
+ let when = shared::time::compact_timestamp(locale, source.time(), now, offset);
let meta = format!("{kind} · {size} · {when}");
let spoken = shell_copy::parts(locale, &[kind, &size, &when]);
let menu_open = self.menu.is_open();
let back = copy::BACK.get(cx);
- let more = copy::more_actions(locale, &artifact.name);
+ let more = copy::more_actions(locale, &name);
let header = h_flex()
.id("files-preview-header")
.test_support()
@@ -1091,13 +1227,13 @@ impl FilesView {
div()
.id("files-preview-name")
.test_support()
- .aria_label(artifact.name.clone())
+ .aria_label(name.clone())
.w_full()
.truncate()
.text_sm()
.font_medium()
.text_color(maka.ink)
- .child(artifact.name.clone()),
+ .child(name),
)
.child(
div()
@@ -1195,10 +1331,11 @@ fn line(id: &'static str, text: SharedString, cx: &App) -> AnyElement {
}
/// The list with nothing in it: the tool's glyph and the line that says
-/// what will be here.
-fn empty_state(cx: &App) -> AnyElement {
+/// what will be here; on a Host on this machine (`local`), also that the
+/// paths a reply names open on a click.
+fn empty_state(local: bool, cx: &App) -> AnyElement {
let maka = cx.maka();
- let text = copy::EMPTY.get(cx);
+ let text = if local { copy::EMPTY_LOCAL.get(cx) } else { copy::EMPTY.get(cx) };
v_flex()
.id("files-empty")
.test_support()
diff --git a/apps/desktop-gpui/crates/files/src/view_tests.rs b/apps/desktop-gpui/crates/files/src/view_tests.rs
index bfd4625639..9c736df176 100644
--- a/apps/desktop-gpui/crates/files/src/view_tests.rs
+++ b/apps/desktop-gpui/crates/files/src/view_tests.rs
@@ -22,7 +22,9 @@
//! keys; each kind's preview; each failure's line; the actions, Copy only
//! for text, Delete after its confirmation, Save As assembling chunks
//! (through a stubbed dialog) and Open in Default App (through a stubbed
-//! opener: nothing opens on the machine running the tests).
+//! opener: nothing opens on the machine running the tests). A path a reply
+//! names opens, shows in (a stubbed) Finder, or previews the file on this
+//! machine.
#![allow(clippy::disallowed_methods)] // Tests read their scratch files.
@@ -36,11 +38,13 @@ use gpui_kit::test::TestWindowExt as _;
use gpui_kit::{
App, AppContext as _, ElementId, Entity, TestAppContext, Window, WindowHandle, point, px, size,
};
-use host_protocol::{ARTIFACT_READ_CHUNK_MAX_BYTES, HostOperationErrorCode};
+use host_protocol::{
+ ARTIFACT_READ_CHUNK_MAX_BYTES, AccessCredential, HostOperationErrorCode, RemoteTransport,
+};
use serde_json::{Value, json};
use shared::copy::{Locale, Text, files as copy};
use shared::domain_element_id;
-use workspace::HostRequestError;
+use workspace::{HostRequestError, HostSession, RemoteHost, RemoteHostProfile, WindowHost};
use crate::tests::{ScriptedHost, artifact, five_files, host_session};
use crate::{Body, Desk, FilesView, FilesViewEvent};
@@ -69,6 +73,8 @@ struct Face {
save_to: Rc<RefCell<Option<PathBuf>>>,
/// What was handed to the default app.
opened: Rc<RefCell<Vec<PathBuf>>>,
+ /// What was shown in Finder.
+ revealed: Rc<RefCell<Vec<PathBuf>>>,
scratch: PathBuf,
}
@@ -80,6 +86,11 @@ impl Drop for Face {
impl Face {
fn open(host: Arc<ScriptedHost>, cx: &mut TestAppContext) -> Self {
+ Self::open_on(host, WindowHost::Local, cx)
+ }
+
+ /// The face of a window talking to `window_host`.
+ fn open_on(host: Arc<ScriptedHost>, window_host: WindowHost, cx: &mut TestAppContext) -> Self {
cx.update(|cx| {
gpui_kit::init(cx);
crate::init(cx);
@@ -87,13 +98,24 @@ impl Face {
});
let scratch =
std::env::temp_dir().join(format!("maka-files-view-{}", uuid::Uuid::new_v4().simple()));
- let session = host_session(&host, cx);
+ let session = match window_host {
+ WindowHost::Local => host_session(&host, cx),
+ window_host => {
+ let transport = host.clone();
+ cx.new(|_| {
+ HostSession::with_transport(PathBuf::from("/tmp/maka-files-tests"), transport)
+ .for_host(window_host)
+ })
+ }
+ };
let events = Rc::new(RefCell::new(Vec::new()));
let suggested = Rc::new(RefCell::new(Vec::new()));
let save_to = Rc::new(RefCell::new(None));
let opened = Rc::new(RefCell::new(Vec::new()));
+ let revealed = Rc::new(RefCell::new(Vec::new()));
let desk = {
let (suggested, save_to, opened) = (suggested.clone(), save_to.clone(), opened.clone());
+ let revealed = revealed.clone();
Desk::new(
Rc::new(move |name: &str, cx: &mut App| {
suggested.borrow_mut().push(name.to_owned());
@@ -105,6 +127,9 @@ impl Face {
}),
Some(scratch.join("copies")),
)
+ .with_reveal(Rc::new(move |path: &std::path::Path, _: &mut App| {
+ revealed.borrow_mut().push(path.to_owned());
+ }))
};
let mut view = None;
let recorded = events.clone();
@@ -130,6 +155,7 @@ impl Face {
suggested,
save_to,
opened,
+ revealed,
scratch,
};
face.view.update(cx, |view, cx| {
@@ -197,10 +223,39 @@ impl Face {
/// The previewed file's id.
fn previewing(&self, cx: &mut TestAppContext) -> Option<String> {
self.view.read_with(cx, |view, cx| {
- view.preview().map(|preview| preview.read(cx).artifact().id.clone())
+ view.preview()
+ .and_then(|preview| preview.read(cx).artifact().map(|artifact| artifact.id.clone()))
+ })
+ }
+
+ /// Where the file on this machine previewed is.
+ fn previewing_local(&self, cx: &mut TestAppContext) -> Option<PathBuf> {
+ self.view.read_with(cx, |view, cx| {
+ view.preview()
+ .and_then(|preview| preview.read(cx).source().local().map(|file| file.path.clone()))
})
}
+ /// A task folder under the scratch directory, symlinks resolved.
+ fn task_folder(&self) -> PathBuf {
+ let folder = self.scratch.join("task");
+ std::fs::create_dir_all(&folder).expect("task folder");
+ std::fs::canonicalize(folder).expect("canonical")
+ }
+
+ /// What a click on `path` in a reply asks of the face.
+ fn open_path(&self, path: PathBuf, cx: &mut TestAppContext) {
+ let view = self.view.clone();
+ self.with_window(cx, |window, cx| {
+ view.update(cx, |view, cx| view.open_path(path, window, cx));
+ });
+ self.frame(cx);
+ }
+
+ fn clipboard(&self, cx: &mut TestAppContext) -> Option<String> {
+ self.with_window(cx, |_, cx| cx.read_from_clipboard().and_then(|item| item.text()))
+ }
+
fn open_preview(&self, id: &str, cx: &mut TestAppContext) {
self.click(domain_element_id("files-row", id), cx);
assert_eq!(self.previewing(cx).as_deref(), Some(id));
@@ -247,10 +302,17 @@ impl Face {
fn menu_items(&self, cx: &mut TestAppContext) -> Vec<&'static str> {
self.click("files-more", cx);
- let items: Vec<&'static str> = ["files-copy", "files-save", "files-open", "files-delete"]
- .into_iter()
- .filter(|key| self.exists(menu_item(key), cx))
- .collect();
+ let items: Vec<&'static str> = [
+ "files-copy",
+ "files-save",
+ "files-reveal",
+ "files-copy-path",
+ "files-open",
+ "files-delete",
+ ]
+ .into_iter()
+ .filter(|key| self.exists(menu_item(key), cx))
+ .collect();
self.press("escape", cx);
items
}
@@ -357,14 +419,28 @@ fn the_filter_narrows_the_list_and_counts_its_matches(cx: &mut TestAppContext) {
assert!(face.exists("files-no-matches", cx));
}
+/// On a Host on this machine the empty list also says that the paths a
+/// reply names open; a Host elsewhere keeps the one sentence.
#[gpui_kit::test]
fn an_empty_task_says_where_files_will_appear(cx: &mut TestAppContext) {
let face = Face::open(ScriptedHost::new(), cx);
- assert_eq!(face.label("files-empty", cx), Some(en(copy::EMPTY)));
+ assert_eq!(face.label("files-empty", cx), Some(en(copy::EMPTY_LOCAL)));
// The empty list still takes the focus and its keys.
face.focus(cx);
face.press("down enter escape", cx);
assert_eq!(*face.events.borrow(), [FilesViewEvent::Dismiss]);
+ drop(face);
+
+ let face = Face::open_on(ScriptedHost::new(), remote_host(), cx);
+ assert_eq!(face.label("files-empty", cx), Some(en(copy::EMPTY)));
+}
+
+fn remote_host() -> WindowHost {
+ let transport = RemoteTransport::tls("wss://box.example.com/runtime-host").expect("tls");
+ let profile =
+ RemoteHostProfile::new("box", "Box", &"a".repeat(64), transport).expect("profile");
+ let credential = AccessCredential::new("mrha_x").expect("credential");
+ WindowHost::Remote(RemoteHost::new(profile, credential))
}
#[gpui_kit::test]
@@ -1013,3 +1089,110 @@ fn open_in_default_app_writes_a_raster_copy_named_by_ids(cx: &mut TestAppContext
face.open_preview("a2", cx);
assert_eq!(face.menu_items(cx), ["files-save"]);
}
+
+/// A path a reply names, on this machine: a document opens in the default
+/// app; a script, a folder, a bundle, and a symlink named like a document
+/// that points at a folder or a program show in Finder, by where they lead.
+/// Nothing previews.
+#[cfg(unix)]
+#[gpui_kit::test]
+fn a_path_opens_a_document_and_shows_anything_else_in_finder(cx: &mut TestAppContext) {
+ use std::os::unix::fs::{PermissionsExt as _, symlink};
+
+ let face = Face::open(ScriptedHost::new(), cx);
+ let task = face.task_folder();
+ std::fs::write(task.join("report.docx"), b"PK").expect("docx");
+ std::fs::write(task.join("setup.command"), b"#!/bin/sh\n").expect("command");
+ std::fs::create_dir_all(task.join("folder")).expect("folder");
+ std::fs::create_dir_all(task.join("Tool.app/Contents/MacOS")).expect("app");
+ std::fs::write(task.join("tool"), b"#!/bin/sh\n").expect("tool");
+ std::fs::set_permissions(task.join("tool"), std::fs::Permissions::from_mode(0o755))
+ .expect("executable");
+ symlink(task.join("folder"), task.join("x.docx")).expect("link");
+ symlink(task.join("tool"), task.join("y.docx")).expect("link");
+
+ face.open_path(task.join("report.docx"), cx);
+ assert_eq!(*face.opened.borrow(), [task.join("report.docx")]);
+ for name in ["setup.command", "folder", "Tool.app", "x.docx", "y.docx"] {
+ face.open_path(task.join(name), cx);
+ }
+ let revealed = ["setup.command", "folder", "Tool.app", "folder", "tool"].map(|n| task.join(n));
+ assert_eq!(*face.revealed.borrow(), revealed);
+ assert_eq!(face.opened.borrow().len(), 1, "nothing else opens");
+ assert_eq!(face.previewing_local(cx), None);
+ assert!(face.events.borrow().is_empty(), "the face is not shown");
+}
+
+/// A Markdown path previews the file on this machine in the face, which
+/// asks the window to show it. Its menu copies the text and the path and
+/// shows the file in Finder; there is no Save As or Delete. An image has
+/// no Copy; an HTML page's Open in Default App opens the page itself; a
+/// file that cannot show offers Finder.
+#[gpui_kit::test]
+fn a_markdown_path_previews_the_file_on_this_machine(cx: &mut TestAppContext) {
+ let face = Face::open(ScriptedHost::new(), cx);
+ let task = face.task_folder();
+ let notes = task.join("notes.md");
+ std::fs::write(¬es, "# Notes\n\nReady.").expect("notes");
+ face.open_path(task.join("./notes.md"), cx);
+ assert_eq!(face.previewing_local(cx), Some(notes.clone()));
+ assert_eq!(*face.events.borrow(), [FilesViewEvent::Show]);
+ assert_eq!(face.text(cx), ("# Notes\n\nReady.".to_owned(), true));
+ assert_eq!(face.label("files-preview-name", cx).as_deref(), Some("notes.md"));
+ assert_eq!(face.menu_items(cx), ["files-copy", "files-reveal", "files-copy-path"]);
+
+ face.click("files-more", cx);
+ face.click(menu_item("files-copy-path"), cx);
+ assert_eq!(face.clipboard(cx), Some(notes.display().to_string()));
+ assert_eq!(face.notice(cx), Some((true, "Copied the path of notes.md".to_owned(), None)));
+ face.click("files-more", cx);
+ face.click(menu_item("files-reveal"), cx);
+ assert_eq!(*face.revealed.borrow(), std::slice::from_ref(¬es));
+ face.click("files-more", cx);
+ face.click(menu_item("files-copy"), cx);
+ assert_eq!(face.clipboard(cx).as_deref(), Some("# Notes\n\nReady."));
+ assert!(face.opened.borrow().is_empty());
+
+ let image = task.join("chart.png");
+ std::fs::write(&image, PNG).expect("image");
+ face.open_path(image.clone(), cx);
+ assert_eq!(face.previewing_local(cx), Some(image));
+ assert!(face.body(cx, |body, _| matches!(body, Body::Image(_))));
+ assert_eq!(face.menu_items(cx), ["files-reveal", "files-copy-path"]);
+
+ let page = task.join("page.html");
+ std::fs::write(&page, "<p>Hi</p>").expect("page");
+ face.open_path(page.clone(), cx);
+ assert_eq!(
+ face.menu_items(cx),
+ ["files-copy", "files-reveal", "files-copy-path", "files-open"]
+ );
+ face.click("files-more", cx);
+ face.click(menu_item("files-open"), cx);
+ assert_eq!(*face.opened.borrow(), [page]);
+
+ // A text file that is not text: the way to it is Finder.
+ let log = task.join("dump.log");
+ std::fs::write(&log, b"\0\0\0\x01binary").expect("log");
+ face.open_path(log.clone(), cx);
+ assert_eq!(face.why(cx), Some(en(copy::WHY_LOCAL_NOT_SHOWN)));
+ assert!(!face.exists("files-body-save", cx));
+ face.click("files-body-reveal", cx);
+ assert_eq!(face.revealed.borrow().last(), Some(&log));
+}
+
+/// A file removed between the reply and the click: the face says it is no
+/// longer there, and nothing opens or shows.
+#[gpui_kit::test]
+fn a_path_gone_before_the_click_says_so(cx: &mut TestAppContext) {
+ let face = Face::open(ScriptedHost::new(), cx);
+ let task = face.task_folder();
+ std::fs::write(task.join("report.docx"), b"PK").expect("docx");
+ std::fs::remove_file(task.join("report.docx")).expect("removed");
+ face.open_path(task.join("report.docx"), cx);
+ let gone = en(copy::FILE_GONE);
+ assert_eq!(face.notice(cx), Some((false, gone, None)));
+ assert!(face.opened.borrow().is_empty());
+ assert!(face.revealed.borrow().is_empty());
+ assert!(face.events.borrow().is_empty());
+}
diff --git a/apps/desktop-gpui/crates/shared/src/copy/conversation.rs b/apps/desktop-gpui/crates/shared/src/copy/conversation.rs
index c9d156c863..1bfce0c1b1 100644
--- a/apps/desktop-gpui/crates/shared/src/copy/conversation.rs
+++ b/apps/desktop-gpui/crates/shared/src/copy/conversation.rs
@@ -86,12 +86,14 @@ texts! {
TOOL_INPUT = "Input", "输入", "輸入";
TOOL_OUTPUT = "Output", "输出", "輸出";
TOOL_NO_OUTPUT = "No output yet", "尚无输出", "尚無輸出";
- /// A finished call whose result has not arrived: the Host sends Tool
- /// results with the turn's record, once the turn ends.
- TOOL_OUTPUT_AT_TURN_END =
- "Output appears when the turn ends",
- "本轮结束后显示输出",
- "本輪結束後顯示輸出";
+ /// A finished call whose arguments and result have not arrived: the
+ /// Host sends them with the turn's record, once the turn ends. Said as
+ /// the answer finishing, Maka Desktop's word for a turn in its copy
+ /// (`editMessageDisabledRunning`).
+ TOOL_DETAILS_AT_TURN_END =
+ "Details appear when this answer finishes",
+ "回答完成后显示详情",
+ "回答完成後顯示詳細資訊";
/// A finished call that returned nothing to show (Maka Desktop's `noOutput`).
TOOL_OUTPUT_NONE = "No output", "无输出", "無輸出";
/// An empty value or list inside a Tool's output (Maka Desktop's `empty`).
@@ -167,7 +169,11 @@ texts! {
/// The model picker's accessible name and tooltip.
MODEL = "Model", "模型", "模型";
/// The model picker's tooltip while a turn runs, when it is disabled.
- MODEL_BUSY = "Switch models when the current turn ends", "本轮结束后再切换模型", "本輪結束後再切換模型";
+ /// Worded as Maka Desktop's `editMessageDisabledRunning`.
+ MODEL_BUSY =
+ "Wait for this answer to finish before switching models",
+ "当前回答仍在进行中,结束后再切换模型",
+ "目前回答仍在進行中,結束後再切換模型";
MODELS_LOADING = "Loading models…", "正在加载模型…", "正在載入模型…";
MODELS_FAILED = "Couldn’t load the models", "无法加载模型", "無法載入模型";
MODELS_NONE = "No models enabled", "没有已启用的模型", "沒有已啟用的模型";
diff --git a/apps/desktop-gpui/crates/shared/src/copy/files.rs b/apps/desktop-gpui/crates/shared/src/copy/files.rs
index f3a7498f26..2f005067dd 100644
--- a/apps/desktop-gpui/crates/shared/src/copy/files.rs
+++ b/apps/desktop-gpui/crates/shared/src/copy/files.rs
@@ -21,8 +21,9 @@
//! file's preview, its actions, and every line that says why something
//! could not be shown or done. Desktop's `ArtifactCopy`
//! (`apps/desktop/src/renderer/locales/artifact-copy.ts`) where it has the
-//! words; this client's own where its Files face differs (no Finder; an
-//! HTML page drawn by the kit's text view, without its scripts or styles).
+//! words; this client's own where its Files face differs (Finder only for
+//! a file on this machine that a reply names; an HTML page drawn by the
+//! kit's text view, without its scripts or styles).
use super::{Locale, plural};
@@ -39,6 +40,12 @@ texts! {
NO_MATCHES = "No files match", "没有匹配的文件", "沒有符合的檔案";
/// The list with nothing in it.
EMPTY = "Files the agent makes appear here.", "Agent 生成的文件会显示在这里。", "Agent 產生的檔案會顯示在這裡。";
+ /// The list with nothing in it, on a Host on this machine, where the
+ /// paths a reply names open on a click.
+ EMPTY_LOCAL =
+ "Files the agent makes appear here. File paths in replies open when clicked.",
+ "Agent 生成的文件会显示在这里。回复中的文件路径可以直接点击打开。",
+ "Agent 產生的檔案會顯示在這裡。回覆中的檔案路徑可以直接點擊開啟。";
LOADING = "Loading files…", "正在读取文件…", "正在讀取檔案…";
LIST_FAILED = "Couldn’t list this task’s files.", "无法列出此任务的文件。", "無法列出此任務的檔案。";
RETRY = "Retry", "重试", "重試";
@@ -84,6 +91,13 @@ texts! {
COPY = "Copy", "复制", "複製";
SAVE_AS = "Save As…", "另存为…", "另存新檔…";
OPEN_DEFAULT = "Open in Default App", "用默认应用打开", "以預設應用程式開啟";
+ /// A file on this machine that a reply names: shown in its folder,
+ /// and its path copied (Desktop's `openInFinder`).
+ REVEAL = "Show in Finder", "在 Finder 中打开", "在 Finder 中開啟";
+ COPY_PATH = "Copy Path", "复制路径", "複製路徑";
+ PATH_COPIED = "Copied the path of {name}", "已复制 {name} 的路径", "已複製 {name} 的路徑";
+ /// A path a reply names, clicked when nothing is there any more.
+ FILE_GONE = "This file is no longer there", "找不到这个文件", "找不到這個檔案";
/// The menu item, which asks first.
DELETE_ITEM = "Delete…", "删除…", "刪除…";
/// The confirmation's button.
@@ -171,6 +185,16 @@ texts! {
"Maka has no folder to put a copy in. Save a copy instead.",
"Maka 没有可用来存放副本的文件夹。请改为另存一份。",
"Maka 沒有可用來存放副本的資料夾。請改為另存一份。";
+ /// A file on this machine that a reply names, whose content the
+ /// preview cannot draw.
+ WHY_LOCAL_NOT_SHOWN =
+ "This file can’t be shown here. Show it in Finder to open it in another app.",
+ "此文件无法在这里显示。可以在 Finder 中找到它,再用其他应用打开。",
+ "此檔案無法在這裡顯示。可以在 Finder 中找到它,再用其他應用程式開啟。";
+ WHY_LOCAL_READ_FAILED =
+ "Couldn’t read this file: {message}",
+ "无法读取此文件:{message}",
+ "無法讀取此檔案:{message}";
WHY_NOT_DRAWN =
"This image can’t be shown here. Save a copy to open it in another app.",
"此图片无法在这里显示。另存一份即可用其他应用打开。",
@@ -226,6 +250,11 @@ pub fn why_host(locale: Locale, message: &str) -> String {
WHY_HOST.fill(locale, &[("message", message)])
}
+/// A file on this machine that could not be read, in the system's words.
+pub fn why_local_read_failed(locale: Locale, message: &str) -> String {
+ WHY_LOCAL_READ_FAILED.fill(locale, &[("message", message)])
+}
+
/// A write that failed, in the system's words.
pub fn why_write_failed(locale: Locale, message: &str) -> String {
WHY_WRITE_FAILED.fill(locale, &[("message", message)])
diff --git a/apps/desktop-gpui/crates/shared/src/links.rs b/apps/desktop-gpui/crates/shared/src/links.rs
index 525881d475..701aed5849 100644
--- a/apps/desktop-gpui/crates/shared/src/links.rs
+++ b/apps/desktop-gpui/crates/shared/src/links.rs
@@ -21,7 +21,9 @@
//! daily review): which ones open. gpui-kit's text view hands any address
//! to the platform by default, so a `javascript:` or `file:` link the agent
//! wrote would reach Launch Services as it is, and a `file:` link can start
-//! an application. Every rendered text takes [`follow_link`] instead.
+//! an application. Every rendered text takes [`follow_link`] instead; a
+//! reply's links to paths on this machine, in the conversation's own
+//! scheme, go to the conversation before it and never reach it.
use gpui_kit::{App, ClickEvent, MouseButton, SharedString};
@@ -37,19 +39,25 @@ pub fn external_link(href: &str) -> Option<String> {
}
/// Opens a link clicked in rendered text when it is a web or mail address
-/// ([`external_link`]); any other link does nothing. Which clicks follow a
-/// link is the kit's own rule, which a handler replaces: the primary or
-/// middle button, a key, a tap.
+/// ([`external_link`]); any other link does nothing.
pub fn follow_link(href: &SharedString, event: &ClickEvent, cx: &mut App) {
- let follows = match event {
+ if follows(event)
+ && let Some(url) = external_link(href)
+ {
+ cx.open_url(&url);
+ }
+}
+
+/// Whether `event` follows the link it clicked: the kit's own rule, which
+/// a handler replaces: the primary or middle button, a key, a tap. A
+/// right-click does not.
+pub fn follows(event: &ClickEvent) -> bool {
+ match event {
ClickEvent::Mouse(click) => {
matches!(click.up.button, MouseButton::Left | MouseButton::Middle)
}
ClickEvent::Keyboard(_) => true,
ClickEvent::Touch(tap) => !tap.long_press,
- };
- if follows && let Some(url) = external_link(href) {
- cx.open_url(&url);
}
}
diff --git a/apps/desktop-gpui/docs/plan/phase-4-modules.md b/apps/desktop-gpui/docs/plan/phase-4-modules.md
index cf8c8e8f75..d6885db999 100644
--- a/apps/desktop-gpui/docs/plan/phase-4-modules.md
+++ b/apps/desktop-gpui/docs/plan/phase-4-modules.md
@@ -58,8 +58,8 @@ two reviewers (Opus and Fable) without a sign-off per step; each package is comm
candidates). Links in rendered text open only `http:`, `https:` and `mailto:` (Desktop's
rule); a page's images draw only from `data:` URLs, as the app has no HTTP client. Open in
Default App for PDFs, raster images and HTML pages (the browser runs a page's scripts), as a
- copy under the app's cache named by ids; Save As for every kind; no Show in Finder (no path
- in the protocol).
+ copy under the app's cache named by ids; Save As for every kind; no Show in Finder for an
+ Artifact (no path in the protocol).
- **Trace (Desktop's Inspector)** is a workbar face after Files: persisted for the task, one
face, the `activity` glyph (added to the icon set), no shortcut, as Desktop's. It shows what
Desktop's panel shows from the same three reads, `execution.inspect.query`
@@ -129,6 +129,18 @@ two reviewers (Opus and Fable) without a sign-off per step; each package is comm
and operators mixed from the palette's ink and background. Every role keeps APCA Lc 45 on the
fills code sits on (code, sunken, a diff's added and removed rows) in every palette and mode,
comments Lc 35.
+- **Paths in replies (F46)** open on a click, on a Host on this machine only (Zed's agent panel
+ does this; Desktop does not). When a reply settles, one background pass checks each inline
+ code span that is wholly a path (absolute, `~/…`, or relative to the task's folder; a trailing
+ `:line[:col]` dropped) and each link to a `file:` URL or a plain path. Those naming something
+ that exists become links with the client's own `maka-file:` scheme in the Markdown handed to
+ the text view, so they draw as the kit's link over a code chip; find searches the reply's own
+ text and maps its ranges onto the rewritten one. A click decides again from the file there,
+ symlinks resolved: nothing there says so; a folder, a bundle or an unknown kind shows in
+ Finder; a document on a fixed list (Office, iWork, OpenDocument, PDF, CSV, RTF, EPUB) opens in
+ the default app; text, source, an HTML page or an image within the Files face's limits
+ previews there, with Show in Finder and Copy Path. Nothing else is opened or launched. No
+ right-click menu or tooltip on a path: the kit's text view has no hook for either.
## Packages
@@ -149,6 +161,7 @@ two reviewers (Opus and Fable) without a sign-off per step; each package is comm
| F43 | Files: HTML pages rendered in the face, links by Desktop's rule, pages opened in the default app | 4a05bc0..9b58c10 | done |
| F44 | Side chat fixes from an adversarial review: the ledger merged across runs and never overwritten unread, owner locks taken before they are named, `operation_conflict` settled, removals tried again, the picked mode set again | a754ada..cbbca54 | done |
| F45 | A State Root whose disk identity changed (macOS remounted its volume): Desktop's repair prompt in the disconnected strip, Repair workspace beside Retry, the marker's `rootIdentity` replaced under Maka's marker lock with before and after checks | e6d0a25..b5ec632 | done |
+| F46 | File paths in replies open the file on a Host on this machine: previewed in Files, opened in the default app (documents only) or shown in Finder | bf7cd70..a527e4d | done |
Later candidates: Browser (gpui-kit has a `webview` crate; the model's browser tools need
client capabilities), and a webview for the Files face's HTML pages, which would run their
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org