Can we add keyword search for threads
Search
Plan for keyword search:
- Data: extend
listThreads(workspaceId?, q?)inlib/data.tsto filter with a PostgresILIKEmatch on the thread title and post bodies (exists (select 1 from posts where thread_id = threads.id and body ilike '%q%')). Multiple words are ANDed, sosandbox timeoutfinds threads containing both anywhere. No new tables/migrations — plain substring matching is fine at our scale and keeps "keyword" behaviour predictable (no stemming surprises). - API:
GET /api/threads?q=…passes through. - UI: a compact search form in
.page-headon the home page and the workspace page (?q=in the URL so results are shareable / back-button friendly). Empty state says "No threads match …" with a clear link. - Screenshot via the static-mockup approach since the app can't run in the sandbox.
threadide@a3fce50Keyword search is on branch thread/1555249e (pushed, commit a3fce50 — no PR opened; say so if you want one).
What it does
- Search box in the title row on the home page and the workspace page. Type, hit Enter → URL becomes
?q=…, list filters. "clear" link resets. Empty state reads No threads match “…”. - Matching (
listThreads(workspaceId?, q?)inlib/data.ts): each whitespace-separated term must appear, case-insensitively, in the thread title or any post body in that thread. Sosandbox timeoutfinds a thread where the title says "sandbox" and a reply mentions "timeout". Terms are capped (8 terms, 60 chars each) and% _ \are escaped sosnake_case/100%match literally. GET /api/threads?q=…(optionally withworkspaceId) exposes the same filter.
Choices worth knowing
- Substring
ILIKE, not Postgres full-text (tsvector). Predictable for identifiers likerequireMember(no stemming surprises), zero migrations. If the thread count grows into the thousands and it gets slow, the upgrade path is apg_trgmGIN index onposts.bodyandthreads.title— the query stays the same. - The form is a plain no-JS GET form (
components/thread-search.tsx), so results are shareable and back-button friendly. No live-as-you-type filtering; happy to add that if you'd prefer. - Layout: the box lives inside the existing
.page-headflex row (title · search · New thread). ≤560px the row wraps and the search box takes its own full-width line under the title + CTA (screenshots attached — static mockup against the realglobals.css, since the app can't run in the sandbox).
Verified: tsc --noEmit clean; dry-ran the Drizzle query with toSQL() to confirm both the workspace filter and the ILIKE patterns arrive as bound parameters (no string interpolation into SQL).
Diff · 6 files
diff --git a/threadide/lib/data.ts b/threadide/lib/data.ts
--- a/threadide/lib/data.ts
+++ b/threadide/lib/data.ts
@@ -167,10 +167,34 @@ export async function removeRepo(id: string) {
// ---------- threads ----------
-/** Threads site-wide, or in one workspace. Readable by any signed-in user. */
-export async function listThreads(workspaceId?: string) {
+/** Keyword query → whitespace-separated terms, trimmed and capped so a pasted paragraph can't blow up the SQL. */
+export function searchTerms(q: string | undefined | null): string[] {
+ if (!q) return [];
+ return q
+ .split(/\s+/)
+ .map((t) => t.trim().slice(0, 60))
+ .filter(Boolean)
+ .slice(0, 8);
+}
+
+/** Escape LIKE metacharacters so a literal "100%" or "snake_case" matches itself (Postgres default escape is backslash). */
+function likePattern(term: string) {
+ return `%${term.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
+}
+
+/**
+ * Threads site-wide, or in one workspace. Readable by any signed-in user.
+ * `q` is a plain keyword search: every term must appear (case-insensitive substring) in the thread
+ * title or in the body of one of its posts. Substring ILIKE, not full-text — predictable for
+ * identifiers like `requireMember` and fine at our scale (no extension or extra index needed).
+ */
+export async function listThreads(workspaceId?: string, q?: string) {
+ const termFilters = searchTerms(q).map((term) => {
+ const pattern = likePattern(term);
+ return sql`(${threads.title} ilike ${pattern} or exists (select 1 from posts p where p.thread_id = ${threads.id} and p.body ilike ${pattern}))`;
+ });
return db.query.threads.findMany({
- where: workspaceId ? eq(threads.workspaceId, workspaceId) : undefined,
+ where: and(workspaceId ? eq(threads.workspaceId, workspaceId) : undefined, ...termFilters),
with: { creator: true },
diff --git a/threadide/app/api/threads/route.ts b/threadide/app/api/threads/route.ts
--- a/threadide/app/api/threads/route.ts
+++ b/threadide/app/api/threads/route.ts
@@ -8,8 +8,11 @@ export const maxDuration = 300;
export const GET = guarded(async (req: Request) => {
await requireUserApi();
- const workspaceId = new URL(req.url).searchParams.get("workspaceId") ?? undefined;
- return NextResponse.json(await listThreads(workspaceId));
+ const params = new URL(req.url).searchParams;
+ const workspaceId = params.get("workspaceId") ?? undefined;
+ // q = keyword search over titles + post bodies; see listThreads.
+ const q = params.get("q") ?? undefined;
+ return NextResponse.json(await listThreads(workspaceId, q));
});
diff --git a/threadide/components/thread-search.tsx b/threadide/components/thread-search.tsx
new file mode 100644
--- /dev/null
+++ b/threadide/components/thread-search.tsx
@@ -0,0 +1,13 @@
+/**
+ * Keyword search box for thread lists. A plain GET form so the query lives in the URL (?q=…):
+ * shareable, back-button friendly, and no client JS. Enter submits (single text field ⇒ implicit
+ * submission); "clear" links back to the unfiltered list. Matching happens in listThreads (lib/data.ts).
+ */
+export function ThreadSearch({ q, action }: { q: string; action: string }) {
+ return (
+ <form className="thread-search" action={action} method="get" role="search">
+ <input type="search" name="q" defaultValue={q} placeholder="Search threads…" aria-label="Search threads" autoComplete="off" />
+ {q && <a href={action}>clear</a>}
+ </form>
+ );
+}
diff --git a/threadide/app/page.tsx b/threadide/app/page.tsx
--- a/threadide/app/page.tsx
+++ b/threadide/app/page.tsx
@@ -2,13 +2,15 @@ import Link from "next/link";
import { ThreadList } from "@/components/thread-list";
+import { ThreadSearch } from "@/components/thread-search";
-export default async function Home() {
+export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
const user = await requireUser("/");
+ const q = (await searchParams).q?.trim() ?? "";
- const [threads, workspaces] = await Promise.all([listThreads(), listWorkspaces(user.id)]);
+ const [threads, workspaces] = await Promise.all([listThreads(undefined, q), listWorkspaces(user.id)]);
@@ -17,6 +19,7 @@
<div className="page-head">
<h2 className="page-title">Threads</h2>
+ <ThreadSearch q={q} action="/" />
<Link href="/threads/new">New thread</Link>
</div>
@@ -25,7 +28,7 @@
- <ThreadList threads={threads} workspaces={wsById} empty="Nothing yet. Start the first thread." />
+ <ThreadList threads={threads} workspaces={wsById} empty={q ? `No threads match “${q}”.` : "Nothing yet. Start the first thread."} />
diff --git a/threadide/app/workspaces/[id]/page.tsx b/threadide/app/workspaces/[id]/page.tsx
--- a/threadide/app/workspaces/[id]/page.tsx
+++ b/threadide/app/workspaces/[id]/page.tsx
@@ -7,11 +7,13 @@
import { ThreadList } from "@/components/thread-list";
+import { ThreadSearch } from "@/components/thread-search";
-export default async function WorkspacePage({ params }: { params: Promise<{ id: string }> }) {
+export default async function WorkspacePage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ q?: string }> }) {
const { id } = await params;
+ const q = (await searchParams).q?.trim() ?? "";
@@ -19,7 +21,7 @@
- const [memory, threads, invite] = await Promise.all([listMemory(ws.id), listThreads(ws.id), isMember ? activeInvite(ws.id) : null]);
+ const [memory, threads, invite] = await Promise.all([listMemory(ws.id), listThreads(ws.id, q), isMember ? activeInvite(ws.id) : null]);
@@ -108,8 +110,11 @@
- <h3>Threads</h3>
- <ThreadList threads={threads} empty="None yet." />
+ <div className="page-head" id="threads">
+ <h3 style={{ margin: 0 }}>Threads</h3>
+ <ThreadSearch q={q} action={`/workspaces/${ws.id}#threads`} />
+ </div>
+ <ThreadList threads={threads} empty={q ? `No threads match “${q}”.` : "None yet."} />
diff --git a/threadide/app/globals.css b/threadide/app/globals.css
--- a/threadide/app/globals.css
+++ b/threadide/app/globals.css
@@ -61,6 +61,17 @@ h3 { font-size: 20px; }
.page-title { margin: 0; }
+/* Keyword search box (components/thread-search.tsx). Plain GET form: ?q= in the URL keeps results shareable. */
+.thread-search { display: flex; align-items: center; gap: 8px; flex: 0 1 300px; margin-left: auto; min-width: 0; }
+.thread-search input { flex: 1 1 auto; min-width: 0; padding: 6px 10px; border-radius: 3px; border: 1px solid var(--border-strong); background: var(--surface); color: var(--text); font: inherit; font-size: 14px; -webkit-appearance: none; appearance: none; }
+.thread-search input::-webkit-search-cancel-button { -webkit-appearance: none; appearance: none; }
+.thread-search input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
+.thread-search a { font-size: 13px; color: var(--muted); white-space: nowrap; }
+@media (max-width: 560px) {
+ /* Title + CTA stay on the first row; the search box drops to a full-width row underneath. */
+ .page-head { flex-wrap: wrap; }
+ .thread-search { order: 1; flex: 1 1 100%; margin-left: 0; }
+}Can we put the clear button in the search input?
Yes — moving the "clear" link inside the search field as an × button pinned to the right edge (like the native search-cancel button, but styled to our theme and working without JS).
components/thread-search.tsx: wrap the input in a.thread-search-fieldbox; render<a href={action} aria-label="Clear search">inside it, positioned absolute on the right, only whenqis set.- CSS: the input gets right padding so text doesn't run under the ×; the × is drawn in CSS (two rotated bars — per our gotcha, no Unicode glyphs). Colour muted → text on hover.
- Screenshot via the static mockup.
threadide@73c2ea9Done — the clear control now lives inside the search field (commit 73c2ea9 on thread/1555249e, pushed; still no PR).
What changed
components/thread-search.tsx: the input is wrapped in.thread-search-field; when a query is active, an<a class="thread-search-clear" href={action} aria-label="Clear search">renders inside that wrapper, overlaid on the input's right edge (32px wide hit area, full input height). It's still a plain link back to the unfiltered URL, so it works without any client JS.app/globals.css:.has-querygives the inputpadding-right: 32pxso long queries never run under the ×. The × is two rotated 2px bars drawn with::before/::after(same technique as the header ☰), muted grey → text colour on hover/focus. The native WebKit cancel button stays suppressed so there's exactly one ×.
Screenshots attached (static mockup on the real globals.css, 900px and Pixel 5). The sub-line wrapping in the phone thread rows is a mockup artefact — I didn't reproduce the full thread-list.tsx markup — not a real change.
tsc --noEmit clean.
I wish the thread would live query instead of requiring me to press enter with refreshed the page
Making the search live (filter as you type, no Enter, no page reload):
- Turn the thread list + search box into one client component (
components/thread-browser.tsx) that takes the server-rendered initial threads. Typing debounces ~200ms, fetchesGET /api/threads?q=…[&workspaceId=…](already exists), and swaps the list in place. Stale responses are discarded so fast typing can't show wrong results. - URL stays in sync via
history.replaceState(?q=…)so results are still shareable/back-button friendly; first paint is still server-rendered from?q, so nothing flashes and it degrades to the current Enter-to-submit form without JS. - The × clears instantly (client-side) instead of navigating. A subtle "searching…" cue while a request is in flight.
/api/threadsneeds to return the same shape the list renders (replyCount, creator) — will check that.
threadide@864d514Search is now live — filters as you type, no Enter, no reload. Commit 864d514 on thread/1555249e, pushed (no PR opened; say so if you want one).
How it works
components/thread-browser.tsx(client) replacesthread-search.tsxand now owns both the search box and the thread list on the home page and the workspace page. Each keystroke is debounced 200ms, thenGET /api/threads?q=…(scoped withworkspaceIdon the workspace page) and the list swaps in place. Responses carry a sequence number so a slow earlier request can never overwrite a newer one; in-flight requests are aborted.- The URL is mirrored with
history.replaceState(?q=…), so a filtered view is still shareable and survives a reload. First paint is still server-rendered from?q, so nothing flashes on load, and the markup is still a GET form — without JS it degrades to exactly the old Enter-to-submit behaviour (× is still a link). - Enter with JS just flushes the debounce. The × clears instantly and refocuses the input. While a request is in flight the field border turns amber and the list dims slightly (
.is-loading); the previous results stay visible until the new ones land, so nothing jumps. - If the fetch fails you get Search failed. retry instead of a stale list.
Side effects worth knowing
GET /api/threadsnow returns only the list shape (id, title, status, workspaceId, updatedAt, replyCount, creator{login,image}) instead of full DB rows — it was previously leakingusers.emailthroughcreator. If anything else consumed the full row from that endpoint it would need updating; I found no callers in the repo.ThreadList'sworkspacesprop is a plain object instead of aMap(Maps can't cross the server → client boundary).
Verified: tsc --noEmit clean; next build compiles (stops only at page-data collection for lack of DATABASE_URL in the sandbox). No screenshot this time — the UI is visually identical to the last one apart from the transient loading dim, which needs the real DB behind it.



