Open History to see the last commit
1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { RefreshCw, RotateCcw, Send } from 'lucide-react'
4import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
5import type { UIMessage } from '@tanstack/ai-react'
6import { MODEL_OPTIONS, getDefaultModelOption } from '@/lib/model-selection'
7import type { ModelOption } from '@/lib/model-selection'
8
9const THREAD_STORAGE_KEY = 'panel-memory-thread'
10
11// Shapes returned by /api/memory-inspect. These mirror the `inMemory()`
12// snapshot payload + the RecallResult contract; kept local so the page has no
13// build-time dependency on server internals.
14interface RecordRow {
15 id: string
16 text: string
17 kind: string
18 role?: 'user' | 'assistant'
19 createdAt: number
20 importance?: number
21}
22interface FactRow {
23 id: string
24 text: string
25 source?: string
26 createdAt?: string
27}
28interface Fragment {
29 text: string
30 source: string
31}
32interface LastRecall {
33 systemPrompt: string
34 fragments?: Array<Fragment>
35 toolGuidance?: string
36}
37interface InspectResponse {
38 snapshot: { takenAt: string; data: { records?: Array<RecordRow> } } | null
39 facts: Array<FactRow>
40 lastRecall: LastRecall | null
41}
42
43function getMessageText(parts: UIMessage['parts']): string {
44 return parts
45 .filter((part) => part.type === 'text' && 'content' in part && part.content)
46 .map((part) => (part as { type: 'text'; content: string }).content)
47 .join('')
48}
49
50function formatTime(value: number | string | undefined): string {
51 if (value === undefined) return ''
52 const date = new Date(value)
53 if (Number.isNaN(date.getTime())) return ''
54 return date.toLocaleTimeString()
55}
56
57function MemoryPage() {
58 const [selectedModel, setSelectedModel] = useState<ModelOption>(
59 getDefaultModelOption(),
60 )
61 const [threadId, setThreadId] = useState('')
62 const [inspect, setInspect] = useState<InspectResponse | null>(null)
63 const [input, setInput] = useState('')
64
65 // Resolve (or create) a stable thread id, persisted so memory survives reloads.
66 useEffect(() => {
67 let existing = localStorage.getItem(THREAD_STORAGE_KEY)
68 if (!existing) {
69 existing = crypto.randomUUID()
70 localStorage.setItem(THREAD_STORAGE_KEY, existing)
71 }
72 setThreadId(existing)
73 }, [])
74
75 const body = useMemo(
76 () => ({
77 provider: selectedModel.provider,
78 model: selectedModel.model,
79 }),
80 [selectedModel.provider, selectedModel.model],
81 )
82
83 const { messages, sendMessage, isLoading } = useChat({
84 threadId,
85 connection: fetchServerSentEvents('/api/memory-chat'),
86 forwardedProps: body,
87 devtools: { name: 'Memory' },
88 })
89
90 const refreshInspect = useCallback(async () => {
91 if (!threadId) return
92 try {
93 const res = await fetch(
94 `/api/memory-inspect?threadId=${encodeURIComponent(threadId)}`,
95 )
96 if (res.ok) setInspect(await res.json())
97 } catch {
98 // Non-fatal: the inspector is a read-only view; leave the last snapshot.
99 }
100 }, [threadId])
101
102 // Refresh the inspector whenever the thread changes and each time a turn
103 // finishes (isLoading falls back to false).
104 const wasLoading = useRef(false)
105 useEffect(() => {
106 if (wasLoading.current && !isLoading) refreshInspect()
107 wasLoading.current = isLoading
108 }, [isLoading, refreshInspect])
109 useEffect(() => {
110 refreshInspect()
111 }, [refreshInspect])
112
113 const startNewThread = () => {
114 const next = crypto.randomUUID()
115 localStorage.setItem(THREAD_STORAGE_KEY, next)
116 setThreadId(next)
117 setInspect(null)
118 }
119
120 const submit = () => {
121 const text = input.trim()
122 if (!text || isLoading) return
123 sendMessage(text)
124 setInput('')
125 }
126
127 const records = inspect?.snapshot?.data.records ?? []
128 const facts = inspect?.facts ?? []
129 const lastRecall = inspect?.lastRecall ?? null
130
131 return (
132 <div className="flex h-[calc(100vh-72px)] bg-gray-900 text-white">
133 {/* Left: chat */}
134 <div className="flex w-1/2 flex-col border-r border-cyan-500/20">
135 <div className="border-b border-cyan-500/20 bg-gray-800 px-4 py-3">
136 <label className="mb-2 block text-sm text-gray-400">
137 Select Model:
138 </label>
139 <select
140 value={MODEL_OPTIONS.findIndex(
141 (opt) =>
142 opt.provider === selectedModel.provider &&
143 opt.model === selectedModel.model,
144 )}
145 onChange={(e) =>
146 setSelectedModel(MODEL_OPTIONS[parseInt(e.target.value)])
147 }
148 disabled={isLoading}
149 className="w-full rounded-lg border border-cyan-500/20 bg-gray-900 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-cyan-500/50 disabled:opacity-50"
150 >
151 {MODEL_OPTIONS.map((option, index) => (
152 <option key={index} value={index}>
153 {option.label}
154 </option>
155 ))}
156 </select>
157 </div>
158
159 <div className="flex-1 overflow-y-auto px-4 py-4">
160 {messages.length === 0 ? (
161 <p className="mt-8 text-center text-sm text-gray-500">
162 Say something like "My name is Jack and I love guitars", then in a
163 later turn ask "What's my name?" — the answer comes from memory.
164 </p>
165 ) : (
166 messages.map(({ id, role, parts }) => (
167 <div
168 key={id}
169 className={`mb-3 flex ${role === 'user' ? 'justify-end' : 'justify-start'}`}
170 >
171 <div
172 className={`max-w-[80%] whitespace-pre-wrap rounded-lg px-3 py-2 text-sm ${
173 role === 'user'
174 ? 'bg-cyan-600 text-white'
175 : 'bg-gray-800 text-gray-100'
176 }`}
177 >
178 {getMessageText(parts)}
179 </div>
180 </div>
181 ))
182 )}
183 </div>
184
185 <div className="border-t border-cyan-500/10 bg-gray-900/80 px-4 py-3">
186 <div className="flex gap-2">
187 <input
188 value={input}
189 onChange={(e) => setInput(e.target.value)}
190 onKeyDown={(e) => {
191 if (e.key === 'Enter' && !e.shiftKey) {
192 e.preventDefault()
193 submit()
194 }
195 }}
196 placeholder="Type a message…"
197 disabled={isLoading}
198 className="flex-1 rounded-lg border border-cyan-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-cyan-500/50 disabled:opacity-50"
199 />
200 <button
201 onClick={submit}
202 disabled={!input.trim() || isLoading}
203 className="flex items-center gap-2 rounded-lg bg-cyan-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-cyan-700 disabled:opacity-50"
204 >
205 <Send size={16} />
206 Send
207 </button>
208 </div>
209 </div>
210 </div>
211
212 {/* Right: memory inspector */}
213 <div className="flex w-1/2 flex-col bg-gray-950">
214 <div className="flex items-center justify-between border-b border-cyan-500/20 bg-gray-800 px-4 py-3">
215 <div>
216 <h2 className="text-sm font-semibold">What's in memory</h2>
217 <p className="font-mono text-xs text-gray-500">
218 thread: {threadId ? threadId.slice(0, 8) : '…'}
219 </p>
220 </div>
221 <div className="flex gap-2">
222 <button
223 onClick={refreshInspect}
224 className="flex items-center gap-1.5 rounded-lg border border-cyan-500/20 px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-gray-800"
225 >
226 <RefreshCw size={14} />
227 Refresh
228 </button>
229 <button
230 onClick={startNewThread}
231 className="flex items-center gap-1.5 rounded-lg border border-cyan-500/20 px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-gray-800"
232 >
233 <RotateCcw size={14} />
234 New thread
235 </button>
236 </div>
237 </div>
238
239 <div className="flex-1 space-y-6 overflow-y-auto p-4">
240 {/* Last recalled */}
241 <section>
242 <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-cyan-400">
243 Last recalled (injected into the prompt)
244 </h3>
245 {lastRecall && lastRecall.systemPrompt ? (
246 <div className="space-y-2">
247 <pre className="whitespace-pre-wrap rounded-lg border border-gray-800 bg-gray-900 p-3 text-xs text-gray-200">
248 {lastRecall.systemPrompt}
249 </pre>
250 {lastRecall.fragments && lastRecall.fragments.length > 0 && (
251 <ul className="space-y-1">
252 {lastRecall.fragments.map((frag, i) => (
253 <li
254 key={i}
255 className="rounded border border-gray-800 bg-gray-900 px-2 py-1 text-xs text-gray-300"
256 >
257 <span className="text-gray-500">{frag.source}:</span>{' '}
258 {frag.text}
259 </li>
260 ))}
261 </ul>
262 )}
263 </div>
264 ) : (
265 <p className="text-xs text-gray-600">
266 Nothing recalled yet — send a follow-up question that relates to
267 an earlier message.
268 </p>
269 )}
270 </section>
271
272 {/* Records */}
273 <section>
274 <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-cyan-400">
275 Stored records ({records.length})
276 </h3>
277 {records.length === 0 ? (
278 <p className="text-xs text-gray-600">
279 No memories yet — send a message to store the first turn.
280 </p>
281 ) : (
282 <ul className="space-y-2">
283 {records.map((rec) => (
284 <li
285 key={rec.id}
286 className="rounded-lg border border-gray-800 bg-gray-900 p-3"
287 >
288 <div className="mb-1 flex items-center gap-2 text-xs text-gray-500">
289 <span className="rounded bg-cyan-500/10 px-1.5 py-0.5 text-cyan-300">
290 {rec.kind}
291 </span>
292 {rec.role && <span>{rec.role}</span>}
293 {rec.importance !== undefined && (
294 <span>importance {rec.importance.toFixed(2)}</span>
295 )}
296 <span className="ml-auto">
297 {formatTime(rec.createdAt)}
298 </span>
299 </div>
300 <p className="text-sm text-gray-100">{rec.text}</p>
301 </li>
302 ))}
303 </ul>
304 )}
305 </section>
306
307 {/* Facts */}
308 <section>
309 <h3 className="mb-2 text-xs font-semibold uppercase tracking-wider text-cyan-400">
310 listFacts() ({facts.length})
311 </h3>
312 {facts.length === 0 ? (
313 <p className="text-xs text-gray-600">No facts.</p>
314 ) : (
315 <ul className="space-y-1">
316 {facts.map((fact) => (
317 <li
318 key={fact.id}
319 className="rounded border border-gray-800 bg-gray-900 px-2 py-1 text-xs text-gray-300"
320 >
321 {fact.source && (
322 <span className="text-gray-500">{fact.source}: </span>
323 )}
324 {fact.text}
325 </li>
326 ))}
327 </ul>
328 )}
329 </section>
330 </div>
331 </div>
332 </div>
333 )
334}
335
336export const Route = createFileRoute('/memory')({
337 component: MemoryPage,
338})