Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: update layout

Gus3536a16a49f0
diff --git a/src/web/app/(app)/agents/[id]/edit/page.tsx b/src/web/app/(app)/agents/[id]/edit/page.tsx
new file mode 100644
index 000000000..df06604f1
--- /dev/null
+++ b/src/web/app/(app)/agents/[id]/edit/page.tsx
@@ -0,0 +1,251 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useParams, useRouter } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+ SelectGroup,
+ SelectGroupLabel,
+} from "@/components/ui/select";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import { Loader2 } from "lucide-react";
+import type { Runtime } from "@/lib/types";
+
+export default function EditAgentPage() {
+ const params = useParams();
+ const router = useRouter();
+ const agentId = params.id as string;
+ const {
+ agents,
+ runtimes,
+ loading,
+ handleUpdateAgent,
+ handleDeleteAgent,
+ } = useAgentContext();
+
+ const agent = agents.find((a) => a.id === agentId);
+
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [instructions, setInstructions] = useState("");
+ const [runtimeId, setRuntimeId] = useState("");
+ const [saving, setSaving] = useState(false);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const [initialized, setInitialized] = useState(false);
+
+ // Populate form when agent data loads
+ useEffect(() => {
+ if (agent && !initialized) {
+ setName(agent.name);
+ setDescription(agent.description);
+ setInstructions(agent.instructions);
+ setRuntimeId(agent.runtime_id);
+ setInitialized(true);
+ }
+ }, [agent, initialized]);
+
+ // Group runtimes by machine
+ const runtimeGroups = new Map<
+ string,
+ { label: string; runtimes: Runtime[] }
+ >();
+ for (const rt of runtimes) {
+ const key = rt.daemon_id || rt.id;
+ if (!runtimeGroups.has(key)) {
+ runtimeGroups.set(key, {
+ label:
+ (typeof rt.device_info === "string" ? rt.device_info : "") ||
+ rt.name ||
+ key,
+ runtimes: [],
+ });
+ }
+ runtimeGroups.get(key)!.runtimes.push(rt);
+ }
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setSaving(true);
+ try {
+ const ok = await handleUpdateAgent(agentId, {
+ name,
+ description,
+ instructions,
+ runtime_id: runtimeId,
+ });
+ if (ok) router.back();
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleDelete = async () => {
+ setDeleting(true);
+ try {
+ const ok = await handleDeleteAgent(agentId);
+ if (ok) router.push("/home");
+ } finally {
+ setDeleting(false);
+ setConfirmOpen(false);
+ }
+ };
+
+ if (loading || !agent) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ {loading ? (
+ <Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
+ ) : (
+ <p className="text-sm text-muted-foreground">Agent not found.</p>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex items-center justify-between gap-3 border-b border-border/50 px-5 py-2.5">
+ <h1 className="text-sm font-medium">Edit Agent</h1>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-destructive hover:text-destructive"
+ onClick={() => setConfirmOpen(true)}
+ >
+ Delete
+ </Button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-5 py-6">
+ <form
+ onSubmit={handleSubmit}
+ className="mx-auto max-w-md space-y-4"
+ >
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-agent-name">Name</Label>
+ <Input
+ id="edit-agent-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="My Agent"
+ required
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-agent-description">Description</Label>
+ <Input
+ id="edit-agent-description"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="What does this agent do?"
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-agent-instructions">Instructions</Label>
+ <Textarea
+ id="edit-agent-instructions"
+ value={instructions}
+ onChange={(e) => setInstructions(e.target.value)}
+ placeholder="System prompt or instructions..."
+ rows={6}
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-agent-runtime">Runtime</Label>
+ <Select
+ value={runtimeId}
+ onValueChange={(val: string | null) => {
+ if (val) setRuntimeId(val);
+ }}
+ disabled={
+ runtimes.length === 0 ||
+ runtimes.every((r) => r.status !== "online")
+ }
+ items={runtimes.map((rt) => {
+ const machine =
+ (typeof rt.device_info === "string" ? rt.device_info : "") ||
+ rt.name ||
+ "";
+ const label = machine
+ ? `${rt.provider} (${machine})`
+ : rt.provider;
+ return { value: rt.id, label };
+ })}
+ >
+ <SelectTrigger>
+ <SelectValue
+ placeholder={
+ runtimes.length === 0
+ ? "No runtimes — start a daemon first"
+ : runtimes.every((r) => r.status !== "online")
+ ? "All runtimes offline"
+ : "Select a runtime"
+ }
+ />
+ </SelectTrigger>
+ <SelectPopup portal={false}>
+ {Array.from(runtimeGroups.entries()).map(([key, group]) => (
+ <SelectGroup key={key}>
+ <SelectGroupLabel className="truncate">
+ {group.label}
+ </SelectGroupLabel>
+ {group.runtimes.map((rt) => (
+ <SelectItem
+ key={rt.id}
+ value={rt.id}
+ disabled={rt.status !== "online"}
+ >
+ <span className="flex items-center gap-2">
+ <span>{rt.provider}</span>
+ <span className="text-muted-foreground text-xs">
+ ({rt.status})
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ))}
+ </SelectPopup>
+ </Select>
+ </div>
+
+ <div className="flex items-center gap-2 pt-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => router.back()}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={saving || !name}>
+ {saving ? "Saving..." : "Save"}
+ </Button>
+ </div>
+ </form>
+ </div>
+
+ <ConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ title="Remove agent"
+ description={`This will permanently delete "${agent.name}" and all its conversations.`}
+ loading={deleting}
+ onConfirm={handleDelete}
+ />
+ </>
+ );
+}
diff --git a/src/web/app/(app)/agents/new/page.tsx b/src/web/app/(app)/agents/new/page.tsx
new file mode 100644
index 000000000..c4dc5470f
--- /dev/null
+++ b/src/web/app/(app)/agents/new/page.tsx
@@ -0,0 +1,197 @@
+"use client";
+
+import { useState } from "react";
+import { useRouter } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Textarea } from "@/components/ui/textarea";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+ SelectGroup,
+ SelectGroupLabel,
+} from "@/components/ui/select";
+import type { Runtime } from "@/lib/types";
+
+export default function CreateAgentPage() {
+ const router = useRouter();
+ const {
+ runtimes,
+ handleCreateAgent,
+ chatWithAgent,
+ getFirstOnlineRuntimeId,
+ } = useAgentContext();
+
+ const [name, setName] = useState("");
+ const [description, setDescription] = useState("");
+ const [instructions, setInstructions] = useState("");
+ const [runtimeId, setRuntimeId] = useState(getFirstOnlineRuntimeId());
+ const [creating, setCreating] = useState(false);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setCreating(true);
+ try {
+ const agent = await handleCreateAgent({
+ name,
+ description: description || undefined,
+ instructions: instructions || undefined,
+ runtime_id: runtimeId,
+ });
+ if (agent) {
+ const conversationId = await chatWithAgent(agent.id);
+ if (conversationId) {
+ router.push(`/chat/${conversationId}?agent=${agent.id}`);
+ } else {
+ router.push("/home");
+ }
+ }
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ // Group runtimes by machine
+ const runtimeGroups = new Map<
+ string,
+ { label: string; runtimes: Runtime[] }
+ >();
+ for (const rt of runtimes) {
+ const key = rt.daemon_id || rt.id;
+ if (!runtimeGroups.has(key)) {
+ runtimeGroups.set(key, {
+ label:
+ (typeof rt.device_info === "string" ? rt.device_info : "") ||
+ rt.name ||
+ key,
+ runtimes: [],
+ });
+ }
+ runtimeGroups.get(key)!.runtimes.push(rt);
+ }
+
+ return (
+ <>
+ <div className="flex items-center gap-3 border-b border-border/50 px-5 py-2.5">
+ <h1 className="text-sm font-medium">Create Agent</h1>
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-5 py-6">
+ <form
+ onSubmit={handleSubmit}
+ className="mx-auto max-w-md space-y-4"
+ >
+ <div className="space-y-1.5">
+ <Label htmlFor="agent-name">Name</Label>
+ <Input
+ id="agent-name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="My Agent"
+ required
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="agent-description">Description</Label>
+ <Input
+ id="agent-description"
+ value={description}
+ onChange={(e) => setDescription(e.target.value)}
+ placeholder="What does this agent do?"
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="agent-instructions">Instructions</Label>
+ <Textarea
+ id="agent-instructions"
+ value={instructions}
+ onChange={(e) => setInstructions(e.target.value)}
+ placeholder="System prompt or instructions..."
+ rows={6}
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="agent-runtime">Runtime</Label>
+ <Select
+ value={runtimeId}
+ onValueChange={(val: string | null) => {
+ if (val) setRuntimeId(val);
+ }}
+ disabled={
+ runtimes.length === 0 ||
+ runtimes.every((r) => r.status !== "online")
+ }
+ items={runtimes.map((rt) => {
+ const machine =
+ (typeof rt.device_info === "string" ? rt.device_info : "") ||
+ rt.name ||
+ "";
+ const label = machine
+ ? `${rt.provider} (${machine})`
+ : rt.provider;
+ return { value: rt.id, label };
+ })}
+ >
+ <SelectTrigger>
+ <SelectValue
+ placeholder={
+ runtimes.length === 0
+ ? "No runtimes — start a daemon first"
+ : runtimes.every((r) => r.status !== "online")
+ ? "All runtimes offline"
+ : "Select a runtime"
+ }
+ />
+ </SelectTrigger>
+ <SelectPopup portal={false}>
+ {Array.from(runtimeGroups.entries()).map(([key, group]) => (
+ <SelectGroup key={key}>
+ <SelectGroupLabel className="truncate">
+ {group.label}
+ </SelectGroupLabel>
+ {group.runtimes.map((rt) => (
+ <SelectItem
+ key={rt.id}
+ value={rt.id}
+ disabled={rt.status !== "online"}
+ >
+ <span className="flex items-center gap-2">
+ <span>{rt.provider}</span>
+ <span className="text-muted-foreground text-xs">
+ ({rt.status})
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ))}
+ </SelectPopup>
+ </Select>
+ </div>
+
+ <div className="flex items-center gap-2 pt-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => router.back()}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={creating || !runtimeId}>
+ {creating ? "Creating..." : "Create"}
+ </Button>
+ </div>
+ </form>
+ </div>
+ </>
+ );
+}
diff --git a/src/web/app/(app)/chat/[id]/page.tsx b/src/web/app/(app)/chat/[id]/page.tsx
index 778dda951..776bfdf8e 100644
--- a/src/web/app/(app)/chat/[id]/page.tsx
+++ b/src/web/app/(app)/chat/[id]/page.tsx
@@ -1,11 +1,23 @@
"use client";
import { useEffect, useState, useRef, useCallback } from "react";
-import { useParams, useRouter } from "next/navigation";
+import { useParams, useRouter, useSearchParams } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
-import { Separator } from "@/components/ui/separator";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+ SelectGroup,
+ SelectGroupLabel,
+} from "@/components/ui/select";
import {
getConversation,
listMessages,
@@ -13,29 +25,91 @@ import {
getTask,
getTaskMessages,
} from "@/lib/api";
-import type { Conversation, Message, Task, TaskMessage } from "@/lib/types";
+import type { Conversation, Message, Task, TaskMessage, Runtime } from "@/lib/types";
import { toast } from "sonner";
+import { cn } from "@/lib/utils";
+import { Send, Loader2, Pencil, Trash2, X } from "lucide-react";
export default function ChatPage() {
const params = useParams();
const router = useRouter();
+ const searchParams = useSearchParams();
const conversationId = params.id as string;
+ const { agents, runtimes, handleDeleteAgent, handleUpdateAgent } =
+ useAgentContext();
+
+ const agentId = searchParams.get("agent");
+ const agent = agents.find((a) => a.id === agentId);
const [conversation, setConversation] = useState<Conversation | null>(null);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [deleting, setDeleting] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [sending, setSending] = useState(false);
const [activeTask, setActiveTask] = useState<Task | null>(null);
const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);
const [loading, setLoading] = useState(true);
-
const [connectionLost, setConnectionLost] = useState(false);
+ // Inline edit state
+ const [editing, setEditing] = useState(false);
+ const [editName, setEditName] = useState("");
+ const [editDescription, setEditDescription] = useState("");
+ const [editInstructions, setEditInstructions] = useState("");
+ const [editRuntimeId, setEditRuntimeId] = useState("");
+ const [saving, setSaving] = useState(false);
+
const scrollRef = useRef<HTMLDivElement>(null);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const lastSeqRef = useRef(0);
const pollFailures = useRef(0);
+ const openEdit = () => {
+ if (!agent) return;
+ setEditName(agent.name);
+ setEditDescription(agent.description);
+ setEditInstructions(agent.instructions);
+ setEditRuntimeId(agent.runtime_id);
+ setEditing(true);
+ };
+
+ const handleSave = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!agent) return;
+ setSaving(true);
+ try {
+ const ok = await handleUpdateAgent(agent.id, {
+ name: editName,
+ description: editDescription,
+ instructions: editInstructions,
+ runtime_id: editRuntimeId,
+ });
+ if (ok) setEditing(false);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ // Runtime groups for edit form
+ const runtimeGroups = new Map<
+ string,
+ { label: string; runtimes: Runtime[] }
+ >();
+ for (const rt of runtimes) {
+ const key = rt.daemon_id || rt.id;
+ if (!runtimeGroups.has(key)) {
+ runtimeGroups.set(key, {
+ label:
+ (typeof rt.device_info === "string" ? rt.device_info : "") ||
+ rt.name ||
+ key,
+ runtimes: [],
+ });
+ }
+ runtimeGroups.get(key)!.runtimes.push(rt);
+ }
+
const scrollToBottom = useCallback(() => {
setTimeout(() => {
scrollRef.current?.scrollTo({
@@ -56,7 +130,7 @@ export default function ChatPage() {
setMessages(msgs);
} catch {
toast.error("Conversation not found");
- router.push("/agents");
+ router.push("/home");
} finally {
setLoading(false);
}
@@ -156,7 +230,9 @@ export default function ChatPage() {
} catch (err) {
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
setInput(content);
- toast.error(err instanceof Error ? err.message : "Failed to send message");
+ toast.error(
+ err instanceof Error ? err.message : "Failed to send message"
+ );
} finally {
setSending(false);
}
@@ -171,119 +247,318 @@ export default function ChatPage() {
if (loading) {
return (
- <div className="flex min-h-screen items-center justify-center">
- <p className="text-muted-foreground">Loading...</p>
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
</div>
);
}
return (
- <div className="flex h-screen flex-col bg-background">
- <div className="flex items-center gap-3 border-b px-6 py-2">
- <Button variant="ghost" size="sm" onClick={() => router.push("/agents")}>
- &larr; Agents
- </Button>
- <Separator orientation="vertical" className="h-5" />
- <h1 className="text-sm font-medium">
- {conversation?.title || "Chat"}
- </h1>
+ <>
+ {/* Agent navbar — stable regardless of edit/chat view */}
+ <div className="flex items-center justify-between border-b border-border/50 px-5 py-2.5">
+ <div className="flex items-center gap-2 min-w-0">
+ {agent && (() => {
+ const runtime = runtimes.find((r) => r.id === agent.runtime_id);
+ const isOnline = runtime?.status === "online";
+ return (
+ <span
+ title={isOnline ? "Runtime online" : "Runtime offline"}
+ className={cn(
+ "size-2 rounded-full shrink-0",
+ isOnline ? "bg-status-online" : "bg-status-offline"
+ )}
+ />
+ );
+ })()}
+ <h1 className="text-sm font-medium truncate">
+ {agent?.name || "Agent"}
+ </h1>
+ {!editing && conversation?.title && (
+ <span className="text-xs text-muted-foreground truncate">
+ / {conversation.title}
+ </span>
+ )}
+ {editing && (
+ <span className="text-xs text-muted-foreground">/ Settings</span>
+ )}
+ </div>
+ {agent && (
+ <div className="flex items-center gap-0.5 shrink-0">
+ {editing ? (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-muted-foreground h-7 gap-1 px-2"
+ onClick={() => setEditing(false)}
+ >
+ <X className="size-3" />
+ Cancel
+ </Button>
+ ) : (
+ <>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-muted-foreground h-7 gap-1 px-2"
+ onClick={openEdit}
+ >
+ <Pencil className="size-3" />
+ Edit
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-muted-foreground h-7 px-2 hover:text-destructive"
+ onClick={() => setConfirmOpen(true)}
+ >
+ <Trash2 className="size-3" />
+ Remove
+ </Button>
+ </>
+ )}
+ </div>
+ )}
</div>
- <div className="flex-1 overflow-y-auto px-6" ref={scrollRef}>
- <div className="mx-auto max-w-2xl py-6 space-y-4">
- {messages.length === 0 && !activeTask && (
- <p className="text-center text-muted-foreground py-20">
- Send a message to start chatting with the agent.
- </p>
- )}
+ {editing && agent ? (
+ /* Inline edit form */
+ <div className="flex-1 overflow-y-auto px-5 py-6">
+ <form onSubmit={handleSave} className="mx-auto max-w-md space-y-4">
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-name">Name</Label>
+ <Input
+ id="edit-name"
+ value={editName}
+ onChange={(e) => setEditName(e.target.value)}
+ placeholder="My Agent"
+ required
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-description">Description</Label>
+ <Input
+ id="edit-description"
+ value={editDescription}
+ onChange={(e) => setEditDescription(e.target.value)}
+ placeholder="What does this agent do?"
+ />
+ </div>
- {messages.map((msg) => (
- <div
- key={msg.id}
- className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
- >
- <div
- className={`max-w-[80%] rounded-lg px-4 py-2 text-sm whitespace-pre-wrap ${
- msg.role === "user"
- ? "bg-primary text-primary-foreground"
- : "bg-muted"
- }`}
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-instructions">Instructions</Label>
+ <Textarea
+ id="edit-instructions"
+ value={editInstructions}
+ onChange={(e) => setEditInstructions(e.target.value)}
+ placeholder="System prompt or instructions..."
+ rows={6}
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="edit-runtime">Runtime</Label>
+ <Select
+ value={editRuntimeId}
+ onValueChange={(val: string | null) => {
+ if (val) setEditRuntimeId(val);
+ }}
+ disabled={
+ runtimes.length === 0 ||
+ runtimes.every((r) => r.status !== "online")
+ }
+ items={runtimes.map((rt) => {
+ const machine =
+ (typeof rt.device_info === "string"
+ ? rt.device_info
+ : "") ||
+ rt.name ||
+ "";
+ const label = machine
+ ? `${rt.provider} (${machine})`
+ : rt.provider;
+ return { value: rt.id, label };
+ })}
>
- {msg.content}
- </div>
+ <SelectTrigger>
+ <SelectValue
+ placeholder={
+ runtimes.length === 0
+ ? "No runtimes — start a daemon first"
+ : runtimes.every((r) => r.status !== "online")
+ ? "All runtimes offline"
+ : "Select a runtime"
+ }
+ />
+ </SelectTrigger>
+ <SelectPopup portal={false}>
+ {Array.from(runtimeGroups.entries()).map(([key, group]) => (
+ <SelectGroup key={key}>
+ <SelectGroupLabel className="truncate">
+ {group.label}
+ </SelectGroupLabel>
+ {group.runtimes.map((rt) => (
+ <SelectItem
+ key={rt.id}
+ value={rt.id}
+ disabled={rt.status !== "online"}
+ >
+ <span className="flex items-center gap-2">
+ <span>{rt.provider}</span>
+ <span className="text-muted-foreground text-xs">
+ ({rt.status})
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectGroup>
+ ))}
+ </SelectPopup>
+ </Select>
</div>
- ))}
-
- {activeTask && (
- <div className="rounded-lg border bg-muted/50 p-4 space-y-2">
- <div className="flex items-center gap-2">
- <Badge variant="secondary">
- {activeTask.status === "running"
- ? "Agent working..."
- : activeTask.status}
- </Badge>
- </div>
- {taskMessages.length > 0 && (
- <div className="mt-2 max-h-60 overflow-y-auto rounded bg-background p-3 font-mono text-xs space-y-1">
- {taskMessages.map((tm) => (
- <div key={tm.id} className="text-muted-foreground">
- {tm.type === "tool-use" && (
- <span className="text-primary">
- [tool] {tm.tool}
- </span>
- )}
- {tm.type === "tool-result" && (
- <span className="text-accent-foreground">
- [result] {tm.output || tm.content}
- </span>
- )}
- {tm.type === "text" && <span>{tm.content}</span>}
- {tm.type === "thinking" && (
- <span className="italic opacity-60">{tm.content}</span>
- )}
- {!["tool-use", "tool-result", "text", "thinking"].includes(
- tm.type
- ) && (
- <span>
- [{tm.type}] {tm.content}
- </span>
- )}
+
+ <div className="flex items-center gap-2 pt-2">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setEditing(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={saving || !editName}>
+ {saving ? "Saving..." : "Save"}
+ </Button>
+ </div>
+ </form>
+ </div>
+ ) : (
+ <>
+ {/* Messages */}
+ <div className="flex-1 overflow-y-auto px-5" ref={scrollRef}>
+ <div className="mx-auto max-w-2xl py-6 space-y-4">
+ {messages.length === 0 && !activeTask && (
+ <p className="text-center text-muted-foreground py-20 text-sm">
+ Send a message to start chatting with the agent.
+ </p>
+ )}
+
+ {messages.map((msg) => (
+ <div
+ key={msg.id}
+ className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
+ >
+ <div
+ className={`max-w-[80%] rounded-lg px-4 py-2 text-sm whitespace-pre-wrap ${
+ msg.role === "user"
+ ? "bg-primary text-primary-foreground"
+ : "bg-muted"
+ }`}
+ >
+ {msg.content}
+ </div>
+ </div>
+ ))}
+
+ {activeTask && (
+ <div className="rounded-lg border bg-muted/50 p-4 space-y-2">
+ <div className="flex items-center gap-2">
+ <Badge variant="secondary">
+ {activeTask.status === "running"
+ ? "Agent working..."
+ : activeTask.status}
+ </Badge>
+ </div>
+ {taskMessages.length > 0 && (
+ <div className="mt-2 max-h-60 overflow-y-auto rounded bg-background p-3 font-mono text-xs space-y-1">
+ {taskMessages.map((tm) => (
+ <div key={tm.id} className="text-muted-foreground">
+ {tm.type === "tool-use" && (
+ <span className="text-primary">
+ [tool] {tm.tool}
+ </span>
+ )}
+ {tm.type === "tool-result" && (
+ <span className="text-accent-foreground">
+ [result] {tm.output || tm.content}
+ </span>
+ )}
+ {tm.type === "text" && <span>{tm.content}</span>}
+ {tm.type === "thinking" && (
+ <span className="italic opacity-60">
+ {tm.content}
+ </span>
+ )}
+ {!["tool-use", "tool-result", "text", "thinking"].includes(
+ tm.type
+ ) && (
+ <span>
+ [{tm.type}] {tm.content}
+ </span>
+ )}
+ </div>
+ ))}
</div>
- ))}
+ )}
+ {activeTask.status === "failed" && activeTask.error && (
+ <p className="text-sm text-destructive">
+ {activeTask.error}
+ </p>
+ )}
+ {connectionLost && (
+ <p className="text-xs text-muted-foreground animate-pulse">
+ Connection lost — retrying...
+ </p>
+ )}
</div>
)}
- {activeTask.status === "failed" && activeTask.error && (
- <p className="text-sm text-destructive">{activeTask.error}</p>
- )}
- {connectionLost && (
- <p className="text-xs text-muted-foreground animate-pulse">
- Connection lost — retrying...
- </p>
- )}
</div>
- )}
- </div>
- </div>
+ </div>
- <div className="border-t px-6 py-4">
- <div className="mx-auto flex max-w-2xl gap-2">
- <Textarea
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={handleKeyDown}
- placeholder="Type a message..."
- rows={1}
- className="min-h-[40px] resize-none"
- disabled={sending || !!activeTask}
- />
- <Button
- onClick={handleSend}
- disabled={!input.trim() || sending || !!activeTask}
- >
- Send
- </Button>
- </div>
- </div>
- </div>
+ {/* Input */}
+ <div className="border-t border-border/50 px-5 py-3">
+ <div className="mx-auto flex max-w-2xl gap-2">
+ <Textarea
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder="Type a message..."
+ rows={1}
+ className="min-h-[40px] resize-none"
+ disabled={sending || !!activeTask}
+ />
+ <Button
+ size="icon"
+ onClick={handleSend}
+ disabled={!input.trim() || sending || !!activeTask}
+ >
+ <Send className="size-4" />
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+
+ {agent && (
+ <ConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ title="Remove agent"
+ description={`This will permanently delete "${agent.name}" and all its conversations.`}
+ loading={deleting}
+ onConfirm={async () => {
+ setDeleting(true);
+ try {
+ const ok = await handleDeleteAgent(agent.id);
+ if (ok) router.push("/home");
+ } finally {
+ setDeleting(false);
+ setConfirmOpen(false);
+ }
+ }}
+ />
+ )}
+ </>
);
}
diff --git a/src/web/app/(app)/home/page.tsx b/src/web/app/(app)/home/page.tsx
index b1edf44d7..cf1a8c2d0 100644
--- a/src/web/app/(app)/home/page.tsx
+++ b/src/web/app/(app)/home/page.tsx
@@ -1,638 +1,81 @@
"use client";
-import { useEffect, useState, useCallback, useRef } from "react";
+import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
import { Button } from "@/components/ui/button";
-import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
-} from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Textarea } from "@/components/ui/textarea";
-import {
- Sheet,
- SheetContent,
- SheetHeader,
- SheetTitle,
- SheetDescription,
- SheetBody,
- SheetFooter,
-} from "@/components/ui/sheet";
-import {
- listAgents,
- listRuntimes,
- createAgent,
- updateAgent,
- createConversation,
- deleteAgent,
-} from "@/lib/api";
-import { ConfirmDialog } from "@/components/ui/confirm-dialog";
-import {
- Select,
- SelectTrigger,
- SelectValue,
- SelectPopup,
- SelectItem,
- SelectGroup,
- SelectGroupLabel,
-} from "@/components/ui/select";
-import { toast } from "sonner";
-import type { Agent, Runtime } from "@/lib/types";
-
-function statusVariant(status: string) {
- switch (status) {
- case "working":
- return "default" as const;
- case "idle":
- return "secondary" as const;
- default:
- return "outline" as const;
- }
-}
+import { Loader2 } from "lucide-react";
export default function HomePage() {
const router = useRouter();
- const [agents, setAgents] = useState<Agent[]>([]);
- const [runtimes, setRuntimes] = useState<Runtime[]>([]);
- const [loading, setLoading] = useState(true);
- const [createSheetOpen, setCreateSheetOpen] = useState(false);
- const [editSheetOpen, setEditSheetOpen] = useState(false);
- const [editingAgent, setEditingAgent] = useState<Agent | null>(null);
- const [creating, setCreating] = useState(false);
- const [saving, setSaving] = useState(false);
- const hasAnimated = useRef(false);
-
- // Confirm dialog state
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [confirmTitle, setConfirmTitle] = useState("");
- const [confirmDescription, setConfirmDescription] = useState("");
- const [confirmLoading, setConfirmLoading] = useState(false);
- const confirmAction = useRef<(() => Promise<void>) | null>(null);
+ const { agents, runtimes, loading, chatWithAgent } = useAgentContext();
+ const redirectedRef = useRef(false);
- const openConfirm = (
- title: string,
- description: string,
- action: () => Promise<void>
- ) => {
- setConfirmTitle(title);
- setConfirmDescription(description);
- confirmAction.current = action;
- setConfirmOpen(true);
- };
-
- const handleConfirm = async () => {
- if (!confirmAction.current) return;
- setConfirmLoading(true);
- try {
- await confirmAction.current();
- } finally {
- setConfirmLoading(false);
- setConfirmOpen(false);
- confirmAction.current = null;
- }
- };
-
- // Create form state
- const [name, setName] = useState("");
- const [description, setDescription] = useState("");
- const [instructions, setInstructions] = useState("");
- const [runtimeId, setRuntimeId] = useState("");
+ // Auto-redirect to first agent's chat
+ useEffect(() => {
+ if (loading || redirectedRef.current) return;
+ if (agents.length === 0) return;
- // Edit form state
- const [editName, setEditName] = useState("");
- const [editDescription, setEditDescription] = useState("");
- const [editInstructions, setEditInstructions] = useState("");
- const [editRuntimeId, setEditRuntimeId] = useState("");
+ redirectedRef.current = true;
+ const sorted = [...agents].sort((a, b) => a.name.localeCompare(b.name));
+ const first = sorted[0];
- const loadData = useCallback(async () => {
- try {
- const [a, r] = await Promise.all([listAgents(), listRuntimes()]);
- setAgents(a);
- setRuntimes(r);
- const firstOnline = r.find((rt: Runtime) => rt.status === "online");
- if (firstOnline) {
- if (!runtimeId) setRuntimeId(firstOnline.id);
+ chatWithAgent(first.id).then((conversationId) => {
+ if (conversationId) {
+ router.replace(`/chat/${conversationId}?agent=${first.id}`);
} else {
- setRuntimeId("");
+ redirectedRef.current = false;
}
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to load data");
- } finally {
- setLoading(false);
- // Mark entrance animations as done after first load so they
- // don't replay on subsequent re-renders (e.g. sheet dismiss).
- requestAnimationFrame(() => {
- hasAnimated.current = true;
- });
- }
- }, [runtimeId]);
-
- useEffect(() => {
- loadData();
- }, [loadData]);
-
- const handleCreate = async (e: React.FormEvent) => {
- e.preventDefault();
- setCreating(true);
- try {
- await createAgent({
- name,
- description: description || undefined,
- instructions: instructions || undefined,
- runtime_id: runtimeId,
- });
- setCreateSheetOpen(false);
- setName("");
- setDescription("");
- setInstructions("");
- await loadData();
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to create agent");
- } finally {
- setCreating(false);
- }
- };
-
- const openEditSheet = (agent: Agent) => {
- setEditingAgent(agent);
- setEditName(agent.name);
- setEditDescription(agent.description);
- setEditInstructions(agent.instructions);
- setEditRuntimeId(agent.runtime_id);
- setEditSheetOpen(true);
- };
-
- const handleEdit = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!editingAgent) return;
- setSaving(true);
- try {
- await updateAgent(editingAgent.id, {
- name: editName,
- description: editDescription,
- instructions: editInstructions,
- runtime_id: editRuntimeId,
- });
- setEditSheetOpen(false);
- setEditingAgent(null);
- await loadData();
- } catch (err) {
- toast.error(err instanceof Error ? err.message : "Failed to update agent");
- } finally {
- setSaving(false);
- }
- };
-
- const handleChat = async (agent: Agent) => {
- try {
- const conversation = await createConversation(agent.id);
- router.push(`/chat/${conversation.id}`);
- } catch (err) {
- toast.error(
- err instanceof Error ? err.message : "Failed to start conversation"
- );
- }
- };
-
- const runtimeMap = new Map(runtimes.map((r) => [r.id, r]));
+ });
+ }, [agents, loading, chatWithAgent, router]);
if (loading) {
return (
- <div className="min-h-screen bg-background">
- <main className="mx-auto max-w-5xl px-6 py-8">
- <div className="mb-8">
- <div className="h-6 w-32 rounded bg-muted animate-pulse mb-2" />
- <div className="h-4 w-56 rounded bg-muted animate-pulse" />
- </div>
- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
- {[0, 1, 2].map((i) => (
- <div
- key={i}
- className="rounded-xl ring-1 ring-foreground/10 bg-card p-4 space-y-3"
- >
- <div className="flex justify-between">
- <div className="h-4 w-24 rounded bg-muted animate-pulse" />
- <div className="h-5 w-12 rounded-full bg-muted animate-pulse" />
- </div>
- <div className="h-3 w-full rounded bg-muted animate-pulse" />
- <div className="h-3 w-2/3 rounded bg-muted animate-pulse" />
- </div>
- ))}
- </div>
- </main>
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
</div>
);
}
- return (
- <div className="min-h-screen bg-background">
- {/* Create Agent Sheet (opened programmatically) */}
- <Sheet open={createSheetOpen} onOpenChange={setCreateSheetOpen}>
- <SheetContent>
- <form onSubmit={handleCreate} className="flex flex-col h-full">
- <SheetHeader>
- <SheetTitle>Create Agent</SheetTitle>
- <SheetDescription>
- Set up a new AI agent to work with.
- </SheetDescription>
- </SheetHeader>
- <SheetBody>
- <div className="space-y-5">
- <div className="space-y-1.5">
- <Label htmlFor="agent-name">Name</Label>
- <Input
- id="agent-name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="My Agent"
- required
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="agent-description">Description</Label>
- <Input
- id="agent-description"
- value={description}
- onChange={(e) => setDescription(e.target.value)}
- placeholder="What does this agent do?"
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="agent-instructions">Instructions</Label>
- <Textarea
- id="agent-instructions"
- value={instructions}
- onChange={(e) => setInstructions(e.target.value)}
- placeholder="System prompt or instructions..."
- rows={6}
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="agent-runtime">Runtime</Label>
- <Select
- value={runtimeId}
- onValueChange={(val: string | null) => {
- if (val) setRuntimeId(val);
- }}
- disabled={runtimes.length === 0 || runtimes.every((r) => r.status !== "online")}
- items={runtimes.map((rt) => {
- const machine =
- (typeof rt.device_info === "string"
- ? rt.device_info
- : "") ||
- rt.name ||
- "";
- const label = machine
- ? `${rt.provider} (${machine})`
- : rt.provider;
- return { value: rt.id, label };
- })}
- >
- <SelectTrigger>
- <SelectValue
- placeholder={
- runtimes.length === 0
- ? "No runtimes — start a daemon first"
- : runtimes.every((r) => r.status !== "online")
- ? "All runtimes offline"
- : "Select a runtime"
- }
- />
- </SelectTrigger>
- <SelectPopup portal={false}>
- {(() => {
- // Group runtimes by daemon_id (machine)
- const groups = new Map<
- string,
- {
- label: string;
- runtimes: Runtime[];
- }
- >();
- for (const rt of runtimes) {
- const key = rt.daemon_id || rt.id;
- if (!groups.has(key)) {
- groups.set(key, {
- label:
- (typeof rt.device_info === "string"
- ? rt.device_info
- : "") ||
- rt.name ||
- key,
- runtimes: [],
- });
- }
- groups.get(key)!.runtimes.push(rt);
- }
- return Array.from(groups.entries()).map(
- ([key, group]) => (
- <SelectGroup key={key}>
- <SelectGroupLabel className="truncate">
- {group.label}
- </SelectGroupLabel>
- {group.runtimes.map((rt) => (
- <SelectItem key={rt.id} value={rt.id} disabled={rt.status !== "online"}>
- <span className="flex items-center gap-2">
- <span>{rt.provider}</span>
- <span className="text-muted-foreground text-[11px]">
- ({rt.status})
- </span>
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- )
- );
- })()}
- </SelectPopup>
- </Select>
- </div>
- </div>
- </SheetBody>
- <SheetFooter>
- <Button type="submit" disabled={creating || !runtimeId}>
- {creating ? "Creating..." : "Create"}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
+ // Redirecting to first agent chat
+ if (agents.length > 0) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+
+ // Empty state — no agents
+ const hasMachines = runtimes.length > 0;
- {/* ── Main ── */}
- <main className="mx-auto max-w-5xl px-6 py-8">
- {agents.length === 0 ? (
- <div className="py-20 text-center animate-[fade-up_400ms_ease-out_both]">
- <p className="text-muted-foreground text-sm">
- No agents yet.
- </p>
- <p className="text-xs text-muted-foreground mt-2 max-w-xs mx-auto">
- Start a daemon with{" "}
- <code className="font-mono text-foreground/70 bg-muted px-1 py-0.5 rounded text-[11px]">
- npx @alook/cli daemon start
- </code>
- , then create your first agent.
- </p>
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <div className="text-center animate-[fade-up_400ms_ease-out_both]">
+ {hasMachines ? (
+ <>
+ <p className="text-muted-foreground text-sm">No agents yet.</p>
<Button
size="sm"
- className="mt-5"
- onClick={() => setCreateSheetOpen(true)}
+ className="mt-4"
+ onClick={() => router.push("/agents/new")}
>
Create Agent
</Button>
- </div>
+ </>
) : (
- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
- {agents.map((agent, i) => {
- const runtime = runtimeMap.get(agent.runtime_id);
- return (
- <Card
- key={agent.id}
- size="sm"
- className="group cursor-pointer transition-all duration-200 ease-out hover:-translate-y-px hover:shadow-md hover:ring-foreground/15 active:translate-y-0 active:shadow-sm"
- style={
- !hasAnimated.current
- ? {
- animation: `fade-up 300ms cubic-bezier(0.16, 1, 0.3, 1) both`,
- animationDelay: `${i * 60}ms`,
- }
- : undefined
- }
- onClick={() => handleChat(agent)}
- >
- <CardHeader className="pb-2">
- <div className="flex items-start justify-between gap-2">
- <CardTitle className="text-sm font-medium tracking-tight">
- {agent.name}
- </CardTitle>
- <Badge variant={statusVariant(agent.status)}>
- {agent.status}
- </Badge>
- </div>
- {agent.description && (
- <CardDescription className="line-clamp-2 text-xs">
- {agent.description}
- </CardDescription>
- )}
- </CardHeader>
- <CardContent className="mt-auto">
- <div className="flex items-center justify-between">
- <p className="text-xs text-muted-foreground">
- {runtime?.provider ?? "unknown"}{" "}
- <span className="text-muted-foreground/60">
- ({runtime?.status ?? "offline"})
- </span>
- </p>
- <div className="flex items-center gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
- <Button
- variant="ghost"
- size="sm"
- className="text-[11px] text-muted-foreground h-6 px-2"
- onClick={(e) => {
- e.stopPropagation();
- openEditSheet(agent);
- }}
- >
- Edit
- </Button>
- <Button
- variant="ghost"
- size="sm"
- className="text-[11px] text-muted-foreground h-6 px-2 hover:text-destructive"
- onClick={(e) => {
- e.stopPropagation();
- openConfirm(
- "Remove agent",
- `This will permanently delete "${agent.name}" and all its conversations.`,
- async () => {
- try {
- await deleteAgent(agent.id);
- await loadData();
- } catch (err) {
- toast.error(
- err instanceof Error
- ? err.message
- : "Failed to remove agent"
- );
- }
- }
- );
- }}
- >
- Remove
- </Button>
- </div>
- </div>
- </CardContent>
- </Card>
- );
- })}
-
- {/* Create agent card — hidden content revealed on hover */}
- <button
- type="button"
- onClick={() => setCreateSheetOpen(true)}
- className="group/create rounded-xl ring-1 ring-dashed ring-foreground/10 bg-transparent cursor-pointer flex flex-col items-center justify-center min-h-[120px] transition-all duration-200 ease-out hover:ring-foreground/20 hover:bg-muted/50 hover:-translate-y-px active:translate-y-0"
- style={
- !hasAnimated.current
- ? {
- animation: `fade-up 300ms cubic-bezier(0.16, 1, 0.3, 1) both`,
- animationDelay: `${agents.length * 60}ms`,
- }
- : undefined
- }
+ <>
+ <p className="text-muted-foreground text-sm">No machines yet.</p>
+ <Button
+ size="sm"
+ className="mt-4"
+ onClick={() => router.push("/runtimes")}
>
- <span className="text-4xl font-extralight text-muted-foreground/0 group-hover/create:text-muted-foreground transition-colors leading-none">
- +
- </span>
- <span className="text-xs text-muted-foreground/0 group-hover/create:text-muted-foreground mt-1.5 transition-colors">
- New Agent
- </span>
- </button>
- </div>
+ Connect Machine
+ </Button>
+ </>
)}
- </main>
-
- {/* Edit agent sheet */}
- <Sheet open={editSheetOpen} onOpenChange={setEditSheetOpen}>
- <SheetContent>
- <form onSubmit={handleEdit} className="flex flex-col h-full">
- <SheetHeader>
- <SheetTitle>Edit Agent</SheetTitle>
- <SheetDescription>
- Update your agent&apos;s configuration.
- </SheetDescription>
- </SheetHeader>
- <SheetBody>
- <div className="space-y-5">
- <div className="space-y-1.5">
- <Label htmlFor="edit-agent-name">Name</Label>
- <Input
- id="edit-agent-name"
- value={editName}
- onChange={(e) => setEditName(e.target.value)}
- placeholder="My Agent"
- required
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="edit-agent-description">Description</Label>
- <Input
- id="edit-agent-description"
- value={editDescription}
- onChange={(e) => setEditDescription(e.target.value)}
- placeholder="What does this agent do?"
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="edit-agent-instructions">Instructions</Label>
- <Textarea
- id="edit-agent-instructions"
- value={editInstructions}
- onChange={(e) => setEditInstructions(e.target.value)}
- placeholder="System prompt or instructions..."
- rows={6}
- />
- </div>
- <div className="space-y-1.5">
- <Label htmlFor="edit-agent-runtime">Runtime</Label>
- <Select
- value={editRuntimeId}
- onValueChange={(val: string | null) => {
- if (val) setEditRuntimeId(val);
- }}
- disabled={runtimes.length === 0 || runtimes.every((r) => r.status !== "online")}
- items={runtimes.map((rt) => {
- const machine =
- (typeof rt.device_info === "string"
- ? rt.device_info
- : "") ||
- rt.name ||
- "";
- const label = machine
- ? `${rt.provider} (${machine})`
- : rt.provider;
- return { value: rt.id, label };
- })}
- >
- <SelectTrigger>
- <SelectValue
- placeholder={
- runtimes.length === 0
- ? "No runtimes — start a daemon first"
- : runtimes.every((r) => r.status !== "online")
- ? "All runtimes offline"
- : "Select a runtime"
- }
- />
- </SelectTrigger>
- <SelectPopup portal={false}>
- {(() => {
- const groups = new Map<
- string,
- { label: string; runtimes: Runtime[] }
- >();
- for (const rt of runtimes) {
- const key = rt.daemon_id || rt.id;
- if (!groups.has(key)) {
- groups.set(key, {
- label:
- (typeof rt.device_info === "string"
- ? rt.device_info
- : "") ||
- rt.name ||
- key,
- runtimes: [],
- });
- }
- groups.get(key)!.runtimes.push(rt);
- }
- return Array.from(groups.entries()).map(
- ([key, group]) => (
- <SelectGroup key={key}>
- <SelectGroupLabel className="truncate">
- {group.label}
- </SelectGroupLabel>
- {group.runtimes.map((rt) => (
- <SelectItem key={rt.id} value={rt.id} disabled={rt.status !== "online"}>
- <span className="flex items-center gap-2">
- <span>{rt.provider}</span>
- <span className="text-muted-foreground text-[11px]">
- ({rt.status})
- </span>
- </span>
- </SelectItem>
- ))}
- </SelectGroup>
- )
- );
- })()}
- </SelectPopup>
- </Select>
- </div>
- </div>
- </SheetBody>
- <SheetFooter>
- <Button type="submit" disabled={saving || !editName}>
- {saving ? "Saving..." : "Save"}
- </Button>
- </SheetFooter>
- </form>
- </SheetContent>
- </Sheet>
-
- <ConfirmDialog
- open={confirmOpen}
- onOpenChange={setConfirmOpen}
- title={confirmTitle}
- description={confirmDescription}
- loading={confirmLoading}
- onConfirm={handleConfirm}
- />
+ </div>
</div>
);
}
diff --git a/src/web/app/(app)/layout.tsx b/src/web/app/(app)/layout.tsx
index 757404f9c..cf49deb54 100644
--- a/src/web/app/(app)/layout.tsx
+++ b/src/web/app/(app)/layout.tsx
@@ -2,7 +2,8 @@
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
-import { DashboardNavbar } from "@/components/dashboard-navbar";
+import { AgentProvider } from "@/contexts/agent-context";
+import { AppSidebar } from "@/components/app-sidebar";
export default function AppLayout({ children }: { children: React.ReactNode }) {
const router = useRouter();
@@ -24,9 +25,18 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {
if (!ready) return null;
return (
- <>
- <DashboardNavbar />
- {children}
- </>
+ <AgentProvider>
+ <div className="flex h-screen bg-background overflow-hidden">
+ {/* Sidebar rail — stable across route changes */}
+ <AppSidebar />
+
+ {/* Floating content panel */}
+ <div className="flex-1 min-w-0 p-2 pl-0">
+ <main className="h-full rounded-xl bg-card shadow-sm ring-1 ring-border/50 overflow-hidden flex flex-col">
+ {children}
+ </main>
+ </div>
+ </div>
+ </AgentProvider>
);
}
diff --git a/src/web/app/(app)/runtimes/page.tsx b/src/web/app/(app)/runtimes/page.tsx
new file mode 100644
index 000000000..901752110
--- /dev/null
+++ b/src/web/app/(app)/runtimes/page.tsx
@@ -0,0 +1,364 @@
+"use client";
+
+import { useState, useRef, useEffect, useCallback } from "react";
+import { useAgentContext } from "@/contexts/agent-context";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import {
+ Card,
+ CardHeader,
+ CardTitle,
+ CardAction,
+ CardContent,
+} from "@/components/ui/card";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetDescription,
+ SheetBody,
+} from "@/components/ui/sheet";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import { toast } from "sonner";
+import { Loader2, Monitor, Plus } from "lucide-react";
+import type { Runtime } from "@/lib/types";
+
+function ConnectMachineSteps({
+ generatedToken,
+ generatingToken,
+ onGenerateToken,
+}: {
+ generatedToken: string;
+ generatingToken: boolean;
+ onGenerateToken: () => void;
+}) {
+ const hasTriggered = useRef(false);
+ useEffect(() => {
+ if (!generatedToken && !generatingToken && !hasTriggered.current) {
+ hasTriggered.current = true;
+ onGenerateToken();
+ }
+ }, [generatedToken, generatingToken, onGenerateToken]);
+
+ const copyToClipboard = (text: string) => {
+ navigator.clipboard.writeText(text);
+ toast("Copied to clipboard");
+ };
+
+ return (
+ <div className="space-y-6">
+ {/* Step 1 */}
+ <div className="space-y-2">
+ <p className="text-xs font-medium flex items-center gap-2">
+ <span className="flex items-center justify-center size-5 rounded-full bg-foreground text-background text-[10px] font-semibold">
+ 1
+ </span>
+ Register your CLI
+ </p>
+ <p className="text-xs text-muted-foreground pl-7">
+ Run this in your terminal to link your machine.
+ </p>
+ {generatingToken ? (
+ <div className="pl-7">
+ <div className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground animate-pulse">
+ Generating token...
+ </div>
+ </div>
+ ) : generatedToken ? (
+ <div className="pl-7 space-y-2">
+ <div
+ className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() =>
+ copyToClipboard(
+ `npx @alook/cli register --token ${generatedToken}`
+ )
+ }
+ title="Click to copy"
+ >
+ npx @alook/cli register --token{" "}
+ <span className="text-foreground/70">
+ {generatedToken.slice(0, 12)}...
+ </span>
+ </div>
+ <Button
+ size="sm"
+ onClick={() => {
+ navigator.clipboard.writeText(
+ `npx @alook/cli register --token ${generatedToken}`
+ );
+ toast("Copied to clipboard");
+ }}
+ className="w-full"
+ >
+ Copy Command
+ </Button>
+ </div>
+ ) : null}
+ </div>
+
+ {/* Step 2 */}
+ <div
+ className={`space-y-2 ${!generatedToken ? "opacity-40 pointer-events-none" : ""}`}
+ >
+ <p className="text-xs font-medium flex items-center gap-2">
+ <span className="flex items-center justify-center size-5 rounded-full bg-foreground text-background text-[10px] font-semibold">
+ 2
+ </span>
+ Start the daemon
+ </p>
+ <p className="text-xs text-muted-foreground pl-7">
+ The daemon connects your local agents to Alook.
+ </p>
+ <div
+ className="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"
+ onClick={() =>
+ copyToClipboard("npx @alook/cli daemon start --foreground")
+ }
+ title="Click to copy"
+ >
+ npx @alook/cli daemon start --foreground
+ </div>
+ </div>
+
+ </div>
+ );
+}
+
+export default function RuntimesPage() {
+ const { runtimes, loading, handleGenerateToken, handleDeleteMachine, reload } =
+ useAgentContext();
+
+ const [sheetOpen, setSheetOpen] = useState(false);
+ const [generatedToken, setGeneratedToken] = useState("");
+ const [generatingToken, setGeneratingToken] = useState(false);
+
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [confirmTitle, setConfirmTitle] = useState("");
+ const [confirmDescription, setConfirmDescription] = useState("");
+ const [confirmLoading, setConfirmLoading] = useState(false);
+ const confirmAction = useRef<(() => Promise<void>) | null>(null);
+
+ useEffect(() => {
+ reload();
+ }, [reload]);
+
+ const openConfirm = (
+ title: string,
+ description: string,
+ action: () => Promise<void>
+ ) => {
+ setConfirmTitle(title);
+ setConfirmDescription(description);
+ confirmAction.current = action;
+ setConfirmOpen(true);
+ };
+
+ const handleConfirm = async () => {
+ if (!confirmAction.current) return;
+ setConfirmLoading(true);
+ try {
+ await confirmAction.current();
+ } finally {
+ setConfirmLoading(false);
+ setConfirmOpen(false);
+ confirmAction.current = null;
+ }
+ };
+
+ const onGenerateToken = useCallback(async () => {
+ setGeneratingToken(true);
+ try {
+ const token = await handleGenerateToken();
+ if (token) setGeneratedToken(token);
+ } finally {
+ setGeneratingToken(false);
+ }
+ }, [handleGenerateToken]);
+
+ // Group runtimes by machine
+ const machines = new Map<
+ string,
+ { deviceInfo: string; name: string; runtimes: Runtime[] }
+ >();
+ for (const rt of runtimes) {
+ const key = rt.daemon_id || rt.id;
+ if (!machines.has(key)) {
+ machines.set(key, {
+ deviceInfo: typeof rt.device_info === "string" ? rt.device_info : "",
+ name: rt.name || "",
+ runtimes: [],
+ });
+ }
+ machines.get(key)!.runtimes.push(rt);
+ }
+
+ if (loading) {
+ return (
+ <div className="flex flex-1 items-center justify-center">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ );
+ }
+
+ return (
+ <>
+ {/* Title bar */}
+ <div className="flex items-center justify-between border-b border-border/50 px-5 py-2.5">
+ <div className="flex items-center gap-3">
+ <h1 className="text-sm font-medium">Runtimes</h1>
+ <p className="text-xs text-muted-foreground">
+ Your machines and their agent runtimes.
+ </p>
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => {
+ setGeneratedToken("");
+ setSheetOpen(true);
+ }}
+ disabled={generatingToken}
+ >
+ <Plus className="size-3.5" />
+ New machine
+ </Button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-5 py-5">
+ {runtimes.length === 0 ? (
+ <div className="flex flex-1 items-center justify-center py-12">
+ <div className="text-center animate-[fade-up_400ms_ease-out_both]">
+ <p className="text-muted-foreground text-sm">
+ No machines connected.
+ </p>
+ <p className="text-xs text-muted-foreground mt-2 max-w-xs mx-auto">
+ Connect a machine to start running agents locally.
+ </p>
+ <Button
+ size="sm"
+ className="mt-5"
+ onClick={() => {
+ setGeneratedToken("");
+ setSheetOpen(true);
+ }}
+ >
+ Connect Machine
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ {Array.from(machines.entries()).map(([daemonId, machine]) => {
+ const displayName =
+ machine.deviceInfo || machine.name || daemonId;
+ return (
+ <Card key={daemonId} size="sm" className="group">
+ <CardHeader>
+ <div className="flex items-center gap-2">
+ <Monitor className="size-4 text-muted-foreground shrink-0" />
+ <CardTitle className="truncate">
+ {displayName}
+ </CardTitle>
+ </div>
+ <CardAction>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-muted-foreground h-6 px-2 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
+ onClick={() => {
+ openConfirm(
+ "Remove machine",
+ `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,
+ async () => {
+ await handleDeleteMachine(daemonId);
+ }
+ );
+ }}
+ >
+ Remove
+ </Button>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ {machine.runtimes.map((runtime) => (
+ <div
+ key={runtime.id}
+ className="flex items-center justify-between gap-2"
+ >
+ <div className="min-w-0">
+ <p className="text-xs font-medium truncate">
+ {runtime.provider}
+ {runtime.metadata?.version ? (
+ <span className="ml-1.5 font-normal text-muted-foreground">
+ {String(runtime.metadata.version)}
+ </span>
+ ) : null}
+ </p>
+ <p className="text-xs text-muted-foreground tabular-nums">
+ {new Date(
+ runtime.last_seen_at
+ ).toLocaleString()}
+ </p>
+ </div>
+ <Badge
+ variant={
+ runtime.status === "online"
+ ? "default"
+ : "outline"
+ }
+ className="shrink-0"
+ >
+ {runtime.status}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ </CardContent>
+ </Card>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* Connect machine sheet */}
+ <Sheet
+ open={sheetOpen}
+ onOpenChange={(open) => {
+ setSheetOpen(open);
+ if (!open) {
+ setGeneratedToken("");
+ }
+ }}
+ >
+ <SheetContent className="data-[side=right]:inset-y-2 data-[side=right]:right-2 data-[side=right]:h-auto data-[side=right]:rounded-xl data-[side=right]:border data-[side=right]:border-l">
+ <SheetHeader>
+ <SheetTitle>Connect a machine</SheetTitle>
+ <SheetDescription>
+ Your machine runs AI agents locally using Claude Code, Codex, or
+ OpenCode.
+ </SheetDescription>
+ </SheetHeader>
+ <SheetBody>
+ <ConnectMachineSteps
+ generatedToken={generatedToken}
+ generatingToken={generatingToken}
+ onGenerateToken={onGenerateToken}
+ />
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+
+ <ConfirmDialog
+ open={confirmOpen}
+ onOpenChange={setConfirmOpen}
+ title={confirmTitle}
+ description={confirmDescription}
+ loading={confirmLoading}
+ onConfirm={handleConfirm}
+ />
+ </>
+ );
+}
diff --git a/src/web/app/api/agents/[id]/route.test.ts b/src/web/app/api/agents/[id]/route.test.ts
index 5c2e4dd92..103de099b 100644
--- a/src/web/app/api/agents/[id]/route.test.ts
+++ b/src/web/app/api/agents/[id]/route.test.ts
@@ -58,7 +58,7 @@ describe("DELETE /api/agents/[id]", () => {
});
it("returns 404 for non-existent agent", async () => {
- mockDelete.mockResolvedValue(null);
+ mockDelete.mockResolvedValue(null as any);
const { DELETE } = await import("./route");
const res = await DELETE(
new NextRequest("http://localhost/api/agents/nope", { method: "DELETE" }),
@@ -86,7 +86,7 @@ describe("PATCH /api/agents/[id]", () => {
});
it("returns 404 for non-existent agent", async () => {
- mockUpdate.mockResolvedValue(null);
+ mockUpdate.mockResolvedValue(null as any);
const { PATCH } = await import("./route");
const res = await PATCH(
new NextRequest("http://localhost/api/agents/nope", {
diff --git a/src/web/app/api/auth/verify-code/route.test.ts b/src/web/app/api/auth/verify-code/route.test.ts
index ed5857b29..15efddca9 100644
--- a/src/web/app/api/auth/verify-code/route.test.ts
+++ b/src/web/app/api/auth/verify-code/route.test.ts
@@ -124,7 +124,7 @@ describe("POST /api/auth/verify-code", () => {
code: "123456",
} as any);
- mockGetUserByEmail.mockResolvedValue(null);
+ mockGetUserByEmail.mockResolvedValue(null as any);
const createdUser = {
id: "u2",
name: "new",
diff --git a/src/web/app/api/runtimes/machine/route.test.ts b/src/web/app/api/runtimes/machine/route.test.ts
index a66a3df90..11dbd96f2 100644
--- a/src/web/app/api/runtimes/machine/route.test.ts
+++ b/src/web/app/api/runtimes/machine/route.test.ts
@@ -19,10 +19,10 @@ vi.mock("@/lib/middleware/auth", () => ({
vi.mock("@/lib/db", () => ({ db: {} }));
vi.mock("@/lib/db/queries/runtime", () => ({
- deleteRuntimesByDaemonId: (...args: any[]) => mockDeleteRuntimes(...args),
+ deleteRuntimesByDaemonId: (...args: Parameters<typeof mockDeleteRuntimes>) => mockDeleteRuntimes(...args),
}));
vi.mock("@/lib/db/queries/member", () => ({
- getMemberByUserAndWorkspace: (...args: any[]) => mockGetMember(...args),
+ getMemberByUserAndWorkspace: (...args: Parameters<typeof mockGetMember>) => mockGetMember(...args),
}));
describe("DELETE /api/runtimes/machine", () => {
@@ -56,7 +56,7 @@ describe("DELETE /api/runtimes/machine", () => {
});
it("returns 404 when user is not a workspace member", async () => {
- mockGetMember.mockResolvedValueOnce(null);
+ mockGetMember.mockResolvedValueOnce(null as any);
const res = await DELETE(
new NextRequest(
"http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",
diff --git a/src/web/app/globals.css b/src/web/app/globals.css
index c0802b6fb..39a2a2167 100644
--- a/src/web/app/globals.css
+++ b/src/web/app/globals.css
@@ -27,6 +27,8 @@
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
+ --color-status-online: var(--status-online);
+ --color-status-offline: var(--status-offline);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
@@ -74,6 +76,8 @@
--chart-4: oklch(0.37 0.01 60);
--chart-5: oklch(0.27 0.01 60);
--radius: 0.625rem;
+ --status-online: oklch(0.72 0.19 145);
+ --status-offline: oklch(0.65 0.2 25);
--sidebar: oklch(0.98 0.005 80);
--sidebar-foreground: oklch(0.18 0.01 60);
--sidebar-primary: oklch(0.25 0.012 60);
@@ -108,6 +112,8 @@
--chart-3: oklch(0.44 0.01 60);
--chart-4: oklch(0.37 0.01 60);
--chart-5: oklch(0.27 0.01 60);
+ --status-online: oklch(0.75 0.18 145);
+ --status-offline: oklch(0.7 0.18 25);
--sidebar: oklch(0.21 0.008 60);
--sidebar-foreground: oklch(0.93 0.006 80);
--sidebar-primary: oklch(0.488 0.243 264.376);
@@ -139,6 +145,15 @@
}
}
+/* ── Utility: hide scrollbar ── */
+.scrollbar-none {
+ -ms-overflow-style: none;
+ scrollbar-width: none;
+}
+.scrollbar-none::-webkit-scrollbar {
+ display: none;
+}
+
@layer base {
* {
@apply border-border outline-ring/50;
diff --git a/src/web/components/app-sidebar.tsx b/src/web/components/app-sidebar.tsx
new file mode 100644
index 000000000..30519aed7
--- /dev/null
+++ b/src/web/components/app-sidebar.tsx
@@ -0,0 +1,124 @@
+"use client";
+
+import { useRouter, usePathname, useSearchParams } from "next/navigation";
+import { useAgentContext } from "@/contexts/agent-context";
+import { Logo } from "@/components/logo";
+import { cn } from "@/lib/utils";
+import { Monitor, LogOut, Plus, Loader2 } from "lucide-react";
+import { useState } from "react";
+
+export function AppSidebar() {
+ const router = useRouter();
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+ const { agents, loading, chatWithAgent } = useAgentContext();
+ const [navigatingAgentId, setNavigatingAgentId] = useState<string | null>(
+ null
+ );
+
+ const sorted = [...agents].sort((a, b) => a.name.localeCompare(b.name));
+
+ const isRuntimes = pathname === "/runtimes";
+ const isCreateAgent = pathname === "/agents/new";
+
+ const urlAgentId = searchParams.get("agent");
+ const activeAgentId = navigatingAgentId ?? urlAgentId;
+
+ const handleAgentClick = async (agentId: string) => {
+ setNavigatingAgentId(agentId);
+ try {
+ const conversationId = await chatWithAgent(agentId);
+ if (conversationId) {
+ router.push(`/chat/${conversationId}?agent=${agentId}`);
+ }
+ } finally {
+ setNavigatingAgentId(null);
+ }
+ };
+
+ return (
+ <nav className="flex h-full w-14 flex-col items-center py-2 gap-0.5">
+ {/* Agent avatars */}
+ <div className="flex flex-1 w-full flex-col items-center gap-1.5 overflow-y-auto py-1 scrollbar-none">
+ {loading ? (
+ <div className="flex items-center justify-center size-10">
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
+ </div>
+ ) : (
+ sorted.map((agent) => {
+ const isActive = activeAgentId === agent.id;
+ const isNavigating = navigatingAgentId === agent.id;
+ return (
+ <button
+ key={agent.id}
+ type="button"
+ title={agent.name}
+ disabled={isNavigating}
+ onClick={() => handleAgentClick(agent.id)}
+ className={cn(
+ "relative flex shrink-0 items-center justify-center size-10 rounded-xl text-sm font-medium transition-colors duration-200 cursor-pointer",
+ isActive
+ ? "bg-primary text-primary-foreground shadow-sm"
+ : "bg-secondary text-secondary-foreground hover:bg-accent",
+ isNavigating && "opacity-60"
+ )}
+ >
+ {agent.name.charAt(0).toUpperCase()}
+ </button>
+ );
+ })
+ )}
+
+ {/* Create agent */}
+ <button
+ type="button"
+ title="New agent"
+ onClick={() => router.push("/agents/new")}
+ className={cn(
+ "flex shrink-0 items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
+ "border border-dashed border-foreground/15 text-muted-foreground",
+ "hover:border-foreground/30 hover:text-foreground hover:bg-accent",
+ isCreateAgent &&
+ "border-solid border-foreground/25 bg-accent text-foreground"
+ )}
+ >
+ <Plus className="size-4" />
+ </button>
+ </div>
+
+ {/* Bottom section */}
+ <div className="flex flex-col items-center gap-1 pt-2 border-t border-border/50 mt-1">
+ <div className="mb-1">
+ <Logo size="sm" iconOnly />
+ </div>
+
+ <button
+ type="button"
+ title="Runtimes"
+ onClick={() => router.push("/runtimes")}
+ className={cn(
+ "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
+ "text-muted-foreground hover:text-foreground hover:bg-accent",
+ isRuntimes && "bg-accent text-foreground"
+ )}
+ >
+ <Monitor className="size-4" />
+ </button>
+
+ <button
+ type="button"
+ title="Sign out"
+ onClick={() => {
+ localStorage.removeItem("alook_token");
+ localStorage.removeItem("alook_workspace_id");
+ document.cookie = "alook_session=; path=/; max-age=0";
+ router.push("/login");
+ }}
+ className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
+ >
+ <LogOut className="size-4" />
+ </button>
+ </div>
+ </nav>
+ );
+}
diff --git a/src/web/components/logo.tsx b/src/web/components/logo.tsx
index f06dc1d23..72ad0487c 100644
--- a/src/web/components/logo.tsx
+++ b/src/web/components/logo.tsx
@@ -12,9 +12,11 @@ const sizes = {
export function Logo({
size = "sm",
className,
+ iconOnly = false,
}: {
size?: "sm" | "lg";
className?: string;
+ iconOnly?: boolean;
}) {
const { icon, text } = sizes[size];
const { resolvedTheme, setTheme } = useTheme();
@@ -56,12 +58,14 @@ export function Logo({
) : (
<span style={{ width: icon, height: icon }} />
)}
- <span
- className={cn(text, "font-black tracking-tight")}
- style={{ fontFamily: "var(--font-brand)" }}
- >
- Alook
- </span>
+ {!iconOnly && (
+ <span
+ className={cn(text, "font-black tracking-tight")}
+ style={{ fontFamily: "var(--font-brand)" }}
+ >
+ Alook
+ </span>
+ )}
</button>
);
}
diff --git a/src/web/contexts/agent-context.tsx b/src/web/contexts/agent-context.tsx
new file mode 100644
index 000000000..c897b2fba
--- /dev/null
+++ b/src/web/contexts/agent-context.tsx
@@ -0,0 +1,190 @@
+"use client";
+
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useState,
+ useCallback,
+ useRef,
+ type ReactNode,
+} from "react";
+import {
+ listAgents,
+ listRuntimes,
+ createAgent,
+ updateAgent,
+ deleteAgent,
+ createConversation,
+ createMachineToken,
+ deleteMachine,
+} from "@/lib/api";
+import { toast } from "sonner";
+import type {
+ Agent,
+ Runtime,
+ CreateAgentRequest,
+ UpdateAgentRequest,
+} from "@/lib/types";
+
+interface AgentContextValue {
+ agents: Agent[];
+ runtimes: Runtime[];
+ loading: boolean;
+ reload: () => Promise<void>;
+ handleCreateAgent: (req: CreateAgentRequest) => Promise<Agent | null>;
+ handleUpdateAgent: (id: string, req: UpdateAgentRequest) => Promise<boolean>;
+ handleDeleteAgent: (id: string) => Promise<boolean>;
+ chatWithAgent: (agentId: string) => Promise<string | null>;
+ getFirstOnlineRuntimeId: () => string;
+ handleGenerateToken: () => Promise<string | null>;
+ handleDeleteMachine: (daemonId: string) => Promise<boolean>;
+}
+
+const AgentContext = createContext<AgentContextValue | null>(null);
+
+export function useAgentContext() {
+ const ctx = useContext(AgentContext);
+ if (!ctx) throw new Error("useAgentContext must be used within AgentProvider");
+ return ctx;
+}
+
+export function AgentProvider({ children }: { children: ReactNode }) {
+ const [agents, setAgents] = useState<Agent[]>([]);
+ const [runtimes, setRuntimes] = useState<Runtime[]>([]);
+ const [loading, setLoading] = useState(true);
+ const loadedRef = useRef(false);
+
+ const reload = useCallback(async () => {
+ try {
+ const [a, r] = await Promise.all([listAgents(), listRuntimes()]);
+ setAgents(a);
+ setRuntimes(r);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to load data");
+ } finally {
+ setLoading(false);
+ loadedRef.current = true;
+ }
+ }, []);
+
+ useEffect(() => {
+ reload();
+ }, [reload]);
+
+ const handleCreateAgent = useCallback(
+ async (req: CreateAgentRequest): Promise<Agent | null> => {
+ try {
+ const agent = await createAgent(req);
+ await reload();
+ return agent;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to create agent"
+ );
+ return null;
+ }
+ },
+ [reload]
+ );
+
+ const handleUpdateAgent = useCallback(
+ async (id: string, req: UpdateAgentRequest): Promise<boolean> => {
+ try {
+ await updateAgent(id, req);
+ await reload();
+ return true;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to update agent"
+ );
+ return false;
+ }
+ },
+ [reload]
+ );
+
+ const handleDeleteAgent = useCallback(
+ async (id: string): Promise<boolean> => {
+ try {
+ await deleteAgent(id);
+ await reload();
+ return true;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to remove agent"
+ );
+ return false;
+ }
+ },
+ [reload]
+ );
+
+ const chatWithAgent = useCallback(
+ async (agentId: string): Promise<string | null> => {
+ try {
+ const conversation = await createConversation(agentId);
+ return conversation.id;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to start conversation"
+ );
+ return null;
+ }
+ },
+ []
+ );
+
+ const getFirstOnlineRuntimeId = useCallback(() => {
+ const first = runtimes.find((r) => r.status === "online");
+ return first?.id ?? "";
+ }, [runtimes]);
+
+ const handleGenerateToken = useCallback(async (): Promise<string | null> => {
+ try {
+ const res = await createMachineToken("cli");
+ return res.token;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to generate token"
+ );
+ return null;
+ }
+ }, []);
+
+ const handleDeleteMachine = useCallback(
+ async (daemonId: string): Promise<boolean> => {
+ try {
+ await deleteMachine(daemonId);
+ await reload();
+ return true;
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to remove machine"
+ );
+ return false;
+ }
+ },
+ [reload]
+ );
+
+ return (
+ <AgentContext.Provider
+ value={{
+ agents,
+ runtimes,
+ loading,
+ reload,
+ handleCreateAgent,
+ handleUpdateAgent,
+ handleDeleteAgent,
+ chatWithAgent,
+ getFirstOnlineRuntimeId,
+ handleGenerateToken,
+ handleDeleteMachine,
+ }}
+ >
+ {children}
+ </AgentContext.Provider>
+ );
+}
diff --git a/src/web/drizzle/0000_known_diamondback.sql b/src/web/drizzle/0000_known_diamondback.sql
new file mode 100644
index 000000000..51e2588dd
--- /dev/null
+++ b/src/web/drizzle/0000_known_diamondback.sql
@@ -0,0 +1,156 @@
+CREATE TABLE "agent" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "name" text NOT NULL,
+ "description" text DEFAULT '' NOT NULL,
+ "instructions" text DEFAULT '' NOT NULL,
+ "avatar_url" text,
+ "runtime_id" uuid,
+ "runtime_mode" text DEFAULT 'local' NOT NULL,
+ "runtime_config" jsonb,
+ "visibility" text DEFAULT 'private' NOT NULL,
+ "status" text DEFAULT 'idle' NOT NULL,
+ "max_concurrent_tasks" integer DEFAULT 6 NOT NULL,
+ "owner_id" uuid,
+ "tools" jsonb,
+ "triggers" jsonb,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "agent_runtime" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "daemon_id" text NOT NULL,
+ "name" text DEFAULT '' NOT NULL,
+ "runtime_mode" text DEFAULT 'local' NOT NULL,
+ "provider" text NOT NULL,
+ "status" text DEFAULT 'offline' NOT NULL,
+ "device_info" text DEFAULT '' NOT NULL,
+ "metadata" jsonb,
+ "last_seen_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "agent_runtime_workspace_daemon_provider" UNIQUE("workspace_id","daemon_id","provider")
+);
+--> statement-breakpoint
+CREATE TABLE "agent_task_queue" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "agent_id" uuid NOT NULL,
+ "runtime_id" uuid NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "conversation_id" uuid NOT NULL,
+ "prompt" text NOT NULL,
+ "status" text DEFAULT 'queued' NOT NULL,
+ "priority" integer DEFAULT 0 NOT NULL,
+ "result" jsonb,
+ "context" jsonb,
+ "session_id" text,
+ "work_dir" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "dispatched_at" timestamp with time zone,
+ "started_at" timestamp with time zone,
+ "completed_at" timestamp with time zone,
+ "error" text
+);
+--> statement-breakpoint
+CREATE TABLE "conversation" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "agent_id" uuid NOT NULL,
+ "user_id" uuid NOT NULL,
+ "title" text DEFAULT '' NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "machine_token" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "user_id" uuid NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "token_hash" text NOT NULL,
+ "name" text DEFAULT '' NOT NULL,
+ "last_used_at" timestamp with time zone,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "machine_token_token_hash_unique" UNIQUE("token_hash")
+);
+--> statement-breakpoint
+CREATE TABLE "member" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "workspace_id" uuid NOT NULL,
+ "user_id" uuid NOT NULL,
+ "role" text DEFAULT 'member' NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "member_workspace_user" UNIQUE("workspace_id","user_id")
+);
+--> statement-breakpoint
+CREATE TABLE "message" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "conversation_id" uuid NOT NULL,
+ "role" text NOT NULL,
+ "content" text DEFAULT '' NOT NULL,
+ "task_id" uuid,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "task_message" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "task_id" uuid NOT NULL,
+ "seq" integer NOT NULL,
+ "type" text DEFAULT '' NOT NULL,
+ "tool" text DEFAULT '' NOT NULL,
+ "content" text DEFAULT '' NOT NULL,
+ "input" jsonb,
+ "output" text DEFAULT '' NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "user" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "name" text DEFAULT '' NOT NULL,
+ "email" text NOT NULL,
+ "avatar_url" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "user_email_unique" UNIQUE("email")
+);
+--> statement-breakpoint
+CREATE TABLE "verification_code" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "email" text NOT NULL,
+ "code" text NOT NULL,
+ "used" boolean DEFAULT false NOT NULL,
+ "attempts" integer DEFAULT 0 NOT NULL,
+ "expires_at" timestamp with time zone NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+CREATE TABLE "workspace" (
+ "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
+ "name" text NOT NULL,
+ "slug" text NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "workspace_slug_unique" UNIQUE("slug")
+);
+--> statement-breakpoint
+ALTER TABLE "agent" ADD CONSTRAINT "agent_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent" ADD CONSTRAINT "agent_runtime_id_agent_runtime_id_fk" FOREIGN KEY ("runtime_id") REFERENCES "public"."agent_runtime"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent" ADD CONSTRAINT "agent_owner_id_user_id_fk" FOREIGN KEY ("owner_id") REFERENCES "public"."user"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_runtime" ADD CONSTRAINT "agent_runtime_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_agent_id_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_runtime_id_agent_runtime_id_fk" FOREIGN KEY ("runtime_id") REFERENCES "public"."agent_runtime"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "agent_task_queue" ADD CONSTRAINT "agent_task_queue_conversation_id_conversation_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversation"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "conversation" ADD CONSTRAINT "conversation_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "conversation" ADD CONSTRAINT "conversation_agent_id_agent_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agent"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "conversation" ADD CONSTRAINT "conversation_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "machine_token" ADD CONSTRAINT "machine_token_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "machine_token" ADD CONSTRAINT "machine_token_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "member" ADD CONSTRAINT "member_workspace_id_workspace_id_fk" FOREIGN KEY ("workspace_id") REFERENCES "public"."workspace"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "member" ADD CONSTRAINT "member_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "message" ADD CONSTRAINT "message_conversation_id_conversation_id_fk" FOREIGN KEY ("conversation_id") REFERENCES "public"."conversation"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "task_message" ADD CONSTRAINT "task_message_task_id_agent_task_queue_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."agent_task_queue"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE UNIQUE INDEX "idx_one_pending_per_conversation" ON "agent_task_queue" USING btree ("conversation_id") WHERE status IN ('queued', 'dispatched');--> statement-breakpoint
+CREATE INDEX "idx_task_queue_pending" ON "agent_task_queue" USING btree ("agent_id","status") WHERE status IN ('queued', 'dispatched');--> statement-breakpoint
+CREATE INDEX "idx_machine_token_hash" ON "machine_token" USING btree ("token_hash");--> statement-breakpoint
+CREATE INDEX "idx_task_message_task_seq" ON "task_message" USING btree ("task_id","seq");
\ No newline at end of file
diff --git a/src/web/drizzle/meta/0000_snapshot.json b/src/web/drizzle/meta/0000_snapshot.json
new file mode 100644
index 000000000..f81703b28
--- /dev/null
+++ b/src/web/drizzle/meta/0000_snapshot.json
@@ -0,0 +1,1142 @@
+{
+ "id": "436de5d0-fe5b-4f08-a341-8e62b871314a",
+ "prevId": "00000000-0000-0000-0000-000000000000",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.agent": {
+ "name": "agent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "instructions": {
+ "name": "instructions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runtime_id": {
+ "name": "runtime_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "runtime_mode": {
+ "name": "runtime_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local'"
+ },
+ "runtime_config": {
+ "name": "runtime_config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'idle'"
+ },
+ "max_concurrent_tasks": {
+ "name": "max_concurrent_tasks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 6
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tools": {
+ "name": "tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "triggers": {
+ "name": "triggers",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_workspace_id_workspace_id_fk": {
+ "name": "agent_workspace_id_workspace_id_fk",
+ "tableFrom": "agent",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_runtime_id_agent_runtime_id_fk": {
+ "name": "agent_runtime_id_agent_runtime_id_fk",
+ "tableFrom": "agent",
+ "tableTo": "agent_runtime",
+ "columnsFrom": [
+ "runtime_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_owner_id_user_id_fk": {
+ "name": "agent_owner_id_user_id_fk",
+ "tableFrom": "agent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_runtime": {
+ "name": "agent_runtime",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "daemon_id": {
+ "name": "daemon_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "runtime_mode": {
+ "name": "runtime_mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local'"
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'offline'"
+ },
+ "device_info": {
+ "name": "device_info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_runtime_workspace_id_workspace_id_fk": {
+ "name": "agent_runtime_workspace_id_workspace_id_fk",
+ "tableFrom": "agent_runtime",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_runtime_workspace_daemon_provider": {
+ "name": "agent_runtime_workspace_daemon_provider",
+ "nullsNotDistinct": false,
+ "columns": [
+ "workspace_id",
+ "daemon_id",
+ "provider"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_task_queue": {
+ "name": "agent_task_queue",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "runtime_id": {
+ "name": "runtime_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'queued'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "result": {
+ "name": "result",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context": {
+ "name": "context",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "work_dir": {
+ "name": "work_dir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "dispatched_at": {
+ "name": "dispatched_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_one_pending_per_conversation": {
+ "name": "idx_one_pending_per_conversation",
+ "columns": [
+ {
+ "expression": "conversation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "status IN ('queued', 'dispatched')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_task_queue_pending": {
+ "name": "idx_task_queue_pending",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "status IN ('queued', 'dispatched')",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_task_queue_agent_id_agent_id_fk": {
+ "name": "agent_task_queue_agent_id_agent_id_fk",
+ "tableFrom": "agent_task_queue",
+ "tableTo": "agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_task_queue_runtime_id_agent_runtime_id_fk": {
+ "name": "agent_task_queue_runtime_id_agent_runtime_id_fk",
+ "tableFrom": "agent_task_queue",
+ "tableTo": "agent_runtime",
+ "columnsFrom": [
+ "runtime_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_task_queue_workspace_id_workspace_id_fk": {
+ "name": "agent_task_queue_workspace_id_workspace_id_fk",
+ "tableFrom": "agent_task_queue",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "agent_task_queue_conversation_id_conversation_id_fk": {
+ "name": "agent_task_queue_conversation_id_conversation_id_fk",
+ "tableFrom": "agent_task_queue",
+ "tableTo": "conversation",
+ "columnsFrom": [
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.conversation": {
+ "name": "conversation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "conversation_workspace_id_workspace_id_fk": {
+ "name": "conversation_workspace_id_workspace_id_fk",
+ "tableFrom": "conversation",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "conversation_agent_id_agent_id_fk": {
+ "name": "conversation_agent_id_agent_id_fk",
+ "tableFrom": "conversation",
+ "tableTo": "agent",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "conversation_user_id_user_id_fk": {
+ "name": "conversation_user_id_user_id_fk",
+ "tableFrom": "conversation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.machine_token": {
+ "name": "machine_token",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_machine_token_hash": {
+ "name": "idx_machine_token_hash",
+ "columns": [
+ {
+ "expression": "token_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "machine_token_user_id_user_id_fk": {
+ "name": "machine_token_user_id_user_id_fk",
+ "tableFrom": "machine_token",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "machine_token_workspace_id_workspace_id_fk": {
+ "name": "machine_token_workspace_id_workspace_id_fk",
+ "tableFrom": "machine_token",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "machine_token_token_hash_unique": {
+ "name": "machine_token_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'member'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_workspace_id_workspace_id_fk": {
+ "name": "member_workspace_id_workspace_id_fk",
+ "tableFrom": "member",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_user_id_user_id_fk": {
+ "name": "member_user_id_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_workspace_user": {
+ "name": "member_workspace_user",
+ "nullsNotDistinct": false,
+ "columns": [
+ "workspace_id",
+ "user_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.message": {
+ "name": "message",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "message_conversation_id_conversation_id_fk": {
+ "name": "message_conversation_id_conversation_id_fk",
+ "tableFrom": "message",
+ "tableTo": "conversation",
+ "columnsFrom": [
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_message": {
+ "name": "task_message",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "input": {
+ "name": "input",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output": {
+ "name": "output",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "idx_task_message_task_seq": {
+ "name": "idx_task_message_task_seq",
+ "columns": [
+ {
+ "expression": "task_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_message_task_id_agent_task_queue_id_fk": {
+ "name": "task_message_task_id_agent_task_queue_id_fk",
+ "tableFrom": "task_message",
+ "tableTo": "agent_task_queue",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification_code": {
+ "name": "verification_code",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "code": {
+ "name": "code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "used": {
+ "name": "used",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workspace": {
+ "name": "workspace",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "workspace_slug_unique": {
+ "name": "workspace_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/src/web/drizzle/meta/_journal.json b/src/web/drizzle/meta/_journal.json
new file mode 100644
index 000000000..53d4110df
--- /dev/null
+++ b/src/web/drizzle/meta/_journal.json
@@ -0,0 +1,13 @@
+{
+ "version": "7",
+ "dialect": "postgresql",
+ "entries": [
+ {
+ "idx": 0,
+ "version": "7",
+ "when": 1775725287516,
+ "tag": "0000_known_diamondback",
+ "breakpoints": true
+ }
+ ]
+}
\ No newline at end of file
diff --git a/src/web/lib/api.test.ts b/src/web/lib/api.test.ts
index 17958d409..924bf1622 100644
--- a/src/web/lib/api.test.ts
+++ b/src/web/lib/api.test.ts
@@ -25,8 +25,8 @@ vi.stubGlobal("fetch", mockFetch);
// Prevent 401 redirect from blowing up
Object.defineProperty(globalThis, "window", {
value: {
+ ...(globalThis.window || {}),
location: { href: "" },
- ...globalThis.window,
},
writable: true,
});
diff --git a/src/web/lib/db/queries/agent.ts b/src/web/lib/db/queries/agent.ts
index dbcd68ef9..d19802d7d 100644
--- a/src/web/lib/db/queries/agent.ts
+++ b/src/web/lib/db/queries/agent.ts
@@ -1,5 +1,5 @@
import { eq, and, desc, sql } from "drizzle-orm";
-import { agent } from "../schema";
+import { agent, agentTaskQueue } from "../schema";
import type { Database } from "../index";
export async function getAgent(db: Database, id: string) {
@@ -71,11 +71,16 @@ export async function deleteAgent(
id: string,
workspaceId: string
) {
- const rows = await db
- .delete(agent)
- .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)))
- .returning();
- return rows[0] ?? null;
+ return db.transaction(async (tx) => {
+ await tx
+ .delete(agentTaskQueue)
+ .where(eq(agentTaskQueue.agentId, id));
+ const rows = await tx
+ .delete(agent)
+ .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+ });
}
export async function updateAgent(
diff --git a/src/web/lib/db/schema.ts b/src/web/lib/db/schema.ts
index 301c31334..294b3a448 100644
--- a/src/web/lib/db/schema.ts
+++ b/src/web/lib/db/schema.ts
@@ -126,7 +126,7 @@ export const agentTaskQueue = pgTable(
id: uuid("id").primaryKey().defaultRandom(),
agentId: uuid("agent_id")
.notNull()
- .references(() => agent.id),
+ .references(() => agent.id, { onDelete: "cascade" }),
runtimeId: uuid("runtime_id")
.notNull()
.references(() => agentRuntime.id),
diff --git a/src/web/lib/middleware/auth.test.ts b/src/web/lib/middleware/auth.test.ts
index 2eb2eedbf..00c3f1306 100644
--- a/src/web/lib/middleware/auth.test.ts
+++ b/src/web/lib/middleware/auth.test.ts
@@ -53,7 +53,7 @@ describe("withAuth", () => {
});
it("authenticates valid JWT and passes userId/email to handler", async () => {
- mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", iat: 0, exp: 0 });
+ mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", name: "" });
const wrapped = withAuth(handler);
const res = await wrapped(makeReq({ Authorization: "Bearer valid-jwt" }));
expect(res.status).toBe(200);
@@ -120,7 +120,7 @@ describe("withAuth", () => {
});
it("resolves dynamic params from context", async () => {
- mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", iat: 0, exp: 0 });
+ mockVerifyJWT.mockResolvedValue({ sub: "u1", email: "[email protected]", name: "" });
const paramHandler = vi.fn(async (_req, ctx) =>
NextResponse.json({ taskId: ctx.params?.taskId }),
);
diff --git a/src/web/lib/middleware/auth.ts b/src/web/lib/middleware/auth.ts
index 111e0ca28..42f969af3 100644
--- a/src/web/lib/middleware/auth.ts
+++ b/src/web/lib/middleware/auth.ts
@@ -11,7 +11,7 @@ export interface AuthContext {
export type AuthenticatedHandler = (
req: NextRequest,
ctx: AuthContext & { params?: Record<string, string> }
-) => Promise<NextResponse>;
+) => Promise<NextResponse | Response>;
export function withAuth(handler: AuthenticatedHandler) {
return async (
diff --git a/src/web/lib/services/task.test.ts b/src/web/lib/services/task.test.ts
index 9054dabd3..198c5d9e6 100644
--- a/src/web/lib/services/task.test.ts
+++ b/src/web/lib/services/task.test.ts
@@ -24,7 +24,7 @@ beforeEach(() => {
describe("TaskService", () => {
describe("enqueueTask", () => {
it("throws when agent not found", async () => {
- mockAgentQueries.getAgent.mockResolvedValue(null);
+ mockAgentQueries.getAgent.mockResolvedValue(null as any);
const svc = makeService();
await expect(
svc.enqueueTask("a1", "c1", "w1", "do stuff")
@@ -72,7 +72,7 @@ describe("TaskService", () => {
describe("claimTask", () => {
it("returns null when agent not found", async () => {
- mockAgentQueries.getAgent.mockResolvedValue(null);
+ mockAgentQueries.getAgent.mockResolvedValue(null as any);
const svc = makeService();
expect(await svc.claimTask("a1")).toBeNull();
});
@@ -137,7 +137,7 @@ describe("TaskService", () => {
{ agentId: "a2", runtimeId: "rt1" },
] as any);
- mockAgentQueries.getAgent.mockResolvedValue(null);
+ mockAgentQueries.getAgent.mockResolvedValue(null as any);
const svc = makeService();
await svc.claimTaskForRuntime("rt1");
@@ -149,7 +149,7 @@ describe("TaskService", () => {
describe("startTask", () => {
it("throws when not in dispatched status", async () => {
- mockTaskQueries.startTask.mockResolvedValue(null);
+ mockTaskQueries.startTask.mockResolvedValue(null as any);
const svc = makeService();
await expect(svc.startTask("t1")).rejects.toThrow(
"task not in dispatched status"