Skip to content

Commit 31cd10f

Browse files
fix(search): address review on query operators
Token-start operator parsing (no hyphen/slash false positives), discriminated unresolved from:/in: so searches never silently widen, include humans in from: resolution, wire e2eBridge operator filters, clarify after/before inclusivity, and simplify the hook enable gate. Signed-off-by: Jatinder Mahajan <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 82bdba7 commit 31cd10f

6 files changed

Lines changed: 200 additions & 57 deletions

File tree

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

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,8 @@ fn search_messages_filter_requests_prefix_mode_for_topbar_typeahead() {
9393

9494
#[test]
9595
fn search_messages_filter_emits_operator_fields() {
96-
let authors = vec![
97-
"aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899".to_string(),
98-
];
96+
let authors =
97+
vec!["aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899".to_string()];
9998
let filter = build_search_messages_filter(
10099
"deploy",
101100
20,
@@ -109,9 +108,7 @@ fn search_messages_filter_emits_operator_fields() {
109108
assert_eq!(filter["#h"], serde_json::json!(["channel-uuid"]));
110109
assert_eq!(
111110
filter["authors"],
112-
serde_json::json!([
113-
"aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"
114-
])
111+
serde_json::json!(["aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"])
115112
);
116113
assert_eq!(filter["since"], serde_json::json!(1_700_000_000));
117114
assert_eq!(filter["until"], serde_json::json!(1_700_086_400));

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

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,9 @@ export function useSearchMessagesQuery(
4040
since: since ?? undefined,
4141
until: until ?? undefined,
4242
}),
43-
enabled:
44-
enabled &&
45-
(trimmedQuery.length >= 2 ||
46-
Boolean(authors?.length) ||
47-
since != null ||
48-
until != null ||
49-
Boolean(channelId)),
43+
// Call sites own the "when to search" floor (FTS length / unresolved
44+
// operators). Keep a single threshold here so it cannot drift.
45+
enabled: enabled && trimmedQuery.length >= 2,
5046
staleTime: 30_000,
5147
gcTime: 5 * 60 * 1_000,
5248
});

‎desktop/src/features/search/lib/parseSearchOperators.test.mjs‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,10 @@ test("extracts from / in / after / before and keeps remaining FTS text", () => {
2929
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
3030
);
3131
assert.equal(parsed.in, "#general");
32-
assert.equal(parsed.since, Math.floor(new Date(2024, 0, 15).getTime() / 1000));
32+
assert.equal(
33+
parsed.since,
34+
Math.floor(new Date(2024, 0, 15).getTime() / 1000),
35+
);
3336
assert.equal(parsed.until, Math.floor(new Date(2024, 1, 1).getTime() / 1000));
3437
});
3538

@@ -56,16 +59,47 @@ test("rejects impossible calendar dates", () => {
5659
assert.equal(parsed.text, "x after:2024-02-30");
5760
});
5861

62+
test("does not treat hyphen or slash adjacent tokens as operators", () => {
63+
assert.deepEqual(parseSearchOperators("built-in:react hooks"), {
64+
text: "built-in:react hooks",
65+
from: null,
66+
in: null,
67+
since: null,
68+
until: null,
69+
});
70+
assert.deepEqual(parseSearchOperators("sign-in:flow broken"), {
71+
text: "sign-in:flow broken",
72+
from: null,
73+
in: null,
74+
since: null,
75+
until: null,
76+
});
77+
assert.deepEqual(parseSearchOperators("https://x.com/in:foo"), {
78+
text: "https://x.com/in:foo",
79+
from: null,
80+
in: null,
81+
since: null,
82+
until: null,
83+
});
84+
});
85+
86+
test("strips trailing punctuation from operator values", () => {
87+
const parsed = parseSearchOperators("deploy in:general, from:@alice.");
88+
assert.equal(parsed.in, "#general".replace("#", "") || "general");
89+
assert.equal(parsed.in, "general");
90+
assert.equal(parsed.from, "@alice");
91+
assert.equal(parsed.text, "deploy");
92+
});
93+
5994
test("helpers recognize hex pubkeys and channel uuids", () => {
6095
assert.equal(
61-
isHexPubkey("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"),
96+
isHexPubkey(
97+
"deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
98+
),
6299
true,
63100
);
64101
assert.equal(isHexPubkey("npub1abc"), false);
65-
assert.equal(
66-
isChannelUuid("11111111-1111-1111-1111-111111111111"),
67-
true,
68-
);
102+
assert.equal(isChannelUuid("11111111-1111-1111-1111-111111111111"), true);
69103
assert.equal(normalizeFromHandle("@alice"), "alice");
70104
assert.equal(normalizeInChannel("#general"), "general");
71105
});

‎desktop/src/features/search/lib/parseSearchOperators.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
*
77
* Name resolution for `from:` / `in:` happens at the call site (autocomplete or
88
* local channel/user lists). This module only splits syntax.
9+
*
10+
* Operators must start at a token boundary (start of string or whitespace). A
11+
* word-boundary `\b` is intentionally avoided: it also matches after `-` / `/`,
12+
* which would turn `built-in:react` or `https://x.com/in:foo` into operators.
913
*/
1014

1115
export type ParsedSearchOperators = {
@@ -15,13 +19,21 @@ export type ParsedSearchOperators = {
1519
from: string | null;
1620
/** Raw `in:` value (channel uuid, #name, …), if present. */
1721
in: string | null;
18-
/** `after:YYYY-MM-DD` → unix seconds at local start of day. */
22+
/**
23+
* `after:YYYY-MM-DD` → unix seconds at local start of that day (inclusive).
24+
* Messages at or after this timestamp match.
25+
*/
1926
since: number | null;
20-
/** `before:YYYY-MM-DD` → unix seconds at local start of day. */
27+
/**
28+
* `before:YYYY-MM-DD` → unix seconds at local start of that day (exclusive).
29+
* Messages strictly before this timestamp match, so the named calendar day
30+
* itself is not included (Slack-compatible).
31+
*/
2132
until: number | null;
2233
};
2334

24-
const OPERATOR_RE = /\b(from|in|after|before):(\S+)/gi;
35+
/** Token-start only — not `\b`, which fires after hyphens and slashes. */
36+
const OPERATOR_RE = /(?:^|\s)(from|in|after|before):(\S+)/gi;
2537

2638
function parseLocalDayStart(value: string): number | null {
2739
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
@@ -48,11 +60,19 @@ function parseLocalDayStart(value: string): number | null {
4860
return Math.floor(date.getTime() / 1000);
4961
}
5062

63+
/** Drop trailing punctuation so `in:general,` still resolves to `general`. */
64+
function cleanOperatorValue(value: string): string {
65+
return value.replace(/[.,;:!?]+$/g, "");
66+
}
67+
5168
/**
5269
* Extract `from:` / `in:` / `after:` / `before:` operators from `raw`.
5370
*
5471
* Later occurrences of the same operator win. Date operators that are not
5572
* `YYYY-MM-DD` stay in the returned `text`.
73+
*
74+
* Multi-word handles (`from:@Will Pfleger`) are a known limitation of part 1:
75+
* only the first whitespace-delimited token is captured.
5676
*/
5777
export function parseSearchOperators(raw: string): ParsedSearchOperators {
5878
let from: string | null = null;
@@ -69,7 +89,7 @@ export function parseSearchOperators(raw: string): ParsedSearchOperators {
6989
lastIndex = index + match[0].length;
7090

7191
const kind = match[1].toLowerCase();
72-
const value = match[2];
92+
const value = cleanOperatorValue(match[2]);
7393

7494
if (kind === "from") {
7595
from = value;
@@ -132,3 +152,14 @@ export function normalizeInChannel(value: string): string {
132152
export function isChannelUuid(value: string): boolean {
133153
return UUID_RE.test(value);
134154
}
155+
156+
/**
157+
* Result of resolving a `from:` / `in:` operator against local candidates.
158+
*
159+
* Distinguishes "no operator" from "operator present but unmatched" so callers
160+
* never silently widen the search when resolution fails.
161+
*/
162+
export type OperatorResolveResult<T> =
163+
| { status: "none" }
164+
| { status: "resolved"; value: T }
165+
| { status: "unresolved" };

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

Lines changed: 84 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
normalizeFromHandle,
1818
normalizeInChannel,
1919
parseSearchOperators,
20+
type OperatorResolveResult,
2021
} from "@/features/search/lib/parseSearchOperators";
2122
import type { SearchResult } from "@/features/search/ui/SearchResultItem";
2223
import type { Channel, SearchHit, UserSearchResult } from "@/shared/api/types";
@@ -45,13 +46,13 @@ function resolveChannelIdFromOperator(
4546
raw: string | null,
4647
channels: Channel[],
4748
channelLabels?: Record<string, string>,
48-
): string | null {
49+
): OperatorResolveResult<string> {
4950
if (!raw) {
50-
return null;
51+
return { status: "none" };
5152
}
5253
const value = normalizeInChannel(raw);
5354
if (isChannelUuid(value)) {
54-
return value;
55+
return { status: "resolved", value };
5556
}
5657
const needle = value.toLowerCase();
5758
const match = channels.find((channel) => {
@@ -60,28 +61,32 @@ function resolveChannelIdFromOperator(
6061
channel.name.toLowerCase() === needle || label.toLowerCase() === needle
6162
);
6263
});
63-
return match?.id ?? null;
64+
return match
65+
? { status: "resolved", value: match.id }
66+
: { status: "unresolved" };
6467
}
6568

6669
function resolveAuthorFromOperator(
6770
raw: string | null,
6871
candidates: Array<{ pubkey: string; displayName?: string | null }>,
69-
): string | null {
72+
): OperatorResolveResult<string> {
7073
if (!raw) {
71-
return null;
74+
return { status: "none" };
7275
}
7376
if (isHexPubkey(raw)) {
74-
return normalizePubkey(raw);
77+
return { status: "resolved", value: normalizePubkey(raw) };
7578
}
7679
const handle = normalizeFromHandle(raw).toLowerCase();
7780
if (!handle) {
78-
return null;
81+
return { status: "unresolved" };
7982
}
8083
const match = candidates.find((candidate) => {
8184
const name = candidate.displayName?.trim().toLowerCase();
8285
return name === handle || normalizePubkey(candidate.pubkey) === handle;
8386
});
84-
return match ? normalizePubkey(match.pubkey) : null;
87+
return match
88+
? { status: "resolved", value: normalizePubkey(match.pubkey) }
89+
: { status: "unresolved" };
8590
}
8691

8792
export function useSearchResults({
@@ -110,9 +115,8 @@ export function useSearchResults({
110115
[debouncedQuery],
111116
);
112117

113-
const operatorChannelId = React.useMemo(
114-
() =>
115-
resolveChannelIdFromOperator(parsedQuery.in, channels, channelLabels),
118+
const channelResolution = React.useMemo(
119+
() => resolveChannelIdFromOperator(parsedQuery.in, channels, channelLabels),
116120
[parsedQuery.in, channels, channelLabels],
117121
);
118122

@@ -127,45 +131,100 @@ export function useSearchResults({
127131

128132
const searchBackedQueriesEnabled = enabled && hasSearchQuery;
129133

134+
const fromHandleForLookup =
135+
parsedQuery.from && !isHexPubkey(parsedQuery.from)
136+
? normalizeFromHandle(parsedQuery.from)
137+
: "";
138+
130139
const managedAgentsQuery = useManagedAgentsQuery({
131140
enabled: searchBackedQueriesEnabled,
132141
});
133142
const relayAgentsQuery = useRelayAgentsQuery({
134143
enabled: searchBackedQueriesEnabled,
135144
});
145+
// Resolve `from:@name` against people, not only agents.
146+
const fromUserSearchQuery = useUserSearchQuery(fromHandleForLookup, {
147+
enabled: searchBackedQueriesEnabled && fromHandleForLookup.length >= 1,
148+
limit,
149+
});
150+
const userSearchQuery = useUserSearchQuery(ftsQuery, {
151+
enabled: searchBackedQueriesEnabled,
152+
limit,
153+
});
136154

137155
const authorCandidateSeed = React.useMemo(() => {
138156
const candidates: Array<{ pubkey: string; displayName?: string | null }> =
139157
[];
158+
const seen = new Set<string>();
159+
const push = (pubkey: string, displayName?: string | null) => {
160+
const key = normalizePubkey(pubkey);
161+
if (seen.has(key)) {
162+
return;
163+
}
164+
seen.add(key);
165+
candidates.push({ pubkey: key, displayName });
166+
};
140167
for (const agent of managedAgentsQuery.data ?? []) {
141-
candidates.push({ pubkey: agent.pubkey, displayName: agent.name });
168+
push(agent.pubkey, agent.name);
142169
}
143170
for (const agent of relayAgentsQuery.data ?? []) {
144-
candidates.push({ pubkey: agent.pubkey, displayName: agent.name });
171+
push(agent.pubkey, agent.name);
172+
}
173+
for (const user of fromUserSearchQuery.data ?? []) {
174+
push(user.pubkey, user.displayName);
175+
}
176+
for (const user of userSearchQuery.data ?? []) {
177+
push(user.pubkey, user.displayName);
145178
}
146179
return candidates;
147-
}, [managedAgentsQuery.data, relayAgentsQuery.data]);
180+
}, [
181+
managedAgentsQuery.data,
182+
relayAgentsQuery.data,
183+
fromUserSearchQuery.data,
184+
userSearchQuery.data,
185+
]);
148186

149-
const resolvedAuthor = React.useMemo(
187+
const authorResolution = React.useMemo(
150188
() => resolveAuthorFromOperator(parsedQuery.from, authorCandidateSeed),
151189
[parsedQuery.from, authorCandidateSeed],
152190
);
153191

192+
const hasUnresolvedOperator =
193+
authorResolution.status === "unresolved" ||
194+
channelResolution.status === "unresolved";
195+
196+
// While `from:@name` user search is still loading, hold off so we do not
197+
// flash an unresolved empty state before candidates arrive.
198+
const waitingOnFromResolution =
199+
Boolean(fromHandleForLookup) &&
200+
fromUserSearchQuery.isLoading &&
201+
authorResolution.status === "unresolved";
202+
154203
const searchQuery = useSearchMessagesQuery(ftsQuery, {
155-
// Operators refine an FTS query. Empty FTS short-circuits on the relay
156-
// search path, so require real search text (same floor as before).
157-
enabled: enabled && ftsQuery.length >= MIN_SEARCH_QUERY_LENGTH,
204+
enabled:
205+
enabled &&
206+
!hasUnresolvedOperator &&
207+
!waitingOnFromResolution &&
208+
ftsQuery.length >= MIN_SEARCH_QUERY_LENGTH,
158209
limit,
159-
channelId: operatorChannelId ?? undefined,
160-
authors: resolvedAuthor ? [resolvedAuthor] : undefined,
210+
channelId:
211+
channelResolution.status === "resolved"
212+
? channelResolution.value
213+
: undefined,
214+
authors:
215+
authorResolution.status === "resolved"
216+
? [authorResolution.value]
217+
: undefined,
161218
since: parsedQuery.since,
162219
until: parsedQuery.until,
163220
});
164221

165-
const messageResults = React.useMemo(
166-
() => dedupeSearchHits(searchQuery.data?.hits ?? []),
167-
[searchQuery.data?.hits],
168-
);
222+
const messageResults = React.useMemo(() => {
223+
if (hasUnresolvedOperator && !waitingOnFromResolution) {
224+
return [];
225+
}
226+
return dedupeSearchHits(searchQuery.data?.hits ?? []);
227+
}, [hasUnresolvedOperator, waitingOnFromResolution, searchQuery.data?.hits]);
169228
const channelResults = React.useMemo(() => {
170229
if (ftsQuery.length < MIN_SEARCH_QUERY_LENGTH) {
171230
return [];
@@ -203,11 +262,6 @@ export function useSearchResults({
203262
})
204263
.slice(0, 5);
205264
}, [channelLabels, channels, ftsQuery]);
206-
207-
const userSearchQuery = useUserSearchQuery(ftsQuery, {
208-
enabled: searchBackedQueriesEnabled,
209-
limit,
210-
});
211265
const managedAgentPubkeys = React.useMemo(
212266
() =>
213267
new Set(

0 commit comments

Comments
 (0)