-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathmy-agents.tsx
More file actions
413 lines (382 loc) · 14 KB
/
Copy pathmy-agents.tsx
File metadata and controls
413 lines (382 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"use client";
import { DashboardPageContainer, useSetPageHeader } from "@elizaos/ui";
import {
ArrowRight,
BookOpen,
CreditCard,
KeyRound,
Loader2,
MessageCircle,
MonitorSmartphone,
Server,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "sonner";
import { logger } from "@/lib/utils/logger";
import { CharacterFilters } from "./character-filters";
import type { AgentWithOwnership } from "./character-library-grid";
import { CharacterLibraryGrid } from "./character-library-grid";
export type ViewMode = "grid" | "list";
export type SortOption = "name" | "created" | "modified" | "recent";
/** Response type for saved agents API */
interface SavedAgent {
id: string;
name: string;
bio?: string | string[];
avatarUrl?: string;
avatar_url?: string;
username?: string | null;
owner_id: string;
owner_name: string | null;
last_interaction_time?: string;
}
const ADMIN_SECTIONS = [
{
title: "Runtime",
description: "Monitor the hosted process, logs, health, and deployments.",
to: "/dashboard/containers",
icon: Server,
},
{
title: "API keys",
description: "Create and rotate keys for programmatic access.",
to: "/dashboard/api-keys",
icon: KeyRound,
},
{
title: "Billing",
description: "Review credits, payment methods, and usage controls.",
to: "/dashboard/billing",
icon: CreditCard,
},
{
title: "App devices",
description: "Manage connected apps and device-facing integrations.",
to: "/dashboard/apps",
icon: MonitorSmartphone,
},
{
title: "Docs",
description: "Read setup guides, APIs, MCP, apps, and runtime docs.",
to: "/docs",
icon: BookOpen,
},
] as const;
function getAgentChatPath(agent: AgentWithOwnership | null): string {
if (!agent) return "/dashboard/containers";
return agent.username ? `/chat/@${agent.username}` : `/chat/${agent.id}`;
}
function AgentConsoleOverview({
agents,
onCreateNew,
}: {
agents: AgentWithOwnership[];
onCreateNew: () => void;
}) {
const ownedAgents = agents.filter((agent) => agent.isOwned !== false);
const primaryAgent = ownedAgents[0] ?? agents[0] ?? null;
const runningCount = ownedAgents.filter(
(agent) => agent.stats?.deploymentStatus === "deployed",
).length;
const chatPath = getAgentChatPath(primaryAgent);
return (
<section className="grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(360px,0.8fr)]">
<div className="border border-white/10 bg-black p-5">
<div className="flex flex-col gap-5 md:flex-row md:items-start md:justify-between">
<div className="max-w-2xl space-y-3">
<p className="text-[11px] font-semibold uppercase tracking-[0.2em] text-[var(--brand-orange)]">
Agent console
</p>
<div className="space-y-2">
<h1 className="text-2xl font-semibold text-white md:text-3xl">
Administer and enter your running agent
</h1>
<p className="text-sm leading-6 text-white/60">
Use this page as the control room for your hosted Eliza agent:
open the live chat, inspect runtime state, manage API access,
connect app devices, and keep billing in view.
</p>
</div>
</div>
<div className="flex shrink-0 flex-col gap-2 sm:flex-row md:flex-col">
<Link
to={chatPath}
className="inline-flex h-10 items-center justify-center gap-2 border border-[var(--brand-orange)] bg-[var(--brand-orange)] px-4 text-sm font-medium text-black transition-colors hover:bg-[var(--brand-orange)]/90"
>
<MessageCircle className="h-4 w-4" />
{primaryAgent ? "Open agent chat" : "Go to my agent"}
</Link>
<button
type="button"
onClick={onCreateNew}
className="inline-flex h-10 items-center justify-center gap-2 border border-white/15 bg-black px-4 text-sm font-medium text-white/80 transition-colors hover:bg-white/5"
>
<Server className="h-4 w-4" />
Runtime admin
</button>
</div>
</div>
<div className="mt-5 grid gap-px border border-white/10 bg-white/5 sm:grid-cols-3">
<div className="bg-black p-4">
<p className="text-[11px] uppercase tracking-[0.2em] text-white/35">
Owned agents
</p>
<p className="mt-1 text-2xl font-semibold text-white tabular-nums">
{ownedAgents.length}
</p>
</div>
<div className="bg-black p-4">
<p className="text-[11px] uppercase tracking-[0.2em] text-white/35">
Running
</p>
<p className="mt-1 text-2xl font-semibold text-white tabular-nums">
{runningCount}
</p>
</div>
<div className="bg-black p-4">
<p className="text-[11px] uppercase tracking-[0.2em] text-white/35">
Chat target
</p>
<p className="mt-1 truncate text-sm font-medium text-white">
{primaryAgent?.name ?? "Create or deploy an agent"}
</p>
</div>
</div>
</div>
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-1">
{ADMIN_SECTIONS.map((section) => {
const Icon = section.icon;
return (
<Link
key={section.title}
to={section.to}
className="group flex items-start gap-3 border border-white/10 bg-black p-4 transition-colors hover:border-[var(--brand-orange)]/40 hover:bg-white/[0.03]"
>
<span className="flex h-9 w-9 shrink-0 items-center justify-center border border-white/10 bg-black text-[var(--brand-orange)]">
<Icon className="h-4 w-4" />
</span>
<span className="min-w-0 flex-1">
<span className="flex items-center justify-between gap-3">
<span className="text-sm font-medium text-white">
{section.title}
</span>
<ArrowRight className="h-4 w-4 shrink-0 text-white/30 transition-colors group-hover:text-[var(--brand-orange)]" />
</span>
<span className="mt-1 block text-xs leading-5 text-white/55">
{section.description}
</span>
</span>
</Link>
);
})}
</div>
</section>
);
}
/**
* My Agent client component that handles agent listing, filtering, and management.
* Fetches both owned and saved agents client-side to enable real-time updates.
*/
export function MyAgentsClient() {
const navigate = useNavigate();
const claimAttempted = useRef(false);
const [characters, setCharacters] = useState<AgentWithOwnership[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [viewMode, setViewMode] = useState<ViewMode>("grid");
const [sortBy, setSortBy] = useState<SortOption>("modified");
// Fetch both owned and saved characters
const fetchCharacters = useCallback(async () => {
try {
// Fetch owned and saved agents in parallel
const [ownedResponse, savedResponse] = await Promise.all([
fetch("/api/my-agents/characters"),
fetch("/api/my-agents/saved"),
]);
// Process owned agents
let ownedAgents: AgentWithOwnership[] = [];
let ownedFetchFailed = false;
if (ownedResponse.ok) {
const ownedResult = await ownedResponse.json();
ownedAgents = (ownedResult.data?.characters || []).map(
(char: AgentWithOwnership) => ({
...char,
isOwned: true,
}),
);
} else {
ownedFetchFailed = true;
logger.error("[MyAgents] Failed to fetch owned characters");
}
// Process saved agents (may not exist yet - gracefully handle 404)
let savedAgents: AgentWithOwnership[] = [];
if (savedResponse.ok) {
const savedResult = await savedResponse.json();
savedAgents = (savedResult.data?.agents || []).map(
(agent: SavedAgent) => ({
id: agent.id,
name: agent.name,
bio: agent.bio || "",
avatarUrl: agent.avatarUrl || agent.avatar_url,
avatar_url: agent.avatar_url || agent.avatarUrl,
username: agent.username,
isOwned: false,
ownerUsername: agent.owner_name || "Unknown",
lastInteraction: agent.last_interaction_time,
}),
);
} else if (savedResponse.status !== 404) {
// Only log error if it's not a 404 (endpoint may not exist yet)
logger.error("[MyAgents] Failed to fetch saved agents");
}
// Show error toast if owned agents failed to load
if (ownedFetchFailed) {
toast.error("Failed to load your agents");
}
// Merge both lists
setCharacters([...ownedAgents, ...savedAgents]);
} catch (error) {
logger.error("[MyAgents] Failed to fetch characters:", error);
toast.error("Failed to load your agents");
} finally {
setIsLoading(false);
}
}, []);
// Initial fetch and listen for updates
useEffect(() => {
fetchCharacters();
// Listen for character updates
const handleUpdate = () => fetchCharacters();
window.addEventListener("characters-updated", handleUpdate);
return () => window.removeEventListener("characters-updated", handleUpdate);
}, [fetchCharacters]);
// Claim any affiliate characters the user has interacted with
useEffect(() => {
if (claimAttempted.current) return;
claimAttempted.current = true;
const sessionToken = localStorage.getItem("eliza-anon-session-token");
fetch("/api/my-agents/claim-affiliate-characters", {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sessionToken: sessionToken || undefined }),
})
.then((res) => res.json())
.then((data) => {
if (data.success && data.claimed?.length > 0) {
toast.success(
`${data.claimed.length} agent(s) added to your library!`,
{
description: data.claimed
.map((c: { name: string }) => c.name)
.join(", "),
},
);
fetchCharacters();
if (sessionToken) {
try {
localStorage.removeItem("eliza-anon-session-token");
} catch {
// Ignore cleanup errors
}
}
}
})
.catch((error) => {
logger.error("[MyAgents] Failed to claim affiliate characters:", error);
});
}, [fetchCharacters]);
// Filter characters based on search
const filteredCharacters = characters.filter((char) => {
if (!searchQuery) return true;
const query = searchQuery.toLowerCase();
const agent = char as AgentWithOwnership & {
topics?: string[];
adjectives?: string[];
};
return (
agent.name?.toLowerCase().includes(query) ||
(typeof agent.bio === "string" &&
agent.bio.toLowerCase().includes(query)) ||
(Array.isArray(agent.bio) &&
agent.bio.some((b) => b.toLowerCase().includes(query))) ||
agent.topics?.some((t: string) => t.toLowerCase().includes(query)) ||
agent.adjectives?.some((a: string) => a.toLowerCase().includes(query))
);
});
// Sort characters - most recent interaction first by default
const sortedCharacters = [...filteredCharacters].sort((a, b) => {
if (sortBy === "name") {
return (a.name || "").localeCompare(b.name || "");
}
if (sortBy === "created") {
// Sort by created_at timestamp (newest first)
const getCreatedTime = (char: AgentWithOwnership): number => {
return char.created_at ? new Date(char.created_at).getTime() : 0;
};
const timeDiff = getCreatedTime(b) - getCreatedTime(a);
if (timeDiff !== 0) return timeDiff;
return (a.name || "").localeCompare(b.name || "");
}
// Default: sort by most recent activity
const getRecentTime = (char: AgentWithOwnership): number => {
if (char.isOwned) {
return char.updated_at ? new Date(char.updated_at).getTime() : 0;
}
return char.lastInteraction
? new Date(char.lastInteraction).getTime()
: 0;
};
const timeDiff = getRecentTime(b) - getRecentTime(a);
if (timeDiff !== 0) return timeDiff;
return (a.name || "").localeCompare(b.name || "");
});
const handleCreateNew = useCallback(() => {
navigate("/dashboard/containers");
}, [navigate]);
// Handler for removing saved agents from the list
const handleRemoveSaved = useCallback((characterId: string) => {
setCharacters((prev) => prev.filter((char) => char.id !== characterId));
}, []);
useSetPageHeader(
{
title: "My Agent",
description: "Administer your running cloud agent",
},
[],
);
if (isLoading) {
return (
<div className="flex items-center justify-center h-64">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
);
}
return (
<DashboardPageContainer>
<div className="flex flex-col h-full gap-6">
<AgentConsoleOverview
agents={characters}
onCreateNew={handleCreateNew}
/>
<CharacterFilters
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
viewMode={viewMode}
onViewModeChange={setViewMode}
sortBy={sortBy}
onSortChange={setSortBy}
totalCount={characters.length}
filteredCount={filteredCharacters.length}
/>
<CharacterLibraryGrid
characters={sortedCharacters}
viewMode={viewMode}
onCreateNew={handleCreateNew}
onRemoveSaved={handleRemoveSaved}
/>
</div>
</DashboardPageContainer>
);
}