From e9d651751353403f319e2995e3b6f388febd72bb Mon Sep 17 00:00:00 2001 From: Nico Wiedemann Date: Sat, 7 Nov 2026 15:40:26 +0100 Subject: [PATCH 1/5] Suggest project files when typing @, from a folder linked to each context A context can now be linked to its project folder, and typing @ in a stash suggests the files in it. Picking one writes @src/app.ts, the form Claude Code uses, with quotes only when the path has whitespace, so an agent working in the project opens the file directly. The link is a device-local fact: a folder path means nothing on another machine. It lives in its own context_folders table with no foreign key, because every context write is INSERT OR REPLACE, which would reset a column on the row and fire a cascade. Tests cover a save and a sync pull of the context, and that the path never reaches the sync payload. The folder is picked in a backend dialog and the page only ever receives file names, as handover.rs does for files. The index comes from the ignore crate, so .gitignore is honoured. A stash in a linked context shows an @path the folder no longer holds as unresolved, with a same-named file elsewhere as the suggestion. Nothing is stored beside the path. Context archives carry projectFolder; an import links it only when the folder exists on this device and never replaces a link already made here. Signing out asks whether to keep the links, keeping them by default. Checked with cargo test, clippy and fmt, the frontend tests and a vite build. Not yet run in the dev build. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 15 + screenshots/mock-backend.ts | 4 + src-tauri/Cargo.lock | 63 ++- src-tauri/Cargo.toml | 3 + src-tauri/src/db.rs | 107 +++++ src-tauri/src/lib.rs | 6 + src-tauri/src/project_folders.rs | 420 ++++++++++++++++++ src-tauri/src/transfer.rs | 45 +- src/app.css | 8 + src/lib/components/ConfirmationDialog.svelte | 6 + src/lib/components/ContextManagerItem.svelte | 86 ++++ src/lib/components/Editor.svelte | 130 ++++++ src/lib/components/ImportDialog.svelte | 3 + src/lib/components/Settings.svelte | 46 +- src/lib/components/StashCard.svelte | 14 +- src/lib/i18n/locales/de.json | 22 +- src/lib/i18n/locales/en.json | 22 +- src/lib/i18n/locales/zh.json | 22 +- src/lib/services/desktop-adapter.ts | 22 +- .../stores/__tests__/context-folders.test.ts | 171 +++++++ src/lib/stores/context-folders.svelte.ts | 134 ++++++ src/lib/types.ts | 33 ++ src/lib/utils/__tests__/file-refs.test.ts | 147 ++++++ src/lib/utils/__tests__/markdown.test.ts | 22 + src/lib/utils/file-refs.ts | 154 +++++++ src/lib/utils/markdown.ts | 46 +- 26 files changed, 1728 insertions(+), 23 deletions(-) create mode 100644 src-tauri/src/project_folders.rs create mode 100644 src/lib/stores/__tests__/context-folders.test.ts create mode 100644 src/lib/stores/context-folders.svelte.ts create mode 100644 src/lib/utils/__tests__/file-refs.test.ts create mode 100644 src/lib/utils/file-refs.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a1a981..89e834b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,21 @@ popover, not for the person who wrote the commit. ## [Unreleased] +### Added + +- **Type `@` to reference a file from your project.** Link a context to its project folder in + the context manager, and typing `@` in a stash suggests the files in it. Picking one writes + `@src/app.ts` into the stash, the same form Claude Code uses (paths with spaces are quoted), + so an AI tool working in that project can open the file directly. Files ignored by + `.gitignore` are left out. The link is saved only on this device and is never synced, so + each computer can point at its own copy of the project +- **Stashes show when a referenced file has moved.** In a context with a linked folder, an + `@path` that no longer exists is shown dashed and underlined, and hovering it suggests a file + of the same name elsewhere in the project. The stash text itself is never changed +- Exporting a context includes its project folder. Importing restores the link when that folder + exists on this device, and skips it otherwise. Signing out asks whether to keep this device's + folder links, and keeps them by default + ## [1.11.6] - 2026-11-05 ### Fixed diff --git a/screenshots/mock-backend.ts b/screenshots/mock-backend.ts index 9cc4972..70ac13b 100644 --- a/screenshots/mock-backend.ts +++ b/screenshots/mock-backend.ts @@ -198,6 +198,10 @@ export function installMockBackend(overrides: Partial = {}): void { return 'You are a precise engineering assistant. Rewrite the note as a task.'; case 'write_reference_file': return `/home/dev/.stashpad/cache/${payload?.contextId}/${payload?.stashId}/refs/${payload?.targetId}.md`; + case 'get_context_folders': + return []; + case 'list_context_files': + return { files: [], truncated: false }; case 'get_system_prompt_path_str': return '/home/dev/.stashpad/system-prompt.md'; case 'e2ee_status': diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index a427db6..a6c7a48 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -570,6 +570,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.2" @@ -1055,6 +1065,25 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.21" @@ -2208,6 +2237,19 @@ dependencies = [ "xkeysym", ] +[[package]] +name = "globset" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "gobject-sys" version = "0.18.0" @@ -2733,6 +2775,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ignore" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "image" version = "0.25.9" @@ -4666,9 +4724,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.14" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -5571,6 +5629,7 @@ dependencies = [ "futures-util", "global-hotkey", "hkdf", + "ignore", "keyring", "log", "mime_guess", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 13ba185..1a89532 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -74,6 +74,9 @@ tokio = { version = "1.50.0", features = ["time", "macros"] } # not need, and every archive we read or write uses deflate. zip = { version = "2", default-features = false, features = ["deflate"] } serde_yaml = "0.9" +# Walks a context's linked project folder for the editor's `@path` picker. ripgrep's walker, +# so .gitignore, .ignore and git's excludes are honoured without reimplementing them. +ignore = "0.4.30" # Apple Intelligence (Foundation Models) - macOS 26+ only # keyring ships NO default features and, without one, silently compiles its in-memory diff --git a/src-tauri/src/db.rs b/src-tauri/src/db.rs index 03b8edf..5a23d2e 100644 --- a/src-tauri/src/db.rs +++ b/src-tauri/src/db.rs @@ -176,6 +176,20 @@ impl DbManager { [], )?; + // The project folder each context is linked to on this device. Its own table, not a + // column on `contexts`: every context write there is INSERT OR REPLACE, which would + // reset a column the statement does not name, so each save or sync pull would unlink + // the folder. No foreign key either, for the same reason - REPLACE deletes the row + // and a cascade would fire. Sync never reads or writes this table. + self.conn.execute( + "CREATE TABLE IF NOT EXISTS context_folders ( + context_id TEXT PRIMARY KEY, + path TEXT NOT NULL, + linked_at INTEGER NOT NULL + )", + [], + )?; + // Check/Migrate syntax column let syntax_exists: bool = self .conn @@ -722,6 +736,47 @@ impl DbManager { Ok(contexts) } + /// Every context's linked project folder on this device, as `(context_id, path)`. + pub fn get_context_folders(&self) -> Result> { + let mut stmt = self + .conn + .prepare("SELECT context_id, path FROM context_folders")?; + let rows = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?; + rows.collect() + } + + pub fn get_context_folder(&self, context_id: &str) -> Result> { + self.conn + .query_row( + "SELECT path FROM context_folders WHERE context_id = ?1", + params![context_id], + |row| row.get(0), + ) + .optional() + } + + pub fn set_context_folder(&self, context_id: &str, path: &str) -> Result<()> { + self.conn.execute( + "INSERT INTO context_folders (context_id, path, linked_at) VALUES (?1, ?2, ?3) + ON CONFLICT(context_id) DO UPDATE SET path = excluded.path, linked_at = excluded.linked_at", + params![context_id, path, now_ts()], + )?; + Ok(()) + } + + pub fn remove_context_folder(&self, context_id: &str) -> Result<()> { + self.conn.execute( + "DELETE FROM context_folders WHERE context_id = ?1", + params![context_id], + )?; + Ok(()) + } + + pub fn clear_context_folders(&self) -> Result<()> { + self.conn.execute("DELETE FROM context_folders", [])?; + Ok(()) + } + pub fn save_context(&mut self, ctx: &Context, origin: WriteOrigin) -> Result<()> { // Protect default context from being renamed or having rules modified let (name, rules_json) = if ctx.id == "default" { @@ -3249,4 +3304,56 @@ mod tests { .expect("tombstone must be sent to the server"); assert!(tombstone.deleted, "tombstone must be flagged as deleted"); } + #[test] + fn a_folder_link_survives_saves_and_sync_pulls_of_its_context() { + // Every context write is INSERT OR REPLACE. A link stored on the row - or one + // hanging off it by a cascading foreign key - would be gone after either of these. + let mut db = create_test_db(); + db.conn + .execute_batch("PRAGMA foreign_keys = ON;") + .expect("enable foreign keys"); + let id = "00000000-0000-4000-8000-00000000f01d"; + db.save_context(&plain_context(id, false), WriteOrigin::LocalEdit) + .unwrap(); + db.set_context_folder(id, "/home/me/project").unwrap(); + + let mut renamed = plain_context(id, false); + renamed.name = "Renamed".to_string(); + db.save_context(&renamed, WriteOrigin::LocalEdit).unwrap(); + renamed.updated_at = Some(now_ts() + 1_000); + db.import_contexts(&[renamed]).unwrap(); + + assert_eq!( + db.get_context_folder(id).unwrap().as_deref(), + Some("/home/me/project") + ); + } + + #[test] + fn a_folder_link_never_reaches_the_sync_payload() { + let mut db = create_test_db(); + let id = "00000000-0000-4000-8000-00000000f01e"; + db.save_context(&plain_context(id, false), WriteOrigin::LocalEdit) + .unwrap(); + db.set_context_folder(id, "/home/me/secret-project") + .unwrap(); + + let payload = serde_json::to_string(&db.get_contexts_for_sync().unwrap()).unwrap(); + assert!(!payload.contains("secret-project")); + } + + #[test] + fn relinking_replaces_the_folder_and_clearing_removes_every_link() { + let db = create_test_db(); + db.set_context_folder("a", "/one").unwrap(); + db.set_context_folder("a", "/two").unwrap(); + db.set_context_folder("b", "/three").unwrap(); + assert_eq!(db.get_context_folder("a").unwrap().as_deref(), Some("/two")); + + db.remove_context_folder("b").unwrap(); + assert_eq!(db.get_context_folders().unwrap().len(), 1); + + db.clear_context_folders().unwrap(); + assert!(db.get_context_folders().unwrap().is_empty()); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 65a2d31..62f546e 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -40,6 +40,7 @@ mod keychain; mod localkey; mod logging; mod models; +mod project_folders; mod settings; mod shortcuts; mod stashes; @@ -554,6 +555,11 @@ pub fn run() { contexts::claim_pending_contexts, contexts::mark_contexts_synced, contexts::delete_context, + project_folders::get_context_folders, + project_folders::pick_context_folder, + project_folders::unlink_context_folder, + project_folders::clear_context_folders, + project_folders::list_context_files, utils::set_autostart, utils::get_autostart_enabled, sync::fetch_cloud_account, diff --git a/src-tauri/src/project_folders.rs b/src-tauri/src/project_folders.rs new file mode 100644 index 0000000..5a0c0b7 --- /dev/null +++ b/src-tauri/src/project_folders.rs @@ -0,0 +1,420 @@ +// SPDX-License-Identifier: AGPL-3.0-only + +// Copyright (C) 2026 Nico Wiedemann +// +// This file is part of Stashpad. +// Stashpad is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License, version 3, +// as published by the Free Software Foundation. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +// See the GNU Affero General Public License for more details. + +//! The project folder a context is linked to on this device, and the file list behind the +//! editor's `@path` picker. +//! +//! A folder path only means something on the machine it was picked on, so the link lives in +//! its own local table (see `context_folders` in db.rs) and never reaches sync. +//! +//! The webview never names a folder. It is picked in a dialog that runs here, the same rule +//! handover.rs applies to files, and what goes back to the page is the folder's path for +//! display and the *names* of the files inside it - never their contents. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; + +use serde::Serialize; +use tauri::{AppHandle, State}; +use tauri_plugin_dialog::DialogExt; + +use crate::db::DbManager; +use crate::state::DbState; +use crate::uierror::UiError; + +/// More files than this and the picker stops listing. A repository that large is mostly +/// generated or vendored files nobody `@`-mentions, and walking it on every refresh would +/// stall the editor. +const MAX_FILES: usize = 20_000; + +/// A context's folder link, as the UI shows it. +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ContextFolder { + pub context_id: String, + pub path: String, + /// False when the folder is gone - an unmounted drive, a renamed parent. The link is + /// kept so the user can relink it rather than silently losing it. + pub exists: bool, +} + +/// The files of a linked folder, relative to it, with `/` separators on every platform. +#[derive(Debug, Clone, Default, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct FileIndex { + pub files: Vec, + /// The folder held more than [`MAX_FILES`] files and the list stops there. + pub truncated: bool, +} + +fn folder(context_id: String, path: String) -> ContextFolder { + let exists = Path::new(&path).is_dir(); + ContextFolder { + context_id, + path, + exists, + } +} + +// --------------------------------------------------------------------------- +// The file index +// --------------------------------------------------------------------------- + +/// Built indexes, by context, with the folder each was built from so a relink invalidates it. +type IndexCache = HashMap)>; + +static INDEXES: OnceLock> = OnceLock::new(); + +fn indexes() -> &'static Mutex { + INDEXES.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn forget_index(context_id: &str) { + crate::state::lock_or_recover(indexes()).remove(context_id); +} + +/// List the files under `root` the way the picker offers them. +/// +/// Honours `.gitignore` and friends whether or not the folder is a git checkout, and keeps +/// dotfiles such as `.github/` - only `.git` itself is skipped. A path containing `"` is left +/// out: the editor quotes paths with spaces, and there is no clean way to quote a quote. +pub fn index_folder(root: &Path, max_files: usize) -> FileIndex { + let walker = ignore::WalkBuilder::new(root) + .hidden(false) + .require_git(false) + .follow_links(false) + .filter_entry(|entry| entry.file_name() != ".git") + .build(); + + let mut files = Vec::new(); + let mut truncated = false; + for entry in walker.flatten() { + if !entry.file_type().is_some_and(|t| t.is_file()) { + continue; + } + let Some(relative) = relative_path(root, entry.path()) else { + continue; + }; + if files.len() == max_files { + truncated = true; + break; + } + files.push(relative); + } + files.sort(); + FileIndex { files, truncated } +} + +/// `path` relative to `root` with `/` separators, or `None` for a path the picker skips. +fn relative_path(root: &Path, path: &Path) -> Option { + let relative = path.strip_prefix(root).ok()?; + let mut parts = Vec::new(); + for component in relative.components() { + parts.push(component.as_os_str().to_str()?); + } + let joined = parts.join("/"); + if joined.is_empty() || joined.contains('"') { + return None; + } + Some(joined) +} + +// --------------------------------------------------------------------------- +// Import +// --------------------------------------------------------------------------- + +/// Folders read from import archives, by import token, until the import is committed or +/// discarded. Kept here rather than handed to the webview and back, so the page cannot +/// substitute a folder of its own choosing on the way. +static PENDING_IMPORTS: OnceLock>> = OnceLock::new(); + +fn pending_imports() -> &'static Mutex> { + PENDING_IMPORTS.get_or_init(|| Mutex::new(HashMap::new())) +} + +/// Note the folder an archive names, if it exists on this device. A folder that does not +/// exist is treated as no folder at all. Returns what the import will link. +pub fn remember_import_folder(token: &str, folder: Option) -> Option { + let folder = folder.filter(|path| Path::new(path).is_dir())?; + crate::state::lock_or_recover(pending_imports()).insert(token.to_string(), folder.clone()); + Some(folder) +} + +pub fn take_import_folder(token: &str) -> Option { + crate::state::lock_or_recover(pending_imports()).remove(token) +} + +/// Link an imported context to the folder its archive named. +/// +/// A link the user already made on this device wins over the archive's: it was chosen here, +/// for this machine, and an archive may have been written somewhere else entirely. +pub fn apply_imported_folder( + db: &DbManager, + context_id: &str, + folder: &str, +) -> rusqlite::Result { + if !Path::new(folder).is_dir() || db.get_context_folder(context_id)?.is_some() { + return Ok(false); + } + db.set_context_folder(context_id, folder)?; + forget_index(context_id); + Ok(true) +} + +// --------------------------------------------------------------------------- +// Commands +// --------------------------------------------------------------------------- + +#[tauri::command] +pub async fn get_context_folders( + state: State<'_, Arc>, +) -> Result, UiError> { + let links = state + .lock_db() + .get_context_folders() + .map_err(|e| e.to_string())?; + Ok(links + .into_iter() + .map(|(context_id, path)| folder(context_id, path)) + .collect()) +} + +/// Ask the user for the context's project folder and link it. `None` when they cancel. +#[tauri::command] +pub async fn pick_context_folder( + app: AppHandle, + state: State<'_, Arc>, + context_id: String, + title: String, +) -> Result, UiError> { + let dialog = app.dialog().file().set_title(title); + // The dialog blocks until the user answers, so it waits on the blocking pool. + let picked = tauri::async_runtime::spawn_blocking(move || dialog.blocking_pick_folder()) + .await + .map_err(|e| format!("Folder dialog failed: {}", e))?; + + let Some(path) = picked.and_then(|p| p.into_path().ok()) else { + return Ok(None); + }; + let path = path.to_string_lossy().into_owned(); + state + .lock_db() + .set_context_folder(&context_id, &path) + .map_err(|e| e.to_string())?; + forget_index(&context_id); + log::info!("Linked a project folder to context {}", context_id); + Ok(Some(folder(context_id, path))) +} + +#[tauri::command] +pub async fn unlink_context_folder( + state: State<'_, Arc>, + context_id: String, +) -> Result<(), UiError> { + state + .lock_db() + .remove_context_folder(&context_id) + .map_err(|e| e.to_string())?; + forget_index(&context_id); + log::info!("Unlinked the project folder of context {}", context_id); + Ok(()) +} + +/// Drop every folder link on this device - the sign-out choice not to keep them. +#[tauri::command] +pub async fn clear_context_folders(state: State<'_, Arc>) -> Result<(), UiError> { + state + .lock_db() + .clear_context_folders() + .map_err(|e| e.to_string())?; + crate::state::lock_or_recover(indexes()).clear(); + log::info!("Cleared every project folder link"); + Ok(()) +} + +/// The files in the context's linked folder. Empty when no folder is linked or it is gone. +/// +/// Built once and then served from memory; `refresh` walks the folder again, which the +/// editor asks for when it opens, so files added since show up. +#[tauri::command] +pub async fn list_context_files( + state: State<'_, Arc>, + context_id: String, + refresh: bool, +) -> Result { + let Some(root) = state + .lock_db() + .get_context_folder(&context_id) + .map_err(|e| e.to_string())? + .map(PathBuf::from) + else { + return Ok(FileIndex::default()); + }; + + if !refresh { + if let Some((built_from, index)) = crate::state::lock_or_recover(indexes()).get(&context_id) + { + if *built_from == root { + return Ok(index.as_ref().clone()); + } + } + } + + if !root.is_dir() { + forget_index(&context_id); + return Ok(FileIndex::default()); + } + + let walk_root = root.clone(); + let index = tauri::async_runtime::spawn_blocking(move || index_folder(&walk_root, MAX_FILES)) + .await + .map_err(|e| format!("Indexing the project folder failed: {}", e))?; + if index.truncated { + log::warn!( + "Project folder of context {} holds more than {} files; the picker lists the first {}", + context_id, + MAX_FILES, + MAX_FILES + ); + } + + let index = Arc::new(index); + crate::state::lock_or_recover(indexes()).insert(context_id, (root, index.clone())); + Ok(index.as_ref().clone()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + fn write(root: &Path, relative: &str) { + let path = root.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"x").unwrap(); + } + + #[test] + fn the_index_lists_relative_paths_with_forward_slashes() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "src/lib/types.ts"); + write(dir.path(), "README.md"); + + let index = index_folder(dir.path(), MAX_FILES); + assert_eq!(index.files, vec!["README.md", "src/lib/types.ts"]); + assert!(!index.truncated); + } + + #[test] + fn the_index_honours_gitignore_without_a_git_checkout() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join(".gitignore"), "node_modules/\n*.log\n").unwrap(); + write(dir.path(), "node_modules/pkg/index.js"); + write(dir.path(), "debug.log"); + write(dir.path(), "src/app.ts"); + + let index = index_folder(dir.path(), MAX_FILES); + assert_eq!(index.files, vec![".gitignore", "src/app.ts"]); + } + + #[test] + fn dotfiles_are_listed_but_the_git_directory_is_not() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), ".github/workflows/test.yml"); + write(dir.path(), ".git/config"); + + let index = index_folder(dir.path(), MAX_FILES); + assert_eq!(index.files, vec![".github/workflows/test.yml"]); + } + + #[test] + fn a_path_with_spaces_is_kept_and_one_with_a_quote_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + write(dir.path(), "docs/release notes.md"); + // Windows does not allow `"` in a file name, so this half only runs elsewhere. + if cfg!(not(windows)) { + write(dir.path(), "docs/say \"hi\".md"); + } + + let index = index_folder(dir.path(), MAX_FILES); + assert_eq!(index.files, vec!["docs/release notes.md"]); + } + + #[test] + fn the_index_stops_at_the_cap_and_says_so() { + let dir = tempfile::tempdir().unwrap(); + for i in 0..5 { + write(dir.path(), &format!("f{}.txt", i)); + } + + let index = index_folder(dir.path(), 3); + assert_eq!(index.files.len(), 3); + assert!(index.truncated); + } + + fn test_db() -> DbManager { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + let db = DbManager { conn }; + db.init_tables().unwrap(); + db + } + + #[test] + fn an_imported_folder_that_exists_is_linked() { + let db = test_db(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().to_string_lossy().into_owned(); + + assert!(apply_imported_folder(&db, "ctx", &path).unwrap()); + assert_eq!(db.get_context_folder("ctx").unwrap(), Some(path)); + } + + #[test] + fn an_imported_folder_that_is_missing_is_treated_as_none() { + let db = test_db(); + let dir = tempfile::tempdir().unwrap(); + let gone = dir.path().join("gone").to_string_lossy().into_owned(); + + assert!(!apply_imported_folder(&db, "ctx", &gone).unwrap()); + assert_eq!(db.get_context_folder("ctx").unwrap(), None); + assert_eq!(remember_import_folder("token-missing", Some(gone)), None); + assert_eq!(take_import_folder("token-missing"), None); + } + + #[test] + fn an_existing_link_wins_over_the_imported_one() { + let db = test_db(); + let mine = tempfile::tempdir().unwrap(); + let theirs = tempfile::tempdir().unwrap(); + let mine = mine.path().to_string_lossy().into_owned(); + db.set_context_folder("ctx", &mine).unwrap(); + + let theirs = theirs.path().to_string_lossy().into_owned(); + assert!(!apply_imported_folder(&db, "ctx", &theirs).unwrap()); + assert_eq!(db.get_context_folder("ctx").unwrap(), Some(mine)); + } + + #[test] + fn a_remembered_import_folder_is_handed_out_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().to_string_lossy().into_owned(); + + assert_eq!( + remember_import_folder("token-once", Some(path.clone())), + Some(path.clone()) + ); + assert_eq!(take_import_folder("token-once"), Some(path)); + assert_eq!(take_import_folder("token-once"), None); + } +} diff --git a/src-tauri/src/transfer.rs b/src-tauri/src/transfer.rs index 06c490f..4cf1684 100644 --- a/src-tauri/src/transfer.rs +++ b/src-tauri/src/transfer.rs @@ -63,6 +63,12 @@ pub struct ArchiveMetadata { pub description: String, #[serde(default)] pub rules: Vec, + /// The project folder the context was linked to on the exporting device. Restored on + /// import only when that folder exists where the archive is read; otherwise the import + /// reports none. Left out of the frontmatter when there is no link, so an archive of an + /// unlinked context reads exactly as it did before. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub project_folder: Option, } /// What an archive turned out to contain, for the conflict UI to act on. @@ -733,10 +739,13 @@ pub async fn write_context_archive( ) -> Result { let wanted: HashSet = stash_ids.into_iter().collect(); - let (context, stashes) = { + let (context, project_folder, stashes) = { let db = state.lock_db(); let contexts = db.get_contexts().map_err(|e| e.to_string())?; let context = contexts.into_iter().find(|c: &Context| c.id == context_id); + let project_folder = db + .get_context_folder(&context_id) + .map_err(|e| e.to_string())?; let all = db.get_stashes().map_err(|e| e.to_string())?; let selected: Vec = all @@ -744,7 +753,7 @@ pub async fn write_context_archive( .filter(|s| s.context_id == context_id && wanted.contains(&s.id)) .collect(); - (context, selected) + (context, project_folder, selected) }; let context_name = context @@ -767,6 +776,7 @@ pub async fn write_context_archive( .collect() }) .unwrap_or_default(), + project_folder, }; let archived: HashMap> = if include_attachments { @@ -931,7 +941,9 @@ pub async fn read_import_archive( .await .map_err(|e| format!("Import task failed: {}", e))??; - let parsed = parse_markdown(&markdown, &context_id); + let mut parsed = parse_markdown(&markdown, &context_id); + parsed.metadata.project_folder = + crate::project_folders::remember_import_folder(&token, parsed.metadata.project_folder); let existing = { let db = state.lock_db(); @@ -1056,6 +1068,13 @@ pub async fn commit_import( return Err(e.to_string().into()); } + if let Some(folder) = crate::project_folders::take_import_folder(&token) { + let db = state.lock_db(); + if let Err(e) = crate::project_folders::apply_imported_folder(&db, &context_id, &folder) { + log::warn!("Could not link the imported project folder: {}", e); + } + } + let cleanup_dir = temp_dir.clone(); let _ = tauri::async_runtime::spawn_blocking(move || fs::remove_dir_all(&cleanup_dir)).await; @@ -1142,6 +1161,7 @@ pub async fn discard_import(token: String) -> Result<(), UiError> { if Uuid::parse_str(&token).is_err() { return Err("Invalid import token".into()); } + crate::project_folders::take_import_folder(&token); let _ = fs::remove_dir_all(transfer_temp_root().join(token)); Ok(()) } @@ -1171,9 +1191,28 @@ mod tests { name: "Work".to_string(), description: "notes".to_string(), rules: Vec::new(), + project_folder: None, } } + #[test] + fn the_project_folder_survives_a_round_trip() { + let mut with_folder = metadata(); + with_folder.project_folder = Some("/home/me/project".to_string()); + let stashes = vec![stash("a", "see @src/app.ts", "2026-08-18T10:00:00Z", false)]; + + let md = build_markdown("Work", &with_folder, &stashes, None, time::now()); + assert!(md.contains("projectFolder: /home/me/project")); + assert_eq!(parse_markdown(&md, "ctx").metadata, with_folder); + } + + #[test] + fn an_unlinked_context_writes_no_project_folder_key() { + let stashes = vec![stash("a", "entry", "2026-08-18T10:00:00Z", false)]; + let md = build_markdown("Work", &metadata(), &stashes, None, time::now()); + assert!(!md.contains("projectFolder")); + } + #[test] fn a_document_survives_a_round_trip() { let stashes = vec![ diff --git a/src/app.css b/src/app.css index 4067ce8..2fb299e 100644 --- a/src/app.css +++ b/src/app.css @@ -214,6 +214,14 @@ font-weight: 500; } +/* An @path the context's linked project folder does not hold (any more). */ +.ai-mention.file-ref-unresolved { + opacity: 0.7; + text-decoration: underline dashed; + text-underline-offset: 3px; + cursor: help; +} + .ai-command { color: var(--amber); font-weight: 500; diff --git a/src/lib/components/ConfirmationDialog.svelte b/src/lib/components/ConfirmationDialog.svelte index 6d6e739..be9975f 100644 --- a/src/lib/components/ConfirmationDialog.svelte +++ b/src/lib/components/ConfirmationDialog.svelte @@ -7,6 +7,7 @@ import { _ } from "$lib/i18n"; import { portal } from "$lib/actions/portal"; import { trapFocus } from "$lib/actions/trapFocus"; + import type { Snippet } from "svelte"; let { open = $bindable(false), @@ -17,6 +18,7 @@ variant = "default", onConfirm, onCancel, + children, } = $props<{ open: boolean; title: string; @@ -26,6 +28,8 @@ variant?: "default" | "destructive"; onConfirm: () => void; onCancel?: () => void; + /** Extra controls under the description, such as an option the confirm applies. */ + children?: Snippet; }>(); let isConfirmed = $state(false); @@ -135,6 +139,8 @@

+ {@render children?.()} +
{/if} + + {#if !isDefault} +
+
+ + {$_("contexts.folder.label")} + +
+ + + {folder + ? $_("contexts.folder.change") + : $_("contexts.folder.link")} + + {#if folder} + + + + + {/if} +
+
+ {#if folder} +
+ {folder.path} + {#if !folder.exists} + {$_("contexts.folder.missing")} + {/if} +
+ {:else} +

+ {$_("contexts.folder.hint")} +

+ {/if} +
+ {/if} + {#if !isDefault}
diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index c0013e4..84c76b8 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -44,6 +44,16 @@ rankRefCandidates, refLabel, } from "$lib/utils/stash-refs"; + import { + findFileTrigger, + formatFileRef, + rankFileCandidates, + } from "$lib/utils/file-refs"; + import { + getContextFiles, + loadContextFiles, + loadContextFolders, + } from "$lib/stores/context-folders.svelte"; import { applyWrap, applyCode, @@ -153,6 +163,21 @@ let focusedRefIndex = $state(0); let refTriggerStart = $state(null); + // File picker, opened by `@` when the context has a project folder on this device + let showFileSuggestions = $state(false); + let fileSuggestions = $state([]); + let focusedFileIndex = $state(0); + let fileTriggerStart = $state(null); + let projectFiles = $derived(getContextFiles(currentContextId)); + + // Walk the folder again whenever an editor opens on a context, so files added since the + // last walk are offered. + $effect(() => { + const contextId = currentContextId; + if (!contextId) return; + loadContextFolders().then(() => loadContextFiles(contextId, true)); + }); + // File preview state let previewModalOpen = $state(false); let selectedPreviewFilePath = $state(""); @@ -377,6 +402,50 @@ function handleInput() { checkForTagTrigger(); checkForRefTrigger(); + checkForFileTrigger(); + } + + function checkForFileTrigger() { + if (!textareaRef || !projectFiles) { + showFileSuggestions = false; + return; + } + + const end = getCursorParams().end; + const trigger = findFileTrigger(content.slice(0, end)); + if (!trigger) { + showFileSuggestions = false; + return; + } + + fileSuggestions = rankFileCandidates(trigger.query, projectFiles); + if (fileSuggestions.length === 0) { + showFileSuggestions = false; + return; + } + showSuggestions = false; + showRefSuggestions = false; + showFileSuggestions = true; + focusedFileIndex = 0; + fileTriggerStart = trigger.start; + updateSuggestionPosition(end); + } + + function insertFile(path: string) { + if (!textareaRef || fileTriggerStart === null) return; + + const before = content.slice(0, fileTriggerStart); + const after = content.slice(textareaRef.selectionEnd); + const ref = formatFileRef(path); + content = before + ref + " " + after; + + const newCursorPos = before.length + ref.length + 1; + showFileSuggestions = false; + + setTimeout(() => { + textareaRef?.focus(); + textareaRef?.setSelectionRange(newCursorPos, newCursorPos); + }, 0); } function checkForRefTrigger() { @@ -805,6 +874,32 @@ } function handleKeydown(e: KeyboardEvent) { + if (showFileSuggestions && fileSuggestions.length > 0) { + if (e.key === "ArrowDown") { + e.preventDefault(); + focusedFileIndex = (focusedFileIndex + 1) % fileSuggestions.length; + return; + } + if (e.key === "ArrowUp") { + e.preventDefault(); + focusedFileIndex = + (focusedFileIndex - 1 + fileSuggestions.length) % fileSuggestions.length; + return; + } + if (e.key === "Enter" || e.key === "Tab") { + e.preventDefault(); + if (fileSuggestions[focusedFileIndex]) { + insertFile(fileSuggestions[focusedFileIndex]); + } + return; + } + if (e.key === "Escape") { + e.preventDefault(); + showFileSuggestions = false; + return; + } + } + if (showRefSuggestions && refSuggestions.length > 0) { if (e.key === "ArrowDown") { e.preventDefault(); @@ -1309,6 +1404,7 @@ if (!hoveringSuggestions) { showSuggestions = false; showRefSuggestions = false; + showFileSuggestions = false; } }, 200)} use:focusOnMount @@ -1372,6 +1468,40 @@
{/if} + {#if showFileSuggestions} +
(hoveringSuggestions = true)} + onmouseleave={() => (hoveringSuggestions = false)} + role="listbox" + aria-label={$_("editor.referenceFile")} + tabindex="-1" + > + {#each fileSuggestions as path, i (path)} + {@const slash = path.lastIndexOf("/")} + + {/each} +
+ {/if} +
diff --git a/src/lib/components/ImportDialog.svelte b/src/lib/components/ImportDialog.svelte index a4f40a5..1fa6569 100644 --- a/src/lib/components/ImportDialog.svelte +++ b/src/lib/components/ImportDialog.svelte @@ -4,6 +4,7 @@ --> + +{#if isLoading} + +
+
+ {$_("common.loading")} +
+
+{:else if error} + +
+
+ {error} +
+
+{:else if previewData} + + {#if previewData.fileType === "image" || previewData.fileType === "video" || previewData.fileType === "text"} +
+ {#if previewData.fileType === "image"} + {previewData.fileName} + {:else if previewData.fileType === "video"} + + + {:else if previewData.fileType === "text"} +
{previewData.content.slice(
+                        0,
+                        500,
+                    )}
+ {/if} +
+ {:else if previewData.fileType === "withheld"} + +
+ {$_("fileRef.withheld")} +
+ {/if} + +
+
+ {previewData.fileName} +
+
+{:else} + +
+
+ {fileName} +
+
+{/if} diff --git a/src/lib/components/FilePreviewTooltip.svelte b/src/lib/components/FilePreviewTooltip.svelte index f979153..dc5b11f 100644 --- a/src/lib/components/FilePreviewTooltip.svelte +++ b/src/lib/components/FilePreviewTooltip.svelte @@ -17,7 +17,6 @@ import { _ } from "$lib/i18n"; import { DesktopStorageAdapter } from "$lib/services/desktop-adapter"; import type { FilePreviewData } from "$lib/types"; - import { convertFileSrc } from "@tauri-apps/api/core"; import { FileText, Image, @@ -28,6 +27,7 @@ Loader2, } from "lucide-svelte"; import Tooltip from "./Tooltip.svelte"; + import FilePreviewContent from "./FilePreviewContent.svelte"; import { attachmentSync } from "$lib/stores/attachment-sync.svelte"; import { formatBytes } from "$lib/utils/format"; import { getAttachmentKind } from "$lib/utils/files"; @@ -180,11 +180,6 @@ adapter.startDrag("", [resolvedPath]); } - function getVideoSrc(content: string): string { - // Convert file path to Tauri asset URL for local files - return convertFileSrc(content); - } - // Derive from the name, not the path: a pending attachment has no path yet, but its // filename is always known. const fileType = $derived(getAttachmentKind(fileName || filePath)); @@ -241,69 +236,6 @@ position={showBelow ? "bottom" : "top"} > {#snippet children()} - {#if isLoading} - -
-
- {$_("common.loading")} -
-
- {:else if error} - -
-
- {error} -
-
- {:else if previewData} - - {#if previewData.fileType === "image" || previewData.fileType === "video" || previewData.fileType === "text"} -
- {#if previewData.fileType === "image"} - {previewData.fileName} - {:else if previewData.fileType === "video"} - - - {:else if previewData.fileType === "text"} -
{previewData.content.slice(
-                                0,
-                                500,
-                            )}
- {/if} -
- {/if} - -
-
- {previewData.fileName} -
-
- {:else} - -
-
- {fileName} -
-
- {/if} + {/snippet} diff --git a/src/lib/components/FileRefPreview.svelte b/src/lib/components/FileRefPreview.svelte new file mode 100644 index 0000000..c1597fe --- /dev/null +++ b/src/lib/components/FileRefPreview.svelte @@ -0,0 +1,99 @@ + + + + + + {#snippet children()} + {#if display?.state === "unresolved"} +
+ {path} +

{$_("fileRef.missing")}

+ {#if display.suggestion} +

+ {$_("fileRef.didYouMean", { + values: { path: display.suggestion }, + })} +

+ {/if} +
+ {:else} + + {/if} + {/snippet} +
diff --git a/src/lib/components/StashCard.svelte b/src/lib/components/StashCard.svelte index 6ba11bf..62de3d9 100644 --- a/src/lib/components/StashCard.svelte +++ b/src/lib/components/StashCard.svelte @@ -73,6 +73,7 @@ type ResolvedRef, } from "$lib/utils/stash-refs"; import StashRefPreview from "./StashRefPreview.svelte"; + import FileRefPreview from "./FileRefPreview.svelte"; import ActionButton from "./ActionButton.svelte"; import TagBadge from "./TagBadge.svelte"; import ColorBadge from "./ColorBadge.svelte"; @@ -252,16 +253,7 @@ // `@path`s are checked against the context's project folder, when this device has one. let fileResolver = $derived(getFileRefResolver(item.contextId)); - let renderedContent = $derived( - safeParse( - displayContent, - displayRef, - fileResolver && { - resolve: fileResolver, - missingLabel: $_("fileRef.missing"), - }, - ), - ); + let renderedContent = $derived(safeParse(displayContent, displayRef, fileResolver)); function refIdAt(target: EventTarget | null): string | null { const el = (target as HTMLElement | null)?.closest?.("[data-ref-id]"); @@ -321,6 +313,46 @@ hoveredRef = null; } + // The same for `@path` file chips, which only exist when the context has a folder here. + let hoveredFile = $state(null); + let fileHoverTimeout: ReturnType | undefined; + let fileHoverChip: Element | null = null; + + function showFilePreview(target: EventTarget | null) { + const chip = + (target as HTMLElement | null)?.closest?.("[data-file-path]") ?? null; + if (chip === fileHoverChip) return; + hideFilePreview(); + if (!chip) return; + fileHoverChip = chip; + const path = chip.getAttribute("data-file-path"); + fileHoverTimeout = setTimeout(() => { + if (!path) return; + const rect = chip.getBoundingClientRect(); + refPreviewX = rect.left + rect.width / 2; + refPreviewBelow = rect.top < window.innerHeight / 2; + refPreviewY = refPreviewBelow ? rect.bottom + 8 : rect.top - 8; + hoveredFile = path; + }, 300); + } + + function hideFilePreview() { + clearTimeout(fileHoverTimeout); + fileHoverTimeout = undefined; + fileHoverChip = null; + hoveredFile = null; + } + + function showChipPreview(target: EventTarget | null) { + showRefPreview(target); + showFilePreview(target); + } + + function hideChipPreviews() { + hideRefPreview(); + hideFilePreview(); + } + let stashData = $derived(extractTagsAndColors(item.content)); let stashTags = $derived(() => stashData.tags); let stashColors = $derived(() => stashData.colors); @@ -757,10 +789,10 @@ ondblclick={handleDoubleClick} onclick={handleContentClick} onkeydown={handleContentKeydown} - onmouseover={(e) => showRefPreview(e.target)} - onmouseleave={hideRefPreview} - onfocusin={(e) => showRefPreview(e.target)} - onfocusout={hideRefPreview} + onmouseover={(e) => showChipPreview(e.target)} + onmouseleave={hideChipPreviews} + onfocusin={(e) => showChipPreview(e.target)} + onfocusout={hideChipPreviews} role="presentation" > {@html renderedContent} @@ -1013,6 +1045,16 @@
+ + { + return await invoke('preview_context_file', { contextId, path }); + } + async listContextFiles(contextId: string, refresh: boolean): Promise { return await invoke('list_context_files', { contextId, refresh }); } diff --git a/src/lib/stores/context-folders.svelte.ts b/src/lib/stores/context-folders.svelte.ts index 2ebeee8..954c568 100644 --- a/src/lib/stores/context-folders.svelte.ts +++ b/src/lib/stores/context-folders.svelte.ts @@ -19,7 +19,7 @@ */ import { DesktopStorageAdapter } from "$lib/services/desktop-adapter"; -import type { ContextFolder } from "$lib/types"; +import type { ContextFolder, FilePreviewData } from "$lib/types"; import { log } from "$lib/utils/log"; import { makeFileRefResolver, type FileRefResolver } from "$lib/utils/file-refs"; @@ -78,6 +78,30 @@ export function getContextFiles(contextId: string | undefined): string[] | undef return files[contextId]; } +// Previews already fetched, by context and path. Dropped with the context's file list, so a +// refresh, relink or unlink never shows a file as it was before. +const peeks = new Map>(); + +function forgetPeeks(contextId?: string) { + if (!contextId) return peeks.clear(); + for (const key of peeks.keys()) { + if (key.startsWith(`${contextId}\n`)) peeks.delete(key); + } +} + +/** The preview of a file in the context's linked folder, fetched once per file list. */ +export function peekContextFile(contextId: string, path: string): Promise { + const key = `${contextId}\n${path}`; + let peek = peeks.get(key); + if (!peek) { + peek = adapter.previewContextFile(contextId, path); + // A failure is not kept: the next hover asks again. + peek.catch(() => peeks.delete(key)); + peeks.set(key, peek); + } + return peek; +} + // One resolver per file list, shared by every card rendering that context. const resolvers = new WeakMap(); @@ -102,6 +126,7 @@ export async function loadContextFiles(contextId: string, refresh = false): Prom if (!refresh && files[contextId]) return; try { const index = await adapter.listContextFiles(contextId, refresh); + forgetPeeks(contextId); files = { ...files, [contextId]: index.files }; } catch (e) { log.error("Failed to list the project folder:", e); @@ -113,6 +138,7 @@ export async function linkContextFolder(contextId: string, title: string): Promi const folder = await adapter.pickContextFolder(contextId, title); if (!folder) return false; folders = { ...folders, [contextId]: folder }; + forgetPeeks(contextId); const { [contextId]: _stale, ...rest } = files; files = rest; return true; @@ -120,6 +146,7 @@ export async function linkContextFolder(contextId: string, title: string): Promi export async function unlinkContextFolder(contextId: string): Promise { await adapter.unlinkContextFolder(contextId); + forgetPeeks(contextId); const { [contextId]: _folder, ...remainingFolders } = folders; const { [contextId]: _files, ...remainingFiles } = files; folders = remainingFolders; @@ -129,6 +156,7 @@ export async function unlinkContextFolder(contextId: string): Promise { /** Drop every link on this device. */ export async function clearContextFolders(): Promise { await adapter.clearContextFolders(); + forgetPeeks(); folders = {}; files = {}; } diff --git a/src/lib/types.ts b/src/lib/types.ts index 6d53b4f..40e63bf 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -248,6 +248,12 @@ export interface IStorageService { previewContextDigest(contextId: string): Promise; /** Draft a description of the context's project from its folder. A proposal; nothing is saved. */ suggestContextDescription(contextId: string): Promise; + /** + * The preview of a file in a context's linked folder, for the hover card on an `@path` - + * the same shape an attachment's has. `fileType` is `withheld` for a file named like + * one that holds secrets, whose contents are never read. + */ + previewContextFile(contextId: string, path: string): Promise; /** The files in a context's linked folder; `refresh` walks the folder again. */ listContextFiles(contextId: string, refresh: boolean): Promise; isWindows10(): Promise; diff --git a/src/lib/utils/__tests__/markdown.test.ts b/src/lib/utils/__tests__/markdown.test.ts index c307aeb..04829d3 100644 --- a/src/lib/utils/__tests__/markdown.test.ts +++ b/src/lib/utils/__tests__/markdown.test.ts @@ -44,15 +44,34 @@ describe('markdown utilities', () => { expect(result).toContain('@src/app.ts.'); }); - it('should mark an @ path the linked folder does not hold, with a suggestion', () => { - const resolveFile = { - resolve: makeFileRefResolver(['src/app.ts', 'src/lib/moved.ts']), - missingLabel: 'Not in the project folder', - }; - const result = safeParse('@src/app.ts and @src/moved.ts', undefined, resolveFile); - expect(result).toContain('@src/app.ts'); - expect(result).toContain('class="ai-mention file-ref-unresolved"'); - expect(result).toContain('Not in the project folder → src/lib/moved.ts'); + it('should turn @ paths into hoverable file chips when a folder is linked', () => { + const resolve = makeFileRefResolver(['src/app.ts', 'docs/release notes.md']); + const result = safeParse( + '@src/app.ts and @src/gone.ts and @"docs/release notes.md"', + undefined, + resolve, + ); + expect(result).toContain( + '@src/app.ts', + ); + expect(result).toContain( + '', + ); + expect(result).toContain('data-file-path="docs/release notes.md"'); + // No native tooltip left to compete with the preview card. + expect(result).not.toContain('title="file:'); + }); + + it('should keep markup in a path inert in the file chip', () => { + const result = safeParse('@a.ts', undefined, makeFileRefResolver([])); + // The serializer leaves `<` unescaped inside an attribute value, so look at what + // the markup builds rather than at its text: one chip, no element from the path. + const template = document.createElement('template'); + template.innerHTML = result; + expect(template.content.querySelector('img')).toBeNull(); + const chip = template.content.querySelector('[data-file-path]'); + expect(chip?.dataset.filePath).toBe('a.ts'); + expect(chip?.textContent).toBe('@a.ts'); }); it('should highlight @ mentions after whitespace', () => { diff --git a/src/lib/utils/markdown.ts b/src/lib/utils/markdown.ts index b9c3cbf..4151310 100644 --- a/src/lib/utils/markdown.ts +++ b/src/lib/utils/markdown.ts @@ -36,8 +36,6 @@ export type RefResolver = (id: string) => RefDisplay; let activeRefResolver: RefResolver | null = null; // The same, for `@path` references to files in the context's linked project folder. let activeFileResolver: FileRefResolver | null = null; -// The translated "not in the project folder" text for an unresolved path's title. -let activeFileMissingLabel = ""; const STASH_HREF = /^stash:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; @@ -104,19 +102,19 @@ const markedInstance = new Marked( }; } }, - // With a linked folder, a path it does not hold is marked, and a file of - // the same name elsewhere is offered in the title. Without one, a mention + // With a linked folder, the mention becomes a file chip the card can show a + // preview for, marked when the folder does not hold it. Like a stash chip, + // the path rides in `title` because DOMPurify drops data attributes; + // `injectFileRefs` moves it after sanitizing. Without a folder, a mention // renders as it always has. renderer(token) { const display = activeFileResolver?.(token.path as string); - if (!display || display.state === 'resolved') { + if (!display) { return `${escapeHtml(token.text)}`; } - const title = display.suggestion - ? `${activeFileMissingLabel} → ${display.suggestion}` - : activeFileMissingLabel; + const state = display.state === 'resolved' ? '' : ' file-ref-unresolved'; return ( - `` + + `` + `${escapeHtml(token.text)}` ); } @@ -397,6 +395,27 @@ function injectRefs(html: string): string { ); } +/** + * Give the file chips left by the mention renderer their behaviour: the path moves from + * `title` (so no native tooltip competes with the preview card) to `data-file-path`, and + * the chip becomes focusable so the preview is reachable from the keyboard. + * + * Only spans that carry the renderer's own class are touched, and the path is read back as + * an attribute value, never spliced into markup. + */ +function injectFileRefs(html: string): string { + if (!html.includes('title="file:')) return html; + const template = document.createElement('template'); + template.innerHTML = html; + for (const chip of template.content.querySelectorAll('span.file-ref[title^="file:"]')) { + const path = chip.getAttribute('title')!.slice('file:'.length); + chip.removeAttribute('title'); + chip.setAttribute('data-file-path', path); + chip.setAttribute('tabindex', '0'); + } + return template.innerHTML; +} + /** * Parse markdown content and sanitize the output to prevent XSS. * Use this instead of raw `marked.parse()` + `{@html}`. @@ -406,6 +425,7 @@ function injectRefs(html: string): string { * 2. DOMPurify – strips anything unsafe (XSS prevention) * 3. injectBadges – expands placeholders into fully-styled badge HTML * 4. injectRefs – makes `stash:` reference chips clickable + * 5. injectFileRefs – makes `@path` file chips hoverable * * `resolveRef` supplies the live label and state of each referenced stash, and * `resolveFile` checks `@path`s against the context's linked project folder. @@ -413,11 +433,10 @@ function injectRefs(html: string): string { export function safeParse( content: string, resolveRef?: RefResolver, - resolveFile?: { resolve: FileRefResolver; missingLabel: string }, + resolveFile?: FileRefResolver, ): string { activeRefResolver = resolveRef ?? null; - activeFileResolver = resolveFile?.resolve ?? null; - activeFileMissingLabel = resolveFile?.missingLabel ?? ""; + activeFileResolver = resolveFile ?? null; let raw: string; try { raw = markedInstance.parse(content) as string; @@ -426,7 +445,7 @@ export function safeParse( activeFileResolver = null; } const sanitized = sanitizeHtml(raw); - return injectRefs(injectBadges(sanitized)); + return injectFileRefs(injectRefs(injectBadges(sanitized))); } From be6579507604f03d33d54bc0cc26b008158633fe Mon Sep 17 00:00:00 2001 From: Nico Wiedemann Date: Sat, 7 Nov 2026 18:09:30 +0100 Subject: [PATCH 5/5] chore: bump version to v1.12.0 Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 ++ package.json | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/tauri.conf.json | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3136532..6a63976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ popover, not for the person who wrote the commit. ## [Unreleased] +## [1.12.0] - 2026-11-07 + ### Added - **Type `@` to reference a file from your project.** Link a context to its project folder in diff --git a/package.json b/package.json index 48f20f9..740f6c7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad", - "version": "1.11.6", + "version": "1.12.0", "description": "The staging area for your AI context.", "author": { "name": "Nico Wiedemann", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index a6c7a48..72cf123 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -5615,7 +5615,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stashpad" -version = "1.11.6" +version = "1.12.0" dependencies = [ "active-win-pos-rs", "aes-gcm", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1a89532..5029522 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stashpad" -version = "1.11.6" +version = "1.12.0" description = "The staging area for your AI context." authors = ["Nico Wiedemann "] repository = "https://github.com/EarMaster/stashpad" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index f24213b..5254a52 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "stashpad", - "version": "1.11.6", + "version": "1.12.0", "identifier": "org.stashpad", "build": { "frontendDist": "../dist",