All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.
Rust
fix(macos): open conversation file links in Finder
YTwsy43f976052e8a
diff --git a/Cargo.lock b/Cargo.lockindex 9472446..932dbb2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7750,6 +7750,7 @@ dependencies = ["gpui-component","gpui_platform","image",+ "percent-encoding","semver","serde","serde_json",@@ -7757,6 +7758,7 @@ dependencies = ["tempfile","unicode-segmentation","unicode-width",+ "url","wake-core","winresource","zed-reqwest 0.12.15-zed (registry+https://github.com/rust-lang/crates.io-index)",diff --git a/crates/wake/Cargo.toml b/crates/wake/Cargo.tomlindex e4ec006..335da4f 100644--- a/crates/wake/Cargo.toml+++ b/crates/wake/Cargo.toml@@ -28,6 +28,8 @@ unicode-width = "0.2"# GetUserDefaultLocaleName、Linux 读 LC_ALL/LANG,三平台一份接口sys-locale = "0.3"unicode-segmentation = "1.13"+percent-encoding = "2.3"+url = "2.5"[dev-dependencies]gpui = { git = "https://github.com/zed-industries/zed", features = ["test-support"] }diff --git a/crates/wake/locales/zh-Hans.json b/crates/wake/locales/zh-Hans.jsonindex f274759..aa4f8a5 100644--- a/crates/wake/locales/zh-Hans.json+++ b/crates/wake/locales/zh-Hans.json@@ -247,6 +247,7 @@"Syncing {}…": "正在同步 {}…","Syncing…": "正在同步…","System": "跟随系统",+ "The linked path is unavailable on this Mac.": "此链接的路径在这台 Mac 上不存在或无法访问。","The session file will be moved to Trash. You can restore it anytime:": "会话文件将被移到废纸篓,随时可以还原:","The session file will be moved to the Recycle Bin. You can restore it anytime:": "会话文件将被移到回收站,随时可以还原:","Thinking": "思考",diff --git a/crates/wake/src/i18n.rs b/crates/wake/src/i18n.rsindex f2bd76e..1ab6e84 100644--- a/crates/wake/src/i18n.rs+++ b/crates/wake/src/i18n.rs@@ -587,6 +587,7 @@ mod tests {include_str!("workbench.rs"),include_str!("settings.rs"),include_str!("main.rs"),+ include_str!("markdown_links.rs"),include_str!("format.rs"),];for (tag, _, text) in BUNDLED {diff --git a/crates/wake/src/main.rs b/crates/wake/src/main.rsindex cdf4832..dc9e251 100644--- a/crates/wake/src/main.rs+++ b/crates/wake/src/main.rs@@ -10,6 +10,7 @@ mod assets;mod format;mod i18n;mod main_window;+mod markdown_links;mod prefs;mod settings;mod theme;diff --git a/crates/wake/src/markdown_links.rs b/crates/wake/src/markdown_links.rsnew file mode 100644index 0000000..d8bbddd--- /dev/null+++ b/crates/wake/src/markdown_links.rs@@ -0,0 +1,538 @@+//! macOS 会话正文的文件链接。路径归属来自会话,不能从本机同名文件推断。+use std::path::{Path, PathBuf};++use gpui::{ClickEvent, MouseButton};+use gpui_component::{notification::Notification, text::TextView, WindowExt as _};+use percent_encoding::percent_decode_str;+use url::Url;++use crate::i18n::t;++pub(crate) fn with_session_links(view: TextView, host: &str, project_path: &str) -> TextView {+ // 本轮只接管 macOS;其余平台保留组件默认行为,仍参与编译检查。+ if !cfg!(target_os = "macos") {+ return view;+ }+ let remote = !host.is_empty();+ let project_path = project_path.to_owned();+ view.on_link_click(move |href, event, window, cx| {+ // 组件设置 handler 后会连右键一起转发,须保留默认激活规则。+ let activate = match event {+ ClickEvent::Mouse(click) => {+ matches!(click.up.button, MouseButton::Left | MouseButton::Middle)+ }+ ClickEvent::Keyboard(_) => true,+ ClickEvent::Touch(click) => !click.long_press,+ };+ if !activate {+ return;+ }+ match resolve_link(href, remote, &project_path, dirs::home_dir) {+ LinkTarget::External => cx.open_url(href),+ LinkTarget::File(path) => {+ if let Some(path) = path.to_str() {+ wake_core::services::terminal::open_in_file_manager(path);+ } else {+ window.push_notification(+ Notification::info(t("The linked path is unavailable on this Mac.")),+ cx,+ );+ }+ }+ LinkTarget::Remote => window.push_notification(+ Notification::info(t(+ "Remote sessions are read-only — files stay on the remote host",+ )),+ cx,+ ),+ LinkTarget::Unavailable => window.push_notification(+ Notification::info(t("The linked path is unavailable on this Mac.")),+ cx,+ ),+ LinkTarget::Ignore => {}+ }+ })+}++#[derive(Debug, PartialEq, Eq)]+enum LinkTarget {+ External,+ File(PathBuf),+ Remote,+ Unavailable,+ Ignore,+}++fn resolve_link(+ href: &str,+ remote: bool,+ project_path: &str,+ home_dir: impl FnOnce() -> Option<PathBuf>,+) -> LinkTarget {+ if href.is_empty() || href.starts_with('#') {+ return LinkTarget::Ignore;+ }+ // 盘符须先于 scheme 识别,否则 C:/... 会被交给 URL 打开器。+ let windows = windows_path(href);+ let scheme = (!windows).then(|| url_scheme(href)).flatten();+ if scheme.is_some_and(|scheme| !scheme.eq_ignore_ascii_case("file")) {+ return LinkTarget::External;+ }+ // rsync 只镜像会话数据。远程正文路径不能展开本机 HOME,也不能探测本机。+ if remote {+ return LinkTarget::Remote;+ }+ if windows || href.chars().any(char::is_control) {+ return LinkTarget::Unavailable;+ }+ if scheme.is_some() {+ let Some(path) = file_uri_path(href) else {+ return LinkTarget::Unavailable;+ };+ if path.exists() {+ return LinkTarget::File(path);+ }+ return without_line_number(href)+ .and_then(file_uri_path)+ .filter(|path| path.is_file())+ .map_or(LinkTarget::Unavailable, LinkTarget::File);+ }++ let home = home_dir();+ if let Some(path) = existing_local_path(href, project_path, home.as_deref()) {+ return LinkTarget::File(path);+ }+ without_line_number(href)+ .and_then(|href| existing_local_path(href, project_path, home.as_deref()))+ .filter(|path| path.is_file())+ .map_or(LinkTarget::Unavailable, LinkTarget::File)+}++fn existing_local_path(href: &str, project_path: &str, home: Option<&Path>) -> Option<PathBuf> {+ // 裸路径先按原字面查找,保留真实文件名里的 %, #, ? 等字符。+ if let Some(path) = local_path(href, project_path, home).filter(|p| p.exists()) {+ return Some(path);+ }+ // Markdown href 也可能编码了空格/中文。只解码一次,不把失败的文件路径+ // 回退为 open_url,也不猜测缺失的 file URI authority。+ if href.contains('%') {+ if let Ok(decoded) = percent_decode_str(href).decode_utf8() {+ return local_path(&decoded, project_path, home).filter(|p| p.exists());+ }+ }+ None+}++fn without_line_number(href: &str) -> Option<&str> {+ // 完整文件名不存在时才尝试 :行号。先于百分号解码,避免把文件名里的+ // %3A 误当定位符;Finder 只选中文件,不负责跳转到该行。+ let (path, line) = href.rsplit_once(':')?;+ (!path.is_empty()+ && line.bytes().all(|byte| byte.is_ascii_digit())+ && line.parse::<usize>().is_ok_and(|line| line > 0))+ .then_some(path)+}++fn url_scheme(href: &str) -> Option<&str> {+ let (scheme, _) = href.split_once(':')?;+ let mut bytes = scheme.bytes();+ (bytes.next()?.is_ascii_alphabetic()+ && bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')))+ .then_some(scheme)+}++fn windows_path(path: &str) -> bool {+ let bytes = path.as_bytes();+ path.starts_with("\\\\")+ || (bytes.len() >= 2+ && bytes[0].is_ascii_alphabetic()+ && bytes[1] == b':'+ && (bytes.len() == 2+ || bytes[2] == b'\\'+ || (bytes[2] == b'/' && bytes.get(3) != Some(&b'/'))))+}++fn file_uri_path(href: &str) -> Option<PathBuf> {+ // file:relative 和反斜杠纠正不在本轮范围,不让宽松 URL 解析猜成本机路径。+ if !href.split_once(':')?.1.starts_with('/') || href.contains('\\') {+ return None;+ }+ let url = Url::parse(href).ok()?;+ if url.host_str().is_some_and(|host| host != "localhost")+ || url.query().is_some()+ || url.fragment().is_some()+ {+ return None;+ }+ let path = url.to_file_path().ok()?;+ let text = path.to_str()?;+ if !path.is_absolute() || text.starts_with("//") || windows_path(text.trim_start_matches('/')) {+ return None;+ }+ Some(path)+}++fn local_path(href: &str, project_path: &str, home: Option<&Path>) -> Option<PathBuf> {+ if href.is_empty()+ || href.starts_with(['#', '?'])+ || href.starts_with("//")+ || windows_path(href)+ || href.chars().any(char::is_control)+ {+ return None;+ }+ let path = if href == "~" {+ home?.to_path_buf()+ } else if let Some(relative) = href.strip_prefix("~/") {+ home?.join(relative.trim_start_matches('/'))+ } else if href.starts_with('~') {+ return None;+ } else if Path::new(href).is_absolute() {+ PathBuf::from(href)+ } else {+ let project = Path::new(project_path);+ if !project.is_absolute() || !project.is_dir() {+ return None;+ }+ project.join(href)+ };+ path.is_absolute().then_some(path)+}++#[cfg(all(test, target_os = "macos"))]+mod tests {+ use super::*;+ use gpui::AppContext as _;+ use std::fs;++ #[test]+ fn local_files_directories_and_encoded_links() {+ let temp = tempfile::tempdir().unwrap();+ let project = temp.path().join("OpenSurge for Mac");+ let file = project.join("internal/controlapi/mihomo_recovery.go");+ fs::create_dir_all(file.parent().unwrap()).unwrap();+ fs::write(&file, "package controlapi\n").unwrap();+ let project_text = project.to_str().unwrap();+ let file_text = file.to_str().unwrap();+ let file_url = Url::from_file_path(&file).unwrap();+ for href in [+ file_text.to_owned(),+ file_text.replace(' ', "%20"),+ file_url.to_string(),+ format!("file:{}", file_url.path()),+ format!("FILE://localhost{}", file_url.path()),+ "internal/controlapi/mihomo_recovery.go".into(),+ "./internal/controlapi/mihomo_recovery.go".into(),+ "../OpenSurge for Mac/internal/controlapi/mihomo_recovery.go".into(),+ "~/OpenSurge for Mac/internal/controlapi/mihomo_recovery.go".into(),+ ] {+ let target = resolve_link(&href, false, project_text, || Some(temp.path().into()));+ let LinkTarget::File(path) = target else {+ panic!("{href:?}: {target:?}");+ };+ assert_eq!(path.canonicalize().unwrap(), file.canonicalize().unwrap());+ }+ assert_eq!(+ resolve_link(project_text, false, "", || None),+ LinkTarget::File(project)+ );+ }++ #[test]+ fn line_number_links_resolve_to_existing_files() {+ let temp = tempfile::tempdir().unwrap();+ let project = temp.path().join("Wake with spaces");+ fs::create_dir_all(project.join("src")).unwrap();+ for (name, line) in [("markdown_links.rs", 11), ("workbench.rs", 7955)] {+ let file = project.join("src").join(name);+ fs::write(&file, "").unwrap();+ for href in [+ format!("{}:{line}", file.display()),+ format!("{}:{line}", file.to_str().unwrap().replace(' ', "%20")),+ format!("{}:{line}", Url::from_file_path(&file).unwrap()),+ format!("src/{name}:{line}"),+ format!("./src/{name}:{line}"),+ format!("~/Wake with spaces/src/{name}:{line}"),+ ] {+ let target = resolve_link(&href, false, project.to_str().unwrap(), || {+ Some(temp.path().into())+ });+ let LinkTarget::File(path) = target else {+ panic!("{href:?}: {target:?}");+ };+ assert_eq!(path.canonicalize().unwrap(), file.canonicalize().unwrap());+ }+ }+ }++ #[test]+ fn line_numbers_preserve_literal_names_and_require_a_file() {+ let temp = tempfile::tempdir().unwrap();+ let file = temp.path().join("source file.rs");+ let literal = temp.path().join("source file.rs:11");+ // 即使去掉行号后两种拼法都存在,完整的解码文件名也优先。+ for path in [&file, &literal, &temp.path().join("source%20file.rs")] {+ fs::write(path, "").unwrap();+ }+ for href in [+ literal.to_str().unwrap().to_owned(),+ literal.to_str().unwrap().replace(' ', "%20"),+ Url::from_file_path(&literal).unwrap().to_string(),+ ] {+ assert_eq!(+ resolve_link(&href, false, "", || None),+ LinkTarget::File(literal.clone())+ );+ }+ for suffix in [":0", ":+11", ":-11", ":line11", "%3A12", ":11#fragment"] {+ for base in [+ file.to_str().unwrap().to_owned(),+ Url::from_file_path(&file).unwrap().to_string(),+ ] {+ let href = format!("{base}{suffix}");+ assert_eq!(+ resolve_link(&href, false, "", || None),+ LinkTarget::Unavailable,+ "{href}"+ );+ }+ }+ assert_eq!(+ resolve_link(&format!("{}:11", temp.path().display()), false, "", || None),+ LinkTarget::Unavailable+ );+ }++ #[test]+ fn filenames_are_not_reinterpreted_or_decoded_twice() {+ let temp = tempfile::tempdir().unwrap();+ for name in [+ "中文 #1%.md",+ "literal%20space.md",+ "literal space.md",+ "name:42",+ "name#L42",+ ] {+ let path = temp.path().join(name);+ fs::write(&path, "").unwrap();+ for href in [+ path.to_str().unwrap().to_owned(),+ Url::from_file_path(&path).unwrap().to_string(),+ ] {+ assert_eq!(+ resolve_link(&href, false, "", || None),+ LinkTarget::File(path.clone())+ );+ }+ }+ fs::write(temp.path().join("once decoded.md"), "").unwrap();+ assert_eq!(+ resolve_link(+ "once%2520decoded.md",+ false,+ temp.path().to_str().unwrap(),+ || None+ ),+ LinkTarget::Unavailable+ );+ }++ #[test]+ fn remote_paths_never_resolve_against_this_mac() {+ let temp = tempfile::tempdir().unwrap();+ let file = temp.path().join("exists.md");+ fs::write(&file, "").unwrap();+ let with_line = format!("{}:11", file.display());+ for href in [+ file.to_str().unwrap(),+ &with_line,+ "~/exists.md",+ "~/exists.md:11",+ "exists.md",+ "./exists.md:11",+ "file:///tmp/exists.md",+ "file:///tmp/exists.md:11",+ "C:/work/a.rs",+ ] {+ assert_eq!(+ resolve_link(href, true, temp.path().to_str().unwrap(), || panic!(+ "remote path requested local HOME"+ )),+ LinkTarget::Remote+ );+ }+ }++ #[test]+ fn invalid_or_unavailable_paths_never_become_external_urls() {+ let temp = tempfile::tempdir().unwrap();+ for href in [+ "/wake-link-test-missing/a.rs",+ "/wake-link-test-missing/a.rs:11",+ "missing.rs",+ "file:relative.rs",+ "file://Users/example/a.rs",+ "file://server/share/a.rs",+ "file://server/share/a.rs:11",+ "file:///C:/work/a.rs",+ "C:/work/a.rs",+ r"C:\work\a.rs",+ r"\\server\share\a.rs",+ "//server/share/a.rs",+ "file:///tmp/a.rs?x=1",+ "file:///tmp/a.rs#L42",+ "file:///tmp/a%00.rs",+ "~someone/a.rs",+ ] {+ assert_eq!(+ resolve_link(href, false, temp.path().to_str().unwrap(), || None),+ LinkTarget::Unavailable,+ "{href}"+ );+ }+ // 即使当前工作目录中确有 Cargo.toml,也不能在会话基准缺席时使用 cwd。+ assert_eq!(+ resolve_link("Cargo.toml", false, "", || None),+ LinkTarget::Unavailable+ );+ assert_eq!(+ resolve_link("Cargo.toml", false, ".", || None),+ LinkTarget::Unavailable+ );+ }++ #[test]+ fn external_schemes_and_anchors_keep_their_own_meaning() {+ for remote in [false, true] {+ for href in [+ "https://example.com/a%20b?q=1#x",+ "http://example.com",+ "mailto:[email protected]",+ "vscode://file/tmp/a.rs",+ "vscode://file/tmp/a.rs:11",+ "https://example.com/a.rs:11",+ "custom+app:value",+ "x://example.com",+ ] {+ assert_eq!(+ resolve_link(href, remote, "", || panic!("URL requested local HOME")),+ LinkTarget::External+ );+ }+ for href in ["", "#section"] {+ assert_eq!(resolve_link(href, remote, "", || None), LinkTarget::Ignore);+ }+ }+ }++ struct LinkView {+ href: String,+ host: &'static str,+ }++ impl gpui::Render for LinkView {+ fn render(+ &mut self,+ _: &mut gpui::Window,+ _: &mut gpui::Context<Self>,+ ) -> impl gpui::IntoElement {+ use gpui::{ParentElement as _, Styled as _};+ gpui::div().w(gpui::px(360.)).child(with_session_links(+ TextView::markdown("test-link", format!("[example link](<{}>)", self.href))+ .selectable(true),+ self.host,+ "",+ ))+ }+ }++ #[gpui::test]+ fn missing_file_click_is_handled_in_wake(cx: &mut gpui::TestAppContext) {+ use gpui::{point, px, Modifiers};+ use gpui_component::Root;+ cx.update(gpui_component::init);+ let (root, cx) = cx.add_window_view(|window, cx| {+ let view = cx.new(|_| LinkView {+ href: "/wake-link-test-missing/OpenSurge for Mac/a.go".into(),+ host: "",+ });+ Root::new(view, window, cx)+ });+ cx.run_until_parked();+ cx.update(|window, cx| {+ let _ = window.draw(cx);+ });+ let notifications = root.read_with(cx, |root, _| root.notification.clone());+ cx.simulate_mouse_down(+ point(px(15.), px(12.)),+ MouseButton::Right,+ Modifiers::default(),+ );+ cx.simulate_mouse_up(+ point(px(15.), px(12.)),+ MouseButton::Right,+ Modifiers::default(),+ );+ assert!(notifications.read_with(cx, |list, _| list.notifications().is_empty()));+ assert_eq!(cx.opened_url(), None);+ cx.simulate_click(point(px(15.), px(12.)), Modifiers::default());+ assert_eq!(+ notifications.read_with(cx, |list, _| list.notifications().len()),+ 1+ );+ assert_eq!(cx.opened_url(), None);+ }++ #[gpui::test]+ #[allow(deprecated)]+ fn external_links_preserve_selection_and_middle_click(cx: &mut gpui::TestAppContext) {+ use gpui::{point, px, Modifiers};+ use gpui_component::Root;+ let href = "https://example.com/a%20b?q=1#anchor";+ cx.update(gpui_component::init);+ let (_, cx) = cx.add_window_view(|window, cx| {+ let view = cx.new(|_| LinkView {+ href: href.into(),+ host: "remote-host",+ });+ Root::new(view, window, cx)+ });+ cx.run_until_parked();+ cx.update(|window, cx| {+ let _ = window.draw(cx);+ });+ cx.simulate_mouse_down(+ point(px(5.), px(12.)),+ MouseButton::Left,+ Modifiers::default(),+ );+ cx.simulate_mouse_move(+ point(px(65.), px(12.)),+ Some(MouseButton::Left),+ Modifiers::default(),+ );+ cx.simulate_mouse_up(+ point(px(65.), px(12.)),+ MouseButton::Left,+ Modifiers::default(),+ );+ assert_eq!(cx.opened_url(), None);+ assert!(!cx.update(|window, cx| window.selected_text(cx)).is_empty());+ // 点空白处取消选区后,中键仍按组件原来的规则打开外链。+ cx.simulate_click(point(px(300.), px(100.)), Modifiers::default());+ cx.update(|window, cx| {+ let _ = window.draw(cx);+ });+ cx.simulate_mouse_down(+ point(px(15.), px(12.)),+ MouseButton::Middle,+ Modifiers::default(),+ );+ cx.simulate_mouse_up(+ point(px(15.), px(12.)),+ MouseButton::Middle,+ Modifiers::default(),+ );+ assert_eq!(cx.opened_url().as_deref(), Some(href));+ }+}diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rsindex 3d7ce2e..998eab6 100644--- a/crates/wake/src/workbench.rs+++ b/crates/wake/src/workbench.rs@@ -5570,6 +5570,7 @@ impl Workbench {ix,m.seq,&m.text,+ &detail.meta,&shots,FONT_MSG_USER,gpui::rems(0.5),@@ -5607,6 +5608,7 @@ impl Workbench {ix,m.seq,&m.text,+ &detail.meta,&shots,FONT_MSG_BODY,gpui::rems(0.6),@@ -7667,6 +7669,7 @@ fn message_content(message_index: usize,seq: i64,text: &str,+ session: &SessionMeta,slots: &[ImageSlot],base: Pixels,paragraph_gap: gpui::Rems,@@ -7695,6 +7698,7 @@ fn message_content(markdown_body(format!("dmsg-{seq}-part-{part}").into(),segment,+ session,base,paragraph_gap,dark,@@ -7870,10 +7874,11 @@ fn centered_pill(text: impl Into<SharedString>, cx: &App) -> Div {}/// 对话正文共用的 Markdown 视图。表格、引用块与分隔线由组件原生解析;-/// Wake 只覆写标题层级、代码块表面、语法配色和代码操作区。+/// Wake 覆写样式、代码操作区,并按会话所属主机处理 macOS 正文链接。fn markdown_body(id: SharedString,text: &str,+ session: &SessionMeta,base: Pixels,paragraph_gap: gpui::Rems,dark: bool,@@ -7887,7 +7892,7 @@ fn markdown_body(// 首次解析路径,避免代码块短暂保留上一种模式的颜色。let themed_id: SharedString = format!("{id}-{}", if dark { "dark" } else { "light" }).into();- TextView::markdown(themed_id, text)+ let view = TextView::markdown(themed_id, text).style(TextViewStyle {heading_base_font_size: base,@@ -7946,7 +7951,8 @@ fn markdown_body(.child(icon("icons/copy.svg").with_size(px(12.))),)})- .selectable(true)+ .selectable(true);+ crate::markdown_links::with_session_links(view, &session.host, &session.project_path)}/// Thinking 折叠面板:收起是一行摘要,展开后显示完整原文。