Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

compaction.tsx

292 lines10.1 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { RefreshCw, RotateCcw, Send, Scissors } 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-compaction-thread'
10​
11// Mirror of /api/compaction-inspect. Kept local so the page has no build-time
12// dependency on server internals.
13interface CompactionEvent {
14 before: number
15 after: number
16 messagesBefore: number
17 messagesAfter: number
18 at: number
20interface InspectResponse {
21 events: Array<CompactionEvent>
23​
24function getMessageText(parts: UIMessage['parts']): string {
25 return parts
26 .filter((part) => part.type === 'text' && 'content' in part && part.content)
27 .map((part) => (part as { type: 'text'; content: string }).content)
28 .join('')
30​
31function CompactionPage() {
32 const [selectedModel, setSelectedModel] = useState<ModelOption>(
33 getDefaultModelOption(),
34 )
35 const [threadId, setThreadId] = useState('')
36 const [maxTokens, setMaxTokens] = useState(400)
37 const [strategy, setStrategy] = useState<'evict' | 'summarize'>('evict')
38 const [inspect, setInspect] = useState<InspectResponse | null>(null)
39 const [input, setInput] = useState('')
40​
41 useEffect(() => {
42 let existing = localStorage.getItem(THREAD_STORAGE_KEY)
43 if (!existing) {
44 existing = crypto.randomUUID()
45 localStorage.setItem(THREAD_STORAGE_KEY, existing)
46 }
47 setThreadId(existing)
48 }, [])
49​
50 const body = useMemo(
51 () => ({
52 provider: selectedModel.provider,
53 model: selectedModel.model,
54 maxTokens,
55 strategy,
56 }),
57 [selectedModel.provider, selectedModel.model, maxTokens, strategy],
58 )
59​
60 const { messages, sendMessage, isLoading } = useChat({
61 threadId,
62 connection: fetchServerSentEvents('/api/compaction-chat'),
63 forwardedProps: body,
64 devtools: { name: 'Compaction' },
65 })
66​
67 const refreshInspect = useCallback(async () => {
68 if (!threadId) return
69 try {
70 const res = await fetch(
71 `/api/compaction-inspect?threadId=${encodeURIComponent(threadId)}`,
72 )
73 if (res.ok) setInspect(await res.json())
74 } catch {
75 // Non-fatal: read-only view.
76 }
77 }, [threadId])
78​
79 const wasLoading = useRef(false)
80 useEffect(() => {
81 if (wasLoading.current && !isLoading) refreshInspect()
82 wasLoading.current = isLoading
83 }, [isLoading, refreshInspect])
84 useEffect(() => {
85 refreshInspect()
86 }, [refreshInspect])
87​
88 const startNewThread = async () => {
89 if (threadId) {
90 await fetch(
91 `/api/compaction-inspect?threadId=${encodeURIComponent(threadId)}`,
92 { method: 'DELETE' },
93 ).catch(() => {})
94 }
95 const next = crypto.randomUUID()
96 localStorage.setItem(THREAD_STORAGE_KEY, next)
97 setThreadId(next)
98 setInspect(null)
99 }
100​
101 const submit = () => {
102 const text = input.trim()
103 if (!text || isLoading) return
104 sendMessage(text)
105 setInput('')
106 }
107​
108 const events = inspect?.events ?? []
109​
110 return (
111 <div className="flex h-[calc(100vh-72px)] bg-gray-900 text-white">
112 {/* Left: chat */}
113 <div className="flex w-1/2 flex-col border-r border-cyan-500/20">
114 <div className="space-y-3 border-b border-cyan-500/20 bg-gray-800 px-4 py-3">
115 <div>
116 <label className="mb-2 block text-sm text-gray-400">
117 Select Model:
118 </label>
119 <select
120 value={MODEL_OPTIONS.findIndex(
121 (opt) =>
122 opt.provider === selectedModel.provider &&
123 opt.model === selectedModel.model,
124 )}
125 onChange={(e) =>
126 setSelectedModel(MODEL_OPTIONS[parseInt(e.target.value)])
127 }
128 disabled={isLoading}
129 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"
130 >
131 {MODEL_OPTIONS.map((option, index) => (
132 <option key={index} value={index}>
133 {option.label}
134 </option>
135 ))}
136 </select>
137 </div>
138 <div>
139 <label className="mb-1 block text-sm text-gray-400">
140 maxTokens (compact above this): {maxTokens}
141 </label>
142 <input
143 type="range"
144 min={100}
145 max={2000}
146 step={50}
147 value={maxTokens}
148 onChange={(e) => setMaxTokens(parseInt(e.target.value))}
149 className="w-full accent-cyan-500"
150 />
151 </div>
152 <div>
153 <label className="mb-1 block text-sm text-gray-400">
154 Strategy:
155 </label>
156 <select
157 value={strategy}
158 onChange={(e) =>
159 setStrategy(
160 e.target.value === 'summarize' ? 'summarize' : 'evict',
161 )
162 }
163 disabled={isLoading}
164 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"
165 >
166 <option value="evict">Evict oldest (drop + marker)</option>
167 <option value="summarize">
168 Summarize oldest (extra model call)
169 </option>
170 </select>
171 </div>
172 </div>
173​
174 <div className="flex-1 overflow-y-auto px-4 py-4">
175 {messages.length === 0 ? (
176 <p className="mt-8 text-center text-sm text-gray-500">
177 Chat for a few turns. Once the running transcript passes{' '}
178 {maxTokens} estimated tokens, older messages get compacted away
179 and the events show up on the right.
180 </p>
181 ) : (
182 messages.map(({ id, role, parts }) => (
183 <div
184 key={id}
185 className={`mb-3 flex ${role === 'user' ? 'justify-end' : 'justify-start'}`}
186 >
187 <div
188 className={`max-w-[80%] whitespace-pre-wrap rounded-lg px-3 py-2 text-sm ${
189 role === 'user'
190 ? 'bg-cyan-600 text-white'
191 : 'bg-gray-800 text-gray-100'
192 }`}
193 >
194 {getMessageText(parts)}
195 </div>
196 </div>
197 ))
198 )}
199 </div>
200​
201 <div className="border-t border-cyan-500/10 bg-gray-900/80 px-4 py-3">
202 <div className="flex gap-2">
203 <input
204 value={input}
205 onChange={(e) => setInput(e.target.value)}
206 onKeyDown={(e) => {
207 if (e.key === 'Enter' && !e.shiftKey) {
208 e.preventDefault()
209 submit()
210 }
211 }}
212 placeholder="Type a message…"
213 disabled={isLoading}
214 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"
215 />
216 <button
217 onClick={submit}
218 disabled={!input.trim() || isLoading}
219 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"
220 >
221 <Send size={16} />
222 Send
223 </button>
224 </div>
225 </div>
226 </div>
227​
228 {/* Right: compaction events */}
229 <div className="flex w-1/2 flex-col bg-gray-950">
230 <div className="flex items-center justify-between border-b border-cyan-500/20 bg-gray-800 px-4 py-3">
231 <div>
232 <h2 className="text-sm font-semibold">Compaction events</h2>
233 <p className="font-mono text-xs text-gray-500">
234 thread: {threadId ? threadId.slice(0, 8) : '…'}
235 </p>
236 </div>
237 <div className="flex gap-2">
238 <button
239 onClick={refreshInspect}
240 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"
241 >
242 <RefreshCw size={14} />
243 Refresh
244 </button>
245 <button
246 onClick={startNewThread}
247 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"
248 >
249 <RotateCcw size={14} />
250 New thread
251 </button>
252 </div>
253 </div>
254​
255 <div className="flex-1 space-y-3 overflow-y-auto p-4">
256 {events.length === 0 ? (
257 <p className="mt-8 text-center text-sm text-gray-500">
258 No compaction yet. Lower maxTokens or keep chatting until the
259 transcript grows past the threshold.
260 </p>
261 ) : (
262 events
263 .slice()
264 .reverse()
265 .map((ev, i) => (
266 <div
267 key={events.length - i}
268 className="rounded-lg border border-cyan-500/20 bg-gray-900 p-3"
269 >
270 <div className="mb-1 flex items-center gap-2 text-sm font-medium text-cyan-400">
271 <Scissors size={14} />
272 Compacted {ev.messagesBefore} → {ev.messagesAfter} messages
273 </div>
274 <div className="font-mono text-xs text-gray-300">
275 {ev.before} → {ev.after} tokens (−
276 {ev.before - ev.after})
277 </div>
278 <div className="mt-1 text-[11px] text-gray-500">
279 {new Date(ev.at).toLocaleTimeString()}
280 </div>
281 </div>
282 ))
283 )}
284 </div>
285 </div>
286 </div>
287 )
289​
290export const Route = createFileRoute('/compaction')({
291 component: CompactionPage,
292})