fix: repair memory-list project filter + add type-ahead project dropdown #7

Merged
jknapp merged 1 commits from fix/memory-list-project-filter into main 2026-07-01 23:22:13 +00:00
2 changed files with 184 additions and 18 deletions
Showing only changes of commit 8d51fbff7a - Show all commits
@@ -0,0 +1,151 @@
"use client";
import { useEffect, useId, useRef, useState } from "react";
const field =
"block w-full rounded-md bg-surface-1 border border-border " +
"text-fg placeholder:text-fg-subtle " +
"focus:border-accent-400 focus:outline-none " +
"disabled:opacity-50 transition-colors h-9 px-3 text-sm";
/**
* Type-ahead project filter. A text input whose value submits as `name`
* (default "project") via the enclosing GET form, plus a dropdown of the
* projects the user can read that narrows as they type. Selecting a
* suggestion fills the box and submits the form so the filter applies
* immediately; free text is still allowed (the input value is what
* submits), so an arbitrary key keeps working even if it isn't listed.
*/
export function ProjectCombobox({
name = "project",
defaultValue = "",
options,
className = "",
}: {
name?: string;
defaultValue?: string;
options: string[];
className?: string;
}) {
const [value, setValue] = useState(defaultValue);
const [open, setOpen] = useState(false);
const [active, setActive] = useState(0);
const rootRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const listId = useId();
// Case-insensitive substring match. An empty box shows the full list so
// the control doubles as a "browse my projects" dropdown.
const q = value.trim().toLowerCase();
const matches = q
? options.filter((o) => o.toLowerCase().includes(q))
: options;
// Close when focus/click leaves the widget.
useEffect(() => {
if (!open) return;
function onPointerDown(e: PointerEvent) {
if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
}
document.addEventListener("pointerdown", onPointerDown);
return () => document.removeEventListener("pointerdown", onPointerDown);
}, [open]);
function commit(next: string) {
setValue(next);
setOpen(false);
// Write the DOM value synchronously before submitting: setValue only
// schedules a re-render (React batches it), so the input's serialized
// value would still be the pre-selection text when requestSubmit reads
// it. The upcoming render sets the same value, so there's no flicker.
if (inputRef.current) inputRef.current.value = next;
// requestSubmit fires a real submit (unlike form.submit()).
inputRef.current?.form?.requestSubmit();
}
function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown") {
e.preventDefault();
if (!open) {
setOpen(true);
setActive(0);
} else {
setActive((i) => Math.min(i + 1, matches.length - 1));
}
} else if (e.key === "ArrowUp") {
e.preventDefault();
setActive((i) => Math.max(i - 1, 0));
} else if (e.key === "Enter") {
// Only intercept Enter to pick a highlighted suggestion; otherwise
// let it fall through and submit the form with the typed value.
if (open && matches[active]) {
e.preventDefault();
commit(matches[active]);
}
} else if (e.key === "Escape") {
if (open) {
e.preventDefault();
setOpen(false);
}
}
}
const showList = open && matches.length > 0;
return (
<div ref={rootRef} className={`relative ${className}`}>
<input
ref={inputRef}
type="text"
name={name}
value={value}
placeholder="Project key…"
autoComplete="off"
spellCheck={false}
role="combobox"
aria-expanded={showList}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={
showList ? `${listId}-opt-${active}` : undefined
}
className={field}
onChange={(e) => {
setValue(e.target.value);
setOpen(true);
setActive(0);
}}
onFocus={() => setOpen(true)}
onKeyDown={onKeyDown}
/>
{showList ? (
<ul
id={listId}
role="listbox"
className="absolute z-20 mt-1 max-h-60 w-full overflow-auto rounded-md border border-border bg-surface-1 py-1 shadow-lg"
>
{matches.map((opt, i) => (
<li
key={opt}
id={`${listId}-opt-${i}`}
role="option"
aria-selected={i === active}
className={`cursor-pointer px-3 py-1.5 font-mono text-sm text-fg ${
i === active ? "bg-surface-2" : ""
}`}
// pointerdown (not click) so the choice registers before the
// input's blur/outside-pointerdown handler closes the list.
onPointerDown={(e) => {
e.preventDefault();
commit(opt);
}}
onMouseEnter={() => setActive(i)}
>
{opt}
</li>
))}
</ul>
) : null}
</div>
);
}
+33 -18
View File
@@ -1,10 +1,15 @@
import Link from "next/link"; import Link from "next/link";
import { and, desc, eq, isNull, inArray, or, sql } from "drizzle-orm"; import { and, desc, eq, isNull, inArray, or } from "drizzle-orm";
import { auth } from "@/auth"; import { auth } from "@/auth";
import { db } from "@/lib/db/client"; import { db } from "@/lib/db/client";
import { memories, projects, projectShares } from "@/lib/db/schema"; import { memories, projects, projectShares } from "@/lib/db/schema";
import { searchMemories } from "@/lib/memories"; import { searchMemories } from "@/lib/memories";
import { getUserGroupNames, readableProjectIds } from "@/lib/access"; import {
getAccessibleProjects,
getUserGroupNames,
type AccessibleProject,
} from "@/lib/access";
import { ProjectCombobox } from "./_project-combobox";
import { Container, PageHeader } from "@/app/_components/ui/container"; import { Container, PageHeader } from "@/app/_components/ui/container";
import { Card, CardBody } from "@/app/_components/ui/card"; import { Card, CardBody } from "@/app/_components/ui/card";
import { Badge } from "@/app/_components/ui/badge"; import { Badge } from "@/app/_components/ui/badge";
@@ -50,12 +55,12 @@ async function fetchMemoriesByIds(
async function listRecent( async function listRecent(
userId: string, userId: string,
groupNames: string[], accessible: AccessibleProject[],
scope?: Scope, scope?: Scope,
project?: string, project?: string,
): Promise<MemoryRow[]> { ): Promise<MemoryRow[]> {
// Visibility: own rows OR rows in an accessible project. // Visibility: own rows OR rows in an accessible project.
const accessibleIds = await readableProjectIds(userId, groupNames); const accessibleIds = accessible.map((p) => p.projectId);
const visibility = const visibility =
accessibleIds.length > 0 accessibleIds.length > 0
? or(eq(memories.userId, userId), inArray(memories.projectId, accessibleIds)) ? or(eq(memories.userId, userId), inArray(memories.projectId, accessibleIds))
@@ -63,17 +68,18 @@ async function listRecent(
const filters = [visibility!, isNull(memories.deletedAt)]; const filters = [visibility!, isNull(memories.deletedAt)];
if (scope) filters.push(eq(memories.scope, scope)); if (scope) filters.push(eq(memories.scope, scope));
if (project) { if (project) {
// Project filter — match the project key against any project the // Project filter — resolve the typed key against the projects the
// user can read (owned or shared). When the key matches none of // user can read (owned or shared), owned winning on a key collision
// those, return empty. // to match project.identify / the search path. Filtering by the
filters.push( // resolved id keeps the WHERE clause a plain equality — no raw-SQL
sql`${memories.projectId} IN ( // array binding (the source of the earlier memory.list crash). When
SELECT id FROM ${projects} // the key matches no accessible project, return empty.
WHERE ${projects.key} = ${project} const matches = accessible.filter((p) => p.projectKey === project);
AND (${projects.userId} = ${userId} const resolvedId =
OR ${projects.id} = ANY(${accessibleIds}::uuid[])) matches.find((p) => p.access === "owner")?.projectId ??
)`, matches[0]?.projectId;
); if (!resolvedId) return [];
filters.push(eq(memories.projectId, resolvedId));
} }
const rows = await db const rows = await db
.select({ .select({
@@ -120,6 +126,15 @@ export default async function MemoriesPage({
const scope = params.scope === "user" || params.scope === "project" ? params.scope : undefined; const scope = params.scope === "user" || params.scope === "project" ? params.scope : undefined;
const project = params.project?.trim() || undefined; const project = params.project?.trim() || undefined;
// Projects the user can read (owned shared). Reused both to build the
// list-path WHERE clause and to populate the project filter's type-ahead
// suggestions. Keys are deduped (a key can appear once per owned/shared
// project) and sorted for a stable dropdown order.
const accessible = await getAccessibleProjects(userId, groupNames);
const projectKeys = [...new Set(accessible.map((p) => p.projectKey))].sort(
(a, b) => a.localeCompare(b),
);
let rows: MemoryRow[] = []; let rows: MemoryRow[] = [];
let debug: { vec: number; fts: number; tag: number } | null = null; let debug: { vec: number; fts: number; tag: number } | null = null;
@@ -138,7 +153,7 @@ export default async function MemoriesPage({
}); });
debug = result.debug; debug = result.debug;
} else { } else {
rows = await listRecent(userId, groupNames, scope, project); rows = await listRecent(userId, accessible, scope, project);
} }
// Annotate which rows belong to projects that have any active share. // Annotate which rows belong to projects that have any active share.
@@ -182,10 +197,10 @@ export default async function MemoriesPage({
className="flex-1 min-w-[200px]" className="flex-1 min-w-[200px]"
/> />
<FilterSelect name="scope" value={scope} options={["", "project", "user"]} placeholder="Any scope" /> <FilterSelect name="scope" value={scope} options={["", "project", "user"]} placeholder="Any scope" />
<Input <ProjectCombobox
name="project" name="project"
placeholder="Project key…"
defaultValue={project ?? ""} defaultValue={project ?? ""}
options={projectKeys}
className="w-44" className="w-44"
/> />
<Button type="submit" variant="secondary">Apply</Button> <Button type="submit" variant="secondary">Apply</Button>