Skip to content

Commit a70b605

Browse files
jatinder14jatinder-mahajan-certifyoscursoragentwpfleger96
authored
feat(search): parse from:/in:/after:/before: and pass them in the filter (#2871)
## Summary - Adds a pure-TS operator parser (`from:` / `in:` / `after:` / `before:`) with unit tests. Invalid date tokens stay in the FTS text. - Extends `search_messages` so the desktop can send `authors` / `since` / `until` (and existing `#h`) on the filter the relay already understands. - Wires topbar search to strip operators from the prefix query, resolve `in:` against local channels and `from:` against hex pubkeys / known agents, then pass the structured fields through. This is part 1 of #2853 (parser + command plumbing). Autocomplete chips / richer `from:@name` resolution can follow in a second PR. ## Test plan - [x] `node --import ./test-loader.mjs --experimental-strip-types --test src/features/search/lib/parseSearchOperators.test.mjs` - [x] Added `search_messages_filter_emits_operator_fields` unit test (full `buzz-desktop` crate build needs local sidecar binaries in this environment) - [ ] Manual: topbar `deploy from:<hex> after:2024-01-01` emits authors/since on the bridge filter and returns narrowed hits Made with [Cursor](https://cursor.com) --------- Signed-off-by: Jatinder Mahajan <[email protected]> Co-authored-by: Jatinder Mahajan <[email protected]> Co-authored-by: Cursor <[email protected]> Co-authored-by: Will Pfleger <[email protected]>
1 parent 9d4c1db commit a70b605

12 files changed

Lines changed: 756 additions & 67 deletions

File tree

‎desktop/src-tauri/src/commands/messages.rs‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,14 @@ pub async fn get_feed(
138138
})
139139
}
140140

141-
fn build_search_messages_filter(q: &str, cap: u32, channel_id: Option<&str>) -> serde_json::Value {
141+
fn build_search_messages_filter(
142+
q: &str,
143+
cap: u32,
144+
channel_id: Option<&str>,
145+
authors: Option<&[String]>,
146+
since: Option<i64>,
147+
until: Option<i64>,
148+
) -> serde_json::Value {
142149
let mut filter = serde_json::Map::new();
143150
filter.insert(
144151
"kinds".to_string(),
@@ -153,6 +160,25 @@ fn build_search_messages_filter(q: &str, cap: u32, channel_id: Option<&str>) ->
153160
if let Some(cid) = channel_id {
154161
filter.insert("#h".to_string(), serde_json::json!([cid]));
155162
}
163+
// Optional operators from the desktop search parser (#2853). The relay
164+
// already maps authors/since/until onto FTS; search remains never the
165+
// access boundary (hits are refetched and re-authorized).
166+
if let Some(authors) = authors {
167+
let cleaned: Vec<&str> = authors
168+
.iter()
169+
.map(|a| a.trim())
170+
.filter(|a| !a.is_empty())
171+
.collect();
172+
if !cleaned.is_empty() {
173+
filter.insert("authors".to_string(), serde_json::json!(cleaned));
174+
}
175+
}
176+
if let Some(since) = since {
177+
filter.insert("since".to_string(), serde_json::json!(since));
178+
}
179+
if let Some(until) = until {
180+
filter.insert("until".to_string(), serde_json::json!(until));
181+
}
156182
serde_json::Value::Object(filter)
157183
}
158184

@@ -161,10 +187,20 @@ pub async fn search_messages(
161187
q: String,
162188
limit: Option<u32>,
163189
channel_id: Option<String>,
190+
authors: Option<Vec<String>>,
191+
since: Option<i64>,
192+
until: Option<i64>,
164193
state: State<'_, AppState>,
165194
) -> Result<SearchResponse, String> {
166195
let cap = limit.unwrap_or(20).min(100);
167-
let filter = build_search_messages_filter(&q, cap, channel_id.as_deref());
196+
let filter = build_search_messages_filter(
197+
&q,
198+
cap,
199+
channel_id.as_deref(),
200+
authors.as_deref(),
201+
since,
202+
until,
203+
);
168204

169205
let events = query_relay(&state, &[filter]).await?;
170206
Ok(nostr_convert::search_response_from_events(&events))

‎desktop/src-tauri/src/commands/messages_tests.rs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,38 @@ fn managed_agent_message_builder_rejects_invalid_mentions() {
8080
}
8181
#[test]
8282
fn search_messages_filter_requests_prefix_mode_for_topbar_typeahead() {
83-
let filter = build_search_messages_filter(" pro ", 12, Some("channel-1"));
83+
let filter = build_search_messages_filter(" pro ", 12, Some("channel-1"), None, None, None);
8484

8585
assert_eq!(filter["search"], serde_json::json!("pro"));
8686
assert_eq!(filter["search_mode"], serde_json::json!("prefix"));
8787
assert_eq!(filter["limit"], serde_json::json!(12));
8888
assert_eq!(filter["#h"], serde_json::json!(["channel-1"]));
89+
assert!(filter.get("authors").is_none());
90+
assert!(filter.get("since").is_none());
91+
assert!(filter.get("until").is_none());
92+
}
93+
94+
#[test]
95+
fn search_messages_filter_emits_operator_fields() {
96+
let authors =
97+
vec!["aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899".to_string()];
98+
let filter = build_search_messages_filter(
99+
"deploy",
100+
20,
101+
Some("channel-uuid"),
102+
Some(&authors),
103+
Some(1_700_000_000),
104+
Some(1_700_086_400),
105+
);
106+
107+
assert_eq!(filter["search"], serde_json::json!("deploy"));
108+
assert_eq!(filter["#h"], serde_json::json!(["channel-uuid"]));
109+
assert_eq!(
110+
filter["authors"],
111+
serde_json::json!(["aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"])
112+
);
113+
assert_eq!(filter["since"], serde_json::json!(1_700_000_000));
114+
assert_eq!(filter["until"], serde_json::json!(1_700_086_400));
89115
}
90116

91117
#[test]

‎desktop/src/features/search/hooks.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,45 @@ export function useSearchMessagesQuery(
66
query: string,
77
options?: {
88
channelId?: string;
9+
authors?: string[];
10+
since?: number | null;
11+
until?: number | null;
912
enabled?: boolean;
1013
limit?: number;
14+
unresolvedOperator?: boolean;
1115
},
1216
) {
1317
const trimmedQuery = query.trim();
1418
const enabled = options?.enabled ?? true;
1519
const limit = options?.limit ?? 12;
1620
const channelId = options?.channelId;
21+
const authors = options?.authors;
22+
const since = options?.since ?? null;
23+
const until = options?.until ?? null;
24+
const unresolvedOperator = options?.unresolvedOperator ?? false;
1725

1826
return useQuery({
19-
queryKey: ["search-messages", trimmedQuery, limit, channelId ?? null],
27+
queryKey: [
28+
"search-messages",
29+
trimmedQuery,
30+
limit,
31+
channelId ?? null,
32+
authors ?? null,
33+
since,
34+
until,
35+
unresolvedOperator,
36+
],
2037
queryFn: () =>
2138
searchMessages({
2239
q: trimmedQuery,
2340
limit,
2441
channelId,
42+
authors,
43+
since: since ?? undefined,
44+
until: until ?? undefined,
2545
}),
46+
// Call sites own the "when to search" floor (FTS length / unresolved
47+
// operators). Keep a single threshold here so it cannot drift.
2648
enabled: enabled && trimmedQuery.length >= 2,
2749
staleTime: 30_000,
2850
gcTime: 5 * 60 * 1_000,
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
isChannelUuid,
6+
isHexPubkey,
7+
normalizeFromHandle,
8+
normalizeInChannel,
9+
parseSearchOperators,
10+
} from "./parseSearchOperators.ts";
11+
12+
test("leaves plain text unchanged", () => {
13+
assert.deepEqual(parseSearchOperators(" deploy "), {
14+
text: "deploy",
15+
from: null,
16+
in: null,
17+
since: null,
18+
until: null,
19+
});
20+
});
21+
22+
test("extracts from / in / after / before and keeps remaining FTS text", () => {
23+
const parsed = parseSearchOperators(
24+
"deploy from:deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef in:#general after:2024-01-15 before:2024-02-01 status",
25+
);
26+
assert.equal(parsed.text, "deploy status");
27+
assert.equal(
28+
parsed.from,
29+
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
30+
);
31+
assert.equal(parsed.in, "#general");
32+
assert.equal(
33+
parsed.since,
34+
Math.floor(new Date(2024, 0, 15).getTime() / 1000),
35+
);
36+
assert.equal(
37+
parsed.until,
38+
Math.floor(new Date(2024, 1, 1).getTime() / 1000) - 1,
39+
);
40+
});
41+
42+
test("before: excludes the named day's exact local midnight", () => {
43+
const localMidnight = Math.floor(new Date(2024, 1, 1).getTime() / 1000);
44+
const parsed = parseSearchOperators("deploy before:2024-02-01");
45+
46+
assert.equal(parsed.until, localMidnight - 1);
47+
// The relay keeps events where `created_at <= until`, so a message stamped
48+
// exactly at midnight must fail that predicate.
49+
assert.equal(localMidnight <= parsed.until, false);
50+
});
51+
52+
test("keeps invalid date operators in the FTS text", () => {
53+
const parsed = parseSearchOperators("notes after:yesterday before:soon");
54+
assert.equal(parsed.text, "notes after:yesterday before:soon");
55+
assert.equal(parsed.since, null);
56+
assert.equal(parsed.until, null);
57+
});
58+
59+
test("later operators of the same kind win", () => {
60+
const parsed = parseSearchOperators(
61+
"from:@alice from:@bob in:one in:two after:2024-01-01 after:2024-03-01",
62+
);
63+
assert.equal(parsed.from, "@bob");
64+
assert.equal(parsed.in, "two");
65+
assert.equal(parsed.since, Math.floor(new Date(2024, 2, 1).getTime() / 1000));
66+
assert.equal(parsed.text, "");
67+
});
68+
69+
test("rejects impossible calendar dates", () => {
70+
const parsed = parseSearchOperators("x after:2024-02-30");
71+
assert.equal(parsed.since, null);
72+
assert.equal(parsed.text, "x after:2024-02-30");
73+
});
74+
75+
test("does not treat hyphen or slash adjacent tokens as operators", () => {
76+
assert.deepEqual(parseSearchOperators("built-in:react hooks"), {
77+
text: "built-in:react hooks",
78+
from: null,
79+
in: null,
80+
since: null,
81+
until: null,
82+
});
83+
assert.deepEqual(parseSearchOperators("sign-in:flow broken"), {
84+
text: "sign-in:flow broken",
85+
from: null,
86+
in: null,
87+
since: null,
88+
until: null,
89+
});
90+
assert.deepEqual(parseSearchOperators("https://x.com/in:foo"), {
91+
text: "https://x.com/in:foo",
92+
from: null,
93+
in: null,
94+
since: null,
95+
until: null,
96+
});
97+
});
98+
99+
test("strips trailing punctuation from operator values", () => {
100+
const parsed = parseSearchOperators("deploy in:general, from:@alice.");
101+
assert.equal(parsed.in, "#general".replace("#", "") || "general");
102+
assert.equal(parsed.in, "general");
103+
assert.equal(parsed.from, "@alice");
104+
assert.equal(parsed.text, "deploy");
105+
});
106+
107+
test("helpers recognize hex pubkeys and channel uuids", () => {
108+
assert.equal(
109+
isHexPubkey(
110+
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
111+
),
112+
true,
113+
);
114+
assert.equal(isHexPubkey("npub1abc"), false);
115+
assert.equal(isChannelUuid("11111111-1111-1111-1111-111111111111"), true);
116+
assert.equal(normalizeFromHandle("@alice"), "alice");
117+
assert.equal(normalizeInChannel("#general"), "general");
118+
});

0 commit comments

Comments
 (0)