Skip to content
Merged
255 changes: 225 additions & 30 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
import { useGraphSnapshot, useRecall } from './hooks/useGraphData'
import { useExpandableGraph } from './hooks/useExpandableGraph'
import { normalizeNode } from './lib/normalizeNode'
import { fetchGraphNeighbors, getSnapshotCap } from './api/client'
import {
fetchGraphNeighbors,
getSnapshotCap,
getConnectionInfo,
isAuthErrorMessage,
} from './api/client'
import { useAuth } from './hooks/useAuth'
import { GraphCanvas } from './components/GraphCanvas'
import { Inspector } from './components/Inspector'
Expand All @@ -23,6 +28,7 @@
import { TimelineBar } from './components/TimelineBar'
import { TagCloud } from './components/TagCloud'
import { KeyboardShortcutsHelp } from './components/KeyboardShortcutsHelp'
import { usePersistentState } from './hooks/usePersistentState'
import { useHandLockAndGrab } from './hooks/useHandLockAndGrab'
import { useHandRecording, downloadRecording, listSavedRecordings, loadRecordingFromStorage } from './hooks/useHandRecording'
import { useHandPlayback } from './hooks/useHandPlayback'
Expand Down Expand Up @@ -124,7 +130,7 @@
const EMPTY_EDGES: import('./lib/types').GraphEdge[] = []

export default function App() {
const { setToken, isAuthenticated } = useAuth()
const { setToken, clearAuth, isAuthenticated } = useAuth()
const [selectedNode, setSelectedNode] = useState<GraphNode | null>(null)
const [hoveredNode, setHoveredNode] = useState<GraphNode | null>(null)
const [searchTerm, setSearchTerm] = useState('')
Expand Down Expand Up @@ -243,19 +249,25 @@
})
const [hasSetDefaultImportance, setHasSetDefaultImportance] = useState(false)

// Force configuration state
const [forceConfig, setForceConfig] = useState<ForceConfig>(DEFAULT_FORCE_CONFIG)

// Display configuration state
const [displayConfig, setDisplayConfig] = useState<DisplayConfig>(DEFAULT_DISPLAY_CONFIG)

// Clustering configuration state
const [clusterConfig, setClusterConfig] = useState<ClusterConfig>(DEFAULT_CLUSTER_CONFIG)

// Relationship visibility state
const [relationshipVisibility, setRelationshipVisibility] = useState<RelationshipVisibility>(
DEFAULT_RELATIONSHIP_VISIBILITY
// Tuning configs persist across sessions (localStorage write-through) so the
// workspace looks the same tomorrow morning as it did last night.
const [forceConfig, setForceConfig] = usePersistentState<ForceConfig>(
'automem_settings_forces',
DEFAULT_FORCE_CONFIG
)
const [displayConfig, setDisplayConfig] = usePersistentState<DisplayConfig>(
'automem_settings_display',
DEFAULT_DISPLAY_CONFIG
)
const [clusterConfig, setClusterConfig] = usePersistentState<ClusterConfig>(
'automem_settings_cluster',
DEFAULT_CLUSTER_CONFIG
)
const [relationshipVisibility, setRelationshipVisibility] =
usePersistentState<RelationshipVisibility>(
'automem_settings_relationships',
DEFAULT_RELATIONSHIP_VISIBILITY
)

// Reheat callback - will be set by GraphCanvas
const [reheatFn, setReheatFn] = useState<(() => void) | null>(null)
Expand Down Expand Up @@ -311,7 +323,7 @@
if (recording.isRecording) {
recording.recordFrame(state, trackingInfo.hasLiDAR)
}
}, [recording.isRecording, recording.recordFrame, trackingInfo.hasLiDAR])

Check warning on line 326 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 Down Expand Up @@ -452,6 +464,31 @@
// Sound Effects
const sound = useSoundEffects()

// One-click escape hatch from any persisted-settings tangle. Covers EVERY
// setting the panel exposes — physics, display, clustering, relationship
// visibility, audio, and the tag AND/OR mode — so "Reset all" means all.
// (Filters are view state, not settings, and are deliberately untouched.)
const { setEnabled: setSoundEnabled, setMasterVolume: setSoundVolume } = sound
const { setFilterMode: setTagFilterMode } = tagCloud
const handleResetAllSettings = useCallback(() => {
setForceConfig(DEFAULT_FORCE_CONFIG)
setDisplayConfig(DEFAULT_DISPLAY_CONFIG)
setClusterConfig(DEFAULT_CLUSTER_CONFIG)
setRelationshipVisibility(DEFAULT_RELATIONSHIP_VISIBILITY)
// Audio defaults mirror DEFAULT_SETTINGS in lib/sounds.ts.
setSoundEnabled(false)
setSoundVolume(0.3)
setTagFilterMode('OR')
}, [
setForceConfig,
setDisplayConfig,
setClusterConfig,
setRelationshipVisibility,
setSoundEnabled,
setSoundVolume,
setTagFilterMode,
])

// Pathfinding
const pathfinding = usePathfinding({
nodes: nodes as any,
Expand All @@ -473,7 +510,7 @@
}
prevTimeTravelActive.current = timeTravel.isActive
}
}, [timeTravel.isActive, sound.playTimeTravel])

Check warning on line 513 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 All @@ -497,6 +534,64 @@
}, 1800)
}, [])

// Acknowledge the silent URL-token handshake. A shared /viewer/#token= link
// auto-authenticates with zero feedback — confirm which server answered, once,
// on the first successful load. Standalone (typed-in) auth already had its
// explicit Connect step, so it stays quiet.
const connectionToastShownRef = useRef(false)
useEffect(() => {
if (!data || connectionToastShownRef.current) return
connectionToastShownRef.current = true
const info = getConnectionInfo()
if (info.embedded || info.tokenFromUrl) {
let host = info.serverUrl
try {
host = new URL(info.serverUrl).host
} catch {
// Relative base — keep as-is.
}
showStatus(`Connected to ${host}`)
}
}, [data, showStatus])

// Sign out / re-enter credentials: URL-borne tokens (?token=, #token=) outrank
// localStorage in the auth chain, so clearing storage alone wouldn't sign a
// shared-link session out — strip them from the URL too, then TokenPrompt
// renders naturally via isAuthenticated.
const handleReenterCredentials = useCallback(() => {
const url = new URL(window.location.href)
url.searchParams.delete('token')
if (url.hash) {
const hashParams = new URLSearchParams(url.hash.slice(1))
hashParams.delete('token')
const rest = hashParams.toString()
url.hash = rest ? `#${rest}` : ''
}
window.history.replaceState(null, '', url.toString())
clearAuth()
}, [clearAuth])

// Settings → Connection section. Recomputed when the panel opens (token /
// server state lives in localStorage + URL, both cheap reads).
const connectionInfo = useMemo(() => {
if (!settingsPanelOpen) return undefined
const info = getConnectionInfo()
return {
serverUrl: info.serverUrl,
token: info.token,
tokenFromUrl: info.tokenFromUrl,
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [settingsPanelOpen, isAuthenticated])

// Auth rejections deserve their own story: a bad shared-link token used to
// surface as a generic "Connection Error" + Retry, a dead end that retries
// into the same 401 forever.
const isAuthError = useMemo(
() => !!error && isAuthErrorMessage((error as Error).message ?? ''),
[error]
)

const { push: breadcrumbPush } = breadcrumbs
const handleNodeSelect = useCallback((node: GraphNode | null) => {
// If we're in path selection mode and a node is clicked, complete the path
Expand All @@ -514,7 +609,7 @@
breadcrumbPush(node)
}
setSelectedNode(node)
}, [pathfinding.isSelectingTarget, pathfinding.completePathSelection, sound.playPathFound, sound.playSelect, breadcrumbPush])

Check warning on line 612 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 @@ -587,7 +682,7 @@
sound.playHover()
}
setHoveredNode(node)
}, [sound.playHover])

Check warning on line 685 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 @@ -598,7 +693,7 @@
setSelectedNode(null)
}
setSearchTerm(term)
}, [sound.playSearch])

Check warning on line 696 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 All @@ -612,19 +707,19 @@
// Inspector relationship type toggle
const handleRelationshipTypeClick = useCallback((type: RelationType) => {
setRelationshipVisibility((prev) => ({ ...prev, [type]: !prev[type] }))
}, [])
}, [setRelationshipVisibility])

const handleFilterChange = useCallback((newFilters: Partial<FilterState>) => {
setFilters(prev => ({ ...prev, ...newFilters }))
}, [])

const handleForceConfigChange = useCallback((config: Partial<ForceConfig>) => {
setForceConfig(prev => ({ ...prev, ...config }))
}, [])
}, [setForceConfig])

const handleDisplayConfigChange = useCallback((config: Partial<DisplayConfig>) => {
setDisplayConfig(prev => ({ ...prev, ...config }))
}, [])
}, [setDisplayConfig])

const prevClusterModeRef = useRef<ClusterConfig['mode']>(DEFAULT_CLUSTER_CONFIG.mode)

Expand All @@ -634,30 +729,30 @@
prevClusterModeRef.current = config.mode
showStatus(CLUSTER_MODE_LABELS[config.mode] || `Cluster mode: ${config.mode}`)
}
}, [showStatus])
}, [setClusterConfig, showStatus])

const handleRelationshipVisibilityChange = useCallback((visibility: Partial<RelationshipVisibility>) => {
setRelationshipVisibility(prev => ({ ...prev, ...visibility }))
}, [])
}, [setRelationshipVisibility])

const handleReheat = useCallback(() => {
reheatFn?.()
}, [reheatFn])

const handleResetForces = useCallback(() => {
setForceConfig(DEFAULT_FORCE_CONFIG)
}, [])
}, [setForceConfig])

const handleToggleLabels = useCallback(() => {
setDisplayConfig(prev => ({ ...prev, showLabels: !prev.showLabels }))
}, [])
}, [setDisplayConfig])

// Keyboard navigation
const handleStartPathfindingFromKeyboard = useCallback(() => {
if (selectedNode) {
pathfinding.startPathSelection(selectedNode.id)
}
}, [selectedNode, pathfinding.startPathSelection])

Check warning on line 755 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 @@ -697,15 +792,15 @@

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

Check warning on line 795 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 799 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 803 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 @@ -922,14 +1017,105 @@
{error && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10">
<div className="glass p-6 rounded-xl max-w-md text-center">
<div className="text-danger text-lg mb-2">Connection Error</div>
<div className="text-ink-3 text-sm mb-4">{(error as Error).message}</div>
<button
onClick={() => refetch()}
className="px-4 py-2 bg-accent text-void hover:bg-white rounded-lg transition-colors"
>
Retry
</button>
{isAuthError ? (
<>
<div className="text-danger text-lg mb-2">Access denied</div>
<div className="text-ink-3 text-sm mb-4">
The server rejected this token. If you followed a shared
viewer link, ask for a new one — or enter credentials
yourself.
</div>
<div className="flex items-center justify-center gap-3">
<button
onClick={handleReenterCredentials}
className="px-4 py-2 bg-accent text-void hover:bg-white rounded-lg transition-colors"
>
Enter credentials
</button>
<button
onClick={() => refetch()}
className="px-4 py-2 bg-white/10 hover:bg-white/20 text-ink-2 rounded-lg transition-colors"
>
Retry
</button>
</div>
</>
) : (
<>
<div className="text-danger text-lg mb-2">Connection Error</div>
<div className="text-ink-3 text-sm mb-4">{(error as Error).message}</div>
<button
onClick={() => refetch()}
className="px-4 py-2 bg-accent text-void hover:bg-white rounded-lg transition-colors"
>
Retry
</button>
</>
)}
</div>
</div>
)}

{/* Empty state — a successful load with zero nodes used to leave a
silent black canvas, indistinguishable from a crash. For brand-new
AutoMem deployments (empty store) this was the literal first
impression. */}
{!isLoading && !error && data && nodes.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center z-10">
<div className="glass p-8 rounded-xl max-w-md text-center">
<span className="text-accent text-3xl leading-none" aria-hidden>
✦
</span>
{data.stats.total_nodes === 0 ? (
<>
<div className="font-display text-lg text-ink mt-3 mb-2">
No memories yet
</div>
<div className="text-ink-3 text-sm mb-5">
Once your agent starts storing memories, they'll appear
here as a living graph.
</div>
<div className="flex items-center justify-center gap-3">
<button
onClick={() => refetch()}
className="px-4 py-2 bg-accent text-void hover:bg-white rounded-lg text-sm transition-colors"
>
Refresh
</button>
<a
href="https://github.com/verygoodplugins/automem"
target="_blank"
rel="noopener noreferrer"
className="px-4 py-2 bg-white/10 hover:bg-white/20 text-ink-2 rounded-lg text-sm transition-colors"
>
Wire up an agent
</a>
</div>
</>
) : (
<>
<div className="font-display text-lg text-ink mt-3 mb-2">
No memories match your filters
</div>
<div className="text-ink-3 text-sm mb-5">
{data.stats.total_nodes.toLocaleString()} memories are in
your store, but the current type and importance filters
exclude all of them.
</div>
<button
onClick={() =>
setFilters((prev) => ({
...prev,
types: [],
importanceRange: [0, 1],
}))
}
className="px-4 py-2 bg-accent text-void hover:bg-white rounded-lg text-sm transition-colors"
>
Reset filters
</button>
</>
)}
</div>
</div>
)}
Expand Down Expand Up @@ -1007,7 +1193,13 @@
onPreviousPath={pathfinding.previousPath}
onCancel={pathfinding.cancelPathSelection}
onClear={pathfinding.clearPath}
visible={pathfinding.isSelectingTarget || pathfinding.hasPath}
visible={
pathfinding.isSelectingTarget ||
pathfinding.hasPath ||
// targetId set with no paths = search ran and found nothing
// among loaded memories — show the honest no-path card.
(pathfinding.targetId != null && !pathfinding.hasPath)
}
/>

{/* Time Travel Timeline */}
Expand Down Expand Up @@ -1107,6 +1299,9 @@
onSoundEnabledChange={sound.setEnabled}
soundVolume={sound.settings.masterVolume}
onSoundVolumeChange={sound.setMasterVolume}
onResetAll={handleResetAllSettings}
connection={connectionInfo}
onDisconnect={handleReenterCredentials}
/>
</div>

Expand Down
Loading
Loading