Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: update ui and logo

Gus83baf7bd90cd
diff --git a/.gitignore b/.gitignore
index 47ffd1b6b..e469c6b49 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+.impeccable.md
.agents
.claude
# Logs
diff --git a/AGENTS.md b/AGENTS.md
index 4f9185d6c..b5bacdabf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -21,4 +21,7 @@ Alook's main purpose is to make the cli agent always on, and give it a email add
- never report to me about your code changes without running tests first.
- always write tests for your code changes, only when your code changes are already covered by the current tests.
-## Don't use plan MODE, try to write the plan md directly
\ No newline at end of file
+## Don't use plan MODE, try to write the plan md directly
+
+## UIUX
+read @DESIGN.md
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 000000000..7a8d7695f
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
+read @AGENTS.md
\ No newline at end of file
diff --git a/DESIGN.md b/DESIGN.md
new file mode 100644
index 000000000..72c54654d
--- /dev/null
+++ b/DESIGN.md
@@ -0,0 +1,51 @@
+## Design Context
+
+### Users
+Power users and tasteful hackers who want always-on AI agents with a minimalist, collaborative approach. They value control over their infrastructure, appreciate good tooling, and have strong aesthetic sensibilities. They use Alook in focused work sessions — managing agents, reviewing task output, and iterating on instructions.
+
+### Brand Personality
+**Warm, precise, and utilitarian.** Alook feels like a well-crafted tool made by someone who cares — not cold and corporate, not flashy and consumer. It earns trust through restraint and clarity. Every element has a reason.
+
+3-word personality: **Warm. Sharp. Purposeful.**
+
+Emotional goals: confidence, calm focus, quiet delight in small details.
+
+### Aesthetic Direction
+**Visual tone**: Notion-inspired warmth meets developer-tool precision. Soft neutral palette (warm grays, cream tints) with crisp typography and intentional micro-interactions. Light and airy in light mode, cozy and focused in dark mode.
+
+**References**: Notion (polished, warm, delightful micro-interactions)
+
+**Anti-references**:
+- Generic SaaS dashboards (blue buttons, card grids, cookie-cutter layouts)
+- AI chatbot UIs (ChatGPT-style centered chat with big rounded bubbles and gradients)
+- Playful/consumer apps (bright colors, illustrations, emoji-heavy, gamification)
+
+**Theme**: Both light and dark as first-class citizens. Warm-tinted neutrals in both modes — never pure gray.
+
+### Design Principles
+
+1. **Every pixel earns its place** — No decorative filler. If an element doesn't help the user accomplish their goal, remove it. Whitespace is a feature, not wasted space.
+
+2. **Warm precision** — Technical doesn't mean cold. Use warm color tints, generous spacing, and thoughtful transitions to make the tool feel human without being cute.
+
+3. **Progressive disclosure** — Start simple, reveal depth through interaction. The interface should feel approachable on first use and powerful on the hundredth.
+
+4. **Motion with meaning** — Animate state changes to orient the user, not to impress. A well-timed 200ms transition beats a flashy 2-second animation.
+
+5. **Respect the craft** — This is a tool for people who appreciate good tools. Match the quality they expect from their best CLI utilities — fast, predictable, and delightful in the details.
+
+### Progressive disclosure
+
+Never show all options at once. Complexity exists but stays one interaction away.
+
+- **Hover to preview** — hovering a linked page shows a preview without navigating. Tooltips appear contextually, not eagerly.
+- **Click to expand** — sidebar tree nodes, dropdown menus, and kanban column options are collapsed by default. Expanded state is driven by user action, not by default.
+- **Scrolling reveals depth** — additional features and settings appear as the user scrolls or explores. The first screen is always clean.
+
+## Visual Harmony
+
+Every pixel should reduce mental load, not add it. Whitespace, typography, and hierarchy aren't cosmetic — they're how brains process information.
+
+- The UI should fade into the background. If a user notices the tool instead of their content, something is wrong.
+- Aim for visual calm: Japanese minimalism, Bauhaus clarity. No decoration that doesn't serve comprehension.
+- If a feature makes the interface more complicated without making it more powerful, cut it.
\ No newline at end of file
diff --git a/assets/alook-dark.svg b/assets/alook-dark.svg
index 98abc1a56..8a0d24878 100644
--- a/assets/alook-dark.svg
+++ b/assets/alook-dark.svg
@@ -1,4 +1,4 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="3 5 22 22" fill="none">
<!-- Back block (shadow) — warm umber, softer than gray -->
<rect x="4" y="6" width="18" height="18" rx="3" fill="#8a7a6c" opacity="0.42" />
<!-- Front block — cream / warm paper, not pure white -->
diff --git a/assets/alook.svg b/assets/alook.svg
index 88672e8b1..21770a386 100644
--- a/assets/alook.svg
+++ b/assets/alook.svg
@@ -1,4 +1,4 @@
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="currentColor">
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="3 5 22 22" fill="currentColor">
<!-- Back block (shadow) — rounder corners -->
<rect x="4" y="6" width="18" height="18" rx="3" opacity="0.4" />
<!-- Front block -->
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 64ecea403..0a960f135 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -90,6 +90,9 @@ importers:
shadcn:
specifier: ^4.2.0
version: 4.2.0(@types/[email protected])([email protected])
+ sonner:
+ specifier: ^2.0.7
tailwind-merge:
specifier: ^3.5.0
version: 3.5.0
@@ -3646,6 +3649,12 @@ packages:
resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
+ resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==}
+ peerDependencies:
+ react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+ react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc
+
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
@@ -6011,8 +6020,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.2
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.0.1([email protected]([email protected]))
@@ -6034,7 +6043,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -6045,22 +6054,22 @@ snapshots:
tinyglobby: 0.2.16
unrs-resolver: 1.11.1
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.58.1([email protected]([email protected]))([email protected])
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -6071,7 +6080,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.2
is-core-module: 2.16.1
is-glob: 4.0.3
@@ -7600,6 +7609,11 @@ snapshots:
+ dependencies:
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+
diff --git a/src/web/app/(app)/agents/page.tsx b/src/web/app/(app)/agents/page.tsx
index 2002b6507..f7c38b949 100644
--- a/src/web/app/(app)/agents/page.tsx
+++ b/src/web/app/(app)/agents/page.tsx
@@ -1,328 +1,14 @@
"use client";
-import { useEffect, useState, useCallback } from "react";
+import { useEffect } from "react";
import { useRouter } from "next/navigation";
-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 {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import {
- listAgents,
- listRuntimes,
- createAgent,
- createConversation,
- createMachineToken,
-} from "@/lib/api";
-import { ThemeToggle } from "@/components/theme-toggle";
-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;
- }
-}
-
-export default function AgentsPage() {
+export default function AgentsRedirect() {
const router = useRouter();
- const [agents, setAgents] = useState<Agent[]>([]);
- const [runtimes, setRuntimes] = useState<Runtime[]>([]);
- const [loading, setLoading] = useState(true);
- const [dialogOpen, setDialogOpen] = useState(false);
- const [creating, setCreating] = useState(false);
- const [tokenDialogOpen, setTokenDialogOpen] = useState(false);
- const [generatedToken, setGeneratedToken] = useState("");
- const [generatingToken, setGeneratingToken] = useState(false);
- const [tokenCopied, setTokenCopied] = useState(false);
-
- const [name, setName] = useState("");
- const [description, setDescription] = useState("");
- const [instructions, setInstructions] = useState("");
- const [runtimeId, setRuntimeId] = useState("");
-
- const loadData = useCallback(async () => {
- try {
- const [a, r] = await Promise.all([listAgents(), listRuntimes()]);
- setAgents(a);
- setRuntimes(r);
- if (r.length > 0 && !runtimeId) {
- setRuntimeId(r[0].id);
- }
- } catch {
- // handled by api client (401 redirect)
- } finally {
- setLoading(false);
- }
- }, [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,
- });
- setDialogOpen(false);
- setName("");
- setDescription("");
- setInstructions("");
- await loadData();
- } catch {
- // TODO: show error
- } finally {
- setCreating(false);
- }
- };
-
- const handleChat = async (agent: Agent) => {
- try {
- const conversation = await createConversation(agent.id);
- router.push(`/chat/${conversation.id}`);
- } catch {
- // TODO: show error
- }
- };
-
- const handleGenerateToken = async () => {
- setGeneratingToken(true);
- setTokenCopied(false);
- try {
- const res = await createMachineToken("cli");
- setGeneratedToken(res.token);
- } catch {
- // TODO: show error
- } finally {
- setGeneratingToken(false);
- }
- };
-
- const handleCopyToken = async () => {
- await navigator.clipboard.writeText(generatedToken);
- setTokenCopied(true);
- };
-
- const runtimeMap = new Map(runtimes.map((r) => [r.id, r]));
-
- if (loading) {
- return (
- <div className="flex min-h-screen items-center justify-center">
- <p className="text-muted-foreground">Loading...</p>
- </div>
- );
- }
-
- return (
- <div className="min-h-screen bg-background">
- <header className="border-b">
- <div className="mx-auto flex max-w-4xl items-center justify-between px-6 py-4">
- <h1 className="text-xl font-semibold tracking-tight">Agents</h1>
- <div className="flex items-center gap-3">
- <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
- <DialogTrigger render={<Button />}>
- Create Agent
- </DialogTrigger>
- <DialogContent>
- <form onSubmit={handleCreate}>
- <DialogHeader>
- <DialogTitle>Create Agent</DialogTitle>
- <DialogDescription>
- Set up a new AI agent to work with.
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-4 py-4">
- <div className="space-y-2">
- <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-2">
- <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-2">
- <Label htmlFor="agent-instructions">Instructions</Label>
- <Textarea
- id="agent-instructions"
- value={instructions}
- onChange={(e) => setInstructions(e.target.value)}
- placeholder="System prompt or instructions for the agent..."
- rows={4}
- />
- </div>
- <div className="space-y-2">
- <Label htmlFor="agent-runtime">Runtime</Label>
- <select
- id="agent-runtime"
- className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- value={runtimeId}
- onChange={(e) => setRuntimeId(e.target.value)}
- required
- >
- {runtimes.length === 0 && (
- <option value="" disabled>
- No runtimes available — start a daemon
- </option>
- )}
- {runtimes.map((r) => (
- <option key={r.id} value={r.id}>
- {r.provider} ({r.status})
- </option>
- ))}
- </select>
- </div>
- </div>
- <DialogFooter>
- <Button type="submit" disabled={creating || !runtimeId}>
- {creating ? "Creating..." : "Create"}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- <Dialog
- open={tokenDialogOpen}
- onOpenChange={(open) => {
- setTokenDialogOpen(open);
- if (!open) {
- setGeneratedToken("");
- setTokenCopied(false);
- }
- }}
- >
- <DialogTrigger render={<Button variant="outline" />}>
- CLI Token
- </DialogTrigger>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>CLI Token</DialogTitle>
- <DialogDescription>
- Generate a token to register the CLI and daemon.
- </DialogDescription>
- </DialogHeader>
- {generatedToken ? (
- <div className="space-y-3 py-2">
- <div className="rounded-md bg-muted p-3 font-mono text-sm break-all select-all">
- {generatedToken}
- </div>
- <p className="text-xs text-muted-foreground">
- Copy this token now — it won&apos;t be shown again.
- </p>
- <div className="flex gap-2">
- <Button onClick={handleCopyToken} className="flex-1">
- {tokenCopied ? "Copied!" : "Copy Token"}
- </Button>
- </div>
- <div className="rounded-md border p-3 text-xs font-mono text-muted-foreground">
- alook register --token {generatedToken}
- </div>
- </div>
- ) : (
- <DialogFooter>
- <Button onClick={handleGenerateToken} disabled={generatingToken}>
- {generatingToken ? "Generating..." : "Generate Token"}
- </Button>
- </DialogFooter>
- )}
- </DialogContent>
- </Dialog>
- <ThemeToggle />
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- localStorage.removeItem("alook_token");
- localStorage.removeItem("alook_workspace_id");
- document.cookie = "alook_session=; path=/; max-age=0";
- router.push("/login");
- }}
- >
- Sign Out
- </Button>
- </div>
- </div>
- </header>
+ router.replace("/home");
+ }, [router]);
- <main className="mx-auto max-w-4xl px-6 py-8">
- {agents.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-20 text-center">
- <p className="text-muted-foreground mb-4">No agents yet.</p>
- <p className="text-sm text-muted-foreground">
- Make sure a daemon is running, then create an agent.
- </p>
- </div>
- ) : (
- <div className="grid gap-4 sm:grid-cols-2">
- {agents.map((agent) => {
- const runtime = runtimeMap.get(agent.runtime_id);
- return (
- <Card
- key={agent.id}
- className="cursor-pointer transition-colors hover:bg-accent/50"
- onClick={() => handleChat(agent)}
- >
- <CardHeader className="pb-2">
- <div className="flex items-start justify-between">
- <CardTitle className="text-base">{agent.name}</CardTitle>
- <Badge variant={statusVariant(agent.status)}>
- {agent.status}
- </Badge>
- </div>
- {agent.description && (
- <CardDescription className="line-clamp-2">
- {agent.description}
- </CardDescription>
- )}
- </CardHeader>
- <CardContent>
- <p className="text-xs text-muted-foreground">
- Runtime: {runtime?.provider ?? "unknown"} (
- {runtime?.status ?? "offline"})
- </p>
- </CardContent>
- </Card>
- );
- })}
- </div>
- )}
- </main>
- </div>
- );
+ return null;
}
diff --git a/src/web/app/(app)/chat/[id]/page.tsx b/src/web/app/(app)/chat/[id]/page.tsx
index ec59dc789..d834d5083 100644
--- a/src/web/app/(app)/chat/[id]/page.tsx
+++ b/src/web/app/(app)/chat/[id]/page.tsx
@@ -14,7 +14,8 @@ import {
getTaskMessages,
} from "@/lib/api";
import type { Conversation, Message, Task, TaskMessage } from "@/lib/types";
-import { ThemeToggle } from "@/components/theme-toggle";
+import { Logo } from "@/components/logo";
+import { toast } from "sonner";
export default function ChatPage() {
const params = useParams();
@@ -29,9 +30,12 @@ export default function ChatPage() {
const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);
const [loading, setLoading] = useState(true);
+ const [connectionLost, setConnectionLost] = useState(false);
+
const scrollRef = useRef<HTMLDivElement>(null);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const lastSeqRef = useRef(0);
+ const pollFailures = useRef(0);
const scrollToBottom = useCallback(() => {
setTimeout(() => {
@@ -52,6 +56,7 @@ export default function ChatPage() {
setConversation(conv);
setMessages(msgs);
} catch {
+ toast.error("Conversation not found");
router.push("/agents");
} finally {
setLoading(false);
@@ -68,6 +73,8 @@ export default function ChatPage() {
(taskId: string) => {
if (pollRef.current) clearInterval(pollRef.current);
lastSeqRef.current = 0;
+ pollFailures.current = 0;
+ setConnectionLost(false);
pollRef.current = setInterval(async () => {
try {
@@ -76,6 +83,8 @@ export default function ChatPage() {
getTaskMessages(taskId, lastSeqRef.current || undefined),
]);
+ pollFailures.current = 0;
+ setConnectionLost(false);
setActiveTask(task);
if (tmsgs.length > 0) {
@@ -90,13 +99,25 @@ export default function ChatPage() {
if (pollRef.current) clearInterval(pollRef.current);
pollRef.current = null;
- const updatedMessages = await listMessages(conversationId);
- setMessages(updatedMessages);
+ try {
+ const updatedMessages = await listMessages(conversationId);
+ setMessages(updatedMessages);
+ } catch {
+ toast.error("Failed to refresh messages");
+ }
setActiveTask(null);
setTaskMessages([]);
}
} catch {
- // ignore polling errors
+ pollFailures.current += 1;
+ if (pollFailures.current >= 3) {
+ setConnectionLost(true);
+ }
+ if (pollFailures.current >= 10) {
+ if (pollRef.current) clearInterval(pollRef.current);
+ pollRef.current = null;
+ toast.error("Lost connection to agent");
+ }
}
}, 1000);
},
@@ -133,9 +154,10 @@ export default function ChatPage() {
setActiveTask(task);
setTaskMessages([]);
startPolling(task.id);
- } catch {
+ } catch (err) {
setMessages((prev) => prev.filter((m) => m.id !== optimistic.id));
setInput(content);
+ toast.error(err instanceof Error ? err.message : "Failed to send message");
} finally {
setSending(false);
}
@@ -168,7 +190,7 @@ export default function ChatPage() {
{conversation?.title || "Chat"}
</h1>
</div>
- <ThemeToggle />
+ <Logo />
</header>
<div className="flex-1 overflow-y-auto px-6" ref={scrollRef}>
@@ -237,6 +259,11 @@ export default function ChatPage() {
{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>
diff --git a/src/web/app/(app)/error.tsx b/src/web/app/(app)/error.tsx
new file mode 100644
index 000000000..1ca1e61be
--- /dev/null
+++ b/src/web/app/(app)/error.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+
+export default function AppError({
+ reset,
+}: {
+ error: Error & { digest?: string };
+ reset: () => void;
+}) {
+ return (
+ <div className="flex min-h-screen items-center justify-center bg-background p-4">
+ <div className="text-center space-y-4 max-w-sm">
+ <h2 className="text-lg font-medium tracking-tight">
+ Something went wrong
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ An unexpected error occurred. Please try again.
+ </p>
+ <Button onClick={reset}>Try again</Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/web/app/(app)/home/page.tsx b/src/web/app/(app)/home/page.tsx
new file mode 100644
index 000000000..4bbd1d247
--- /dev/null
+++ b/src/web/app/(app)/home/page.tsx
@@ -0,0 +1,994 @@
+"use client";
+
+import { useEffect, useState, useCallback, useRef } from "react";
+import { useRouter } from "next/navigation";
+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,
+ SheetTrigger,
+} from "@/components/ui/sheet";
+import {
+ listAgents,
+ listRuntimes,
+ createAgent,
+ updateAgent,
+ createConversation,
+ createMachineToken,
+ deleteMachine,
+ deleteAgent,
+} from "@/lib/api";
+import { ConfirmDialog } from "@/components/ui/confirm-dialog";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+ SelectGroup,
+ SelectGroupLabel,
+} from "@/components/ui/select";
+import { Logo } from "@/components/logo";
+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;
+ }
+}
+
+function OnboardingSteps({
+ generatedToken,
+ generatingToken,
+ tokenCopied,
+ onGenerateToken,
+ onCopyToken,
+}: {
+ generatedToken: string;
+ generatingToken: boolean;
+ tokenCopied: boolean;
+ onGenerateToken: () => void;
+ onCopyToken: () => void;
+}) {
+ // Auto-generate token on mount
+ 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">
+ <div>
+ <p className="text-sm font-medium tracking-tight">
+ Connect a machine
+ </p>
+ <p className="text-xs text-muted-foreground mt-1">
+ Your machine runs AI agents locally using Claude Code, Codex, or
+ OpenCode.
+ </p>
+ </div>
+
+ {/* Step 1 — Register CLI */}
+ <div className="space-y-2">
+ <p className="text-xs font-medium flex items-center gap-2">
+ <span className="flex items-center justify-center w-5 h-5 rounded-full bg-foreground text-background text-[10px] font-semibold">
+ 1
+ </span>
+ Register your CLI
+ </p>
+ <p className="text-[11px] 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 — Start daemon */}
+ <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 w-5 h-5 rounded-full bg-foreground text-background text-[10px] font-semibold">
+ 2
+ </span>
+ Start the daemon
+ </p>
+ <p className="text-[11px] 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 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 [runtimeSheetOpen, setRuntimeSheetOpen] = useState(false);
+ const [creating, setCreating] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [generatedToken, setGeneratedToken] = useState("");
+ const [generatingToken, setGeneratingToken] = useState(false);
+ const [tokenCopied, setTokenCopied] = 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 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("");
+
+ // Edit form state
+ const [editName, setEditName] = useState("");
+ const [editDescription, setEditDescription] = useState("");
+ const [editInstructions, setEditInstructions] = useState("");
+ const [editRuntimeId, setEditRuntimeId] = useState("");
+
+ 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);
+ } else {
+ setRuntimeId("");
+ }
+ } 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 handleGenerateToken = async () => {
+ setGeneratingToken(true);
+ setTokenCopied(false);
+ try {
+ const res = await createMachineToken("cli");
+ setGeneratedToken(res.token);
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? err.message : "Failed to generate token"
+ );
+ } finally {
+ setGeneratingToken(false);
+ }
+ };
+
+ const handleCopyToken = async () => {
+ await navigator.clipboard.writeText(generatedToken);
+ setTokenCopied(true);
+ toast("Copied to clipboard");
+ };
+
+ const runtimeMap = new Map(runtimes.map((r) => [r.id, r]));
+
+ if (loading) {
+ return (
+ <div className="min-h-screen bg-background">
+ <header className="border-b">
+ <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">
+ <div className="flex items-center gap-2.5">
+ <div className="h-7 w-7 rounded-md bg-muted animate-pulse" />
+ <div className="h-5 w-16 rounded bg-muted animate-pulse" />
+ </div>
+ <div className="flex items-center gap-2">
+ <div className="h-7 w-24 rounded-md bg-muted animate-pulse" />
+ <div className="h-7 w-20 rounded-md bg-muted animate-pulse" />
+ </div>
+ </div>
+ </header>
+ <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>
+ );
+ }
+
+ return (
+ <div className="min-h-screen bg-background">
+ {/* ── Header ── */}
+ <header className="border-b">
+ <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">
+ <Logo />
+
+ {/* Right: Actions */}
+ <div className="flex items-center gap-1.5">
+ <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>
+
+ <Sheet
+ open={runtimeSheetOpen}
+ onOpenChange={(open) => {
+ setRuntimeSheetOpen(open);
+ if (!open) {
+ setGeneratedToken("");
+ setTokenCopied(false);
+ }
+ }}
+ >
+ <SheetTrigger render={<Button variant="outline" size="sm" />}>
+ Runtimes
+ </SheetTrigger>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Runtimes</SheetTitle>
+ <SheetDescription>
+ Your machines and their agent runtimes.
+ </SheetDescription>
+ </SheetHeader>
+ <SheetBody>
+ {runtimes.length === 0 ? (
+ /* ── Onboarding: Connect a machine ── */
+ <OnboardingSteps
+ generatedToken={generatedToken}
+ generatingToken={generatingToken}
+ tokenCopied={tokenCopied}
+ onGenerateToken={handleGenerateToken}
+ onCopyToken={handleCopyToken}
+ />
+ ) : (
+ /* ── Machines list ── */
+ <div className="space-y-3">
+ {(() => {
+ // Group runtimes by daemon_id (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);
+ }
+
+ return Array.from(machines.entries()).map(
+ ([daemonId, machine]) => {
+ const displayName =
+ machine.deviceInfo || machine.name || daemonId;
+
+ return (
+ <div
+ key={daemonId}
+ className="rounded-lg border p-3.5 space-y-3"
+ >
+ {/* Machine header */}
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium tracking-tight">
+ {displayName}
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-[11px] text-muted-foreground h-6 px-2 hover:text-destructive"
+ onClick={() => {
+ openConfirm(
+ "Remove machine",
+ `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,
+ async () => {
+ try {
+ await deleteMachine(daemonId);
+ const r = await listRuntimes();
+ setRuntimes(r);
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? err.message
+ : "Failed to remove machine"
+ );
+ }
+ }
+ );
+ }}
+ >
+ Remove
+ </Button>
+ </div>
+
+ {/* Nested runtimes */}
+ <div className="space-y-2 pl-0.5">
+ {machine.runtimes.map((runtime) => (
+ <div
+ key={runtime.id}
+ className="rounded-md border border-dashed p-2.5 space-y-1"
+ >
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium">
+ {runtime.provider}
+ {runtime.metadata?.version ? (
+ <span className="ml-1.5 font-normal text-muted-foreground">
+ {String(runtime.metadata.version)}
+ </span>
+ ) : null}
+ </span>
+ <Badge
+ variant={
+ runtime.status === "online"
+ ? "default"
+ : "outline"
+ }
+ className="text-[10px] px-1.5 py-0"
+ >
+ {runtime.status}
+ </Badge>
+ </div>
+ <p className="text-[11px] text-muted-foreground tabular-nums">
+ Last seen{" "}
+ {new Date(
+ runtime.last_seen_at
+ ).toLocaleString()}
+ </p>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+ }
+ );
+ })()}
+
+ {/* Connect another machine */}
+ <div className="pt-3 border-t">
+ {generatedToken ? (
+ <div className="space-y-2">
+ <div className="rounded-md bg-muted p-2.5 font-mono text-xs break-all select-all">
+ {generatedToken}
+ </div>
+ <p className="text-[11px] text-muted-foreground">
+ Copy this token now — it won&apos;t be shown again.
+ </p>
+ <Button
+ size="sm"
+ onClick={handleCopyToken}
+ className="w-full"
+ >
+ {tokenCopied ? "Copied!" : "Copy Token"}
+ </Button>
+ </div>
+ ) : (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={handleGenerateToken}
+ disabled={generatingToken}
+ className="w-full text-xs text-muted-foreground"
+ >
+ {generatingToken
+ ? "Generating..."
+ : "Connect new machine"}
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => {
+ localStorage.removeItem("alook_token");
+ localStorage.removeItem("alook_workspace_id");
+ document.cookie = "alook_session=; path=/; max-age=0";
+ router.push("/login");
+ }}
+ >
+ Sign Out
+ </Button>
+ </div>
+ </div>
+ </header>
+
+ {/* ── 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>
+ <Button
+ size="sm"
+ className="mt-5"
+ onClick={() => setCreateSheetOpen(true)}
+ >
+ 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
+ }
+ >
+ <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>
+ )}
+ </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>
+ );
+}
diff --git a/src/web/app/api/agents/[id]/route.test.ts b/src/web/app/api/agents/[id]/route.test.ts
index 940031c1a..5c2e4dd92 100644
--- a/src/web/app/api/agents/[id]/route.test.ts
+++ b/src/web/app/api/agents/[id]/route.test.ts
@@ -16,8 +16,10 @@ vi.mock("@/lib/api/responses", () => ({
agentToResponse: vi.fn((a: any) => ({ id: a.id })),
}));
-import { getAgentInWorkspace } from "@/lib/db/queries/agent";
+import { getAgentInWorkspace, deleteAgent, updateAgent } from "@/lib/db/queries/agent";
const mockGet = vi.mocked(getAgentInWorkspace);
+const mockDelete = vi.mocked(deleteAgent);
+const mockUpdate = vi.mocked(updateAgent);
beforeEach(() => vi.clearAllMocks());
@@ -42,3 +44,69 @@ describe("GET /api/agents/[id]", () => {
expect(res.status).toBe(404);
});
});
+
+describe("DELETE /api/agents/[id]", () => {
+ it("returns 204 on successful deletion", async () => {
+ mockDelete.mockResolvedValue({ id: "a1" } as any);
+ const { DELETE } = await import("./route");
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" }),
+ { params: Promise.resolve({ id: "a1" }) },
+ );
+ expect(res.status).toBe(204);
+ expect(mockDelete).toHaveBeenCalledWith({}, "a1", "w1");
+ });
+
+ it("returns 404 for non-existent agent", async () => {
+ mockDelete.mockResolvedValue(null);
+ const { DELETE } = await import("./route");
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/agents/nope", { method: "DELETE" }),
+ { params: Promise.resolve({ id: "nope" }) },
+ );
+ expect(res.status).toBe(404);
+ const body = await res.json();
+ expect(body.error).toBe("agent not found");
+ });
+});
+
+describe("PATCH /api/agents/[id]", () => {
+ it("updates agent and returns response", async () => {
+ mockUpdate.mockResolvedValue({ id: "a1", name: "Updated" } as any);
+ const { PATCH } = await import("./route");
+ const res = await PATCH(
+ new NextRequest("http://localhost/api/agents/a1", {
+ method: "PATCH",
+ body: JSON.stringify({ name: "Updated" }),
+ }),
+ { params: Promise.resolve({ id: "a1" }) },
+ );
+ expect(res.status).toBe(200);
+ expect(mockUpdate).toHaveBeenCalledWith({}, "a1", "w1", { name: "Updated" });
+ });
+
+ it("returns 404 for non-existent agent", async () => {
+ mockUpdate.mockResolvedValue(null);
+ const { PATCH } = await import("./route");
+ const res = await PATCH(
+ new NextRequest("http://localhost/api/agents/nope", {
+ method: "PATCH",
+ body: JSON.stringify({ name: "X" }),
+ }),
+ { params: Promise.resolve({ id: "nope" }) },
+ );
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 400 when no fields provided", async () => {
+ const { PATCH } = await import("./route");
+ const res = await PATCH(
+ new NextRequest("http://localhost/api/agents/a1", {
+ method: "PATCH",
+ body: JSON.stringify({}),
+ }),
+ { params: Promise.resolve({ id: "a1" }) },
+ );
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/src/web/app/api/agents/[id]/route.ts b/src/web/app/api/agents/[id]/route.ts
index 19df5de09..4db405b7c 100644
--- a/src/web/app/api/agents/[id]/route.ts
+++ b/src/web/app/api/agents/[id]/route.ts
@@ -1,5 +1,5 @@
import { db } from "@/lib/db";
-import { getAgentInWorkspace } from "@/lib/db/queries/agent";
+import { getAgentInWorkspace, deleteAgent, updateAgent } from "@/lib/db/queries/agent";
import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError } from "@/lib/middleware/helpers";
@@ -21,3 +21,54 @@ export const GET = withAuth(async (req, ctx) => {
return writeJSON(agentToResponse(agent));
});
+
+export const PATCH = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const id = ctx.params?.id;
+ if (!id) {
+ return writeError("agent id is required", 400);
+ }
+
+ let body: Record<string, unknown>;
+ try {
+ body = await req.json();
+ } catch {
+ return writeError("invalid request body", 400);
+ }
+
+ const data: Record<string, unknown> = {};
+ if (typeof body.name === "string") data.name = body.name;
+ if (typeof body.description === "string") data.description = body.description;
+ if (typeof body.instructions === "string") data.instructions = body.instructions;
+ if (typeof body.runtime_id === "string") data.runtimeId = body.runtime_id;
+
+ if (Object.keys(data).length === 0) {
+ return writeError("no fields to update", 400);
+ }
+
+ const updated = await updateAgent(db, id, ws.workspaceId, data as any);
+ if (!updated) {
+ return writeError("agent not found", 404);
+ }
+
+ return writeJSON(agentToResponse(updated));
+});
+
+export const DELETE = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const id = ctx.params?.id;
+ if (!id) {
+ return writeError("agent id is required", 400);
+ }
+
+ const deleted = await deleteAgent(db, id, ws.workspaceId);
+ if (!deleted) {
+ return writeError("agent not found", 404);
+ }
+
+ return new Response(null, { status: 204 });
+});
diff --git a/src/web/app/api/daemon/heartbeat/route.test.ts b/src/web/app/api/daemon/heartbeat/route.test.ts
new file mode 100644
index 000000000..24625ee33
--- /dev/null
+++ b/src/web/app/api/daemon/heartbeat/route.test.ts
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+vi.mock("@/lib/db", () => ({ db: {} }));
+vi.mock("@/lib/db/queries/runtime");
+vi.mock("@/lib/db/queries/task");
+vi.mock("@/lib/services/task");
+
+import {
+ updateAgentRuntimeHeartbeat,
+ markStaleRuntimesOffline,
+} from "@/lib/db/queries/runtime";
+import { failStaleDispatchedTasks } from "@/lib/db/queries/task";
+
+const mockHeartbeat = vi.mocked(updateAgentRuntimeHeartbeat);
+const mockMarkStale = vi.mocked(markStaleRuntimesOffline);
+const mockFailStale = vi.mocked(failStaleDispatchedTasks);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockHeartbeat.mockResolvedValue({ id: "rt1" } as any);
+ mockFailStale.mockResolvedValue([]);
+});
+
+describe("POST /api/daemon/heartbeat", () => {
+ it("updates heartbeat and marks stale runtimes offline", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(
+ new NextRequest("http://localhost/api/daemon/heartbeat", {
+ method: "POST",
+ body: JSON.stringify({ runtime_id: "rt1" }),
+ }),
+ );
+ expect(res.status).toBe(200);
+ expect(mockHeartbeat).toHaveBeenCalledWith({}, "rt1");
+ expect(mockMarkStale).toHaveBeenCalledOnce();
+ });
+
+ it("calls markStaleRuntimesOffline after updating heartbeat", async () => {
+ const callOrder: string[] = [];
+ mockHeartbeat.mockImplementation(async () => {
+ callOrder.push("heartbeat");
+ return { id: "rt1" } as any;
+ });
+ mockMarkStale.mockImplementation(async () => {
+ callOrder.push("markStale");
+ });
+
+ const { POST } = await import("./route");
+ await POST(
+ new NextRequest("http://localhost/api/daemon/heartbeat", {
+ method: "POST",
+ body: JSON.stringify({ runtime_id: "rt1" }),
+ }),
+ );
+ expect(callOrder).toEqual(["heartbeat", "markStale"]);
+ });
+});
diff --git a/src/web/app/api/daemon/heartbeat/route.ts b/src/web/app/api/daemon/heartbeat/route.ts
index a747ecd1e..4a699311d 100644
--- a/src/web/app/api/daemon/heartbeat/route.ts
+++ b/src/web/app/api/daemon/heartbeat/route.ts
@@ -1,6 +1,9 @@
import { NextRequest } from "next/server";
import { db } from "@/lib/db";
-import { updateAgentRuntimeHeartbeat } from "@/lib/db/queries/runtime";
+import {
+ updateAgentRuntimeHeartbeat,
+ markStaleRuntimesOffline,
+} from "@/lib/db/queries/runtime";
import { failStaleDispatchedTasks } from "@/lib/db/queries/task";
import { withAuth } from "@/lib/middleware/auth";
import { writeJSON, parseBody } from "@/lib/middleware/helpers";
@@ -13,6 +16,9 @@ export const POST = withAuth(async (req: NextRequest) => {
await updateAgentRuntimeHeartbeat(db, body.runtime_id);
+ // Mark runtimes that haven't sent a heartbeat in >2 minutes as offline
+ await markStaleRuntimesOffline(db);
+
// Fail tasks stuck in "dispatched" for >20s (daemon likely crashed)
const stale = await failStaleDispatchedTasks(db);
if (stale.length > 0) {
diff --git a/src/web/app/api/daemon/register/route.ts b/src/web/app/api/daemon/register/route.ts
index 3513c6aca..96f42def2 100644
--- a/src/web/app/api/daemon/register/route.ts
+++ b/src/web/app/api/daemon/register/route.ts
@@ -30,12 +30,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
if (!name) {
name = deviceName ? `${provider} (${deviceName})` : provider;
}
- let deviceInfo = deviceName.trim();
- if (rt.version && deviceInfo) {
- deviceInfo = `${deviceInfo} · ${rt.version}`;
- } else if (rt.version) {
- deviceInfo = rt.version;
- }
+ const deviceInfo = deviceName.trim();
const status = rt.status === "offline" ? "offline" : "online";
const metadata: Record<string, unknown> = {
version: rt.version || "",
diff --git a/src/web/app/api/daemon/routes.test.ts b/src/web/app/api/daemon/routes.test.ts
index 84f80d15a..06dfcd67e 100644
--- a/src/web/app/api/daemon/routes.test.ts
+++ b/src/web/app/api/daemon/routes.test.ts
@@ -112,6 +112,48 @@ describe("POST /daemon/register validation", () => {
const res = await POST(makeBadJsonReq());
expect(res.status).toBe(400);
});
+
+ it("stores deviceInfo as device_name only, without version", async () => {
+ const { upsertAgentRuntime } = await import("@/lib/db/queries/runtime");
+ (upsertAgentRuntime as any).mockClear();
+
+ const res = await POST(makeReq({
+ workspace_id: "w1",
+ daemon_id: "d1",
+ device_name: "Gustavos-MacBook-Pro.local",
+ cli_version: "0.1.0",
+ runtimes: [{ type: "claude", version: "2.1.97 (Claude Code)" }],
+ }));
+ expect(res.status).toBe(200);
+ expect(upsertAgentRuntime).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ deviceInfo: "Gustavos-MacBook-Pro.local",
+ }),
+ );
+ });
+
+ it("stores version in metadata, not in deviceInfo", async () => {
+ const { upsertAgentRuntime } = await import("@/lib/db/queries/runtime");
+ (upsertAgentRuntime as any).mockClear();
+
+ await POST(makeReq({
+ workspace_id: "w1",
+ daemon_id: "d1",
+ device_name: "my-host",
+ cli_version: "0.1.0",
+ runtimes: [{ type: "claude", version: "2.1.97 (Claude Code)" }],
+ }));
+ expect(upsertAgentRuntime).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ deviceInfo: "my-host",
+ metadata: expect.objectContaining({
+ version: "2.1.97 (Claude Code)",
+ }),
+ }),
+ );
+ });
});
// ---------------------------------------------------------------------------
diff --git a/src/web/app/api/runtimes/machine/route.test.ts b/src/web/app/api/runtimes/machine/route.test.ts
new file mode 100644
index 000000000..a66a3df90
--- /dev/null
+++ b/src/web/app/api/runtimes/machine/route.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockDeleteRuntimes = vi.fn(async () => {});
+const mockGetMember = vi.fn(async () => ({ id: "m1" }));
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => {
+ return async (req: NextRequest, context?: any) => {
+ const params = context?.params
+ ? context.params instanceof Promise
+ ? await context.params
+ : context.params
+ : undefined;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ };
+ },
+}));
+
+vi.mock("@/lib/db", () => ({ db: {} }));
+vi.mock("@/lib/db/queries/runtime", () => ({
+ deleteRuntimesByDaemonId: (...args: any[]) => mockDeleteRuntimes(...args),
+}));
+vi.mock("@/lib/db/queries/member", () => ({
+ getMemberByUserAndWorkspace: (...args: any[]) => mockGetMember(...args),
+}));
+
+describe("DELETE /api/runtimes/machine", () => {
+ let DELETE: any;
+ beforeEach(async () => {
+ mockDeleteRuntimes.mockClear();
+ mockGetMember.mockClear();
+ mockGetMember.mockResolvedValue({ id: "m1" });
+ mockDeleteRuntimes.mockResolvedValue(undefined);
+ ({ DELETE } = await import("./route"));
+ });
+
+ it("returns 400 when daemon_id is missing", async () => {
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/runtimes/machine?workspace_id=w1", {
+ method: "DELETE",
+ })
+ );
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toBe("daemon_id is required");
+ });
+
+ it("returns 400 when workspace_id is missing", async () => {
+ const res = await DELETE(
+ new NextRequest("http://localhost/api/runtimes/machine?daemon_id=d1", {
+ method: "DELETE",
+ })
+ );
+ expect(res.status).toBe(400);
+ });
+
+ it("returns 404 when user is not a workspace member", async () => {
+ mockGetMember.mockResolvedValueOnce(null);
+ const res = await DELETE(
+ new NextRequest(
+ "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",
+ { method: "DELETE" }
+ )
+ );
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 204 on successful delete", async () => {
+ const res = await DELETE(
+ new NextRequest(
+ "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",
+ { method: "DELETE" }
+ )
+ );
+ expect(res.status).toBe(204);
+ expect(mockDeleteRuntimes).toHaveBeenCalledWith({}, "d1", "w1");
+ });
+
+ it("passes correct daemon_id with dots and dashes", async () => {
+ const res = await DELETE(
+ new NextRequest(
+ "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=My-MacBook-Pro.local",
+ { method: "DELETE" }
+ )
+ );
+ expect(res.status).toBe(204);
+ expect(mockDeleteRuntimes).toHaveBeenCalledWith(
+ {},
+ "My-MacBook-Pro.local",
+ "w1"
+ );
+ });
+
+ it("calls deleteRuntimesByDaemonId exactly once", async () => {
+ await DELETE(
+ new NextRequest(
+ "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",
+ { method: "DELETE" }
+ )
+ );
+ expect(mockDeleteRuntimes).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns 500 when deleteRuntimesByDaemonId throws", async () => {
+ mockDeleteRuntimes.mockRejectedValueOnce(new Error("FK violation"));
+ const res = await DELETE(
+ new NextRequest(
+ "http://localhost/api/runtimes/machine?workspace_id=w1&daemon_id=d1",
+ { method: "DELETE" }
+ )
+ );
+ expect(res.status).toBe(500);
+ const body = await res.json();
+ expect(body.error).toBe("Failed to remove machine");
+ });
+});
diff --git a/src/web/app/api/runtimes/machine/route.ts b/src/web/app/api/runtimes/machine/route.ts
new file mode 100644
index 000000000..63bc25d74
--- /dev/null
+++ b/src/web/app/api/runtimes/machine/route.ts
@@ -0,0 +1,25 @@
+import { NextRequest } from "next/server";
+import { db } from "@/lib/db";
+import { deleteRuntimesByDaemonId } from "@/lib/db/queries/runtime";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON } from "@/lib/middleware/helpers";
+
+export const DELETE = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const daemonId = req.nextUrl.searchParams.get("daemon_id");
+ if (!daemonId) {
+ return writeJSON({ error: "daemon_id is required" }, 400);
+ }
+
+ try {
+ await deleteRuntimesByDaemonId(db, daemonId, ws.workspaceId);
+ } catch (e) {
+ console.error("Failed to delete machine:", e);
+ return writeJSON({ error: "Failed to remove machine" }, 500);
+ }
+
+ return new Response(null, { status: 204 });
+});
diff --git a/src/web/app/api/runtimes/route.test.ts b/src/web/app/api/runtimes/route.test.ts
index a3b6350a6..1c89b8264 100644
--- a/src/web/app/api/runtimes/route.test.ts
+++ b/src/web/app/api/runtimes/route.test.ts
@@ -16,8 +16,12 @@ vi.mock("@/lib/api/responses", () => ({
runtimeToResponse: vi.fn((r: any) => ({ id: r.id })),
}));
-import { listAgentRuntimes } from "@/lib/db/queries/runtime";
+import {
+ listAgentRuntimes,
+ markStaleRuntimesOffline,
+} from "@/lib/db/queries/runtime";
const mockList = vi.mocked(listAgentRuntimes);
+const mockMarkStale = vi.mocked(markStaleRuntimesOffline);
beforeEach(() => vi.clearAllMocks());
@@ -32,4 +36,13 @@ describe("GET /api/runtimes", () => {
const body = await res.json();
expect(body).toHaveLength(2);
});
+
+ it("marks stale runtimes offline before listing", async () => {
+ mockList.mockResolvedValue([{ id: "rt1" }] as any);
+ const { GET } = await import("./route");
+ await GET(
+ new NextRequest("http://localhost/api/runtimes?workspace_id=w1"),
+ );
+ expect(mockMarkStale).toHaveBeenCalledOnce();
+ });
});
diff --git a/src/web/app/api/runtimes/route.ts b/src/web/app/api/runtimes/route.ts
index b14fb81fc..8b8481ea4 100644
--- a/src/web/app/api/runtimes/route.ts
+++ b/src/web/app/api/runtimes/route.ts
@@ -1,5 +1,8 @@
import { db } from "@/lib/db";
-import { listAgentRuntimes } from "@/lib/db/queries/runtime";
+import {
+ listAgentRuntimes,
+ markStaleRuntimesOffline,
+} from "@/lib/db/queries/runtime";
import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON } from "@/lib/middleware/helpers";
@@ -9,6 +12,9 @@ export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
+ // Mark runtimes that haven't sent a heartbeat in >2 minutes as offline
+ await markStaleRuntimesOffline(db);
+
const runtimes = await listAgentRuntimes(db, ws.workspaceId);
return writeJSON(runtimes.map(runtimeToResponse));
});
diff --git a/src/web/app/error.tsx b/src/web/app/error.tsx
new file mode 100644
index 000000000..673dc5058
--- /dev/null
+++ b/src/web/app/error.tsx
@@ -0,0 +1,24 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+
+export default function RootError({
+ reset,
+}: {
+ error: Error & { digest?: string };
+ reset: () => void;
+}) {
+ return (
+ <div className="flex min-h-screen items-center justify-center bg-background p-4">
+ <div className="text-center space-y-4 max-w-sm">
+ <h2 className="text-lg font-medium tracking-tight">
+ Something went wrong
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ An unexpected error occurred. Please try again.
+ </p>
+ <Button onClick={reset}>Try again</Button>
+ </div>
+ </div>
+ );
+}
diff --git a/src/web/app/globals.css b/src/web/app/globals.css
index e57f34489..c0802b6fb 100644
--- a/src/web/app/globals.css
+++ b/src/web/app/globals.css
@@ -10,6 +10,7 @@
--font-sans: var(--font-dm-sans);
--font-mono: var(--font-dm-mono);
--font-heading: var(--font-dm-sans);
+ --font-brand: var(--font-caveat);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
@@ -117,13 +118,34 @@
--sidebar-ring: oklch(0.55 0.01 60);
}
+/* ── Sonner toast: close button only on hover ── */
+[data-sonner-toast] [data-close-button] {
+ opacity: 0;
+ transition: opacity 150ms ease;
+}
+[data-sonner-toast]:hover [data-close-button] {
+ opacity: 1;
+}
+
+/* ── Motion tokens ── */
+@keyframes fade-up {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
- font-feature-settings: "kern" 1;
+ font-kerning: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@@ -132,10 +154,13 @@
font-size: 16px;
line-height: 1.6;
}
+ .dark body {
+ line-height: 1.65;
+ }
h1, h2, h3, h4, h5, h6 {
@apply font-heading;
- line-height: 1.2;
- letter-spacing: -0.01em;
+ line-height: 1.15;
+ letter-spacing: -0.015em;
}
p {
line-height: 1.6;
diff --git a/src/web/app/layout.tsx b/src/web/app/layout.tsx
index 4010c5c8a..03de78574 100644
--- a/src/web/app/layout.tsx
+++ b/src/web/app/layout.tsx
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
-import { DM_Sans, DM_Mono } from "next/font/google";
+import { DM_Sans, DM_Mono, Caveat } from "next/font/google";
import { ThemeProvider } from "@/components/theme-provider";
+import { ToasterProvider } from "@/components/toaster-provider";
import "./globals.css";
const dmSans = DM_Sans({
@@ -15,6 +16,13 @@ const dmMono = DM_Mono({
weight: ["400", "500"],
});
+const caveat = Caveat({
+ variable: "--font-caveat",
+ subsets: ["latin"],
+ weight: ["400", "500", "600", "700"],
+});
+
+
export const metadata: Metadata = {
title: "Alook",
description: "Chat with AI agents",
@@ -28,12 +36,13 @@ export default function RootLayout({
return (
<html
lang="en"
- className={`${dmSans.variable} ${dmMono.variable} h-full antialiased`}
+ className={`${dmSans.variable} ${dmMono.variable} ${caveat.variable} h-full antialiased`}
suppressHydrationWarning
>
<body className="min-h-full flex flex-col">
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
+ <ToasterProvider />
</ThemeProvider>
</body>
</html>
diff --git a/src/web/app/login/page.tsx b/src/web/app/login/page.tsx
index c62971f3f..a99e441c6 100644
--- a/src/web/app/login/page.tsx
+++ b/src/web/app/login/page.tsx
@@ -17,8 +17,9 @@ import {
CardHeader,
CardTitle,
} from "@/components/ui/card";
-import { ThemeToggle } from "@/components/theme-toggle";
+import { Logo } from "@/components/logo";
import { sendCode, verifyCode, listWorkspaces } from "@/lib/api";
+import { ApiError } from "@/lib/errors";
export default function LoginPage() {
const router = useRouter();
@@ -36,7 +37,17 @@ export default function LoginPage() {
await sendCode(email);
setStep("code");
} catch (err) {
- setError(err instanceof Error ? err.message : "Failed to send code");
+ if (err instanceof ApiError) {
+ if (err.isRateLimit) {
+ setError("Please wait before requesting another code");
+ } else if (err.isNetworkError) {
+ setError("Unable to connect — check your network");
+ } else {
+ setError(err.message);
+ }
+ } else {
+ setError(err instanceof Error ? err.message : "Failed to send code");
+ }
} finally {
setLoading(false);
}
@@ -52,14 +63,28 @@ export default function LoginPage() {
const res = await verifyCode(email, value);
localStorage.setItem("alook_token", res.token);
- const workspaces = await listWorkspaces();
- if (workspaces.length > 0) {
- localStorage.setItem("alook_workspace_id", workspaces[0].id);
+ try {
+ const workspaces = await listWorkspaces();
+ if (workspaces.length > 0) {
+ localStorage.setItem("alook_workspace_id", workspaces[0].id);
+ }
+ } catch {
+ setError("Signed in, but failed to load workspace");
}
router.push("/agents");
} catch (err) {
- setError(err instanceof Error ? err.message : "Invalid code");
+ if (err instanceof ApiError) {
+ if (err.isRateLimit) {
+ setError("Please wait before requesting another code");
+ } else if (err.isNetworkError) {
+ setError("Unable to connect — check your network");
+ } else {
+ setError(err.message);
+ }
+ } else {
+ setError(err instanceof Error ? err.message : "Invalid code");
+ }
setCode("");
} finally {
setLoading(false);
@@ -68,12 +93,9 @@ export default function LoginPage() {
return (
<div className="flex min-h-screen items-center justify-center bg-background p-4">
- <div className="fixed top-4 right-4">
- <ThemeToggle />
- </div>
<Card className="w-full max-w-sm">
<CardHeader className="text-center">
- <CardTitle className="text-2xl font-semibold tracking-tight">Alook</CardTitle>
+ <Logo size="lg" className="justify-center" />
<CardDescription>
{step === "email"
? "Sign in with your email"
diff --git a/src/web/app/page.tsx b/src/web/app/page.tsx
index 99a177c8a..1ae2caac7 100644
--- a/src/web/app/page.tsx
+++ b/src/web/app/page.tsx
@@ -9,7 +9,7 @@ export default function Home() {
useEffect(() => {
const token = localStorage.getItem("alook_token");
if (token) {
- router.replace("/agents");
+ router.replace("/home");
} else {
router.replace("/login");
}
diff --git a/src/web/components/logo.tsx b/src/web/components/logo.tsx
new file mode 100644
index 000000000..f06dc1d23
--- /dev/null
+++ b/src/web/components/logo.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { useTheme } from "next-themes";
+import { cn } from "@/lib/utils";
+
+const sizes = {
+ sm: { icon: 28, text: "text-2xl" },
+ lg: { icon: 36, text: "text-4xl" },
+} as const;
+
+export function Logo({
+ size = "sm",
+ className,
+}: {
+ size?: "sm" | "lg";
+ className?: string;
+}) {
+ const { icon, text } = sizes[size];
+ const { resolvedTheme, setTheme } = useTheme();
+ const [mounted, setMounted] = useState(false);
+
+ useEffect(() => setMounted(true), []);
+
+ const toggle = () => {
+ setTheme(resolvedTheme === "dark" ? "light" : "dark");
+ };
+
+ return (
+ <button
+ type="button"
+ onClick={toggle}
+ aria-label="Toggle theme"
+ className={cn(
+ "flex items-center gap-1.5 cursor-pointer select-none transition-opacity hover:opacity-70",
+ className
+ )}
+ >
+ {mounted ? (
+ <>
+ <img
+ src="/alook.svg"
+ alt="Alook"
+ width={icon}
+ height={icon}
+ className="dark:hidden"
+ />
+ <img
+ src="/alook-dark.svg"
+ alt="Alook"
+ width={icon}
+ height={icon}
+ className="hidden dark:block"
+ />
+ </>
+ ) : (
+ <span style={{ width: icon, height: icon }} />
+ )}
+ <span
+ className={cn(text, "font-black tracking-tight")}
+ style={{ fontFamily: "var(--font-brand)" }}
+ >
+ Alook
+ </span>
+ </button>
+ );
+}
diff --git a/src/web/components/toaster-provider.tsx b/src/web/components/toaster-provider.tsx
new file mode 100644
index 000000000..2854c76ad
--- /dev/null
+++ b/src/web/components/toaster-provider.tsx
@@ -0,0 +1,17 @@
+"use client";
+
+import { Toaster } from "sonner";
+import { useTheme } from "next-themes";
+
+export function ToasterProvider() {
+ const { resolvedTheme } = useTheme();
+
+ return (
+ <Toaster
+ theme={(resolvedTheme as "light" | "dark") ?? "system"}
+ richColors
+ closeButton
+ position="bottom-right"
+ />
+ );
+}
diff --git a/src/web/components/ui/button.tsx b/src/web/components/ui/button.tsx
index 09df75367..c751375cc 100644
--- a/src/web/components/ui/button.tsx
+++ b/src/web/components/ui/button.tsx
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
- "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ "group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap cursor-pointer transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
diff --git a/src/web/components/ui/confirm-dialog.tsx b/src/web/components/ui/confirm-dialog.tsx
new file mode 100644
index 000000000..f377b7d93
--- /dev/null
+++ b/src/web/components/ui/confirm-dialog.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Button } from "@/components/ui/button";
+
+interface ConfirmDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ title: string;
+ description: string;
+ confirmLabel?: string;
+ loading?: boolean;
+ onConfirm: () => void;
+}
+
+export function ConfirmDialog({
+ open,
+ onOpenChange,
+ title,
+ description,
+ confirmLabel = "Remove",
+ loading = false,
+ onConfirm,
+}: ConfirmDialogProps) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent showCloseButton={false}>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={loading}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={onConfirm}
+ disabled={loading}
+ >
+ {loading ? "Removing..." : confirmLabel}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/web/components/ui/select.tsx b/src/web/components/ui/select.tsx
new file mode 100644
index 000000000..578516567
--- /dev/null
+++ b/src/web/components/ui/select.tsx
@@ -0,0 +1,132 @@
+"use client"
+
+import * as React from "react"
+import { Select as SelectPrimitive } from "@base-ui/react/select"
+import { cn } from "@/lib/utils"
+import { ChevronDownIcon, CheckIcon } from "lucide-react"
+
+function Select({
+ modal = false,
+ ...props
+}: SelectPrimitive.Root.Props<any>) {
+ return <SelectPrimitive.Root data-slot="select" modal={modal} {...props} />
+}
+
+function SelectTrigger({
+ className,
+ children,
+ ...props
+}: SelectPrimitive.Trigger.Props) {
+ return (
+ <SelectPrimitive.Trigger
+ data-slot="select-trigger"
+ className={cn(
+ "flex h-8 w-full items-center justify-between gap-2 overflow-hidden rounded-lg border border-input bg-transparent px-3 py-1 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 data-[placeholder]:text-muted-foreground [&>*:first-child]:truncate",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon className="shrink-0">
+ <ChevronDownIcon className="size-3.5 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+ )
+}
+
+function SelectValue({ ...props }: SelectPrimitive.Value.Props) {
+ return <SelectPrimitive.Value data-slot="select-value" {...props} />
+}
+
+function SelectPortal({ ...props }: SelectPrimitive.Portal.Props) {
+ return <SelectPrimitive.Portal data-slot="select-portal" {...props} />
+}
+
+function SelectPopup({
+ className,
+ children,
+ portal = true,
+ ...props
+}: SelectPrimitive.Popup.Props & { portal?: boolean }) {
+ const content = (
+ <SelectPrimitive.Positioner>
+ <SelectPrimitive.Popup
+ data-slot="select-popup"
+ className={cn(
+ "z-50 min-w-[var(--anchor-width)] overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-md outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </SelectPrimitive.Popup>
+ </SelectPrimitive.Positioner>
+ )
+
+ if (!portal) {
+ return content
+ }
+
+ return <SelectPortal>{content}</SelectPortal>
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: SelectPrimitive.Item.Props & { className?: string }) {
+ return (
+ <SelectPrimitive.Item
+ data-slot="select-item"
+ className={cn(
+ "relative flex w-full cursor-default select-none items-center rounded-md py-1.5 pl-2 pr-8 text-sm outline-none transition-colors data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50",
+ className
+ )}
+ {...props}
+ >
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ <SelectPrimitive.ItemIndicator className="absolute right-2">
+ <CheckIcon className="size-3.5" />
+ </SelectPrimitive.ItemIndicator>
+ </SelectPrimitive.Item>
+ )
+}
+
+function SelectGroup({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.Group>) {
+ return (
+ <SelectPrimitive.Group
+ data-slot="select-group"
+ className={cn("", className)}
+ {...props}
+ />
+ )
+}
+
+function SelectGroupLabel({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectPrimitive.GroupLabel>) {
+ return (
+ <SelectPrimitive.GroupLabel
+ data-slot="select-group-label"
+ className={cn(
+ "px-2 py-1.5 text-[11px] font-medium text-muted-foreground uppercase tracking-wider",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+ SelectGroup,
+ SelectGroupLabel,
+}
diff --git a/src/web/components/ui/sheet.tsx b/src/web/components/ui/sheet.tsx
new file mode 100644
index 000000000..c277e585a
--- /dev/null
+++ b/src/web/components/ui/sheet.tsx
@@ -0,0 +1,157 @@
+"use client"
+
+import * as React from "react"
+import { Dialog as SheetPrimitive } from "@base-ui/react/dialog"
+
+import { cn } from "@/lib/utils"
+import { Button } from "@/components/ui/button"
+import { XIcon } from "lucide-react"
+
+function Sheet({ ...props }: SheetPrimitive.Root.Props) {
+ return <SheetPrimitive.Root data-slot="sheet" {...props} />
+}
+
+function SheetTrigger({ ...props }: SheetPrimitive.Trigger.Props) {
+ return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
+}
+
+function SheetClose({ ...props }: SheetPrimitive.Close.Props) {
+ return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
+}
+
+function SheetPortal({ ...props }: SheetPrimitive.Portal.Props) {
+ return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
+}
+
+function SheetOverlay({ className, ...props }: SheetPrimitive.Backdrop.Props) {
+ return (
+ <SheetPrimitive.Backdrop
+ data-slot="sheet-overlay"
+ className={cn(
+ "fixed inset-0 z-50 bg-black/20 backdrop-blur-[2px] transition-[opacity,backdrop-filter] duration-200 ease-out data-ending-style:opacity-0 data-ending-style:backdrop-blur-none data-starting-style:opacity-0 data-starting-style:backdrop-blur-none",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SheetContent({
+ className,
+ children,
+ side = "right",
+ showCloseButton = true,
+ ...props
+}: SheetPrimitive.Popup.Props & {
+ side?: "top" | "right" | "bottom" | "left"
+ showCloseButton?: boolean
+}) {
+ return (
+ <SheetPortal>
+ <SheetOverlay />
+ <SheetPrimitive.Popup
+ data-slot="sheet-content"
+ data-side={side}
+ className={cn(
+ "fixed z-50 flex flex-col bg-background shadow-xl outline-none transition duration-300 ease-in-out data-ending-style:opacity-0 data-starting-style:opacity-0",
+ "data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-full data-[side=right]:max-w-md data-[side=right]:border-l data-[side=right]:data-ending-style:translate-x-[2.5rem] data-[side=right]:data-starting-style:translate-x-[2.5rem]",
+ "data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-full data-[side=left]:max-w-md data-[side=left]:border-r data-[side=left]:data-ending-style:translate-x-[-2.5rem] data-[side=left]:data-starting-style:translate-x-[-2.5rem]",
+ "data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=top]:data-ending-style:translate-y-[-2.5rem] data-[side=top]:data-starting-style:translate-y-[-2.5rem]",
+ "data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=bottom]:data-ending-style:translate-y-[2.5rem] data-[side=bottom]:data-starting-style:translate-y-[2.5rem]",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ {showCloseButton && (
+ <SheetPrimitive.Close
+ data-slot="sheet-close"
+ render={
+ <Button
+ variant="ghost"
+ className="absolute top-3 right-3 z-10"
+ size="icon-sm"
+ />
+ }
+ >
+ <XIcon />
+ <span className="sr-only">Close</span>
+ </SheetPrimitive.Close>
+ )}
+ </SheetPrimitive.Popup>
+ </SheetPortal>
+ )
+}
+
+function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-header"
+ className={cn("flex flex-col gap-1 border-b px-6 py-5", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetBody({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-body"
+ className={cn("flex-1 overflow-y-auto px-6 py-5", className)}
+ {...props}
+ />
+ )
+}
+
+function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="sheet-footer"
+ className={cn(
+ "flex flex-col-reverse gap-2 border-t bg-muted/50 px-6 py-4 sm:flex-row sm:justify-end",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SheetTitle({ className, ...props }: SheetPrimitive.Title.Props) {
+ return (
+ <SheetPrimitive.Title
+ data-slot="sheet-title"
+ className={cn(
+ "font-heading text-lg leading-none font-semibold",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function SheetDescription({
+ className,
+ ...props
+}: SheetPrimitive.Description.Props) {
+ return (
+ <SheetPrimitive.Description
+ data-slot="sheet-description"
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+ )
+}
+
+export {
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetBody,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetOverlay,
+ SheetPortal,
+ SheetTitle,
+ SheetTrigger,
+}
diff --git a/src/web/lib/api.test.ts b/src/web/lib/api.test.ts
new file mode 100644
index 000000000..17958d409
--- /dev/null
+++ b/src/web/lib/api.test.ts
@@ -0,0 +1,212 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { ApiError } from "./errors";
+
+// Mock localStorage and window
+const localStorageMock = (() => {
+ let store: Record<string, string> = {};
+ return {
+ getItem: (key: string) => store[key] ?? null,
+ setItem: (key: string, value: string) => { store[key] = value; },
+ removeItem: (key: string) => { delete store[key]; },
+ clear: () => { store = {}; },
+ };
+})();
+
+Object.defineProperty(globalThis, "localStorage", { value: localStorageMock });
+Object.defineProperty(globalThis, "document", {
+ value: { cookie: "" },
+ writable: true,
+});
+
+// We need to mock fetch globally
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+// Prevent 401 redirect from blowing up
+Object.defineProperty(globalThis, "window", {
+ value: {
+ location: { href: "" },
+ ...globalThis.window,
+ },
+ writable: true,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorageMock.clear();
+ // Reset window.location.href
+ if (typeof window !== "undefined") {
+ window.location.href = "";
+ }
+});
+
+describe("ApiError class", () => {
+ it("constructs with message, status, and details", () => {
+ const err = new ApiError("bad request", 400, ["field: required"]);
+ expect(err.message).toBe("bad request");
+ expect(err.status).toBe(400);
+ expect(err.details).toEqual(["field: required"]);
+ expect(err.name).toBe("ApiError");
+ expect(err).toBeInstanceOf(Error);
+ });
+
+ it("isNetworkError returns true for status 0", () => {
+ expect(new ApiError("offline", 0).isNetworkError).toBe(true);
+ expect(new ApiError("not found", 404).isNetworkError).toBe(false);
+ });
+
+ it("isRateLimit returns true for status 429", () => {
+ expect(new ApiError("rate limit", 429).isRateLimit).toBe(true);
+ expect(new ApiError("bad", 400).isRateLimit).toBe(false);
+ });
+
+ it("isUnauthorized returns true for status 401", () => {
+ expect(new ApiError("unauth", 401).isUnauthorized).toBe(true);
+ expect(new ApiError("ok", 200).isUnauthorized).toBe(false);
+ });
+});
+
+// We dynamically import to get the patched fetch
+async function getApiFetch() {
+ // Re-import to pick up mocked fetch
+ const mod = await import("./api");
+ return mod;
+}
+
+describe("apiFetch", () => {
+ it("returns ApiError on 400 with { error } JSON body", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ json: async () => ({ error: "name is required" }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).message).toBe("name is required");
+ expect((e as ApiError).status).toBe(400);
+ }
+ });
+
+ it("propagates details on 400 with details array", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ json: async () => ({
+ error: "validation error",
+ details: ["name: required", "email: invalid"],
+ }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).details).toEqual(["name: required", "email: invalid"]);
+ }
+ });
+
+ it("returns ApiError with status 0 on network TypeError", async () => {
+ mockFetch.mockRejectedValueOnce(new TypeError("Failed to fetch"));
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).status).toBe(0);
+ expect((e as ApiError).message).toBe("Unable to connect — check your network");
+ expect((e as ApiError).isNetworkError).toBe(true);
+ }
+ });
+
+ it("returns ApiError with 'Please wait' on 429", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 429,
+ json: async () => ({ error: "rate limited" }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).status).toBe(429);
+ expect((e as ApiError).message).toBe("Please wait a moment before trying again");
+ expect((e as ApiError).isRateLimit).toBe(true);
+ }
+ });
+
+ it("returns generic message on 500 with non-JSON body", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 500,
+ json: async () => { throw new Error("not json"); },
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).status).toBe(500);
+ expect((e as ApiError).message).toBe("Something went wrong — please try again");
+ }
+ });
+
+ it("uses server error message on 500 with JSON body", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 500,
+ json: async () => ({ error: "database connection failed" }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).message).toBe("database connection failed");
+ }
+ });
+
+ it("returns generic message on 502 with empty body", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 502,
+ json: async () => { throw new Error("empty"); },
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).status).toBe(502);
+ expect((e as ApiError).message).toBe("Something went wrong — please try again");
+ }
+ });
+
+ it("redirects on 401 and throws ApiError", async () => {
+ mockFetch.mockResolvedValueOnce({
+ ok: false,
+ status: 401,
+ json: async () => ({ error: "unauthorized" }),
+ });
+
+ const { listAgents } = await getApiFetch();
+ try {
+ await listAgents();
+ } catch (e) {
+ expect(e).toBeInstanceOf(ApiError);
+ expect((e as ApiError).status).toBe(401);
+ expect((e as ApiError).message).toBe("Unauthorized");
+ expect((e as ApiError).isUnauthorized).toBe(true);
+ }
+ });
+});
diff --git a/src/web/lib/api.ts b/src/web/lib/api.ts
index 3fc305536..1e55c2dea 100644
--- a/src/web/lib/api.ts
+++ b/src/web/lib/api.ts
@@ -2,6 +2,7 @@ import type {
Agent,
Conversation,
CreateAgentRequest,
+ UpdateAgentRequest,
LoginResponse,
Message,
Runtime,
@@ -10,6 +11,7 @@ import type {
User,
Workspace,
} from "./types";
+import { ApiError } from "./errors";
const API_BASE = "";
@@ -21,15 +23,23 @@ async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
? localStorage.getItem("alook_workspace_id")
: null;
- const res = await fetch(API_BASE + path, {
- ...options,
- headers: {
- "Content-Type": "application/json",
- ...(token && { Authorization: `Bearer ${token}` }),
- ...(workspaceId && { "X-Workspace-ID": workspaceId }),
- ...options?.headers,
- },
- });
+ let res: Response;
+ try {
+ res = await fetch(API_BASE + path, {
+ ...options,
+ headers: {
+ "Content-Type": "application/json",
+ ...(token && { Authorization: `Bearer ${token}` }),
+ ...(workspaceId && { "X-Workspace-ID": workspaceId }),
+ ...options?.headers,
+ },
+ });
+ } catch (err) {
+ if (err instanceof TypeError) {
+ throw new ApiError("Unable to connect — check your network", 0);
+ }
+ throw err;
+ }
if (res.status === 401) {
if (typeof window !== "undefined") {
@@ -38,13 +48,40 @@ async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {
document.cookie = "alook_session=; path=/; max-age=0";
window.location.href = "/login";
}
- throw new Error("Unauthorized");
+ throw new ApiError("Unauthorized", 401);
}
if (!res.ok) {
- throw new Error(await res.text());
+ let serverError: string | undefined;
+ let details: string[] | undefined;
+ try {
+ const body = await res.json();
+ serverError = body.error;
+ details = body.details;
+ } catch {
+ // non-JSON body (HTML from proxy, empty body, etc.)
+ }
+
+ if (res.status === 429) {
+ throw new ApiError("Please wait a moment before trying again", 429);
+ }
+
+ if (res.status >= 500) {
+ throw new ApiError(
+ serverError || "Something went wrong — please try again",
+ res.status,
+ details,
+ );
+ }
+
+ throw new ApiError(
+ serverError || "Something went wrong",
+ res.status,
+ details,
+ );
}
+ if (res.status === 204) return undefined as T;
return res.json();
}
@@ -81,9 +118,23 @@ export const createAgent = (req: CreateAgentRequest) =>
body: JSON.stringify(req),
});
+export const updateAgent = (id: string, req: UpdateAgentRequest) =>
+ apiFetch<Agent>(`/api/agents/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify(req),
+ });
+
+export const deleteAgent = (id: string) =>
+ apiFetch<void>(`/api/agents/${id}`, { method: "DELETE" });
+
// Runtimes
export const listRuntimes = () => apiFetch<Runtime[]>("/api/runtimes");
+export const deleteMachine = (daemonId: string) =>
+ apiFetch<void>(`/api/runtimes/machine?daemon_id=${encodeURIComponent(daemonId)}`, {
+ method: "DELETE",
+ });
+
// Conversations
export const listConversations = () =>
apiFetch<Conversation[]>("/api/conversations");
diff --git a/src/web/lib/db/queries/agent.ts b/src/web/lib/db/queries/agent.ts
index 662f3fa91..dbcd68ef9 100644
--- a/src/web/lib/db/queries/agent.ts
+++ b/src/web/lib/db/queries/agent.ts
@@ -1,4 +1,4 @@
-import { eq, and, desc } from "drizzle-orm";
+import { eq, and, desc, sql } from "drizzle-orm";
import { agent } from "../schema";
import type { Database } from "../index";
@@ -66,6 +66,37 @@ export async function createAgent(
return rows[0]!;
}
+export async function deleteAgent(
+ db: Database,
+ 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;
+}
+
+export async function updateAgent(
+ db: Database,
+ id: string,
+ workspaceId: string,
+ data: {
+ name?: string;
+ description?: string;
+ instructions?: string;
+ runtimeId?: string | null;
+ }
+) {
+ const rows = await db
+ .update(agent)
+ .set({ ...data, updatedAt: sql`now()` })
+ .where(and(eq(agent.id, id), eq(agent.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+}
+
export async function updateAgentStatus(
db: Database,
id: string,
diff --git a/src/web/lib/db/queries/runtime.ts b/src/web/lib/db/queries/runtime.ts
index d40040a3f..d0c99cc30 100644
--- a/src/web/lib/db/queries/runtime.ts
+++ b/src/web/lib/db/queries/runtime.ts
@@ -1,5 +1,5 @@
-import { eq, and, asc, sql } from "drizzle-orm";
-import { agentRuntime } from "../schema";
+import { eq, and, asc, sql, or } from "drizzle-orm";
+import { agentRuntime, agent, agentTaskQueue } from "../schema";
import type { Database } from "../index";
export async function upsertAgentRuntime(
@@ -26,7 +26,7 @@ export async function upsertAgentRuntime(
status: data.status,
deviceInfo: data.deviceInfo,
metadata: data.metadata ?? null,
- lastSeenAt: new Date(),
+ lastSeenAt: sql`now()`,
})
.onConflictDoUpdate({
target: [
@@ -40,8 +40,8 @@ export async function upsertAgentRuntime(
status: sql`excluded.status`,
deviceInfo: sql`excluded.device_info`,
metadata: sql`excluded.metadata`,
- lastSeenAt: new Date(),
- updatedAt: new Date(),
+ lastSeenAt: sql`now()`,
+ updatedAt: sql`now()`,
},
})
.returning();
@@ -81,7 +81,7 @@ export async function getAgentRuntimeForWorkspace(
export async function updateAgentRuntimeHeartbeat(db: Database, id: string) {
const rows = await db
.update(agentRuntime)
- .set({ lastSeenAt: new Date(), status: "online", updatedAt: new Date() })
+ .set({ lastSeenAt: sql`now()`, status: "online", updatedAt: sql`now()` })
.where(eq(agentRuntime.id, id))
.returning();
return rows[0] ?? null;
@@ -90,14 +90,57 @@ export async function updateAgentRuntimeHeartbeat(db: Database, id: string) {
export async function setAgentRuntimeOffline(db: Database, id: string) {
await db
.update(agentRuntime)
- .set({ status: "offline", updatedAt: new Date() })
+ .set({ status: "offline", updatedAt: sql`now()` })
.where(eq(agentRuntime.id, id));
}
+export async function deleteRuntimesByDaemonId(
+ db: Database,
+ daemonId: string,
+ workspaceId: string
+) {
+ // Find runtime IDs to delete
+ const runtimes = await db
+ .select({ id: agentRuntime.id })
+ .from(agentRuntime)
+ .where(
+ and(
+ eq(agentRuntime.daemonId, daemonId),
+ eq(agentRuntime.workspaceId, workspaceId)
+ )
+ );
+
+ if (runtimes.length === 0) return;
+
+ const ids = runtimes.map((r) => r.id);
+
+ // Null out agent references and delete tasks per runtime
+ for (const id of ids) {
+ await db
+ .update(agent)
+ .set({ runtimeId: null, updatedAt: sql`now()` })
+ .where(eq(agent.runtimeId, id));
+
+ await db
+ .delete(agentTaskQueue)
+ .where(eq(agentTaskQueue.runtimeId, id));
+ }
+
+ // Delete the runtimes
+ await db
+ .delete(agentRuntime)
+ .where(
+ and(
+ eq(agentRuntime.daemonId, daemonId),
+ eq(agentRuntime.workspaceId, workspaceId)
+ )
+ );
+}
+
export async function markStaleRuntimesOffline(db: Database) {
await db
.update(agentRuntime)
- .set({ status: "offline", updatedAt: new Date() })
+ .set({ status: "offline", updatedAt: sql`now()` })
.where(
and(
eq(agentRuntime.status, "online"),
diff --git a/src/web/lib/errors.ts b/src/web/lib/errors.ts
new file mode 100644
index 000000000..31c78228c
--- /dev/null
+++ b/src/web/lib/errors.ts
@@ -0,0 +1,23 @@
+export class ApiError extends Error {
+ status: number;
+ details?: string[];
+
+ constructor(message: string, status: number, details?: string[]) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.details = details;
+ }
+
+ get isNetworkError(): boolean {
+ return this.status === 0;
+ }
+
+ get isRateLimit(): boolean {
+ return this.status === 429;
+ }
+
+ get isUnauthorized(): boolean {
+ return this.status === 401;
+ }
+}
diff --git a/src/web/lib/types.ts b/src/web/lib/types.ts
index 978337191..3d5ce3b2b 100644
--- a/src/web/lib/types.ts
+++ b/src/web/lib/types.ts
@@ -22,9 +22,12 @@ export interface Agent {
export interface Runtime {
id: string;
+ daemon_id: string | null;
+ name: string;
provider: string;
status: string;
- device_info: Record<string, unknown>;
+ device_info: string;
+ metadata: Record<string, unknown>;
last_seen_at: string;
}
@@ -74,3 +77,10 @@ export interface CreateAgentRequest {
instructions?: string;
runtime_id: string;
}
+
+export interface UpdateAgentRequest {
+ name?: string;
+ description?: string;
+ instructions?: string;
+ runtime_id?: string;
+}
diff --git a/src/web/package.json b/src/web/package.json
index c62c94d8a..6d4c89afd 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -24,6 +24,7 @@
"react-dom": "19.2.4",
"resend": "^4.0.0",
"shadcn": "^4.2.0",
+ "sonner": "^2.0.7",
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0"
},
diff --git a/src/web/public/alook-dark.svg b/src/web/public/alook-dark.svg
new file mode 100644
index 000000000..8a0d24878
--- /dev/null
+++ b/src/web/public/alook-dark.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="3 5 22 22" fill="none">
+ <!-- Back block (shadow) — warm umber, softer than gray -->
+ <rect x="4" y="6" width="18" height="18" rx="3" fill="#8a7a6c" opacity="0.42" />
+ <!-- Front block — cream / warm paper, not pure white -->
+ <rect x="6" y="8" width="18" height="18" rx="3" fill="#e8ddd0" />
+ <!-- Envelope body — deep warm brown -->
+ <rect x="9.5" y="13" width="11" height="9" rx="2" fill="#120e0a" />
+ <!-- Flap — same as front block (card “bg”) -->
+ <path d="M 10 13.5 Q 15 18.5 20 13.5" fill="none" stroke="#e8ddd0" stroke-width="1.4" stroke-linecap="round" />
+</svg>
\ No newline at end of file
diff --git a/src/web/public/alook.svg b/src/web/public/alook.svg
new file mode 100644
index 000000000..21770a386
--- /dev/null
+++ b/src/web/public/alook.svg
@@ -0,0 +1,10 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="3 5 22 22" fill="currentColor">
+ <!-- Back block (shadow) — rounder corners -->
+ <rect x="4" y="6" width="18" height="18" rx="3" opacity="0.4" />
+ <!-- Front block -->
+ <rect x="6" y="8" width="18" height="18" rx="3" />
+ <!-- Envelope body — white contrast, centered in front block -->
+ <rect x="9.5" y="13" width="11" height="9" rx="2" fill="white" />
+ <!-- Flap — smooth curved chevron -->
+ <path d="M 10 13.5 Q 15 18.5 20 13.5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" />
+</svg>