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