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
37 changes: 36 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import { GraphCanvas } from './components/GraphCanvas'
import { Inspector } from './components/Inspector'
import { SearchResultsList } from './components/SearchResultsList'
import { SearchBar } from './components/SearchBar'
import { SearchBar, type RecentSearch } from './components/SearchBar'
import { TokenPrompt } from './components/TokenPrompt'
import { StatsBar } from './components/StatsBar'
import { Breadcrumbs } from './components/Breadcrumbs'
Expand Down Expand Up @@ -326,7 +326,7 @@
if (recording.isRecording) {
recording.recordFrame(state, trackingInfo.hasLiDAR)
}
}, [recording.isRecording, recording.recordFrame, trackingInfo.hasLiDAR])

Check warning on line 329 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'recording'. Either include it or remove the dependency array

const { lock: handLock } = useHandLockAndGrab(gestureState, gestureControlEnabled)

Expand All @@ -348,6 +348,37 @@
// for "search only sees ~2k of ~120k". Disabled until the term is non-empty.
const recall = useRecall(searchTerm, data?.meta?.type_colors)

// Search type refinement (the pills in the results sidebar). Owned here so
// the graph spotlight can follow it: narrowing the list narrows the scene.
// Reset when the term changes — a stale refinement must never silently
// filter a new query.
const [searchTypeFilter, setSearchTypeFilter] = useState<Set<string>>(new Set())
useEffect(() => {
setSearchTypeFilter((prev) => (prev.size > 0 ? new Set<string>() : prev))
}, [searchTerm])

// Recent searches: a query is "real" once it has results AND survives a
// 2.5s dwell (typing intermediates like "groo" → "groover cur" cancel the
// timer, so prefixes never pollute the list). Last 5, most recent first.
const [recentSearches, setRecentSearches] = usePersistentState<RecentSearch[]>(
'automem_recent_searches',
[]
)
useEffect(() => {
const term = searchTerm.trim()
if (!term || !recall.data) return
const { count, capped } = recall.data
// A zero-result query isn't worth offering as a shortcut.
if (count === 0) return
const timer = window.setTimeout(() => {
setRecentSearches((prev) => {
const rest = prev.filter((r) => r.term.toLowerCase() !== term.toLowerCase())
return [{ term, count, capped }, ...rest].slice(0, 5)
})
}, 2500)
return () => window.clearTimeout(timer)
}, [searchTerm, recall.data, setRecentSearches])

// Stable data references. Once the snapshot has seeded the expandable graph,
// read from it (so expansions are visible); fall back to the raw snapshot for
// the one render between data arriving and the reset effect firing (identical
Expand Down Expand Up @@ -513,7 +544,7 @@
}
prevTimeTravelActive.current = timeTravel.isActive
}
}, [timeTravel.isActive, sound.playTimeTravel])

Check warning on line 547 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useEffect has a missing dependency: 'sound'. Either include it or remove the dependency array

// Get source and target nodes for pathfinding overlay
const pathSourceNode = useMemo(() => {
Expand Down Expand Up @@ -622,7 +653,7 @@
breadcrumbPush(node)
}
setSelectedNode(node)
}, [pathfinding.isSelectingTarget, pathfinding.completePathSelection, sound.playPathFound, sound.playSelect, breadcrumbPush])

Check warning on line 656 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has missing dependencies: 'pathfinding' and 'sound'. Either include them or remove the dependency array

const handleInspectorNavigate = useCallback((node: GraphNode | null) => {
if (!node) return
Expand Down Expand Up @@ -749,7 +780,7 @@
sound.playHover()
}
setHoveredNode(node)
}, [sound.playHover])

Check warning on line 783 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'sound'. Either include it or remove the dependency array

const handleSearch = useCallback((term: string) => {
// Play search sound on typing (only if term changed and is not empty)
Expand All @@ -760,7 +791,7 @@
setSelectedNode(null)
}
setSearchTerm(term)
}, [sound.playSearch])

Check warning on line 794 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'sound'. Either include it or remove the dependency array

// Inspector tag click: add tag filter + close inspector + reheat
const { selectTag } = tagCloud
Expand Down Expand Up @@ -819,7 +850,7 @@
if (selectedNode) {
pathfinding.startPathSelection(selectedNode.id)
}
}, [selectedNode, pathfinding.startPathSelection])

Check warning on line 853 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'pathfinding'. Either include it or remove the dependency array

const { shortcuts } = useKeyboardNavigation({
nodes: nodes as any,
Expand Down Expand Up @@ -859,15 +890,15 @@

const handleBreadcrumbBack = useCallback(() => {
breadcrumbs.goBack(nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.goBack, breadcrumbNavigate])

Check warning on line 893 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

const handleBreadcrumbForward = useCallback(() => {
breadcrumbs.goForward(nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.goForward, breadcrumbNavigate])

Check warning on line 897 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

const handleBreadcrumbJumpTo = useCallback((index: number) => {
breadcrumbs.jumpTo(index, nodesRef.current, breadcrumbNavigate)
}, [breadcrumbs.jumpTo, breadcrumbNavigate])

Check warning on line 901 in src/App.tsx

View workflow job for this annotation

GitHub Actions / lint-build

React Hook useCallback has a missing dependency: 'breadcrumbs'. Either include it or remove the dependency array

// Breadcrumb keyboard shortcuts: Cmd+[ back, Cmd+] forward
useEffect(() => {
Expand Down Expand Up @@ -935,6 +966,7 @@
searchResultCount={recall.data?.count}
searchResultCapped={recall.data?.capped}
searchLoading={recall.isLoading}
recentSearches={recentSearches}
/>

<StatsBar
Expand Down Expand Up @@ -1210,6 +1242,7 @@
expansionAnchors={graph.expansionAnchors}
newNodeIds={graph.newNodeIds}
frontierCount={frontierCount}
searchTypeFilter={searchTypeFilter}
onReheatReady={setReheatFn}
onResetViewReady={setResetViewFn}
onNavigateForBookmarks={(fn) => { navigateForBookmarksRef.current = fn }}
Expand Down Expand Up @@ -1324,6 +1357,8 @@
loadingId={loadingResultId}
inGraphIds={visibleNodeIds}
searchTerm={searchTerm}
typeFilter={searchTypeFilter}
onTypeFilterChange={setSearchTypeFilter}
onSelect={handleRemoteResultSelect}
/>
) : (
Expand Down
49 changes: 36 additions & 13 deletions src/components/GraphCanvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ interface GraphCanvasProps {
// Unloaded-neighbor count for the selected node (the expansion frontier).
// > 0 renders a dashed "+N more" ring: this node has more world to pull in.
frontierCount?: number;
// Type refinement from the search sidebar's pills — the graph spotlight
// follows it so narrowing the list narrows the scene too.
searchTypeFilter?: Set<string>;
onReheatReady?: (reheat: () => void) => void;
onResetViewReady?: (resetView: () => void) => void;
// Expose an imperative camera-navigation handle to the parent (used by the
Expand Down Expand Up @@ -189,6 +192,7 @@ export function GraphCanvas({
expansionAnchors,
newNodeIds,
frontierCount = 0,
searchTypeFilter,
onReheatReady,
onResetViewReady,
onNavigateForBookmarks,
Expand Down Expand Up @@ -326,6 +330,7 @@ export function GraphCanvas({
expansionAnchors={expansionAnchors}
newNodeIds={newNodeIds}
frontierCount={frontierCount}
searchTypeFilter={searchTypeFilter}
onReheatReady={onReheatReady}
onResetViewReady={onResetViewReady}
onCameraStateChange={setCameraState}
Expand Down Expand Up @@ -414,6 +419,7 @@ function Scene({
expansionAnchors,
newNodeIds,
frontierCount = 0,
searchTypeFilter,
onReheatReady,
onResetViewReady,
onCameraStateChange,
Expand Down Expand Up @@ -989,10 +995,15 @@ function Scene({
const searchLower = searchTerm.trim().toLowerCase();
const matchingIds = useMemo(() => {
if (!searchLower) return new Set<string>();
const typeGate = searchTypeFilter && searchTypeFilter.size > 0 ? searchTypeFilter : null;
return new Set(
layoutNodes.filter((n) => matchesSearch(n, searchLower)).map((n) => n.id),
layoutNodes
.filter(
(n) => matchesSearch(n, searchLower) && (!typeGate || typeGate.has(n.type)),
)
.map((n) => n.id),
);
}, [layoutNodes, searchLower]);
}, [layoutNodes, searchLower, searchTypeFilter]);

// Spotlight is active only in the "results view": a search is running, it has
// matches, and NO node is selected. When a node is selected we hand the scene
Expand Down Expand Up @@ -1372,7 +1383,11 @@ function Scene({
{/* Cluster boundaries (rendered behind edges) */}
<ClusterBoundaries
clusters={displayClusters}
visible={clusterConfig.showBoundaries}
// The nebulas are ADDITIVE point clouds — thousands of stacked dots
// re-accumulate to full glow at any nonzero opacity, drowning the
// search spotlight. Hide them while results own the scene (the
// component animates its own fade via targetOpacity).
visible={clusterConfig.showBoundaries && !spotlightActive}
opacity={0.2}
hoveredClusterId={hoveredClusterId}
/>
Expand Down Expand Up @@ -1408,7 +1423,8 @@ function Scene({
<EdgeParticles
edges={edges}
nodes={layoutNodes}
enabled={!performanceMode}
// Ambient flow is noise while the search spotlight is on.
enabled={!performanceMode && !spotlightActive}
particlesPerEdge={2}
animatedPositions={animPositions}
nodeIdToIdx={nodeIdToIdx}
Expand Down Expand Up @@ -1639,6 +1655,9 @@ function BatchedEdges({
const strength = typeof edge.strength === "number" ? edge.strength : 0.5;
const strengthBoost = 0.45 + 0.9 * Math.max(0, Math.min(1, strength));

const spotlightOn =
!!searchTerm && !!searchMatchingIds && searchMatchingIds.size > 0;

let alpha = style.opacity * linkOpacity * focusOpacity * strengthBoost;
if (isInPath) {
alpha = 1.0;
Expand All @@ -1648,6 +1667,10 @@ function BatchedEdges({
alpha = 0.9;
} else if (isSearchRelevant) {
alpha = Math.min(1, alpha * 2.0);
} else if (spotlightOn) {
// Results view: the ~7k-edge web recedes with the non-matching nodes
// so the spotlighted matches own the scene.
alpha *= 0.3;
}

const r = color.r * alpha;
Expand Down Expand Up @@ -2076,10 +2099,8 @@ function InstancedNodes({
const tempPosition = useMemo(() => new THREE.Vector3(), []);
const tempQuaternion = useMemo(() => new THREE.Quaternion(), []);
const tempScale = useMemo(() => new THREE.Vector3(), []);
// Reused spotlight colors (allocate once, never per-node/per-frame):
// a neutral slate to desaturate dimmed non-matches, and the cold "accent"
// near-white (--accent) to keep off-focus search matches faintly visible.
const dimGrey = useMemo(() => new THREE.Color("#6b7280"), []);
// Reused off-focus accent (allocate once, never per-node/per-frame): the
// cold near-white (--accent) keeps off-focus search matches faintly visible.
const accentColor = useMemo(() => new THREE.Color("#e8ecf4"), []);

// Update instance matrices and colors each frame
Expand Down Expand Up @@ -2243,10 +2264,12 @@ function InstancedNodes({

if (isDimmed && !isInPath) {
if (spotlightActive && !matchingIds.has(node.id)) {
// Results view: push non-matches well back — desaturate toward neutral
// slate, then darken hard so the matched nodes own the scene.
tempColor.lerp(dimGrey, 0.5);
tempColor.multiplyScalar(0.2);
// Results view: non-matches recede INTO the near-black void — keep
// their hue (no gray lerp; that read as mud) and pull brightness way
// down. Against this backdrop that's visually equivalent to lowering
// opacity, without the depth-write holes true per-instance alpha
// punches in the edge web behind translucent spheres.
tempColor.multiplyScalar(0.15);
} else {
// Path / tag-filter dimming keeps its softer treatment.
tempColor.multiplyScalar(0.5);
Expand All @@ -2260,7 +2283,7 @@ function InstancedNodes({
// Brighten selected/hovered/path/match nodes. Spotlight matches get an
// extra push so they cross the bloom threshold and visibly glow.
let brightenFactor = isInPath ? 1.3 : 1.2;
if (spotlightActive && isSearchMatch) brightenFactor = 1.6;
if (spotlightActive && isSearchMatch) brightenFactor = 2.0;
tempColor.multiplyScalar(brightenFactor);
} else {
// Importance halo: brighter cores for important memories so bloom blooms
Expand Down
123 changes: 121 additions & 2 deletions src/components/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { useState, useEffect, useCallback, useRef, useMemo } from 'react'
import { Search, X } from 'lucide-react'
import { createPortal } from 'react-dom'
import { Search, X, History } from 'lucide-react'
import type { FilterChip } from '@/hooks/useFilterChips'

export interface RecentSearch {
term: string
/** Whole-store match count the term last returned. */
count: number
/** The count hit the server cap when recorded (rendered as "N+"). */
capped?: boolean
}

interface SearchBarProps {
value: string
onChange: (value: string) => void
Expand All @@ -19,6 +28,8 @@ interface SearchBarProps {
searchResultCapped?: boolean
/** Recall request in flight. */
searchLoading?: boolean
/** Recently settled searches, most recent first (offered on focus when empty). */
recentSearches?: RecentSearch[]
}

export function SearchBar({
Expand All @@ -35,6 +46,7 @@ export function SearchBar({
searchResultCount,
searchResultCapped = false,
searchLoading = false,
recentSearches = [],
}: SearchBarProps) {
const [localValue, setLocalValue] = useState(value)
const inputRef = useRef<HTMLInputElement>(null)
Expand All @@ -43,6 +55,39 @@ export function SearchBar({
return navigator.platform.toLowerCase().includes('mac') ? 'Cmd' : 'Ctrl'
}, [])

// Recent-searches dropdown. The header clips vertical overflow (it scrolls
// chips horizontally), so the panel renders through a portal at a fixed
// position measured from the input wrapper.
const [focused, setFocused] = useState(false)
const wrapperRef = useRef<HTMLDivElement>(null)
const [dropdownRect, setDropdownRect] = useState<{
left: number
top: number
width: number
} | null>(null)
const handleFocus = useCallback(() => {
setFocused(true)
const r = wrapperRef.current?.getBoundingClientRect()
if (r) setDropdownRect({ left: r.left, top: r.bottom + 6, width: r.width })
}, [])
const showRecent = focused && !localValue && recentSearches.length > 0 && !!dropdownRect

// Keyboard navigation for the dropdown happens ON THE INPUT (combobox
// pattern): focus never leaves it, so blur can't race the selection.
const [activeRecent, setActiveRecent] = useState(-1)
useEffect(() => {
if (!showRecent) setActiveRecent(-1)
}, [showRecent])

const pickRecent = useCallback(
(term: string) => {
setLocalValue(term)
onChange(term)
setFocused(false)
},
[onChange]
)

const hasChips = chips.length > 0
// During a text search the meaningful number is the whole-store match count
// (from /recall), not "matching-local / loaded" — that would read as exhaustive.
Expand Down Expand Up @@ -155,7 +200,7 @@ export function SearchBar({
)}

{/* Search input */}
<div className="relative flex-1 min-w-[140px]">
<div ref={wrapperRef} className="relative flex-1 min-w-[140px]">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Search className="w-4 h-4 text-ink-3" />
</div>
Expand All @@ -164,7 +209,36 @@ export function SearchBar({
ref={inputRef}
value={localValue}
onChange={(e) => setLocalValue(e.target.value)}
onFocus={handleFocus}
onBlur={() => setFocused(false)}
role="combobox"
aria-expanded={showRecent}
aria-controls="recent-searches-listbox"
aria-autocomplete="list"
onKeyDown={(event) => {
if (showRecent) {
const n = recentSearches.length
if (event.key === 'ArrowDown') {
event.preventDefault()
setActiveRecent((i) => (i + 1) % n)
return
}
if (event.key === 'ArrowUp') {
event.preventDefault()
setActiveRecent((i) => (i - 1 + n) % n)
return
}
if (event.key === 'Enter' && activeRecent >= 0 && activeRecent < n) {
event.preventDefault()
pickRecent(recentSearches[activeRecent].term)
return
}
if (event.key === 'Escape') {
event.preventDefault()
setFocused(false)
return
}
}
if (event.key === 'Escape' && localValue) {
event.preventDefault()
handleClear()
Expand Down Expand Up @@ -222,6 +296,51 @@ export function SearchBar({
{totalCount.toLocaleString()}
</span>
)}

{/* Recent searches — yesterday's question is one click away. Portaled:
the header's overflow clipping would swallow an in-flow dropdown. */}
{showRecent &&
createPortal(
<div
id="recent-searches-listbox"
role="listbox"
aria-label="Recent searches"
className="fixed z-[100] rounded-lg border border-hairline bg-surface-1 shadow-elev-2 overflow-hidden"
style={{
left: dropdownRect.left,
top: dropdownRect.top,
width: dropdownRect.width,
}}
>
<div className="px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-ink-4">
Recent searches
</div>
{recentSearches.map((recent, i) => (
<button
key={recent.term}
type="button"
role="option"
aria-selected={i === activeRecent}
// mousedown (not click) so selection beats the input's blur.
onMouseDown={(e) => {
e.preventDefault()
pickRecent(recent.term)
}}
className={`w-full flex items-center gap-2 px-3 py-1.5 text-sm text-ink-2 text-left transition-colors ${
i === activeRecent ? 'bg-white/15' : 'hover:bg-white/10'
}`}
>
<History className="w-3.5 h-3.5 text-ink-4 flex-shrink-0" />
<span className="truncate flex-1">{recent.term}</span>
<span className="font-mono text-[10px] text-ink-4">
{recent.count.toLocaleString()}
{recent.capped ? '+' : ''} in store
</span>
</button>
))}
</div>,
document.body
)}
</div>
)
}
Loading
Loading