@townco/debugger 0.1.28 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,247 @@
1
+ import { Search } from "lucide-react";
2
+ import { useEffect, useState } from "react";
3
+ import type { SessionAnalysis } from "@/analysis/types";
4
+ import { DebuggerLayout } from "@/components/DebuggerLayout";
5
+ import { Button } from "@/components/ui/button";
6
+ import {
7
+ Card,
8
+ CardContent,
9
+ CardDescription,
10
+ CardHeader,
11
+ CardTitle,
12
+ } from "@/components/ui/card";
13
+ import {
14
+ Select,
15
+ SelectContent,
16
+ SelectItem,
17
+ SelectTrigger,
18
+ SelectValue,
19
+ } from "@/components/ui/select";
20
+
21
+ interface SimilarSession {
22
+ session_id: string;
23
+ distance: number;
24
+ analysis?: SessionAnalysis;
25
+ }
26
+
27
+ export function FindSessions() {
28
+ const [sessions, setSessions] = useState<SessionAnalysis[]>([]);
29
+ const [selectedSessionId, setSelectedSessionId] = useState<string>("");
30
+ const [similarSessions, setSimilarSessions] = useState<SimilarSession[]>([]);
31
+ const [loading, setLoading] = useState(false);
32
+ const [error, setError] = useState<string | null>(null);
33
+
34
+ // Fetch all analyzed sessions on mount
35
+ useEffect(() => {
36
+ fetch("/api/session-analyses")
37
+ .then((res) => res.json())
38
+ .then((data) => {
39
+ if (data.analyses) {
40
+ setSessions(data.analyses);
41
+ }
42
+ })
43
+ .catch((err) => {
44
+ console.error("Failed to fetch sessions:", err);
45
+ });
46
+ }, []);
47
+
48
+ const handleFindSimilar = async () => {
49
+ if (!selectedSessionId) {
50
+ setError("Please select a session");
51
+ return;
52
+ }
53
+
54
+ setLoading(true);
55
+ setError(null);
56
+ setSimilarSessions([]);
57
+
58
+ try {
59
+ const response = await fetch(
60
+ `/api/session-analyses/${selectedSessionId}/similar?limit=10`,
61
+ );
62
+
63
+ if (!response.ok) {
64
+ const errorData = await response.json();
65
+ throw new Error(errorData.error || "Failed to find similar sessions");
66
+ }
67
+
68
+ const data = await response.json();
69
+
70
+ // Fetch full analysis data for each similar session
71
+ const similarWithAnalysis = await Promise.all(
72
+ data.similar.map(async (similar: SimilarSession) => {
73
+ try {
74
+ const analysisRes = await fetch(
75
+ `/api/session-analyses?sessionId=${similar.session_id}`,
76
+ );
77
+ if (analysisRes.ok) {
78
+ const analysis = await analysisRes.json();
79
+ return { ...similar, analysis };
80
+ }
81
+ } catch (err) {
82
+ console.error(`Failed to fetch analysis for ${similar.session_id}:`, err);
83
+ }
84
+ return similar;
85
+ }),
86
+ );
87
+
88
+ setSimilarSessions(similarWithAnalysis);
89
+ } catch (err) {
90
+ setError(err instanceof Error ? err.message : "Unknown error");
91
+ } finally {
92
+ setLoading(false);
93
+ }
94
+ };
95
+
96
+ const selectedSession = sessions.find(
97
+ (s) => s.session_id === selectedSessionId,
98
+ );
99
+
100
+ return (
101
+ <DebuggerLayout title="Find Similar Sessions" showNav={true}>
102
+ <div className="h-full overflow-auto p-6">
103
+ <div className="max-w-4xl mx-auto space-y-6">
104
+ {/* Search Section */}
105
+ <Card>
106
+ <CardHeader>
107
+ <CardTitle>Search by Similarity</CardTitle>
108
+ <CardDescription>
109
+ Find sessions similar to a selected session using AI embeddings
110
+ </CardDescription>
111
+ </CardHeader>
112
+ <CardContent className="space-y-4">
113
+ <div className="space-y-2">
114
+ <label className="text-sm font-medium">Select Session</label>
115
+ <Select
116
+ value={selectedSessionId}
117
+ onValueChange={setSelectedSessionId}
118
+ >
119
+ <SelectTrigger>
120
+ <SelectValue placeholder="Choose a session to find similar ones" />
121
+ </SelectTrigger>
122
+ <SelectContent>
123
+ {sessions.length === 0 && (
124
+ <div className="px-2 py-6 text-center text-sm text-muted-foreground">
125
+ No analyzed sessions found.
126
+ <br />
127
+ Analyze sessions first to use similarity search.
128
+ </div>
129
+ )}
130
+ {sessions.map((session) => (
131
+ <SelectItem
132
+ key={session.session_id}
133
+ value={session.session_id}
134
+ >
135
+ <div className="flex flex-col items-start">
136
+ <span className="font-mono text-xs">
137
+ {session.session_id}
138
+ </span>
139
+ <span className="text-xs text-muted-foreground truncate max-w-[300px]">
140
+ {session.task.user_query}
141
+ </span>
142
+ </div>
143
+ </SelectItem>
144
+ ))}
145
+ </SelectContent>
146
+ </Select>
147
+ </div>
148
+
149
+ {selectedSession && (
150
+ <div className="p-4 bg-muted rounded-lg space-y-2">
151
+ <div className="text-sm">
152
+ <span className="font-medium">Intent:</span>{" "}
153
+ <span className="text-muted-foreground">
154
+ {selectedSession.task.intent_type}
155
+ </span>
156
+ </div>
157
+ <div className="text-sm">
158
+ <span className="font-medium">Summary:</span>{" "}
159
+ <span className="text-muted-foreground">
160
+ {selectedSession.task.task_summary}
161
+ </span>
162
+ </div>
163
+ <div className="text-sm">
164
+ <span className="font-medium">Outcome:</span>{" "}
165
+ <span className="text-muted-foreground">
166
+ {selectedSession.outcome.status}
167
+ </span>
168
+ </div>
169
+ </div>
170
+ )}
171
+
172
+ <Button
173
+ onClick={handleFindSimilar}
174
+ disabled={!selectedSessionId || loading}
175
+ className="w-full"
176
+ >
177
+ <Search className="mr-2 size-4" />
178
+ {loading ? "Searching..." : "Find Similar Sessions"}
179
+ </Button>
180
+
181
+ {error && (
182
+ <div className="p-4 bg-destructive/10 text-destructive rounded-lg text-sm">
183
+ {error}
184
+ </div>
185
+ )}
186
+ </CardContent>
187
+ </Card>
188
+
189
+ {/* Results Section */}
190
+ {similarSessions.length > 0 && (
191
+ <Card>
192
+ <CardHeader>
193
+ <CardTitle>Similar Sessions</CardTitle>
194
+ <CardDescription>
195
+ {similarSessions.length} similar session
196
+ {similarSessions.length !== 1 ? "s" : ""} found
197
+ </CardDescription>
198
+ </CardHeader>
199
+ <CardContent>
200
+ <div className="space-y-3">
201
+ {similarSessions.map((similar) => {
202
+ if (!similar.analysis) return null;
203
+
204
+ return (
205
+ <a
206
+ key={similar.session_id}
207
+ href={`/sessions/${similar.session_id}`}
208
+ className="block p-4 border rounded-lg hover:bg-muted/50 transition-colors"
209
+ >
210
+ <div className="flex items-start justify-between gap-4">
211
+ <div className="flex-1 space-y-1">
212
+ <div className="flex items-center gap-2">
213
+ <span className="font-mono text-xs text-muted-foreground">
214
+ {similar.session_id}
215
+ </span>
216
+ <span className="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded">
217
+ {similar.analysis.task.intent_type}
218
+ </span>
219
+ </div>
220
+ <p className="text-sm line-clamp-2">
221
+ {similar.analysis.task.user_query}
222
+ </p>
223
+ <p className="text-xs text-muted-foreground line-clamp-1">
224
+ {similar.analysis.task.task_summary}
225
+ </p>
226
+ </div>
227
+ <div className="flex flex-col items-end gap-1">
228
+ <span className="text-xs font-medium px-2 py-1 bg-muted rounded">
229
+ {similar.distance.toFixed(3)}
230
+ </span>
231
+ <span className="text-xs text-muted-foreground">
232
+ distance
233
+ </span>
234
+ </div>
235
+ </div>
236
+ </a>
237
+ );
238
+ })}
239
+ </div>
240
+ </CardContent>
241
+ </Card>
242
+ )}
243
+ </div>
244
+ </div>
245
+ </DebuggerLayout>
246
+ );
247
+ }
@@ -1,5 +1,7 @@
1
1
  import { useCallback, useEffect, useState } from "react";
2
2
  import { Button } from "@/components/ui/button";
3
+ import type { SessionAnalysis } from "../analysis/types";
4
+ import { AnalyzeAllButton } from "../components/AnalyzeAllButton";
3
5
  import { DebuggerLayout } from "../components/DebuggerLayout";
4
6
  import type { Session } from "../types";
5
7
 
@@ -24,8 +26,32 @@ function formatRelativeTime(nanoseconds: number): string {
24
26
  return "just now";
25
27
  }
26
28
 
29
+ function formatIntentType(intentType: string): string {
30
+ return intentType
31
+ .split("_")
32
+ .map((word) => word.charAt(0) + word.slice(1).toLowerCase())
33
+ .join(" ");
34
+ }
35
+
36
+ function getOutcomeColor(status: string): string {
37
+ switch (status) {
38
+ case "SUCCESS":
39
+ return "text-green-600 dark:text-green-400";
40
+ case "FAILURE":
41
+ return "text-red-600 dark:text-red-400";
42
+ case "PARTIAL_SUCCESS":
43
+ return "text-yellow-600 dark:text-yellow-400";
44
+ case "ABORTED":
45
+ case "TIMEOUT":
46
+ return "text-gray-600 dark:text-gray-400";
47
+ default:
48
+ return "text-muted-foreground";
49
+ }
50
+ }
51
+
27
52
  interface SessionWithMessage extends Session {
28
53
  firstMessage?: string;
54
+ analysis?: SessionAnalysis;
29
55
  }
30
56
 
31
57
  export function SessionList() {
@@ -36,7 +62,7 @@ export function SessionList() {
36
62
  const [loading, setLoading] = useState(true);
37
63
  const [error, setError] = useState<string | null>(null);
38
64
 
39
- // Fetch sessions, comparison session IDs, and first messages
65
+ // Fetch sessions, comparison session IDs, first messages, and analyses
40
66
  const fetchSessions = useCallback(() => {
41
67
  setLoading(true);
42
68
  Promise.all([
@@ -48,11 +74,23 @@ export function SessionList() {
48
74
  if (!res.ok) return { sessionIds: [] };
49
75
  return res.json();
50
76
  }),
77
+ fetch("/api/session-analyses?limit=1000").then((res) => {
78
+ if (!res.ok) return { analyses: [] };
79
+ return res.json();
80
+ }),
51
81
  ])
52
- .then(async ([sessionsData, comparisonData]) => {
82
+ .then(async ([sessionsData, comparisonData, analysesData]) => {
53
83
  const comparisonIds = new Set<string>(comparisonData.sessionIds || []);
54
84
  setComparisonSessionIds(comparisonIds);
55
85
 
86
+ // Create a map of session_id to analysis
87
+ const analysesMap = new Map<string, SessionAnalysis>(
88
+ (analysesData.analyses || []).map((a: SessionAnalysis) => [
89
+ a.session_id,
90
+ a,
91
+ ]),
92
+ );
93
+
56
94
  // Filter sessions first, then fetch first messages only for filtered sessions
57
95
  const filtered = (sessionsData as Session[]).filter(
58
96
  (s) => !comparisonIds.has(s.session_id),
@@ -61,18 +99,28 @@ export function SessionList() {
61
99
  // Fetch first messages for all filtered sessions in parallel
62
100
  const sessionsWithMessages = await Promise.all(
63
101
  filtered.map(async (session) => {
102
+ const sessionWithData: SessionWithMessage = { ...session };
103
+
104
+ // Add first message
64
105
  try {
65
106
  const res = await fetch(
66
107
  `/api/session-first-message/${session.session_id}`,
67
108
  );
68
109
  if (res.ok) {
69
110
  const data = await res.json();
70
- return { ...session, firstMessage: data.message };
111
+ sessionWithData.firstMessage = data.message;
71
112
  }
72
113
  } catch {
73
114
  // Ignore errors fetching first message
74
115
  }
75
- return session;
116
+
117
+ // Add analysis if exists
118
+ const analysis = analysesMap.get(session.session_id);
119
+ if (analysis) {
120
+ sessionWithData.analysis = analysis;
121
+ }
122
+
123
+ return sessionWithData;
76
124
  }),
77
125
  );
78
126
 
@@ -122,6 +170,10 @@ export function SessionList() {
122
170
  <Button variant="outline" onClick={fetchSessions} disabled={loading}>
123
171
  Refresh
124
172
  </Button>
173
+ <AnalyzeAllButton
174
+ sessionIds={filteredSessions.map((s) => s.session_id)}
175
+ onComplete={fetchSessions}
176
+ />
125
177
  </div>
126
178
 
127
179
  {filteredSessions.length === 0 ? (
@@ -134,22 +186,36 @@ export function SessionList() {
134
186
  href={`/sessions/${session.session_id}`}
135
187
  className="block"
136
188
  >
137
- <div className="flex items-center gap-3 px-3 py-2 rounded-md hover:bg-muted/50 transition-colors cursor-pointer border">
138
- <code className="text-xs text-muted-foreground shrink-0">
189
+ <div className="grid grid-cols-[80px_1fr_180px_160px_120px_80px] items-center gap-3 px-3 py-2 rounded-md hover:bg-muted/50 transition-colors cursor-pointer border">
190
+ <code className="text-xs text-muted-foreground">
139
191
  {session.session_id.slice(0, 8)}
140
192
  </code>
141
- <span className="text-sm truncate flex-1">
193
+ <span className="text-sm truncate">
142
194
  {session.firstMessage || "No message"}
143
195
  </span>
144
- <span className="text-xs text-muted-foreground shrink-0">
196
+ <span className="text-xs text-muted-foreground text-right">
197
+ {session.analysis
198
+ ? formatIntentType(session.analysis.task.intent_type)
199
+ : ""}
200
+ </span>
201
+ <span
202
+ className={`text-xs text-right ${
203
+ session.analysis
204
+ ? getOutcomeColor(session.analysis.outcome.status)
205
+ : ""
206
+ }`}
207
+ >
208
+ {session.analysis ? session.analysis.outcome.status : ""}
209
+ </span>
210
+ <span className="text-xs text-muted-foreground text-right">
145
211
  {session.trace_count}{" "}
146
- {session.trace_count === 1 ? "trace" : "traces"} ·{" "}
212
+ {session.trace_count === 1 ? "trace" : "traces"}{" "}
147
213
  {formatDuration(
148
214
  session.first_trace_time,
149
215
  session.last_trace_time,
150
216
  )}
151
217
  </span>
152
- <span className="text-xs text-muted-foreground shrink-0">
218
+ <span className="text-xs text-muted-foreground text-right">
153
219
  {formatRelativeTime(session.last_trace_time)}
154
220
  </span>
155
221
  </div>
@@ -1,4 +1,7 @@
1
+ import { useEffect, useState } from "react";
2
+ import type { SessionAnalysis } from "../analysis/types";
1
3
  import { DebuggerLayout } from "../components/DebuggerLayout";
4
+ import { SessionAnalysisButton } from "../components/SessionAnalysisButton";
2
5
  import { SessionTimelineView } from "../components/SessionTimelineView";
3
6
 
4
7
  interface SessionViewProps {
@@ -6,9 +9,38 @@ interface SessionViewProps {
6
9
  }
7
10
 
8
11
  export function SessionView({ sessionId }: SessionViewProps) {
12
+ const [existingAnalysis, setExistingAnalysis] =
13
+ useState<SessionAnalysis | null>(null);
14
+ const [loadingAnalysis, setLoadingAnalysis] = useState(true);
15
+
16
+ // Check for existing analysis on mount
17
+ useEffect(() => {
18
+ fetch(`/api/session-analyses?sessionId=${sessionId}`)
19
+ .then((res) => {
20
+ if (res.ok) return res.json();
21
+ return null;
22
+ })
23
+ .then((analysis) => {
24
+ setExistingAnalysis(analysis);
25
+ setLoadingAnalysis(false);
26
+ })
27
+ .catch(() => {
28
+ setLoadingAnalysis(false);
29
+ });
30
+ }, [sessionId]);
31
+
9
32
  return (
10
33
  <DebuggerLayout title={`Session: ${sessionId}`} showBackButton backHref="/">
11
- <div className="flex-1 overflow-y-auto">
34
+ <div className="relative flex-1 overflow-y-auto">
35
+ <div className="absolute top-4 right-4 z-10">
36
+ {!loadingAnalysis && (
37
+ <SessionAnalysisButton
38
+ sessionId={sessionId}
39
+ existingAnalysis={existingAnalysis}
40
+ onAnalysisComplete={(analysis) => setExistingAnalysis(analysis)}
41
+ />
42
+ )}
43
+ </div>
12
44
  <SessionTimelineView sessionId={sessionId} />
13
45
  </div>
14
46
  </DebuggerLayout>