Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
157 changes: 141 additions & 16 deletions asyar-launcher/src-tauri/crates/asyar-storage/src/clipboard.rs

Large diffs are not rendered by default.

54 changes: 47 additions & 7 deletions asyar-launcher/src-tauri/crates/asyar-storage/src/clipboard_fts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub fn rebuild_from_disk(

let mut stmt = conn
.prepare(
"SELECT id, item_type, content, preview, content_hash, source_app \
"SELECT id, item_type, content, preview, content_hash, source_app, custom_title \
FROM clipboard_items ORDER BY created_at DESC, id DESC",
)
.map_err(|e| AppError::Database(format!("FTS rebuild prepare: {e}")))?;
Expand All @@ -52,6 +52,7 @@ pub fn rebuild_from_disk(
raw_preview: Option<String>,
existing_hash: Option<Vec<u8>>,
raw_source_app: Option<String>,
raw_custom_title: Option<String>,
}

let rows: Vec<Row> = stmt
Expand All @@ -63,6 +64,7 @@ pub fn rebuild_from_disk(
raw_preview: r.get(3)?,
existing_hash: r.get(4)?,
raw_source_app: r.get(5)?,
raw_custom_title: r.get(6)?,
})
})
.map_err(|e| AppError::Database(format!("FTS rebuild query: {e}")))?
Expand All @@ -86,12 +88,20 @@ pub fn rebuild_from_disk(
Some(v.to_string())
}
});
let custom_title = row.raw_custom_title.as_deref().and_then(|v| {
if cipher::is_encrypted_value(v) {
cipher::decrypt(v, master_key).ok()
} else {
Some(v.to_string())
}
});
let source_app_text = extract_source_app_text_from_json_str(row.raw_source_app.as_deref());
fts.upsert_with_source_app(
fts.upsert_full(
&row.id,
preview.as_deref(),
content.as_deref(),
Some(&source_app_text),
custom_title.as_deref(),
)?;

if row.existing_hash.is_none() && row.item_type != "image" {
Expand Down Expand Up @@ -175,7 +185,7 @@ impl ClipboardFts {
conn.execute_batch(
"CREATE VIRTUAL TABLE fts_clipboard USING fts5(
clip_id UNINDEXED,
preview, content, source_app,
preview, content, source_app, custom_title,
prefix='2 3',
tokenize='unicode61 remove_diacritics 2'
);
Expand All @@ -197,7 +207,7 @@ impl ClipboardFts {
preview: Option<&str>,
content: Option<&str>,
) -> Result<(), AppError> {
self.upsert_with_source_app(id, preview, content, None)
self.upsert_full(id, preview, content, None, None)
}

/// Insert or replace the FTS row for a clipboard id, including `source_app` metadata.
Expand All @@ -207,18 +217,31 @@ impl ClipboardFts {
preview: Option<&str>,
content: Option<&str>,
source_app: Option<&str>,
) -> Result<(), AppError> {
self.upsert_full(id, preview, content, source_app, None)
}

/// Insert or replace the FTS row for a clipboard id, including `source_app` and `custom_title` metadata.
pub fn upsert_full(
&self,
id: &str,
preview: Option<&str>,
content: Option<&str>,
source_app: Option<&str>,
custom_title: Option<&str>,
) -> Result<(), AppError> {
let rowid = rowid_for(id);
let conn = self.conn.lock().map_err(|_| AppError::Lock)?;
conn.execute(
"INSERT OR REPLACE INTO fts_clipboard(rowid, clip_id, preview, content, source_app) \
VALUES (?1, ?2, ?3, ?4, ?5)",
"INSERT OR REPLACE INTO fts_clipboard(rowid, clip_id, preview, content, source_app, custom_title) \
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
params![
rowid,
id,
preview.unwrap_or(""),
content.unwrap_or(""),
source_app.unwrap_or("")
source_app.unwrap_or(""),
custom_title.unwrap_or(""),
],
)
.map_err(|e| AppError::Database(format!("FTS upsert: {e}")))?;
Expand Down Expand Up @@ -520,6 +543,22 @@ mod tests {
let hits = fts.search("vscode cloudflare", 10).unwrap();
assert_eq!(hits, vec!["id-1".to_string()]);
}

#[test]
fn test_search_matches_custom_title() {
let fts = ClipboardFts::new_in_memory().unwrap();
fts.upsert_full(
"cmd-1",
Some("curl https://api.internal"),
Some("curl https://api.internal/auth -H Token"),
Some("Terminal"),
Some("💠 AGENTS 💠"),
)
.unwrap();

let hits = fts.search("agents", 10).unwrap();
assert_eq!(hits, vec!["cmd-1".to_string()]);
}
}

#[cfg(test)]
Expand Down Expand Up @@ -547,6 +586,7 @@ mod rebuild_tests {
metadata: None,
source_app: None,
redacted_kinds: None,
custom_title: None,
}
}

Expand Down
51 changes: 51 additions & 0 deletions asyar-launcher/src-tauri/crates/asyar-storage/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ pub const MIGRATIONS: &[Migration] = &[
name: "runs_history_quiet_success",
up: migration_11_runs_history_quiet_success,
},
Migration {
version: 12,
name: "clipboard_custom_title",
up: migration_12_clipboard_custom_title,
},
];

/// Bring `conn` up to the newest ledger version. Idempotent.
Expand Down Expand Up @@ -317,6 +322,30 @@ fn migration_11_runs_history_quiet_success(conn: &Connection) -> Result<(), AppE
Ok(())
}

/// Adds `clipboard_items.custom_title` (#1009). The column was first patched into
/// `clipboard::init_table`, which only baseline calls, so every database
/// already stamped past v1 never received it. Guarded because fresh and v0
/// databases get it from baseline's `CREATE TABLE`.
fn migration_12_clipboard_custom_title(conn: &Connection) -> Result<(), AppError> {
let exists: bool = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('clipboard_items') WHERE name='custom_title'",
[],
|row| row.get::<_, i32>(0),
)
.map(|c| c > 0)
.unwrap_or(false);

if !exists {
conn.execute(
"ALTER TABLE clipboard_items ADD COLUMN custom_title TEXT",
[],
)
.map_err(|e| AppError::Database(format!("Failed to add custom_title column: {e}")))?;
}
Ok(())
}

/// Extends `cloud_sync_e2ee_local` mirror with:
/// - `mode` ("passphrase" default for existing rows, "device-key" for new)
/// - `kcv` (BLOB nullable for device-key HMAC-SHA256 check value)
Expand Down Expand Up @@ -683,6 +712,28 @@ mod tests {
assert_eq!(quiet, 0, "existing runs must stay loud");
}

#[test]
fn stamped_db_without_clipboard_custom_title_gets_the_column() {
let conn = Connection::open_in_memory().unwrap();
run_ledger(&conn, &MIGRATIONS[..11]).unwrap();
assert_eq!(user_version(&conn), 11);
// Simulate an install stamped past baseline whose clipboard_items predates
// `custom_title` — baseline's `init_table` never replays for it.
conn.execute_batch(
"ALTER TABLE clipboard_items DROP COLUMN custom_title;
INSERT INTO clipboard_items
(id, item_type, content, preview, created_at, favorite)
VALUES ('c1', 'text', 'enc_content', 'enc_preview', 1000.0, 0);",
)
.unwrap();
assert!(!column_names(&conn, "clipboard_items").contains(&"custom_title".to_string()));

run(&conn).unwrap();

assert_eq!(user_version(&conn), MIGRATIONS.last().unwrap().version);
assert!(column_names(&conn, "clipboard_items").contains(&"custom_title".to_string()));
}

#[test]
fn version_four_db_adds_search_engine_tables_without_losing_existing_rows() {
let conn = Connection::open_in_memory().unwrap();
Expand Down
1 change: 1 addition & 0 deletions asyar-launcher/src-tauri/examples/clipboard_perf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ fn make_text_item(i: u32, base_ms: f64) -> ClipboardItem {
metadata: None,
source_app: None,
redacted_kinds: None,
custom_title: None,
}
}

Expand Down
1 change: 1 addition & 0 deletions asyar-launcher/src-tauri/examples/seed_clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ fn make_item(i: u32, base_time: f64) -> ClipboardItem {
"bundleId": "dev.seed.clipboard",
})),
redacted_kinds: None,
custom_title: None,
}
}

Expand Down
1 change: 1 addition & 0 deletions asyar-launcher/src-tauri/src/commands/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ macro_rules! storage_commands {
$crate::storage::commands::clipboard_record_capture,
$crate::storage::commands::clipboard_apply_synced,
$crate::storage::commands::clipboard_toggle_favorite,
$crate::storage::commands::clipboard_set_custom_title,
$crate::storage::commands::clipboard_delete_item,
$crate::storage::commands::clipboard_clear_non_favorites,
$crate::commands::clipboard_markup::clipboard_strip_html,
Expand Down
5 changes: 5 additions & 0 deletions asyar-launcher/src-tauri/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ fn get_required_permission(call_type: &str) -> Option<&'static str> {
"asyar:api:clipboard:toggleItemFavorite" => Some("clipboard-history:manage"),
"asyar:api:clipboard:deleteItem" => Some("clipboard-history:manage"),
"asyar:api:clipboard:clearNonFavorites" => Some("clipboard-history:manage"),
"asyar:api:clipboard:setItemCustomTitle" => Some("clipboard-history:manage"),
// Notifications
"asyar:api:feedback:sendBackground" => Some("notifications:send"),
"asyar:api:feedback:dismissBackground" => Some("notifications:send"),
Expand Down Expand Up @@ -1245,6 +1246,10 @@ mod tests {
get_required_permission("asyar:api:clipboard:clearNonFavorites"),
Some("clipboard-history:manage")
);
assert_eq!(
get_required_permission("asyar:api:clipboard:setItemCustomTitle"),
Some("clipboard-history:manage")
);
}

#[test]
Expand Down
18 changes: 18 additions & 0 deletions asyar-launcher/src-tauri/src/storage/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,24 @@ pub fn clipboard_toggle_favorite(
Ok(super::clipboard::toggle_favorite(&conn, &id)?)
}

#[tauri::command]
pub fn clipboard_set_custom_title(
id: String,
title: Option<String>,
store: State<'_, DataStore>,
keystore: State<'_, KeystoreState>,
fts: State<'_, Arc<ClipboardFts>>,
) -> Result<(), AppError> {
let conn = store.conn()?;
Ok(super::clipboard::set_custom_title_with_fts(
&conn,
&id,
title.as_deref(),
keystore.master_key(),
fts.inner(),
)?)
}

#[tauri::command]
pub fn clipboard_delete_item(
id: String,
Expand Down
1 change: 1 addition & 0 deletions asyar-launcher/src/bindings.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
import { t } from '../../services/i18n';
import { appListen } from '../../lib/ipc/bridgeEvents';
import { viewManager } from '../../services/extension/viewManager.svelte';
import { actionService } from '../../services/action/actionService.svelte';

const detailDateFormat = new Intl.DateTimeFormat(undefined, {
month: 'long',
Expand Down Expand Up @@ -498,7 +499,10 @@
}
}

function getItemTitle(item: { type: string; preview?: string }) {
function getItemTitle(item: { type: string; preview?: string; customTitle?: string }) {
if (item.customTitle?.trim()) {
return item.customTitle.trim();
}
const preview = item.preview ?? '';
if (!preview)
return item.type === 'image' ? 'Image' : item.type === 'files' ? 'Files' : 'Empty';
Expand Down Expand Up @@ -1166,9 +1170,19 @@
{clipboardViewState.selectedIds.length} items selected · Enter to merge &amp; paste
</div>
{:else if selectedFullItem}
{@const customTitle =
clipboardViewState.selectedItem?.customTitle ?? selectedFullItem.customTitle}
<MetadataList
title={t('common.information')}
items={[
...(customTitle
? [
{
label: t('features.clipboard.ui.custom_title'),
value: customTitle,
},
]
: []),
{
label: t('features.clipboard.ui.source'),
value: (selectedFullItem.sourceApp as any)?.name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ vi.mock('../../services/action/actionService.svelte', () => ({
registerAction: vi.fn(),
unregisterAction: vi.fn(),
setExtensionForwarder: vi.fn(),
openPrompt: vi.fn(),
closePrompt: vi.fn(),
},
}));

Expand Down Expand Up @@ -78,6 +80,10 @@ vi.mock('./state.svelte', () => ({
items: [],
filteredItems: [],
selectedItem: null,
isRenaming: false,
startRename: vi.fn(),
cancelRename: vi.fn(),
saveRename: vi.fn(),
moveSelection: vi.fn(),
moveSelectionAndExtend: vi.fn(),
handleItemAction: vi.fn(),
Expand Down Expand Up @@ -458,8 +464,11 @@ describe('Action registration', () => {
expect(actionIds).toContain('clipboard-history:paste-as-plain-text');
expect(actionIds).toContain('clipboard-history:delete');
expect(actionIds).toContain('clipboard-history:clear-multi-selection');
expect(actionIds).toContain('clipboard-history:rename');

const byId = (id: string) => registerCalls.find((call) => call[0].id === id)?.[0] as any;
expect(byId('clipboard-history:rename')?.shortcut).toBe('Mod+Shift+E');
expect(byId('clipboard-history:rename')?.icon).toBe('icon:pencil');
expect(byId('clipboard-history:paste')?.shortcut).toBe('Enter');
expect(byId('clipboard-history:copy')?.shortcut).toBe('Mod+Enter');
expect(byId('clipboard-history:toggle-html-view')?.shortcut).toBe('Mod+Shift+H');
Expand Down Expand Up @@ -1349,3 +1358,21 @@ it('restores clipboard actions when returning from a child view', async () => {
expect.objectContaining({ id: 'clipboard-history:save-as-snippet' }),
);
});

describe('Action: clipboard-history:rename', () => {
it('triggers startRename on clipboardViewState when executed', async () => {
const { actionService } = await import('../../services/action/actionService.svelte');
const { clipboardViewState } = await import('./state.svelte');

vi.mocked(actionService.registerAction).mockClear();
await extension.viewActivated('clipboard-history/DefaultView');

const renameAction = vi
.mocked(actionService.registerAction)
.mock.calls.find((c) => c[0].id === 'clipboard-history:rename')?.[0];

expect(renameAction).toBeDefined();
await renameAction?.execute();
expect(clipboardViewState.startRename).toHaveBeenCalled();
});
});
Loading
Loading