Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
test(web): re-implement legacy test cases for D1 migration (199 tests)
Genere8d3a6901299
diff --git a/src/email-worker/src/index.test.ts b/src/email-worker/src/index.test.tsindex fc71f9c2c..b25b9245e 100644--- a/src/email-worker/src/index.test.ts+++ b/src/email-worker/src/index.test.ts@@ -14,7 +14,7 @@ const mockGetUser = vi.fn()const mockCreateDb = vi.fn(() => ({}))vi.mock("@alook/shared", () => ({- createDb: (...args: unknown[]) => mockCreateDb(...args),+ createDb: (...args: any[]) => mockCreateDb(...args),parseEmailHandle: (address: string) => {const domain = "@alook.ai"return address.endsWith(domain) ? address.slice(0, -domain.length) : ""@@ -33,7 +33,7 @@ import handler from "./index"const AGENT = {id: "agent-1",workspaceId: "ws-1",- ownerId: "user-1",+ ownerId: "user-1" as string | null,emailHandle: "jarvis",forwardToEmail: "",name: "Jarvis",diff --git a/src/web/app/(app)/agents/[id]/page.tsx b/src/web/app/(app)/agents/[id]/page.tsxdeleted file mode 100644index b8d4960ef..000000000--- a/src/web/app/(app)/agents/[id]/page.tsx+++ /dev/null@@ -1,330 +0,0 @@-"use client";--import { useEffect, useState, useCallback } from "react";-import { useParams, useRouter } from "next/navigation";-import { useAgentContext } from "@/contexts/agent-context";-import { listAgentConversations, deleteConversation } from "@/lib/api";-import type { Conversation } from "@/lib/types";-import { Button } from "@/components/ui/button";-import { ConfirmDialog } from "@/components/ui/confirm-dialog";-import { AgentEditForm } from "@/components/agent-edit-form";-import { cn } from "@/lib/utils";-import { toast } from "sonner";-import { Plus, Loader2, Trash2, Pencil, X } from "lucide-react";--function relativeTime(dateStr: string): string {- const date = new Date(dateStr);- const now = new Date();- const diffMs = now.getTime() - date.getTime();- const diffMin = Math.floor(diffMs / 60000);- if (diffMin < 1) return "just now";- if (diffMin < 60) return `${diffMin}m ago`;- const diffHrs = Math.floor(diffMin / 60);- if (diffHrs < 24) return `${diffHrs}h ago`;- const diffDays = Math.floor(diffHrs / 24);- if (diffDays < 7) return `${diffDays}d ago`;- return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--function formatDate(dateStr: string): string {- return new Date(dateStr).toLocaleDateString(undefined, {- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- });-}--export default function AgentDetailPage() {- const params = useParams();- const router = useRouter();- const agentId = params.id as string;- const {- agents,- runtimes,- chatWithAgent,- handleDeleteAgent,- handleUpdateAgent,- } = useAgentContext();-- const agent = agents.find((a) => a.id === agentId);-- const [conversations, setConversations] = useState<Conversation[]>([]);- const [loading, setLoading] = useState(true);- const [creating, setCreating] = useState(false);-- // Delete conversation state- const [deleteTarget, setDeleteTarget] = useState<Conversation | null>(null);- const [deleting, setDeleting] = useState(false);-- // Delete agent state- const [agentConfirmOpen, setAgentConfirmOpen] = useState(false);- const [agentDeleting, setAgentDeleting] = useState(false);-- // Inline edit state- const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);-- const loadConversations = useCallback(async () => {- try {- const convs = await listAgentConversations(agentId);- setConversations(convs);- } catch {- toast.error("Failed to load sessions");- } finally {- setLoading(false);- }- }, [agentId]);-- useEffect(() => {- loadConversations();- }, [loadConversations]);-- const handleNewSession = async () => {- setCreating(true);- try {- const conversationId = await chatWithAgent(agentId);- if (conversationId) {- router.push(`/chat/${conversationId}?agent=${agentId}`);- }- } finally {- setCreating(false);- }- };-- const handleDeleteConversation = async () => {- if (!deleteTarget) return;- setDeleting(true);- try {- await deleteConversation(deleteTarget.id);- setConversations((prev) =>- prev.filter((c) => c.id !== deleteTarget.id)- );- setDeleteTarget(null);- } catch {- toast.error("Failed to delete session");- } finally {- setDeleting(false);- }- };-- const runtime = agent- ? runtimes.find((r) => r.id === agent.runtime_id)- : null;- const isOnline = runtime?.status === "online";-- return (- <>- {/* Navbar — same pattern as chat page */}- <div className="flex items-center justify-between border-b border-border/50 px-5 py-2.5">- <div className="flex items-center gap-2 min-w-0">- {agent && (- <span- title={isOnline ? "Runtime online" : "Runtime offline"}- className={cn(- "size-2 rounded-full shrink-0",- isOnline ? "bg-status-online" : "bg-status-offline"- )}- />- )}- <h1 className="text-sm font-medium truncate">- {agent?.name || "Agent"}- </h1>- {editing && (- <span className="text-xs text-muted-foreground">/ Settings</span>- )}- </div>- {agent && (- <div className="flex items-center gap-0.5 shrink-0">- {editing ? (- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 gap-1 px-2"- onClick={() => setEditing(false)}- >- <X className="size-3" />- Cancel- </Button>- ) : (- <>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 gap-1 px-2"- onClick={() => setEditing(true)}- >- <Pencil className="size-3" />- Edit- </Button>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 px-2 hover:text-destructive"- onClick={() => setAgentConfirmOpen(true)}- >- <Trash2 className="size-3" />- Remove- </Button>- </>- )}- </div>- )}- </div>-- {editing && agent ? (- <AgentEditForm- agent={agent}- runtimes={runtimes}- saving={saving}- onCancel={() => setEditing(false)}- onSave={async (data) => {- setSaving(true);- try {- const ok = await handleUpdateAgent(agent.id, data);- if (ok) setEditing(false);- return ok;- } finally {- setSaving(false);- }- }}- />- ) : (- /* Session list */- <div className="flex-1 overflow-y-auto px-5">- <div className="mx-auto max-w-2xl py-6">- {/* Agent description */}- {agent?.description && (- <p className="text-base text-muted-foreground mb-6">- {agent.description}- </p>- )}-- {/* Sessions header */}- <div className="flex items-center justify-between mb-4">- <h2 className="text-xs font-medium text-muted-foreground uppercase tracking-wider">- Sessions- </h2>- <Button- size="sm"- className="h-7 text-xs gap-1"- onClick={handleNewSession}- disabled={creating}- >- {creating ? (- <Loader2 className="size-3 animate-spin" />- ) : (- <Plus className="size-3" />- )}- New Session- </Button>- </div>-- {loading ? (- <div className="flex items-center justify-center py-20">- <Loader2 className="size-5 animate-spin text-muted-foreground" />- </div>- ) : conversations.length === 0 ? (- /* Empty state */- <div className="text-center py-20 animate-[fade-up_400ms_ease-out_both]">- <p className="text-sm text-muted-foreground">- No sessions yet.- </p>- <p className="text-xs text-muted-foreground/60 mt-1">- Start a new session to begin chatting with this agent.- </p>- </div>- ) : (- /* Session rows */- <div className="space-y-2">- {conversations.map((conv) => (- <div- key={conv.id}- role="button"- tabIndex={0}- onClick={() =>- router.push(`/chat/${conv.id}?agent=${agentId}`)- }- onKeyDown={(e) => {- if (e.key === "Enter" || e.key === " ") {- e.preventDefault();- router.push(`/chat/${conv.id}?agent=${agentId}`);- }- }}- className="group w-full text-left rounded-lg border border-border/50 bg-background/50 px-4 py-3 transition-colors duration-200 hover:bg-accent/50 cursor-pointer"- >- <div className="flex items-start justify-between gap-3">- <div className="min-w-0 flex-1">- <p className="text-sm font-medium truncate">- {conv.title || (- <span className="text-muted-foreground">- Untitled · {relativeTime(conv.created_at)}- </span>- )}- </p>- <p className="text-xs text-muted-foreground mt-0.5">- {formatDate(conv.created_at)}- {conv.message_count !== undefined && (- <>- {" "}·{" "}- {conv.message_count}{" "}- {conv.message_count === 1 ? "message" : "messages"}- </>- )}- </p>- </div>- <button- type="button"- title="Delete session"- onClick={(e) => {- e.stopPropagation();- setDeleteTarget(conv);- }}- className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 p-1 rounded hover:bg-destructive/10 hover:text-destructive text-muted-foreground"- >- <Trash2 className="size-3.5" />- </button>- </div>- </div>- ))}- </div>- )}- </div>- </div>- )}-- {/* Delete session confirmation */}- <ConfirmDialog- open={!!deleteTarget}- onOpenChange={(open) => {- if (!open) setDeleteTarget(null);- }}- title="Delete session"- description={`This will permanently delete "${deleteTarget?.title || "Untitled"}" and all its messages.`}- loading={deleting}- onConfirm={handleDeleteConversation}- />-- {/* Delete agent confirmation */}- {agent && (- <ConfirmDialog- open={agentConfirmOpen}- onOpenChange={setAgentConfirmOpen}- title="Remove agent"- description={`This will permanently delete "${agent.name}" and all its conversations.`}- loading={agentDeleting}- onConfirm={async () => {- setAgentDeleting(true);- try {- const ok = await handleDeleteAgent(agent.id);- if (ok) router.push("/home");- } finally {- setAgentDeleting(false);- setAgentConfirmOpen(false);- }- }}- />- )}- </>- );-}diff --git a/src/web/app/(app)/agents/new/page.tsx b/src/web/app/(app)/agents/new/page.tsxdeleted file mode 100644index ad338d73f..000000000--- a/src/web/app/(app)/agents/new/page.tsx+++ /dev/null@@ -1,57 +0,0 @@-"use client";--import { useState } from "react";-import { useRouter } from "next/navigation";-import { useAgentContext } from "@/contexts/agent-context";-import { AgentEditForm } from "@/components/agent-edit-form";--export default function CreateAgentPage() {- const router = useRouter();- const {- runtimes,- handleCreateAgent,- chatWithAgent,- getFirstOnlineRuntimeId,- } = useAgentContext();-- const [saving, setSaving] = useState(false);-- return (- <>- <div className="flex items-center border-b border-border/50 px-5 py-2.5">- <h1 className="text-sm font-medium">Create Agent</h1>- </div>-- <AgentEditForm- runtimes={runtimes}- defaultRuntimeId={getFirstOnlineRuntimeId()}- saving={saving}- submitLabel="Create"- savingLabel="Creating..."- onCancel={() => router.back()}- onSave={async (data) => {- setSaving(true);- try {- const agent = await handleCreateAgent({- name: data.name,- description: data.description || undefined,- instructions: data.instructions || undefined,- runtime_id: data.runtime_id,- });- if (agent) {- const conversationId = await chatWithAgent(agent.id);- if (conversationId) {- router.push(`/chat/${conversationId}?agent=${agent.id}`);- } else {- router.push("/home");- }- }- return !!agent;- } finally {- setSaving(false);- }- }}- />- </>- );-}diff --git a/src/web/app/(app)/agents/page.tsx b/src/web/app/(app)/agents/page.tsxdeleted file mode 100644index f7c38b949..000000000--- a/src/web/app/(app)/agents/page.tsx+++ /dev/null@@ -1,14 +0,0 @@-"use client";--import { useEffect } from "react";-import { useRouter } from "next/navigation";--export default function AgentsRedirect() {- const router = useRouter();-- useEffect(() => {- router.replace("/home");- }, [router]);-- return null;-}diff --git a/src/web/app/(app)/chat/[id]/page.tsx b/src/web/app/(app)/chat/[id]/page.tsxdeleted file mode 100644index f097c3d98..000000000--- a/src/web/app/(app)/chat/[id]/page.tsx+++ /dev/null@@ -1,438 +0,0 @@-"use client";--import { useEffect, useState, useRef, useCallback } from "react";-import { useParams, useRouter, useSearchParams } from "next/navigation";-import { useAgentContext } from "@/contexts/agent-context";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import { ConfirmDialog } from "@/components/ui/confirm-dialog";-import { AgentEditForm } from "@/components/agent-edit-form";-import {- getConversation,- listMessages,- sendMessage,- getTask,- getTaskMessages,-} from "@/lib/api";-import type { Conversation, Message, Task, TaskMessage } from "@/lib/types";-import { toast } from "sonner";-import { cn } from "@/lib/utils";-import { ArrowUp, Loader2, Pencil, Trash2, X } from "lucide-react";-import { Streamdown } from "streamdown";--export default function ChatPage() {- const params = useParams();- const router = useRouter();- const searchParams = useSearchParams();- const conversationId = params.id as string;- const { agents, runtimes, handleDeleteAgent, handleUpdateAgent } =- useAgentContext();-- const agentId = searchParams.get("agent");- const agent = agents.find((a) => a.id === agentId);-- const [conversation, setConversation] = useState<Conversation | null>(null);- const [confirmOpen, setConfirmOpen] = useState(false);- const [deleting, setDeleting] = useState(false);- const [messages, setMessages] = useState<Message[]>([]);- const [input, setInput] = useState("");- const [sending, setSending] = useState(false);- const [activeTask, setActiveTask] = useState<Task | null>(null);- const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);- const [loading, setLoading] = useState(true);- const [connectionLost, setConnectionLost] = useState(false);-- // Inline edit state- const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);-- const scrollRef = useRef<HTMLDivElement>(null);- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);- const lastSeqRef = useRef(0);- const pollFailures = useRef(0);-- const scrollToBottom = useCallback(() => {- setTimeout(() => {- scrollRef.current?.scrollTo({- top: scrollRef.current.scrollHeight,- behavior: "smooth",- });- }, 50);- }, []);-- useEffect(() => {- async function load() {- try {- const [conv, msgs] = await Promise.all([- getConversation(conversationId),- listMessages(conversationId),- ]);- setConversation(conv);- setMessages(msgs);- } catch {- toast.error("Conversation not found");- router.push("/home");- } finally {- setLoading(false);- }- }- load();- }, [conversationId, router]);-- useEffect(() => {- scrollToBottom();- }, [messages, taskMessages, scrollToBottom]);-- const startPolling = useCallback(- (taskId: string) => {- if (pollRef.current) clearInterval(pollRef.current);- lastSeqRef.current = 0;- pollFailures.current = 0;- setConnectionLost(false);-- pollRef.current = setInterval(async () => {- try {- const [task, tmsgs] = await Promise.all([- getTask(taskId),- getTaskMessages(taskId, lastSeqRef.current || undefined),- ]);-- pollFailures.current = 0;- setConnectionLost(false);- setActiveTask(task);-- if (tmsgs.length > 0) {- setTaskMessages((prev) => [...prev, ...tmsgs]);- lastSeqRef.current = Math.max(- ...tmsgs.map((m) => m.seq),- lastSeqRef.current- );- }-- if (task.status === "completed" || task.status === "failed") {- if (pollRef.current) clearInterval(pollRef.current);- pollRef.current = null;-- try {- const updatedMessages = await listMessages(conversationId);- setMessages(updatedMessages);- } catch {- toast.error("Failed to refresh messages");- }- setActiveTask(null);- setTaskMessages([]);- }- } catch {- 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);- },- [conversationId]- );-- useEffect(() => {- return () => {- if (pollRef.current) clearInterval(pollRef.current);- };- }, []);-- const handleSend = async () => {- const content = input.trim();- if (!content || sending) return;-- setInput("");- setSending(true);-- const optimistic: Message = {- id: `temp-${Date.now()}`,- conversation_id: conversationId,- role: "user",- content,- created_at: new Date().toISOString(),- };- setMessages((prev) => [...prev, optimistic]);-- try {- const { message, task } = await sendMessage(conversationId, content);- setMessages((prev) =>- prev.map((m) => (m.id === optimistic.id ? message : m))- );- setActiveTask(task);- setTaskMessages([]);- startPolling(task.id);- } 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);- }- };-- const handleKeyDown = (e: React.KeyboardEvent) => {- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- handleSend();- }- };-- if (loading) {- return (- <div className="flex flex-1 items-center justify-center">- <Loader2 className="size-5 animate-spin text-muted-foreground" />- </div>- );- }-- return (- <>- {/* Agent navbar — stable regardless of edit/chat view */}- <div className="flex items-center justify-between border-b border-border/50 px-5 py-2.5">- <div className="flex items-center gap-2 min-w-0">- {agent && (() => {- const runtime = runtimes.find((r) => r.id === agent.runtime_id);- const isOnline = runtime?.status === "online";- return (- <span- title={isOnline ? "Runtime online" : "Runtime offline"}- className={cn(- "size-2 rounded-full shrink-0",- isOnline ? "bg-status-online" : "bg-status-offline"- )}- />- );- })()}- <h1- className={cn(- "text-sm font-medium truncate",- agentId && "cursor-pointer hover:opacity-70 transition-opacity duration-200"- )}- onClick={() => agentId && router.push(`/agents/${agentId}`)}- >- {agent?.name || "Agent"}- </h1>- {!editing && conversation?.title && (- <span className="text-xs text-muted-foreground truncate">- / {conversation.title}- </span>- )}- {editing && (- <span className="text-xs text-muted-foreground">/ Settings</span>- )}- </div>- {agent && (- <div className="flex items-center gap-0.5 shrink-0">- {editing ? (- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 gap-1 px-2"- onClick={() => setEditing(false)}- >- <X className="size-3" />- Cancel- </Button>- ) : (- <>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 gap-1 px-2"- onClick={() => setEditing(true)}- >- <Pencil className="size-3" />- Edit- </Button>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-7 px-2 hover:text-destructive"- onClick={() => setConfirmOpen(true)}- >- <Trash2 className="size-3" />- Remove- </Button>- </>- )}- </div>- )}- </div>-- {editing && agent ? (- <AgentEditForm- agent={agent}- runtimes={runtimes}- saving={saving}- onCancel={() => setEditing(false)}- onSave={async (data) => {- setSaving(true);- try {- const ok = await handleUpdateAgent(agent.id, data);- if (ok) setEditing(false);- return ok;- } finally {- setSaving(false);- }- }}- />- ) : (- <>- {/* Messages */}- <div className="flex-1 overflow-y-auto px-5" ref={scrollRef}>- <div className="mx-auto max-w-2xl py-6 space-y-4">- {messages.length === 0 && !activeTask && (- <p className="text-center text-muted-foreground py-20 text-sm">- Send a message to start chatting with the agent.- </p>- )}-- {messages.map((msg) => (- <div- key={msg.id}- className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}- >- {msg.role === "user" ? (- <div className="max-w-[80%] rounded-lg px-4 py-2 bg-primary text-primary-foreground whitespace-pre-wrap">- {msg.content}- </div>- ) : (- <div className="markdown max-w-full px-1 py-1 text-base text-foreground">- <Streamdown>{msg.content}</Streamdown>- </div>- )}- </div>- ))}-- {activeTask && (- <div className="rounded-lg border bg-muted/50 p-4 space-y-2">- <div className="flex items-center gap-2">- <Badge variant="secondary">- {activeTask.status === "running"- ? "Agent working..."- : activeTask.status}- </Badge>- </div>- {taskMessages.length > 0 && (- <div className="mt-2 max-h-60 overflow-y-auto rounded-lg bg-muted/30 p-3 font-mono text-xs space-y-1">- {taskMessages.map((tm) => (- <div key={tm.id} className="text-muted-foreground">- {tm.type === "tool-use" && (- <span className="text-primary">- [tool] {tm.tool}- </span>- )}- {tm.type === "tool-result" && (- <span className="text-accent-foreground">- [result] {tm.output || tm.content}- </span>- )}- {tm.type === "text" && <span>{tm.content}</span>}- {tm.type === "thinking" && (- <span className="italic opacity-60">- {tm.content}- </span>- )}- {!["tool-use", "tool-result", "text", "thinking"].includes(- tm.type- ) && (- <span>- [{tm.type}] {tm.content}- </span>- )}- </div>- ))}- </div>- )}- {activeTask.status === "failed" && activeTask.error && (- <p className="text-sm text-destructive">- {activeTask.error}- </p>- )}- {connectionLost && (- <p className="text-xs text-muted-foreground animate-pulse">- Connection lost — retrying...- </p>- )}- </div>- )}- </div>- </div>-- {/* Input */}- <div className="px-5 py-3">- <div className="mx-auto max-w-2xl">- <div- className={cn(- "relative flex flex-col rounded-xl border bg-background/60 transition-colors duration-200",- "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",- (sending || !!activeTask) && "opacity-50"- )}- >- <textarea- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={handleKeyDown}- placeholder="Type a message..."- rows={1}- disabled={sending || !!activeTask}- className={cn(- "field-sizing-content w-full resize-none bg-transparent px-3.5 pt-2.5 text-base outline-none",- "placeholder:text-muted-foreground disabled:cursor-not-allowed",- "min-h-[38px] max-h-[200px]"- )}- />- <div className="flex items-center justify-end px-2 pb-2 pt-0.5">- <Button- size="icon-sm"- onClick={handleSend}- disabled={!input.trim() || sending || !!activeTask}- className={cn(- "rounded-lg transition-opacity duration-200",- !input.trim() && "opacity-40"- )}- >- {sending ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <ArrowUp className="size-3.5" />- )}- </Button>- </div>- </div>- </div>- </div>- </>- )}-- {agent && (- <ConfirmDialog- open={confirmOpen}- onOpenChange={setConfirmOpen}- title="Remove agent"- description={`This will permanently delete "${agent.name}" and all its conversations.`}- loading={deleting}- onConfirm={async () => {- setDeleting(true);- try {- const ok = await handleDeleteAgent(agent.id);- if (ok) router.push("/home");- } finally {- setDeleting(false);- setConfirmOpen(false);- }- }}- />- )}- </>- );-}diff --git a/src/web/app/(app)/error.tsx b/src/web/app/(app)/error.tsxdeleted file mode 100644index 1ca1e61be..000000000--- a/src/web/app/(app)/error.tsx+++ /dev/null@@ -1,24 +0,0 @@-"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.tsxdeleted file mode 100644index 3ef3a282c..000000000--- a/src/web/app/(app)/home/page.tsx+++ /dev/null@@ -1,74 +0,0 @@-"use client";--import { useEffect, useRef } from "react";-import { useRouter } from "next/navigation";-import { useAgentContext } from "@/contexts/agent-context";-import { Button } from "@/components/ui/button";-import { Loader2 } from "lucide-react";--export default function HomePage() {- const router = useRouter();- const { agents, runtimes, loading } = useAgentContext();- const redirectedRef = useRef(false);-- // Auto-redirect to first agent's detail page- useEffect(() => {- if (loading || redirectedRef.current) return;- if (agents.length === 0) return;-- redirectedRef.current = true;- const sorted = [...agents].sort((a, b) => a.name.localeCompare(b.name));- const first = sorted[0];- router.replace(`/agents/${first.id}`);- }, [agents, loading, router]);-- if (loading) {- return (- <div className="flex flex-1 items-center justify-center">- <Loader2 className="size-5 animate-spin text-muted-foreground" />- </div>- );- }-- // Redirecting to first agent chat- if (agents.length > 0) {- return (- <div className="flex flex-1 items-center justify-center">- <Loader2 className="size-5 animate-spin text-muted-foreground" />- </div>- );- }-- // Empty state — no agents- const hasMachines = runtimes.length > 0;-- return (- <div className="flex flex-1 items-center justify-center">- <div className="text-center animate-[fade-up_400ms_ease-out_both]">- {hasMachines ? (- <>- <p className="text-muted-foreground text-sm">No agents yet.</p>- <Button- size="sm"- className="mt-4"- onClick={() => router.push("/agents/new")}- >- Create Agent- </Button>- </>- ) : (- <>- <p className="text-muted-foreground text-sm">No machines yet.</p>- <Button- size="sm"- className="mt-4"- onClick={() => router.push("/runtimes")}- >- Connect Machine- </Button>- </>- )}- </div>- </div>- );-}diff --git a/src/web/app/(app)/layout.tsx b/src/web/app/(app)/layout.tsxdeleted file mode 100644index 0330f104d..000000000--- a/src/web/app/(app)/layout.tsx+++ /dev/null@@ -1,46 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { useRouter } from "next/navigation";-import { AgentProvider } from "@/contexts/agent-context";-import { AppSidebar } from "@/components/app-sidebar";-import { GradientBackground } from "@/components/gradient-background";--export default function AppLayout({ children }: { children: React.ReactNode }) {- const router = useRouter();- const [ready, setReady] = useState(false);- const readyRef = useRef(setReady);-- useEffect(() => {- try {- const token = localStorage.getItem("alook_token");- if (!token) {- router.replace("/login");- } else {- readyRef.current(true);- }- } catch {- router.replace("/login");- }- }, [router]);-- if (!ready) return null;-- return (- <AgentProvider>- <div className="flex h-screen overflow-hidden relative">- <GradientBackground />-- {/* Sidebar rail — stable across route changes */}- <AppSidebar />-- {/* Floating content panel */}- <div className="flex-1 min-w-0 p-2 pl-0">- <main className="h-full rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">- {children}- </main>- </div>- </div>- </AgentProvider>- );-}diff --git a/src/web/app/(app)/runtimes/page.tsx b/src/web/app/(app)/runtimes/page.tsxdeleted file mode 100644index 901752110..000000000--- a/src/web/app/(app)/runtimes/page.tsx+++ /dev/null@@ -1,364 +0,0 @@-"use client";--import { useState, useRef, useEffect, useCallback } from "react";-import { useAgentContext } from "@/contexts/agent-context";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import {- Card,- CardHeader,- CardTitle,- CardAction,- CardContent,-} from "@/components/ui/card";-import {- Sheet,- SheetContent,- SheetHeader,- SheetTitle,- SheetDescription,- SheetBody,-} from "@/components/ui/sheet";-import { ConfirmDialog } from "@/components/ui/confirm-dialog";-import { toast } from "sonner";-import { Loader2, Monitor, Plus } from "lucide-react";-import type { Runtime } from "@/lib/types";--function ConnectMachineSteps({- generatedToken,- generatingToken,- onGenerateToken,-}: {- generatedToken: string;- generatingToken: boolean;- onGenerateToken: () => void;-}) {- const hasTriggered = useRef(false);- useEffect(() => {- if (!generatedToken && !generatingToken && !hasTriggered.current) {- hasTriggered.current = true;- onGenerateToken();- }- }, [generatedToken, generatingToken, onGenerateToken]);-- const copyToClipboard = (text: string) => {- navigator.clipboard.writeText(text);- toast("Copied to clipboard");- };-- return (- <div className="space-y-6">- {/* Step 1 */}- <div className="space-y-2">- <p className="text-xs font-medium flex items-center gap-2">- <span className="flex items-center justify-center size-5 rounded-full bg-foreground text-background text-[10px] font-semibold">- 1- </span>- Register your CLI- </p>- <p className="text-xs text-muted-foreground pl-7">- Run this in your terminal to link your machine.- </p>- {generatingToken ? (- <div className="pl-7">- <div className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground animate-pulse">- Generating token...- </div>- </div>- ) : generatedToken ? (- <div className="pl-7 space-y-2">- <div- className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"- onClick={() =>- copyToClipboard(- `npx @alook/cli register --token ${generatedToken}`- )- }- title="Click to copy"- >- npx @alook/cli register --token{" "}- <span className="text-foreground/70">- {generatedToken.slice(0, 12)}...- </span>- </div>- <Button- size="sm"- onClick={() => {- navigator.clipboard.writeText(- `npx @alook/cli register --token ${generatedToken}`- );- toast("Copied to clipboard");- }}- className="w-full"- >- Copy Command- </Button>- </div>- ) : null}- </div>-- {/* Step 2 */}- <div- className={`space-y-2 ${!generatedToken ? "opacity-40 pointer-events-none" : ""}`}- >- <p className="text-xs font-medium flex items-center gap-2">- <span className="flex items-center justify-center size-5 rounded-full bg-foreground text-background text-[10px] font-semibold">- 2- </span>- Start the daemon- </p>- <p className="text-xs text-muted-foreground pl-7">- The daemon connects your local agents to Alook.- </p>- <div- className="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"- onClick={() =>- copyToClipboard("npx @alook/cli daemon start --foreground")- }- title="Click to copy"- >- npx @alook/cli daemon start --foreground- </div>- </div>-- </div>- );-}--export default function RuntimesPage() {- const { runtimes, loading, handleGenerateToken, handleDeleteMachine, reload } =- useAgentContext();-- const [sheetOpen, setSheetOpen] = useState(false);- const [generatedToken, setGeneratedToken] = useState("");- const [generatingToken, setGeneratingToken] = useState(false);-- const [confirmOpen, setConfirmOpen] = useState(false);- const [confirmTitle, setConfirmTitle] = useState("");- const [confirmDescription, setConfirmDescription] = useState("");- const [confirmLoading, setConfirmLoading] = useState(false);- const confirmAction = useRef<(() => Promise<void>) | null>(null);-- useEffect(() => {- reload();- }, [reload]);-- const openConfirm = (- title: string,- description: string,- action: () => Promise<void>- ) => {- setConfirmTitle(title);- setConfirmDescription(description);- confirmAction.current = action;- setConfirmOpen(true);- };-- const handleConfirm = async () => {- if (!confirmAction.current) return;- setConfirmLoading(true);- try {- await confirmAction.current();- } finally {- setConfirmLoading(false);- setConfirmOpen(false);- confirmAction.current = null;- }- };-- const onGenerateToken = useCallback(async () => {- setGeneratingToken(true);- try {- const token = await handleGenerateToken();- if (token) setGeneratedToken(token);- } finally {- setGeneratingToken(false);- }- }, [handleGenerateToken]);-- // Group runtimes by machine- const machines = new Map<- string,- { deviceInfo: string; name: string; runtimes: Runtime[] }- >();- for (const rt of runtimes) {- const key = rt.daemon_id || rt.id;- if (!machines.has(key)) {- machines.set(key, {- deviceInfo: typeof rt.device_info === "string" ? rt.device_info : "",- name: rt.name || "",- runtimes: [],- });- }- machines.get(key)!.runtimes.push(rt);- }-- if (loading) {- return (- <div className="flex flex-1 items-center justify-center">- <Loader2 className="size-5 animate-spin text-muted-foreground" />- </div>- );- }-- return (- <>- {/* Title bar */}- <div className="flex items-center justify-between border-b border-border/50 px-5 py-2.5">- <div className="flex items-center gap-3">- <h1 className="text-sm font-medium">Runtimes</h1>- <p className="text-xs text-muted-foreground">- Your machines and their agent runtimes.- </p>- </div>- <Button- size="sm"- variant="outline"- onClick={() => {- setGeneratedToken("");- setSheetOpen(true);- }}- disabled={generatingToken}- >- <Plus className="size-3.5" />- New machine- </Button>- </div>-- <div className="flex-1 overflow-y-auto px-5 py-5">- {runtimes.length === 0 ? (- <div className="flex flex-1 items-center justify-center py-12">- <div className="text-center animate-[fade-up_400ms_ease-out_both]">- <p className="text-muted-foreground text-sm">- No machines connected.- </p>- <p className="text-xs text-muted-foreground mt-2 max-w-xs mx-auto">- Connect a machine to start running agents locally.- </p>- <Button- size="sm"- className="mt-5"- onClick={() => {- setGeneratedToken("");- setSheetOpen(true);- }}- >- Connect Machine- </Button>- </div>- </div>- ) : (- <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">- {Array.from(machines.entries()).map(([daemonId, machine]) => {- const displayName =- machine.deviceInfo || machine.name || daemonId;- return (- <Card key={daemonId} size="sm" className="group">- <CardHeader>- <div className="flex items-center gap-2">- <Monitor className="size-4 text-muted-foreground shrink-0" />- <CardTitle className="truncate">- {displayName}- </CardTitle>- </div>- <CardAction>- <Button- variant="ghost"- size="sm"- className="text-xs text-muted-foreground h-6 px-2 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"- onClick={() => {- openConfirm(- "Remove machine",- `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,- async () => {- await handleDeleteMachine(daemonId);- }- );- }}- >- Remove- </Button>- </CardAction>- </CardHeader>- <CardContent>- <div className="space-y-2">- {machine.runtimes.map((runtime) => (- <div- key={runtime.id}- className="flex items-center justify-between gap-2"- >- <div className="min-w-0">- <p className="text-xs font-medium truncate">- {runtime.provider}- {runtime.metadata?.version ? (- <span className="ml-1.5 font-normal text-muted-foreground">- {String(runtime.metadata.version)}- </span>- ) : null}- </p>- <p className="text-xs text-muted-foreground tabular-nums">- {new Date(- runtime.last_seen_at- ).toLocaleString()}- </p>- </div>- <Badge- variant={- runtime.status === "online"- ? "default"- : "outline"- }- className="shrink-0"- >- {runtime.status}- </Badge>- </div>- ))}- </div>- </CardContent>- </Card>- );- })}- </div>- )}- </div>-- {/* Connect machine sheet */}- <Sheet- open={sheetOpen}- onOpenChange={(open) => {- setSheetOpen(open);- if (!open) {- setGeneratedToken("");- }- }}- >- <SheetContent className="data-[side=right]:inset-y-2 data-[side=right]:right-2 data-[side=right]:h-auto data-[side=right]:rounded-xl data-[side=right]:border data-[side=right]:border-l">- <SheetHeader>- <SheetTitle>Connect a machine</SheetTitle>- <SheetDescription>- Your machine runs AI agents locally using Claude Code, Codex, or- OpenCode.- </SheetDescription>- </SheetHeader>- <SheetBody>- <ConnectMachineSteps- generatedToken={generatedToken}- generatingToken={generatingToken}- onGenerateToken={onGenerateToken}- />- </SheetBody>- </SheetContent>- </Sheet>-- <ConfirmDialog- open={confirmOpen}- onOpenChange={setConfirmOpen}- title={confirmTitle}- description={confirmDescription}- loading={confirmLoading}- onConfirm={handleConfirm}- />- </>- );-}diff --git a/src/web/app/api/daemon/tasks/[taskId]/progress/route.ts b/src/web/app/api/daemon/tasks/[taskId]/progress/route.tsdeleted file mode 100644index 2da5845fd..000000000--- a/src/web/app/api/daemon/tasks/[taskId]/progress/route.ts+++ /dev/null@@ -1,6 +0,0 @@-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";--export const POST = withAuth(async () => {- return writeJSON({ status: "ok" });-});diff --git a/src/web/app/api/health/route.test.ts b/src/web/app/api/health/route.test.tsdeleted file mode 100644index c6e53c784..000000000--- a/src/web/app/api/health/route.test.ts+++ /dev/null@@ -1,15 +0,0 @@-import { describe, it, expect } from "vitest";-import { GET } from "./route";--describe("GET /api/health", () => {- it("returns { status: 'ok' }", async () => {- const res = await GET();- const body = await res.json();- expect(body).toEqual({ status: "ok" });- });-- it("responds with status code 200", async () => {- const res = await GET();- expect(res.status).toBe(200);- });-});diff --git a/src/web/app/api/health/route.ts b/src/web/app/api/health/route.tsdeleted file mode 100644index ee6aa4f54..000000000--- a/src/web/app/api/health/route.ts+++ /dev/null@@ -1,5 +0,0 @@-import { NextResponse } from "next/server";--export async function GET() {- return NextResponse.json({ status: "ok" });-}diff --git a/src/web/app/apple-icon.png b/src/web/app/apple-icon.pngdeleted file mode 100644index 3cf91e319..000000000Binary files a/src/web/app/apple-icon.png and /dev/null differdiff --git a/src/web/app/error.tsx b/src/web/app/error.tsxdeleted file mode 100644index 673dc5058..000000000--- a/src/web/app/error.tsx+++ /dev/null@@ -1,24 +0,0 @@-"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/favicon.ico b/src/web/app/favicon.icodeleted file mode 100644index a1e69350c..000000000Binary files a/src/web/app/favicon.ico and /dev/null differdiff --git a/src/web/app/globals.css b/src/web/app/globals.cssdeleted file mode 100644index 1f8d7a601..000000000--- a/src/web/app/globals.css+++ /dev/null@@ -1,406 +0,0 @@-@import "tailwindcss";-@import "tw-animate-css";-@import "shadcn/tailwind.css";-@source "../node_modules/streamdown/dist/*.js";--@custom-variant dark (&:is(.dark *));--@theme inline {- --text-base: 0.9375rem;- --text-base--line-height: 1.6;- --color-background: var(--background);- --color-foreground: var(--foreground);- --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);- --color-sidebar-accent: var(--sidebar-accent);- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);- --color-sidebar-primary: var(--sidebar-primary);- --color-sidebar-foreground: var(--sidebar-foreground);- --color-sidebar: var(--sidebar);- --color-chart-5: var(--chart-5);- --color-chart-4: var(--chart-4);- --color-chart-3: var(--chart-3);- --color-chart-2: var(--chart-2);- --color-chart-1: var(--chart-1);- --color-ring: var(--ring);- --color-input: var(--input);- --color-border: var(--border);- --color-status-online: var(--status-online);- --color-status-offline: var(--status-offline);- --color-destructive: var(--destructive);- --color-accent-foreground: var(--accent-foreground);- --color-accent: var(--accent);- --color-muted-foreground: var(--muted-foreground);- --color-muted: var(--muted);- --color-secondary-foreground: var(--secondary-foreground);- --color-secondary: var(--secondary);- --color-primary-foreground: var(--primary-foreground);- --color-primary: var(--primary);- --color-popover-foreground: var(--popover-foreground);- --color-popover: var(--popover);- --color-card-foreground: var(--card-foreground);- --color-card: var(--card);- --radius-sm: calc(var(--radius) * 0.6);- --radius-md: calc(var(--radius) * 0.8);- --radius-lg: var(--radius);- --radius-xl: calc(var(--radius) * 1.4);- --radius-2xl: calc(var(--radius) * 1.8);- --radius-3xl: calc(var(--radius) * 2.2);- --radius-4xl: calc(var(--radius) * 2.6);-}--:root {- --background: oklch(0.995 0.005 80);- --foreground: oklch(0.18 0.01 60);- --card: oklch(1 0.003 80);- --card-foreground: oklch(0.18 0.01 60);- --popover: oklch(1 0.003 80);- --popover-foreground: oklch(0.18 0.01 60);- --primary: oklch(0.25 0.012 60);- --primary-foreground: oklch(0.985 0.005 80);- --secondary: oklch(0.965 0.006 80);- --secondary-foreground: oklch(0.25 0.012 60);- --muted: oklch(0.965 0.006 80);- --muted-foreground: oklch(0.52 0.01 60);- --accent: oklch(0.96 0.008 80);- --accent-foreground: oklch(0.25 0.012 60);- --destructive: oklch(0.577 0.245 27.325);- --border: oklch(0.915 0.008 80);- --input: oklch(0.915 0.008 80);- --ring: oklch(0.68 0.01 60);- --chart-1: oklch(0.85 0.01 80);- --chart-2: oklch(0.55 0.01 60);- --chart-3: oklch(0.44 0.01 60);- --chart-4: oklch(0.37 0.01 60);- --chart-5: oklch(0.27 0.01 60);- --radius: 0.625rem;- --status-online: oklch(0.72 0.19 145);- --status-offline: oklch(0.65 0.2 25);- --sidebar: oklch(0.98 0.005 80);- --sidebar-foreground: oklch(0.18 0.01 60);- --sidebar-primary: oklch(0.25 0.012 60);- --sidebar-primary-foreground: oklch(0.985 0.005 80);- --sidebar-accent: oklch(0.96 0.008 80);- --sidebar-accent-foreground: oklch(0.25 0.012 60);- --sidebar-border: oklch(0.915 0.008 80);- --sidebar-ring: oklch(0.68 0.01 60);-}--.dark {- --background: oklch(0.16 0.008 60);- --foreground: oklch(0.93 0.006 80);- --card: oklch(0.21 0.008 60);- --card-foreground: oklch(0.93 0.006 80);- --popover: oklch(0.21 0.008 60);- --popover-foreground: oklch(0.93 0.006 80);- --primary: oklch(0.9 0.008 80);- --primary-foreground: oklch(0.21 0.008 60);- --secondary: oklch(0.27 0.008 60);- --secondary-foreground: oklch(0.93 0.006 80);- --muted: oklch(0.27 0.008 60);- --muted-foreground: oklch(0.65 0.01 70);- --accent: oklch(0.27 0.008 60);- --accent-foreground: oklch(0.93 0.006 80);- --destructive: oklch(0.704 0.191 22.216);- --border: oklch(1 0.005 80 / 10%);- --input: oklch(1 0.005 80 / 15%);- --ring: oklch(0.55 0.01 60);- --chart-1: oklch(0.85 0.01 80);- --chart-2: oklch(0.55 0.01 60);- --chart-3: oklch(0.44 0.01 60);- --chart-4: oklch(0.37 0.01 60);- --chart-5: oklch(0.27 0.01 60);- --status-online: oklch(0.75 0.18 145);- --status-offline: oklch(0.7 0.18 25);- --sidebar: oklch(0.21 0.008 60);- --sidebar-foreground: oklch(0.93 0.006 80);- --sidebar-primary: oklch(0.488 0.243 264.376);- --sidebar-primary-foreground: oklch(0.985 0.005 80);- --sidebar-accent: oklch(0.27 0.008 60);- --sidebar-accent-foreground: oklch(0.93 0.006 80);- --sidebar-border: oklch(1 0.005 80 / 10%);- --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;-}--/* ── Gradient background blobs ── */-.gradient-blob {- position: absolute;- filter: blur(40px);- opacity: 0.7;- will-change: transform;-}--.gradient-blob-1 {- width: 750px;- height: 450px;- top: -140px;- left: -200px;- border-radius: 30% 70% 64% 36% / 62% 28% 72% 38%;- background: oklch(0.90 0.12 90);- animation: blob-drift-1 25s ease-in-out infinite;-}--.gradient-blob-2 {- width: 500px;- height: 720px;- bottom: -180px;- right: -150px;- border-radius: 68% 32% 25% 75% / 38% 72% 28% 62%;- background: oklch(0.88 0.10 85);- animation: blob-drift-2 30s ease-in-out infinite;-}--.gradient-blob-3 {- width: 680px;- height: 400px;- top: -100px;- right: -180px;- border-radius: 25% 75% 68% 32% / 72% 35% 65% 28%;- background: oklch(0.86 0.14 95);- animation: blob-drift-3 22s ease-in-out infinite;-}--.gradient-blob-4 {- width: 420px;- height: 700px;- bottom: -160px;- left: -120px;- border-radius: 72% 28% 35% 65% / 25% 68% 32% 75%;- background: oklch(0.89 0.11 80);- animation: blob-drift-4 28s ease-in-out infinite;-}--.dark .gradient-blob-1 {- background: oklch(0.38 0.16 290);- opacity: 0.65;-}--.dark .gradient-blob-2 {- background: oklch(0.34 0.14 270);- opacity: 0.6;-}--.dark .gradient-blob-3 {- background: oklch(0.36 0.18 310);- opacity: 0.6;-}--.dark .gradient-blob-4 {- background: oklch(0.32 0.15 280);- opacity: 0.55;-}--/* Blob 1: top-left corner → drifts toward center, morphs shape */-@keyframes blob-drift-1 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 30% 70% 64% 36% / 62% 28% 72% 38%;- }- 50% {- transform: translate(200px, 180px) scale(1.05);- border-radius: 65% 35% 28% 72% / 38% 68% 32% 62%;- }-}--/* Blob 2: bottom-right corner → drifts toward center, morphs shape */-@keyframes blob-drift-2 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 68% 32% 25% 75% / 38% 72% 28% 62%;- }- 50% {- transform: translate(-200px, -180px) scale(1.08);- border-radius: 32% 68% 72% 28% / 65% 30% 70% 35%;- }-}--/* Blob 3: top-right corner → drifts toward center, morphs shape */-@keyframes blob-drift-3 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 25% 75% 68% 32% / 72% 35% 65% 28%;- }- 50% {- transform: translate(-180px, 200px) scale(1.06);- border-radius: 70% 30% 35% 65% / 28% 72% 38% 62%;- }-}--/* Blob 4: bottom-left corner → drifts toward center, morphs shape */-@keyframes blob-drift-4 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 72% 28% 35% 65% / 25% 68% 32% 75%;- }- 50% {- transform: translate(180px, -200px) scale(1.04);- border-radius: 28% 72% 65% 35% / 70% 25% 75% 30%;- }-}--/* ── Motion tokens ── */-@keyframes fade-up {- from {- opacity: 0;- transform: translateY(8px);- }- to {- opacity: 1;- transform: translateY(0);- }-}--/* ── Utility: hide scrollbar ── */-.scrollbar-none {- -ms-overflow-style: none;- scrollbar-width: none;-}-.scrollbar-none::-webkit-scrollbar {- display: none;-}--@layer base {- * {- @apply border-border outline-ring/50;- }- body {- @apply bg-background text-foreground;- font-kerning: normal;- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;- }- html {- @apply font-sans;- 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.15;- letter-spacing: -0.015em;- }- p {- line-height: 1.6;- }-}--/* Markdown content styles */-.markdown {- line-height: 1.65;-}-.markdown > *:first-child {- margin-top: 0;-}-.markdown > *:last-child {- margin-bottom: 0;-}-.markdown h1,-.markdown h2,-.markdown h3,-.markdown h4 {- font-weight: 600;- letter-spacing: -0.015em;- margin-top: 1.25em;- margin-bottom: 0.5em;- line-height: 1.3;-}-.markdown h1 { font-size: 1.25em; }-.markdown h2 { font-size: 1.125em; }-.markdown h3 { font-size: 1em; }-.markdown p {- margin-top: 0.5em;- margin-bottom: 0.5em;-}-.markdown ul,-.markdown ol {- margin-top: 0.5em;- margin-bottom: 0.5em;- padding-left: 1.5em;-}-.markdown ul { list-style-type: disc; }-.markdown ol { list-style-type: decimal; }-.markdown li {- margin-top: 0.2em;- margin-bottom: 0.2em;-}-.markdown li > ul,-.markdown li > ol {- margin-top: 0.15em;- margin-bottom: 0.15em;-}-.markdown code:not(pre code) {- font-family: var(--font-mono);- font-size: 0.85em;- padding: 0.15em 0.35em;- border-radius: 0.3em;- background: var(--muted);-}-.markdown pre {- margin-top: 0.75em;- margin-bottom: 0.75em;- border-radius: 0.5em;- overflow-x: auto;- font-size: 0.85em;- line-height: 1.55;-}-.markdown pre:not(:has(> code)) {- padding: 0.75em 1em;- background: var(--muted);-}-.markdown blockquote {- margin-top: 0.75em;- margin-bottom: 0.75em;- padding-left: 1em;- border-left: 2px solid var(--border);- color: var(--muted-foreground);-}-.markdown a {- text-decoration: underline;- text-underline-offset: 2px;- text-decoration-color: var(--border);- transition: text-decoration-color 200ms;-}-.markdown a:hover {- text-decoration-color: currentColor;-}-.markdown hr {- margin-top: 1.25em;- margin-bottom: 1.25em;- border-color: var(--border);-}-.markdown table {- width: 100%;- margin-top: 0.75em;- margin-bottom: 0.75em;- border-collapse: collapse;- font-size: 0.9em;-}-.markdown th,-.markdown td {- padding: 0.4em 0.75em;- border: 1px solid var(--border);- text-align: left;-}-.markdown th {- font-weight: 600;- background: var(--muted);-}-.markdown strong { font-weight: 600; }-.markdown em { font-style: italic; }diff --git a/src/web/app/icon.svg b/src/web/app/icon.svgdeleted file mode 100644index a751bf229..000000000--- a/src/web/app/icon.svg+++ /dev/null@@ -1,6 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="3 5 22 22" fill="black">- <rect x="4" y="6" width="18" height="18" rx="3" opacity="0.4" />- <rect x="6" y="8" width="18" height="18" rx="3" />- <rect x="9.5" y="13" width="11" height="9" rx="2" fill="white" />- <path d="M 10 13.5 Q 15 18.5 20 13.5" fill="none" stroke="black" stroke-width="1.4" stroke-linecap="round" />-</svg>diff --git a/src/web/app/layout.tsx b/src/web/app/layout.tsxdeleted file mode 100644index 03de78574..000000000--- a/src/web/app/layout.tsx+++ /dev/null@@ -1,50 +0,0 @@-import type { Metadata } from "next";-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({- variable: "--font-dm-sans",- subsets: ["latin"],- weight: ["400", "500", "600"],-});--const dmMono = DM_Mono({- variable: "--font-dm-mono",- subsets: ["latin"],- 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",-};--export default function RootLayout({- children,-}: Readonly<{- children: React.ReactNode;-}>) {- return (- <html- lang="en"- 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.tsxdeleted file mode 100644index bc96da878..000000000--- a/src/web/app/login/page.tsx+++ /dev/null@@ -1,171 +0,0 @@-"use client";--import { useState } from "react";-import { useRouter } from "next/navigation";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import {- InputOTP,- InputOTPGroup,- InputOTPSlot,-} from "@/components/ui/input-otp";-import {- Card,- CardContent,- CardDescription,- CardHeader,-} from "@/components/ui/card";-import { Logo } from "@/components/logo";-import { GradientBackground } from "@/components/gradient-background";-import { sendCode, verifyCode, listWorkspaces } from "@/lib/api";-import { ApiError } from "@/lib/errors";--export default function LoginPage() {- const router = useRouter();- const [email, setEmail] = useState("");- const [code, setCode] = useState("");- const [step, setStep] = useState<"email" | "code">("email");- const [loading, setLoading] = useState(false);- const [error, setError] = useState("");-- const handleSendCode = async (e: React.FormEvent) => {- e.preventDefault();- setError("");- setLoading(true);- try {- await sendCode(email);- setStep("code");- } catch (err) {- 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);- }- };-- const handleVerifyCode = async (value: string) => {- setCode(value);- if (value.length !== 6) return;-- setError("");- setLoading(true);- try {- const res = await verifyCode(email, value);- localStorage.setItem("alook_token", res.token);-- 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) {- 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);- }- };-- return (- <div className="flex min-h-screen items-center justify-center p-4 relative">- <GradientBackground />- <Card className="w-full max-w-sm bg-card/80 backdrop-blur-xl">- <CardHeader className="text-center">- <Logo size="lg" className="justify-center" />- <CardDescription>- {step === "email"- ? "Sign in with your email"- : "Enter the verification code"}- </CardDescription>- </CardHeader>- <CardContent>- {step === "email" ? (- <form onSubmit={handleSendCode} className="space-y-4">- <div className="space-y-2">- <Label htmlFor="email">Email</Label>- <Input- id="email"- type="email"- placeholder="[email protected]"- value={email}- onChange={(e) => setEmail(e.target.value)}- required- autoFocus- />- </div>- {error && (- <p className="text-sm text-destructive">{error}</p>- )}- <Button type="submit" className="w-full" disabled={loading}>- {loading ? "Sending..." : "Send Code"}- </Button>- </form>- ) : (- <div className="space-y-4">- <p className="text-sm text-muted-foreground text-center">- We sent a code to <strong>{email}</strong>- </p>- <div className="flex justify-center">- <InputOTP- maxLength={6}- value={code}- onChange={handleVerifyCode}- disabled={loading}- autoFocus- >- <InputOTPGroup>- <InputOTPSlot index={0} />- <InputOTPSlot index={1} />- <InputOTPSlot index={2} />- <InputOTPSlot index={3} />- <InputOTPSlot index={4} />- <InputOTPSlot index={5} />- </InputOTPGroup>- </InputOTP>- </div>- {error && (- <p className="text-sm text-destructive text-center">{error}</p>- )}- <Button- variant="ghost"- className="w-full"- onClick={() => {- setStep("email");- setCode("");- setError("");- }}- >- Use a different email- </Button>- </div>- )}- </CardContent>- </Card>- </div>- );-}diff --git a/src/web/app/page.tsx b/src/web/app/page.tsxdeleted file mode 100644index 1ae2caac7..000000000--- a/src/web/app/page.tsx+++ /dev/null@@ -1,19 +0,0 @@-"use client";--import { useEffect } from "react";-import { useRouter } from "next/navigation";--export default function Home() {- const router = useRouter();-- useEffect(() => {- const token = localStorage.getItem("alook_token");- if (token) {- router.replace("/home");- } else {- router.replace("/login");- }- }, [router]);-- return null;-}diff --git a/src/web/components/agent-edit-form.tsx b/src/web/components/agent-edit-form.tsxdeleted file mode 100644index 7da927e53..000000000--- a/src/web/components/agent-edit-form.tsx+++ /dev/null@@ -1,118 +0,0 @@-"use client";--import { useState } from "react";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { Textarea } from "@/components/ui/textarea";-import { RuntimeSelect } from "@/components/runtime-select";-import type { Agent, Runtime } from "@/lib/types";--interface AgentEditFormProps {- agent?: Agent;- runtimes: Runtime[];- defaultRuntimeId?: string;- onSave: (data: {- name: string;- description: string;- instructions: string;- runtime_id: string;- }) => Promise<boolean>;- onCancel: () => void;- saving: boolean;- submitLabel?: string;- savingLabel?: string;-}--export function AgentEditForm({- agent,- runtimes,- defaultRuntimeId = "",- onSave,- onCancel,- saving,- submitLabel = "Save",- savingLabel = "Saving...",-}: AgentEditFormProps) {- const [name, setName] = useState(agent?.name ?? "");- const [description, setDescription] = useState(agent?.description ?? "");- const [instructions, setInstructions] = useState(agent?.instructions ?? "");- const [runtimeId, setRuntimeId] = useState(- agent?.runtime_id ?? defaultRuntimeId- );-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();- await onSave({- name,- description,- instructions,- runtime_id: runtimeId,- });- };-- return (- <div className="flex-1 overflow-y-auto px-5 py-6">- <form onSubmit={handleSubmit} className="mx-auto max-w-md space-y-4">- <div className="space-y-1.5">- <Label htmlFor="agent-name">Name</Label>- <Input- id="agent-name"- value={name}- onChange={(e) => setName(e.target.value)}- placeholder="My Agent"- required- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="agent-description">Description</Label>- <Input- id="agent-description"- value={description}- onChange={(e) => setDescription(e.target.value)}- placeholder="What does this agent do?"- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="agent-instructions">Instructions</Label>- <Textarea- id="agent-instructions"- value={instructions}- onChange={(e) => setInstructions(e.target.value)}- placeholder="System prompt or instructions..."- rows={6}- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="agent-runtime">Runtime</Label>- <RuntimeSelect- value={runtimeId}- onValueChange={setRuntimeId}- runtimes={runtimes}- />- </div>-- <div className="flex items-center gap-2 pt-2">- <Button- type="button"- variant="ghost"- size="sm"- onClick={onCancel}- >- Cancel- </Button>- <Button- type="submit"- size="sm"- disabled={saving || !name}- >- {saving ? savingLabel : submitLabel}- </Button>- </div>- </form>- </div>- );-}diff --git a/src/web/components/app-sidebar.tsx b/src/web/components/app-sidebar.tsxdeleted file mode 100644index 444df774a..000000000--- a/src/web/components/app-sidebar.tsx+++ /dev/null@@ -1,111 +0,0 @@-"use client";--import { useRouter, usePathname, useSearchParams } from "next/navigation";-import { useAgentContext } from "@/contexts/agent-context";-import { Logo } from "@/components/logo";-import { cn } from "@/lib/utils";-import { Monitor, LogOut, Plus, Loader2 } from "lucide-react";--export function AppSidebar() {- const router = useRouter();- const pathname = usePathname();- const searchParams = useSearchParams();- const { agents, loading } = useAgentContext();-- const sorted = [...agents].sort((a, b) => a.name.localeCompare(b.name));-- const isRuntimes = pathname === "/runtimes";- const isCreateAgent = pathname === "/agents/new";-- // Detect active agent from ?agent= param or /agents/[id] route- const urlAgentId = searchParams.get("agent");- const pathnameAgentMatch = pathname.match(/^\/agents\/([^/]+)$/);- const activeAgentId = urlAgentId ?? pathnameAgentMatch?.[1] ?? null;-- const handleAgentClick = (agentId: string) => {- router.push(`/agents/${agentId}`);- };-- return (- <nav className="flex h-full w-14 flex-col items-center py-2 gap-0.5">- {/* Agent avatars */}- <div className="flex flex-1 w-full flex-col items-center gap-1.5 overflow-y-auto py-1 scrollbar-none">- {loading ? (- <div className="flex items-center justify-center size-10">- <Loader2 className="size-4 animate-spin text-muted-foreground" />- </div>- ) : (- sorted.map((agent) => {- const isActive = activeAgentId === agent.id;- return (- <button- key={agent.id}- type="button"- title={agent.name}- onClick={() => handleAgentClick(agent.id)}- className={cn(- "relative flex shrink-0 items-center justify-center size-10 rounded-xl text-sm font-medium transition-colors duration-200 cursor-pointer",- isActive- ? "bg-primary text-primary-foreground shadow-sm"- : "bg-secondary text-secondary-foreground hover:bg-accent"- )}- >- {agent.name.charAt(0).toUpperCase()}- </button>- );- })- )}-- {/* Create agent */}- <button- type="button"- title="New agent"- onClick={() => router.push("/agents/new")}- className={cn(- "flex shrink-0 items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",- "border border-dashed border-foreground/15 text-muted-foreground",- "hover:border-foreground/30 hover:text-foreground hover:bg-accent",- isCreateAgent &&- "border-solid border-foreground/25 bg-accent text-foreground"- )}- >- <Plus className="size-4" />- </button>- </div>-- {/* Bottom section */}- <div className="flex flex-col items-center gap-1 pt-2 border-t border-border/50 mt-1">- <div className="mb-1">- <Logo size="sm" iconOnly />- </div>-- <button- type="button"- title="Runtimes"- onClick={() => router.push("/runtimes")}- className={cn(- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",- "text-muted-foreground hover:text-foreground hover:bg-accent",- isRuntimes && "bg-accent text-foreground"- )}- >- <Monitor className="size-4" />- </button>-- <button- type="button"- title="Sign out"- onClick={() => {- localStorage.removeItem("alook_token");- localStorage.removeItem("alook_workspace_id");- document.cookie = "alook_session=; path=/; max-age=0";- router.push("/login");- }}- className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"- >- <LogOut className="size-4" />- </button>- </div>- </nav>- );-}diff --git a/src/web/components/dashboard-navbar.tsx b/src/web/components/dashboard-navbar.tsxdeleted file mode 100644index 4357afa4a..000000000--- a/src/web/components/dashboard-navbar.tsx+++ /dev/null@@ -1,411 +0,0 @@-"use client";--import { useEffect, useState, useCallback, useRef } from "react";-import { useRouter } from "next/navigation";-import { Button } from "@/components/ui/button";-import { Badge } from "@/components/ui/badge";-import {- Sheet,- SheetContent,- SheetHeader,- SheetTitle,- SheetDescription,- SheetBody,- SheetTrigger,-} from "@/components/ui/sheet";-import {- listRuntimes,- createMachineToken,- deleteMachine,-} from "@/lib/api";-import { ConfirmDialog } from "@/components/ui/confirm-dialog";-import { Logo } from "@/components/logo";-import { toast } from "sonner";-import type { Runtime } from "@/lib/types";--function OnboardingSteps({- generatedToken,- generatingToken,- onGenerateToken,-}: {- generatedToken: string;- generatingToken: boolean;- onGenerateToken: () => void;-}) {- const hasTriggered = useRef(false);- useEffect(() => {- if (!generatedToken && !generatingToken && !hasTriggered.current) {- hasTriggered.current = true;- onGenerateToken();- }- }, [generatedToken, generatingToken, onGenerateToken]);-- const copyToClipboard = (text: string) => {- navigator.clipboard.writeText(text);- toast("Copied to clipboard");- };-- return (- <div className="space-y-6">- <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 function DashboardNavbar() {- const router = useRouter();- const [runtimes, setRuntimes] = useState<Runtime[]>([]);- const [runtimeSheetOpen, setRuntimeSheetOpen] = useState(false);- const [generatedToken, setGeneratedToken] = useState("");- const [generatingToken, setGeneratingToken] = useState(false);- const [tokenCopied, setTokenCopied] = useState(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;- }- };-- const loadRuntimes = useCallback(async () => {- try {- const r = await listRuntimes();- setRuntimes(r);- } catch {- // silent — runtimes are supplementary- }- }, []);-- useEffect(() => {- loadRuntimes();- }, [loadRuntimes]);-- 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");- };-- return (- <>- <header className="border-b">- <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">- <Logo />-- <div className="flex items-center gap-1.5">- <Sheet- open={runtimeSheetOpen}- onOpenChange={(open) => {- setRuntimeSheetOpen(open);- if (open) loadRuntimes();- 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 ? (- <OnboardingSteps- generatedToken={generatedToken}- generatingToken={generatingToken}- onGenerateToken={handleGenerateToken}- />- ) : (- <div className="space-y-3">- {(() => {- 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="group rounded-lg border p-3.5 space-y-3"- >- <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 opacity-0 group-hover:opacity-100 transition-opacity"- onClick={() => {- openConfirm(- "Remove machine",- `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,- async () => {- 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>-- <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>- );- }- );- })()}-- <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'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>-- <ConfirmDialog- open={confirmOpen}- onOpenChange={setConfirmOpen}- title={confirmTitle}- description={confirmDescription}- loading={confirmLoading}- onConfirm={handleConfirm}- />- </>- );-}diff --git a/src/web/components/gradient-background.tsx b/src/web/components/gradient-background.tsxdeleted file mode 100644index 144cf7e4b..000000000--- a/src/web/components/gradient-background.tsx+++ /dev/null@@ -1,31 +0,0 @@-"use client";--export function GradientBackground() {- return (- <div- aria-hidden- className="pointer-events-none fixed inset-0 -z-10 overflow-hidden"- >- {/* Blob 1 — warm amber, top-left drift */}- <div className="gradient-blob gradient-blob-1" />- {/* Blob 2 — soft peach, bottom-right drift */}- <div className="gradient-blob gradient-blob-2" />- {/* Blob 3 — cream rose, top-right → center */}- <div className="gradient-blob gradient-blob-3" />- {/* Blob 4 — warm sand, bottom-left → center */}- <div className="gradient-blob gradient-blob-4" />- {/* Noise texture overlay */}- <svg className="absolute inset-0 w-full h-full opacity-[0.25] mix-blend-multiply dark:mix-blend-overlay pointer-events-none">- <filter id="noise">- <feTurbulence type="fractalNoise" baseFrequency="0.75" numOctaves="4" stitchTiles="stitch" />- <feComponentTransfer>- <feFuncR type="linear" slope="0.5" intercept="0" />- <feFuncG type="linear" slope="0.5" intercept="0" />- <feFuncB type="linear" slope="0.5" intercept="0" />- </feComponentTransfer>- </filter>- <rect width="100%" height="100%" filter="url(#noise)" />- </svg>- </div>- );-}diff --git a/src/web/components/logo.tsx b/src/web/components/logo.tsxdeleted file mode 100644index 1cdca1b1a..000000000--- a/src/web/components/logo.tsx+++ /dev/null@@ -1,73 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { useTheme } from "next-themes";-import Image from "next/image";-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,- iconOnly = false,-}: {- size?: "sm" | "lg";- className?: string;- iconOnly?: boolean;-}) {- const { icon, text } = sizes[size];- const { resolvedTheme, setTheme } = useTheme();- const [mounted, setMounted] = useState(false);- const mountedRef = useRef(setMounted);-- useEffect(() => { mountedRef.current(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 ? (- <>- <Image- src="/alook.svg"- alt="Alook"- width={icon}- height={icon}- className="dark:hidden"- />- <Image- src="/alook-dark.svg"- alt="Alook"- width={icon}- height={icon}- className="hidden dark:block"- />- </>- ) : (- <span style={{ width: icon, height: icon }} />- )}- {!iconOnly && (- <span- className={cn(text, "font-black tracking-tight")}- style={{ fontFamily: "var(--font-brand)" }}- >- Alook- </span>- )}- </button>- );-}diff --git a/src/web/components/runtime-select.tsx b/src/web/components/runtime-select.tsxdeleted file mode 100644index 4d79c4f03..000000000--- a/src/web/components/runtime-select.tsx+++ /dev/null@@ -1,101 +0,0 @@-"use client";--import type { Runtime } from "@/lib/types";-import {- Select,- SelectTrigger,- SelectValue,- SelectPopup,- SelectItem,- SelectGroup,- SelectGroupLabel,-} from "@/components/ui/select";--interface RuntimeSelectProps {- value: string;- onValueChange: (value: string) => void;- runtimes: Runtime[];- disabled?: boolean;-}--function groupRuntimes(runtimes: Runtime[]) {- 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 groups;-}--function getPlaceholder(runtimes: Runtime[]) {- if (runtimes.length === 0) return "No runtimes — start a daemon first";- if (runtimes.every((r) => r.status !== "online")) return "All runtimes offline";- return "Select a runtime";-}--export function RuntimeSelect({- value,- onValueChange,- runtimes,- disabled,-}: RuntimeSelectProps) {- const groups = groupRuntimes(runtimes);- const allDisabled =- disabled ||- runtimes.length === 0 ||- runtimes.every((r) => r.status !== "online");-- return (- <Select- value={value}- onValueChange={(val: string | null) => {- if (val) onValueChange(val);- }}- disabled={allDisabled}- 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={getPlaceholder(runtimes)} />- </SelectTrigger>- <SelectPopup portal={false}>- {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-xs">- ({rt.status})- </span>- </span>- </SelectItem>- ))}- </SelectGroup>- ))}- </SelectPopup>- </Select>- );-}diff --git a/src/web/components/theme-provider.tsx b/src/web/components/theme-provider.tsxdeleted file mode 100644index 8613a5f07..000000000--- a/src/web/components/theme-provider.tsx+++ /dev/null@@ -1,11 +0,0 @@-"use client";--import { ThemeProvider as NextThemesProvider } from "next-themes";-import type { ComponentProps } from "react";--export function ThemeProvider({- children,- ...props-}: ComponentProps<typeof NextThemesProvider>) {- return <NextThemesProvider {...props}>{children}</NextThemesProvider>;-}diff --git a/src/web/components/theme-toggle.tsx b/src/web/components/theme-toggle.tsxdeleted file mode 100644index cd3352090..000000000--- a/src/web/components/theme-toggle.tsx+++ /dev/null@@ -1,37 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { useTheme } from "next-themes";-import { Sun, Moon, Monitor } from "lucide-react";-import { Button } from "@/components/ui/button";--const themes = ["system", "light", "dark"] as const;--export function ThemeToggle() {- const { theme, setTheme } = useTheme();- const [mounted, setMounted] = useState(false);- const mountedRef = useRef(setMounted);-- useEffect(() => { mountedRef.current(true); }, []);-- const cycle = () => {- const i = themes.indexOf(theme as (typeof themes)[number]);- setTheme(themes[(i + 1) % themes.length]);- };-- if (!mounted) {- return (- <Button variant="ghost" size="sm" disabled>- <Monitor className="size-4" />- </Button>- );- }-- const Icon = theme === "dark" ? Moon : theme === "light" ? Sun : Monitor;-- return (- <Button variant="ghost" size="sm" onClick={cycle} aria-label="Toggle theme">- <Icon className="size-4" />- </Button>- );-}diff --git a/src/web/components/toaster-provider.tsx b/src/web/components/toaster-provider.tsxdeleted file mode 100644index 2854c76ad..000000000--- a/src/web/components/toaster-provider.tsx+++ /dev/null@@ -1,17 +0,0 @@-"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/avatar.tsx b/src/web/components/ui/avatar.tsxdeleted file mode 100644index e4fed865c..000000000--- a/src/web/components/ui/avatar.tsx+++ /dev/null@@ -1,109 +0,0 @@-"use client"--import * as React from "react"-import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"--import { cn } from "@/lib/utils"--function Avatar({- className,- size = "default",- ...props-}: AvatarPrimitive.Root.Props & {- size?: "default" | "sm" | "lg"-}) {- return (- <AvatarPrimitive.Root- data-slot="avatar"- data-size={size}- className={cn(- "group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",- className- )}- {...props}- />- )-}--function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {- return (- <AvatarPrimitive.Image- data-slot="avatar-image"- className={cn(- "aspect-square size-full rounded-full object-cover",- className- )}- {...props}- />- )-}--function AvatarFallback({- className,- ...props-}: AvatarPrimitive.Fallback.Props) {- return (- <AvatarPrimitive.Fallback- data-slot="avatar-fallback"- className={cn(- "flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",- className- )}- {...props}- />- )-}--function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {- return (- <span- data-slot="avatar-badge"- className={cn(- "absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",- "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",- "group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",- "group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",- className- )}- {...props}- />- )-}--function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="avatar-group"- className={cn(- "group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",- className- )}- {...props}- />- )-}--function AvatarGroupCount({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="avatar-group-count"- className={cn(- "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",- className- )}- {...props}- />- )-}--export {- Avatar,- AvatarImage,- AvatarFallback,- AvatarGroup,- AvatarGroupCount,- AvatarBadge,-}diff --git a/src/web/components/ui/badge.tsx b/src/web/components/ui/badge.tsxdeleted file mode 100644index b20959dd7..000000000--- a/src/web/components/ui/badge.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { mergeProps } from "@base-ui/react/merge-props"-import { useRender } from "@base-ui/react/use-render"-import { cva, type VariantProps } from "class-variance-authority"--import { cn } from "@/lib/utils"--const badgeVariants = cva(- "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",- {- variants: {- variant: {- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",- secondary:- "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",- destructive:- "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",- outline:- "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",- ghost:- "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",- link: "text-primary underline-offset-4 hover:underline",- },- },- defaultVariants: {- variant: "default",- },- }-)--function Badge({- className,- variant = "default",- render,- ...props-}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {- return useRender({- defaultTagName: "span",- props: mergeProps<"span">(- {- className: cn(badgeVariants({ variant }), className),- },- props- ),- render,- state: {- slot: "badge",- variant,- },- })-}--export { Badge, badgeVariants }diff --git a/src/web/components/ui/button.tsx b/src/web/components/ui/button.tsxdeleted file mode 100644index c751375cc..000000000--- a/src/web/components/ui/button.tsx+++ /dev/null@@ -1,58 +0,0 @@-import { Button as ButtonPrimitive } from "@base-ui/react/button"-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 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: {- default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",- outline:- "border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",- secondary:- "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",- ghost:- "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",- destructive:- "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",- link: "text-primary underline-offset-4 hover:underline",- },- size: {- default:- "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",- sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",- lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",- icon: "size-8",- "icon-xs":- "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",- "icon-sm":- "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",- "icon-lg": "size-9",- },- },- defaultVariants: {- variant: "default",- size: "default",- },- }-)--function Button({- className,- variant = "default",- size = "default",- ...props-}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {- return (- <ButtonPrimitive- data-slot="button"- className={cn(buttonVariants({ variant, size, className }))}- {...props}- />- )-}--export { Button, buttonVariants }diff --git a/src/web/components/ui/card.tsx b/src/web/components/ui/card.tsxdeleted file mode 100644index 40cac5f98..000000000--- a/src/web/components/ui/card.tsx+++ /dev/null@@ -1,103 +0,0 @@-import * as React from "react"--import { cn } from "@/lib/utils"--function Card({- className,- size = "default",- ...props-}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {- return (- <div- data-slot="card"- data-size={size}- className={cn(- "group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",- className- )}- {...props}- />- )-}--function CardHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-header"- className={cn(- "group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",- className- )}- {...props}- />- )-}--function CardTitle({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-title"- className={cn(- "font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",- className- )}- {...props}- />- )-}--function CardDescription({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-description"- className={cn("text-sm text-muted-foreground", className)}- {...props}- />- )-}--function CardAction({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-action"- className={cn(- "col-start-2 row-span-2 row-start-1 self-start justify-self-end",- className- )}- {...props}- />- )-}--function CardContent({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-content"- className={cn("px-4 group-data-[size=sm]/card:px-3", className)}- {...props}- />- )-}--function CardFooter({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-footer"- className={cn(- "flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",- className- )}- {...props}- />- )-}--export {- Card,- CardHeader,- CardFooter,- CardTitle,- CardAction,- CardDescription,- CardContent,-}diff --git a/src/web/components/ui/confirm-dialog.tsx b/src/web/components/ui/confirm-dialog.tsxdeleted file mode 100644index f377b7d93..000000000--- a/src/web/components/ui/confirm-dialog.tsx+++ /dev/null@@ -1,60 +0,0 @@-"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/dialog.tsx b/src/web/components/ui/dialog.tsxdeleted file mode 100644index 014f5aa3b..000000000--- a/src/web/components/ui/dialog.tsx+++ /dev/null@@ -1,160 +0,0 @@-"use client"--import * as React from "react"-import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"--import { cn } from "@/lib/utils"-import { Button } from "@/components/ui/button"-import { XIcon } from "lucide-react"--function Dialog({ ...props }: DialogPrimitive.Root.Props) {- return <DialogPrimitive.Root data-slot="dialog" {...props} />-}--function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />-}--function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />-}--function DialogClose({ ...props }: DialogPrimitive.Close.Props) {- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />-}--function DialogOverlay({- className,- ...props-}: DialogPrimitive.Backdrop.Props) {- return (- <DialogPrimitive.Backdrop- data-slot="dialog-overlay"- className={cn(- "fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",- className- )}- {...props}- />- )-}--function DialogContent({- className,- children,- showCloseButton = true,- ...props-}: DialogPrimitive.Popup.Props & {- showCloseButton?: boolean-}) {- return (- <DialogPortal>- <DialogOverlay />- <DialogPrimitive.Popup- data-slot="dialog-content"- className={cn(- "fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm 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}- {showCloseButton && (- <DialogPrimitive.Close- data-slot="dialog-close"- render={- <Button- variant="ghost"- className="absolute top-2 right-2"- size="icon-sm"- />- }- >- <XIcon- />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- )}- </DialogPrimitive.Popup>- </DialogPortal>- )-}--function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="dialog-header"- className={cn("flex flex-col gap-2", className)}- {...props}- />- )-}--function DialogFooter({- className,- showCloseButton = false,- children,- ...props-}: React.ComponentProps<"div"> & {- showCloseButton?: boolean-}) {- return (- <div- data-slot="dialog-footer"- className={cn(- "-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",- className- )}- {...props}- >- {children}- {showCloseButton && (- <DialogPrimitive.Close render={<Button variant="outline" />}>- Close- </DialogPrimitive.Close>- )}- </div>- )-}--function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {- return (- <DialogPrimitive.Title- data-slot="dialog-title"- className={cn(- "font-heading text-base leading-none font-medium",- className- )}- {...props}- />- )-}--function DialogDescription({- className,- ...props-}: DialogPrimitive.Description.Props) {- return (- <DialogPrimitive.Description- data-slot="dialog-description"- className={cn(- "text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",- className- )}- {...props}- />- )-}--export {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogOverlay,- DialogPortal,- DialogTitle,- DialogTrigger,-}diff --git a/src/web/components/ui/input-otp.tsx b/src/web/components/ui/input-otp.tsxdeleted file mode 100644index 941b9d12c..000000000--- a/src/web/components/ui/input-otp.tsx+++ /dev/null@@ -1,87 +0,0 @@-"use client"--import * as React from "react"-import { OTPInput, OTPInputContext } from "input-otp"--import { cn } from "@/lib/utils"-import { MinusIcon } from "lucide-react"--function InputOTP({- className,- containerClassName,- ...props-}: React.ComponentProps<typeof OTPInput> & {- containerClassName?: string-}) {- return (- <OTPInput- data-slot="input-otp"- containerClassName={cn(- "cn-input-otp flex items-center has-disabled:opacity-50",- containerClassName- )}- spellCheck={false}- className={cn("disabled:cursor-not-allowed", className)}- {...props}- />- )-}--function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="input-otp-group"- className={cn(- "flex items-center rounded-lg has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40",- className- )}- {...props}- />- )-}--function InputOTPSlot({- index,- className,- ...props-}: React.ComponentProps<"div"> & {- index: number-}) {- const inputOTPContext = React.useContext(OTPInputContext)- const { char, hasFakeCaret, isActive } = inputOTPContext?.slots[index] ?? {}-- return (- <div- data-slot="input-otp-slot"- data-active={isActive}- className={cn(- "relative flex size-8 items-center justify-center border-y border-r border-input text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg aria-invalid:border-destructive data-[active=true]:z-10 data-[active=true]:border-ring data-[active=true]:ring-3 data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40",- className- )}- {...props}- >- {char}- {hasFakeCaret && (- <div className="pointer-events-none absolute inset-0 flex items-center justify-center">- <div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />- </div>- )}- </div>- )-}--function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="input-otp-separator"- className="flex items-center [&_svg:not([class*='size-'])]:size-4"- role="separator"- {...props}- >- <MinusIcon- />- </div>- )-}--export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }diff --git a/src/web/components/ui/input.tsx b/src/web/components/ui/input.tsxdeleted file mode 100644index 7d21babba..000000000--- a/src/web/components/ui/input.tsx+++ /dev/null@@ -1,20 +0,0 @@-import * as React from "react"-import { Input as InputPrimitive } from "@base-ui/react/input"--import { cn } from "@/lib/utils"--function Input({ className, type, ...props }: React.ComponentProps<"input">) {- return (- <InputPrimitive- type={type}- data-slot="input"- className={cn(- "h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",- className- )}- {...props}- />- )-}--export { Input }diff --git a/src/web/components/ui/label.tsx b/src/web/components/ui/label.tsxdeleted file mode 100644index 74da65c33..000000000--- a/src/web/components/ui/label.tsx+++ /dev/null@@ -1,20 +0,0 @@-"use client"--import * as React from "react"--import { cn } from "@/lib/utils"--function Label({ className, ...props }: React.ComponentProps<"label">) {- return (- <label- data-slot="label"- className={cn(- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",- className- )}- {...props}- />- )-}--export { Label }diff --git a/src/web/components/ui/scroll-area.tsx b/src/web/components/ui/scroll-area.tsxdeleted file mode 100644index 84c1e9fbb..000000000--- a/src/web/components/ui/scroll-area.tsx+++ /dev/null@@ -1,55 +0,0 @@-"use client"--import * as React from "react"-import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"--import { cn } from "@/lib/utils"--function ScrollArea({- className,- children,- ...props-}: ScrollAreaPrimitive.Root.Props) {- return (- <ScrollAreaPrimitive.Root- data-slot="scroll-area"- className={cn("relative", className)}- {...props}- >- <ScrollAreaPrimitive.Viewport- data-slot="scroll-area-viewport"- className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"- >- {children}- </ScrollAreaPrimitive.Viewport>- <ScrollBar />- <ScrollAreaPrimitive.Corner />- </ScrollAreaPrimitive.Root>- )-}--function ScrollBar({- className,- orientation = "vertical",- ...props-}: ScrollAreaPrimitive.Scrollbar.Props) {- return (- <ScrollAreaPrimitive.Scrollbar- data-slot="scroll-area-scrollbar"- data-orientation={orientation}- orientation={orientation}- className={cn(- "flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",- className- )}- {...props}- >- <ScrollAreaPrimitive.Thumb- data-slot="scroll-area-thumb"- className="relative flex-1 rounded-full bg-border"- />- </ScrollAreaPrimitive.Scrollbar>- )-}--export { ScrollArea, ScrollBar }diff --git a/src/web/components/ui/select.tsx b/src/web/components/ui/select.tsxdeleted file mode 100644index c8c974315..000000000--- a/src/web/components/ui/select.tsx+++ /dev/null@@ -1,132 +0,0 @@-"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<string>) {- 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/separator.tsx b/src/web/components/ui/separator.tsxdeleted file mode 100644index 6e1369e43..000000000--- a/src/web/components/ui/separator.tsx+++ /dev/null@@ -1,25 +0,0 @@-"use client"--import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"--import { cn } from "@/lib/utils"--function Separator({- className,- orientation = "horizontal",- ...props-}: SeparatorPrimitive.Props) {- return (- <SeparatorPrimitive- data-slot="separator"- orientation={orientation}- className={cn(- "shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",- className- )}- {...props}- />- )-}--export { Separator }diff --git a/src/web/components/ui/sheet.tsx b/src/web/components/ui/sheet.tsxdeleted file mode 100644index c277e585a..000000000--- a/src/web/components/ui/sheet.tsx+++ /dev/null@@ -1,157 +0,0 @@-"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/components/ui/textarea.tsx b/src/web/components/ui/textarea.tsxdeleted file mode 100644index 04d27f7d1..000000000--- a/src/web/components/ui/textarea.tsx+++ /dev/null@@ -1,18 +0,0 @@-import * as React from "react"--import { cn } from "@/lib/utils"--function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {- return (- <textarea- data-slot="textarea"- className={cn(- "flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",- className- )}- {...props}- />- )-}--export { Textarea }diff --git a/src/web/lib/api.ts b/src/web/lib/api.tsdeleted file mode 100644index b4cf0b1f3..000000000--- a/src/web/lib/api.ts+++ /dev/null@@ -1,185 +0,0 @@-import type {- Agent,- Conversation,- CreateAgentRequest,- UpdateAgentRequest,- LoginResponse,- Message,- Runtime,- Task,- TaskMessage,- User,- Workspace,-} from "./types";-import { ApiError } from "./errors";--const API_BASE = "";--async function apiFetch<T>(path: string, options?: RequestInit): Promise<T> {- const token =- typeof window !== "undefined" ? localStorage.getItem("alook_token") : null;- const workspaceId =- typeof window !== "undefined"- ? localStorage.getItem("alook_workspace_id")- : null;-- 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") {- localStorage.removeItem("alook_token");- localStorage.removeItem("alook_workspace_id");- document.cookie = "alook_session=; path=/; max-age=0";- window.location.href = "/login";- }- throw new ApiError("Unauthorized", 401);- }-- if (!res.ok) {- 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();-}--// Auth-export const sendCode = (email: string) =>- apiFetch("/auth/send-code", {- method: "POST",- body: JSON.stringify({ email }),- });--export const verifyCode = (email: string, code: string) =>- apiFetch<LoginResponse>("/auth/verify-code", {- method: "POST",- body: JSON.stringify({ email, code }),- });--export const getMe = () => apiFetch<User>("/api/me");--// Workspaces-export const listWorkspaces = () => apiFetch<Workspace[]>("/api/workspaces");--export const createWorkspace = (name: string) =>- apiFetch<Workspace>("/api/workspaces", {- method: "POST",- body: JSON.stringify({ name }),- });--// Agents-export const listAgents = () => apiFetch<Agent[]>("/api/agents");--export const createAgent = (req: CreateAgentRequest) =>- apiFetch<Agent>("/api/agents", {- method: "POST",- 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");--export const createConversation = (agentId: string) =>- apiFetch<Conversation>("/api/conversations", {- method: "POST",- body: JSON.stringify({ agent_id: agentId }),- });--export const getConversation = (id: string) =>- apiFetch<Conversation>(`/api/conversations/${id}`);--export const listAgentConversations = (agentId: string) =>- apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations`);--export const deleteConversation = (id: string) =>- apiFetch<void>(`/api/conversations/${id}`, { method: "DELETE" });--export const listMessages = (conversationId: string) =>- apiFetch<Message[]>(`/api/conversations/${conversationId}/messages`);--export const sendMessage = (conversationId: string, content: string) =>- apiFetch<{ message: Message; task: Task }>(- `/api/conversations/${conversationId}/messages`,- {- method: "POST",- body: JSON.stringify({ content }),- }- );--// Machine tokens-export const createMachineToken = (name?: string) =>- apiFetch<{ token: string; id: string; name: string; created_at: string }>(- "/api/machine-tokens",- {- method: "POST",- body: JSON.stringify({ name: name || "default" }),- }- );--// Tasks (polling)-export const getTask = (id: string) => apiFetch<Task>(`/api/tasks/${id}`);--export const getTaskMessages = (id: string, since?: number) =>- apiFetch<TaskMessage[]>(- `/api/tasks/${id}/messages${since ? `?since=${since}` : ""}`- );diff --git a/src/web/lib/api/responses.ts b/src/web/lib/api/responses.tsdeleted file mode 100644index 33f6b67f1..000000000--- a/src/web/lib/api/responses.ts+++ /dev/null@@ -1,147 +0,0 @@-import {- formatTimestamp,- formatTimestampNullable,-} from "@/lib/middleware/helpers";-import { TaskApiBaseSchema } from "@alook/shared";--/* eslint-disable @typescript-eslint/no-explicit-any */--export function userToResponse(u: any) {- return {- id: u.id,- name: u.name,- email: u.email,- avatar_url: u.avatarUrl || null,- created_at: formatTimestamp(u.createdAt),- updated_at: formatTimestamp(u.updatedAt),- };-}--export function workspaceToResponse(w: any) {- return {- id: w.id,- name: w.name,- slug: w.slug,- created_at: formatTimestamp(w.createdAt),- updated_at: formatTimestamp(w.updatedAt),- };-}--export function agentToResponse(a: any) {- let rc = a.runtimeConfig;- if (!rc) rc = {};- return {- id: a.id,- workspace_id: a.workspaceId,- runtime_id: a.runtimeId || "",- name: a.name,- description: a.description,- instructions: a.instructions,- runtime_mode: a.runtimeMode,- runtime_config: rc,- status: a.status,- max_concurrent_tasks: a.maxConcurrentTasks,- created_at: formatTimestamp(a.createdAt),- updated_at: formatTimestamp(a.updatedAt),- };-}--export function taskToResponse(t: {- id: string;- agentId: string;- runtimeId: string;- conversationId: string;- workspaceId: string;- prompt: string;- status: string;- priority: number;- dispatchedAt: Date | null;- startedAt: Date | null;- completedAt: Date | null;- result?: unknown;- error?: string | null;- createdAt: Date;-}) {- return TaskApiBaseSchema.parse({- id: t.id,- agent_id: t.agentId,- runtime_id: t.runtimeId,- conversation_id: t.conversationId,- workspace_id: t.workspaceId,- prompt: t.prompt,- status: t.status,- priority: t.priority,- dispatched_at: formatTimestampNullable(t.dispatchedAt),- started_at: formatTimestampNullable(t.startedAt),- completed_at: formatTimestampNullable(t.completedAt),- result: t.result ?? null,- error: t.error || null,- created_at: formatTimestamp(t.createdAt),- });-}--export function conversationToResponse(c: any) {- const resp: any = {- id: c.id,- agent_id: c.agentId,- title: c.title,- created_at: formatTimestamp(c.createdAt),- };- if (c.messageCount !== undefined) {- resp.message_count = c.messageCount;- }- return resp;-}--export function messageToResponse(m: any) {- return {- id: m.id,- conversation_id: m.conversationId,- role: m.role,- content: m.content,- task_id: m.taskId || null,- created_at: formatTimestamp(m.createdAt),- };-}--export function taskMessageToResponse(m: any) {- const resp: any = {- id: m.id,- task_id: m.taskId,- seq: m.seq,- type: m.type,- tool: m.tool,- content: m.content,- output: m.output,- };- if (m.input) resp.input = m.input;- return resp;-}--export function runtimeToResponse(rt: any) {- let metadata = rt.metadata;- if (!metadata) metadata = {};- return {- id: rt.id,- workspace_id: rt.workspaceId,- daemon_id: rt.daemonId || null,- name: rt.name,- runtime_mode: rt.runtimeMode,- provider: rt.provider,- status: rt.status,- device_info: rt.deviceInfo,- metadata,- last_seen_at: formatTimestampNullable(rt.lastSeenAt),- created_at: formatTimestamp(rt.createdAt),- updated_at: formatTimestamp(rt.updatedAt),- };-}--export function machineTokenToResponse(mt: any) {- return {- id: mt.id,- name: mt.name,- last_used_at: formatTimestampNullable(mt.lastUsedAt),- created_at: formatTimestamp(mt.createdAt),- };-}diff --git a/src/web/lib/errors.ts b/src/web/lib/errors.tsdeleted file mode 100644index 31c78228c..000000000--- a/src/web/lib/errors.ts+++ /dev/null@@ -1,23 +0,0 @@-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/logger.ts b/src/web/lib/logger.tsdeleted file mode 100644index b2e6501d7..000000000--- a/src/web/lib/logger.ts+++ /dev/null@@ -1,62 +0,0 @@-export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";--const LEVELS: Record<LogLevel, number> = {- debug: 0,- info: 1,- warn: 2,- error: 3,- silent: 4,-};--export class Logger {- private level: number;-- constructor(level: LogLevel = "info") {- this.level = LEVELS[level];- }-- debug(msg: string, ctx?: Record<string, unknown>): void {- this.write("debug", msg, ctx);- }-- info(msg: string, ctx?: Record<string, unknown>): void {- this.write("info", msg, ctx);- }-- warn(msg: string, ctx?: Record<string, unknown>): void {- this.write("warn", msg, ctx);- }-- error(msg: string, ctx?: Record<string, unknown>): void {- this.write("error", msg, ctx);- }-- private write(- level: Exclude<LogLevel, "silent">,- msg: string,- ctx?: Record<string, unknown>,- ): void {- if (LEVELS[level] < this.level) return;-- const entry: Record<string, unknown> = {- level,- msg,- ...ctx,- ts: new Date().toISOString(),- };-- // Serialize Error objects in context- for (const [k, v] of Object.entries(entry)) {- if (v instanceof Error) {- entry[k] = v.message;- }- }-- const line = JSON.stringify(entry);- const dest = level === "error" ? process.stderr : process.stdout;- dest.write(line + "\n");- }-}--const envLevel = (process.env.ALOOK_LOG_LEVEL as LogLevel) || "info";-export const log = new Logger(envLevel);diff --git a/src/web/lib/middleware/.gitkeep b/src/web/lib/middleware/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/src/web/lib/middleware/helpers.ts b/src/web/lib/middleware/helpers.tsdeleted file mode 100644index ab203445e..000000000--- a/src/web/lib/middleware/helpers.ts+++ /dev/null@@ -1,55 +0,0 @@-import { NextResponse } from "next/server";--export function writeJSON(data: unknown, status = 200): NextResponse {- return NextResponse.json(data, { status });-}--export function writeError(message: string, status: number): NextResponse {- return NextResponse.json({ error: message }, { status });-}--/** Format a Date as RFC 3339 without sub-second precision (matching Go output). */-export function formatTimestamp(date: Date | null): string {- if (!date) return "";- return date.toISOString().replace(/\.\d{3}Z$/, "Z");-}--/**- * Parse and validate a JSON request body against a Zod schema.- * Returns [data, null] on success or [null, 400 response] on failure.- */-export async function parseBody<T>(- req: Request,- schema: { parse(data: unknown): T },-): Promise<[T, null] | [null, NextResponse]> {- let raw: unknown;- try {- raw = await req.json();- } catch {- return [null, writeError("invalid request body", 400)];- }- try {- const data = schema.parse(raw);- return [data, null];- } catch (err: unknown) {- const e = err as Record<string, unknown>;- const issues: { path: (string | number)[]; message: string }[] =- (e.issues ?? e.errors ?? []) as { path: (string | number)[]; message: string }[];- const fields = issues.map(- (e) => `${e.path.join(".")}: ${e.message}`,- );- return [- null,- NextResponse.json(- { error: "validation error", details: fields },- { status: 400 },- ),- ];- }-}--/** Same as formatTimestamp but returns null instead of empty string. */-export function formatTimestampNullable(date: Date | null): string | null {- if (!date) return null;- return date.toISOString().replace(/\.\d{3}Z$/, "Z");-}diff --git a/src/web/lib/middleware/request-id.ts b/src/web/lib/middleware/request-id.tsdeleted file mode 100644index 299afb44c..000000000--- a/src/web/lib/middleware/request-id.ts+++ /dev/null@@ -1,14 +0,0 @@-import { NextResponse } from "next/server";-import { randomUUID } from "crypto";--export function getRequestId(req: Request): string {- return req.headers.get("X-Request-ID") || randomUUID();-}--export function setRequestIdHeader(- response: NextResponse,- requestId: string-): NextResponse {- response.headers.set("X-Request-ID", requestId);- return response;-}diff --git a/src/web/lib/middleware/request-logger.ts b/src/web/lib/middleware/request-logger.tsdeleted file mode 100644index b3ac648ba..000000000--- a/src/web/lib/middleware/request-logger.ts+++ /dev/null@@ -1,25 +0,0 @@-import { log } from "../logger";--export function logRequest(- method: string,- path: string,- status: number,- durationMs: number,- requestId?: string,- userId?: string-): void {- if (path === "/health" || path === "/api/health") return;-- const ctx: Record<string, unknown> = {- method,- path,- status,- duration: `${durationMs}ms`,- };- if (requestId) ctx.request_id = requestId;- if (userId) ctx.user_id = userId;-- if (status >= 500) log.error("http request", ctx);- else if (status >= 400) log.warn("http request", ctx);- else log.info("http request", ctx);-}diff --git a/src/web/lib/services/.gitkeep b/src/web/lib/services/.gitkeepdeleted file mode 100644index e69de29bb..000000000diff --git a/src/web/lib/services/email.test.ts b/src/web/lib/services/email.test.tsdeleted file mode 100644index 5ffd86016..000000000--- a/src/web/lib/services/email.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--vi.mock("resend", () => ({- Resend: vi.fn().mockImplementation(() => ({- emails: { send: vi.fn().mockResolvedValue({}) },- })),-}));--import { EmailService } from "./email";-import { Resend } from "resend";--const MockResend = vi.mocked(Resend);--beforeEach(() => {- vi.clearAllMocks();- delete process.env.RESEND_API_KEY;- delete process.env.RESEND_FROM_EMAIL;-});--describe("EmailService", () => {- it("logs via logger when RESEND_API_KEY is not set", async () => {- const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true);-- const svc = new EmailService();- await svc.sendVerificationCode("[email protected]", "123456");-- expect(stdoutSpy).toHaveBeenCalled();- const output = stdoutSpy.mock.calls[0][0] as string;- const entry = JSON.parse(output);- expect(entry.msg).toBe("DEV verification code");- expect(entry.to).toBe("[email protected]");- expect(entry.code).toBe("123456");- expect(MockResend).not.toHaveBeenCalled();-- stdoutSpy.mockRestore();- });-- it("uses default fromEmail [email protected]", () => {- process.env.RESEND_API_KEY = "re_test_key";-- const svc = new EmailService();- expect(MockResend).toHaveBeenCalledWith("re_test_key");-- const mockInstance = MockResend.mock.results[0].value;- svc.sendVerificationCode("[email protected]", "123456");-- expect(mockInstance.emails.send).toHaveBeenCalledWith(- expect.objectContaining({ from: "[email protected]" })- );- });-- it("RESEND_FROM_EMAIL overrides default", () => {- process.env.RESEND_API_KEY = "re_test_key";- process.env.RESEND_FROM_EMAIL = "[email protected]";-- const svc = new EmailService();- const mockInstance = MockResend.mock.results[0].value;- svc.sendVerificationCode("[email protected]", "123456");-- expect(mockInstance.emails.send).toHaveBeenCalledWith(- expect.objectContaining({ from: "[email protected]" })- );- });-});diff --git a/src/web/lib/services/email.ts b/src/web/lib/services/email.tsdeleted file mode 100644index 37876d67c..000000000--- a/src/web/lib/services/email.ts+++ /dev/null@@ -1,32 +0,0 @@-import { Resend } from "resend";-import { log } from "../logger";--export class EmailService {- private client: Resend | null;- private fromEmail: string;-- constructor() {- const apiKey = process.env.RESEND_API_KEY;- this.fromEmail = process.env.RESEND_FROM_EMAIL || "[email protected]";- this.client = apiKey ? new Resend(apiKey) : null;- }-- async sendVerificationCode(to: string, code: string): Promise<void> {- if (!this.client) {- log.info("DEV verification code", { to, code });- return;- }-- await this.client.emails.send({- from: this.fromEmail,- to: [to],- subject: "Your Alook verification code",- html: `<div style="font-family: sans-serif; max-width: 400px; margin: 0 auto;">- <h2>Your verification code</h2>- <p style="font-size: 32px; font-weight: bold; letter-spacing: 8px; margin: 24px 0;">${code}</p>- <p>This code expires in 10 minutes.</p>- <p style="color: #666; font-size: 14px;">If you didn't request this code, you can safely ignore this email.</p>- </div>`,- });- }-}diff --git a/src/web/lib/types.ts b/src/web/lib/types.tsdeleted file mode 100644index 1d4f166a4..000000000--- a/src/web/lib/types.ts+++ /dev/null@@ -1,87 +0,0 @@-export interface User {- id: string;- email: string;- name: string;-}--export interface Workspace {- id: string;- name: string;- slug: string;-}--export interface Agent {- id: string;- name: string;- description: string;- instructions: string;- runtime_id: string;- status: string;- created_at: string;-}--export interface Runtime {- id: string;- daemon_id: string | null;- name: string;- provider: string;- status: string;- device_info: string;- metadata: Record<string, unknown>;- last_seen_at: string;-}--export interface Conversation {- id: string;- agent_id: string;- title: string;- created_at: string;- message_count?: number;-}--export interface Message {- id: string;- conversation_id: string;- role: "user" | "assistant";- content: string;- task_id?: string;- created_at: string;-}--export interface Task {- id: string;- status: string;- prompt: string;- result?: string;- error?: string;- created_at: string;-}--export interface TaskMessage {- id: string;- task_id: string;- seq: number;- type: string;- tool: string;- content: string;- output: string;-}--export interface LoginResponse {- token: string;- user: User;-}--export interface CreateAgentRequest {- name: string;- description?: string;- instructions?: string;- runtime_id: string;-}--export interface UpdateAgentRequest {- name?: string;- description?: string;- instructions?: string;- runtime_id?: string;-}diff --git a/src/web/lib/utils.ts b/src/web/lib/utils.tsdeleted file mode 100644index bd0c391dd..000000000--- a/src/web/lib/utils.ts+++ /dev/null@@ -1,6 +0,0 @@-import { clsx, type ClassValue } from "clsx"-import { twMerge } from "tailwind-merge"--export function cn(...inputs: ClassValue[]) {- return twMerge(clsx(inputs))-}diff --git a/src/web/src/app/api/agents/[id]/conversations/route.test.ts b/src/web/src/app/api/agents/[id]/conversations/route.test.tsnew file mode 100644index 000000000..5ee388e9e--- /dev/null+++ b/src/web/src/app/api/agents/[id]/conversations/route.test.ts@@ -0,0 +1,85 @@+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetAgentInWorkspace = vi.fn();+const mockListConversationsByAgent = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ agent: {+ getAgentInWorkspace: (...args: unknown[]) => mockGetAgentInWorkspace(...args),+ },+ conversation: {+ listConversationsByAgent: (...args: unknown[]) => mockListConversationsByAgent(...args),+ },+ },+}));++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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++vi.mock("@/lib/api/responses", () => ({+ conversationToResponse: vi.fn((c: any) => ({ id: c.id, title: c.title })),+}));++import { GET } from "./route";++beforeEach(() => vi.clearAllMocks());++describe("GET /api/agents/[id]/conversations", () => {+ it("returns 200 with filtered conversations", async () => {+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1", name: "Agent 1" });+ mockListConversationsByAgent.mockResolvedValue([+ { id: "c1", title: "Conv 1" },+ { id: "c2", title: "Conv 2" },+ ]);++ const req = new NextRequest("http://localhost/api/agents/a1/conversations");+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await GET(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "c1", title: "Conv 1" },+ { id: "c2", title: "Conv 2" },+ ]);+ });++ it("returns 404 for non-existent agent", async () => {+ mockGetAgentInWorkspace.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/agents/a1/conversations");+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await GET(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("agent not found");+ });++ it("returns empty array for agent with no conversations", async () => {+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1", name: "Agent 1" });+ mockListConversationsByAgent.mockResolvedValue([]);++ const req = new NextRequest("http://localhost/api/agents/a1/conversations");+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await GET(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([]);+ });+});diff --git a/src/web/src/app/api/agents/[id]/route.test.ts b/src/web/src/app/api/agents/[id]/route.test.tsnew file mode 100644index 000000000..a50302c2a--- /dev/null+++ b/src/web/src/app/api/agents/[id]/route.test.ts@@ -0,0 +1,147 @@+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetAgentInWorkspace = vi.fn();+const mockDeleteAgent = vi.fn();+const mockUpdateAgent = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ agent: {+ getAgentInWorkspace: (...args: unknown[]) => mockGetAgentInWorkspace(...args),+ deleteAgent: (...args: unknown[]) => mockDeleteAgent(...args),+ updateAgent: (...args: unknown[]) => mockUpdateAgent(...args),+ },+ },+}));++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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++vi.mock("@/lib/api/responses", () => ({+ agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name })),+}));++import { GET, DELETE, PATCH } from "./route";++beforeEach(() => vi.clearAllMocks());++describe("GET /api/agents/[id]", () => {+ it("returns agent", async () => {+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1", name: "Agent 1" });++ const req = new NextRequest("http://localhost/api/agents/a1");+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await GET(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "a1", name: "Agent 1" });+ });++ it("returns 404 when not found", async () => {+ mockGetAgentInWorkspace.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/agents/a1");+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await GET(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("agent not found");+ });+});++describe("DELETE /api/agents/[id]", () => {+ it("returns 204 on successful deletion", async () => {+ mockDeleteAgent.mockResolvedValue(true);++ const req = new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await DELETE(req, ctx);++ expect(res.status).toBe(204);+ });++ it("returns 404 for non-existent agent", async () => {+ mockDeleteAgent.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await DELETE(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("agent not found");+ });+});++describe("PATCH /api/agents/[id]", () => {+ it("updates agent and returns response", async () => {+ mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Updated" });++ const req = new NextRequest("http://localhost/api/agents/a1", {+ method: "PATCH",+ body: JSON.stringify({ name: "Updated" }),+ });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await PATCH(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "a1", name: "Updated" });+ });++ it("returns 404 for non-existent agent", async () => {+ mockUpdateAgent.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/agents/a1", {+ method: "PATCH",+ body: JSON.stringify({ name: "Updated" }),+ });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await PATCH(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("agent not found");+ });++ it("returns 400 when no fields provided", async () => {+ const req = new NextRequest("http://localhost/api/agents/a1", {+ method: "PATCH",+ body: JSON.stringify({ unknown_field: "value" }),+ });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await PATCH(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("no fields to update");+ });++ it("returns 400 for invalid request body", async () => {+ const req = new NextRequest("http://localhost/api/agents/a1", {+ method: "PATCH",+ body: "not json",+ });+ const ctx = { params: Promise.resolve({ id: "a1" }) };+ const res = await PATCH(req, ctx);+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+});diff --git a/src/web/src/app/api/agents/route.test.ts b/src/web/src/app/api/agents/route.test.tsnew file mode 100644index 000000000..c55c02437--- /dev/null+++ b/src/web/src/app/api/agents/route.test.ts@@ -0,0 +1,160 @@+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockListAgents = vi.fn();+const mockCreateAgent = vi.fn();+const mockGetAgentInWorkspace = vi.fn();+const mockGetAgentRuntimeForWorkspace = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ agent: {+ listAgents: (...args: unknown[]) => mockListAgents(...args),+ createAgent: (...args: unknown[]) => mockCreateAgent(...args),+ getAgentInWorkspace: (...args: unknown[]) => mockGetAgentInWorkspace(...args),+ },+ runtime: {+ getAgentRuntimeForWorkspace: (...args: unknown[]) => mockGetAgentRuntimeForWorkspace(...args),+ },+ },+}));++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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++vi.mock("@/lib/api/responses", () => ({+ agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name })),+}));++const mockReconcileAgentStatus = vi.fn();+vi.mock("@/lib/services/task", () => {+ const Svc = function () {+ return { reconcileAgentStatus: mockReconcileAgentStatus };+ };+ return { TaskService: Svc };+});++import { GET, POST } from "./route";++beforeEach(() => vi.clearAllMocks());++describe("GET /api/agents", () => {+ it("lists agents in workspace", async () => {+ mockListAgents.mockResolvedValue([+ { id: "a1", name: "Agent 1" },+ { id: "a2", name: "Agent 2" },+ ]);++ const req = new NextRequest("http://localhost/api/agents");+ const res = await GET(req, {});+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "a1", name: "Agent 1" },+ { id: "a2", name: "Agent 2" },+ ]);+ });+});++describe("POST /api/agents", () => {+ const validBody = { name: "New Agent", runtime_id: "r1" };++ it("creates agent with valid input", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ status: "offline", runtimeMode: "local" });+ mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });++ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify(validBody),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(body).toEqual({ id: "a1", name: "New Agent" });+ });++ it("returns 400 for missing name", async () => {+ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify({ runtime_id: "r1" }),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("name is required");+ });++ it("returns 400 for missing runtime_id", async () => {+ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify({ name: "Agent" }),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("runtime_id is required");+ });++ it("returns 404 when runtime not in workspace", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify(validBody),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("runtime not found in workspace");+ });++ it("creates agent with reconcile when runtime is online", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ status: "online", runtimeMode: "local" });+ mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });+ mockGetAgentInWorkspace.mockResolvedValue({ id: "a1", name: "Reconciled Agent" });++ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify(validBody),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a1");+ expect(body).toEqual({ id: "a1", name: "Reconciled Agent" });+ });++ it("creates agent without reconcile when runtime is offline", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ status: "offline", runtimeMode: "local" });+ mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });++ const req = new NextRequest("http://localhost/api/agents", {+ method: "POST",+ body: JSON.stringify(validBody),+ });+ const res = await POST(req, {});+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(mockReconcileAgentStatus).not.toHaveBeenCalled();+ expect(body).toEqual({ id: "a1", name: "New Agent" });+ });+});diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.tsnew file mode 100644index 000000000..ecf05fffb--- /dev/null+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts@@ -0,0 +1,205 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetConversation = vi.fn();+const mockUpdateConversationTitle = vi.fn();+const mockListMessages = vi.fn();+const mockCreateMessage = vi.fn();+const mockEnqueueTask = vi.fn();+const mockMessageToResponse = vi.fn((m: any) => ({ id: m.id, content: m.content }));+const mockTaskToResponse = vi.fn((t: any) => ({ id: t.id, status: t.status }));++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ conversation: {+ getConversation: (...args: any[]) => mockGetConversation(...args),+ updateConversationTitle: (...args: any[]) => mockUpdateConversationTitle(...args),+ },+ message: {+ listMessages: (...args: any[]) => mockListMessages(...args),+ createMessage: (...args: any[]) => mockCreateMessage(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ messageToResponse: (...args: any[]) => mockMessageToResponse(...args),+ taskToResponse: (...args: any[]) => mockTaskToResponse(...args),+}));+vi.mock("@/lib/services/task", () => {+ return {+ TaskService: class {+ enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }+ },+ };+});+vi.mock("@/lib/logger", () => ({+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },+}));++import { GET, POST } from "./route";++const withParams = (id: string) => ({ params: Promise.resolve({ id }) });++describe("GET /api/conversations/[id]/messages", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists messages", async () => {+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };+ const msgs = [+ { id: "m1", content: "Hello" },+ { id: "m2", content: "World" },+ ];+ mockGetConversation.mockResolvedValue(conv);+ mockListMessages.mockResolvedValue(msgs);++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1/messages"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "m1", content: "Hello" },+ { id: "m2", content: "World" },+ ]);+ expect(mockListMessages).toHaveBeenCalledWith({}, "c1");+ });+});++describe("POST /api/conversations/[id]/messages", () => {+ beforeEach(() => vi.clearAllMocks());++ it("sends message and enqueues task, returns 201", async () => {+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };+ const msg = { id: "m1", content: "Hi there" };+ const task = { id: "t1", status: "pending" };+ mockGetConversation.mockResolvedValue(conv);+ mockCreateMessage.mockResolvedValue(msg);+ mockUpdateConversationTitle.mockResolvedValue(undefined);+ mockEnqueueTask.mockResolvedValue(task);++ const res = await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({ content: "Hi there" }),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(body.message).toEqual({ id: "m1", content: "Hi there" });+ expect(body.task).toEqual({ id: "t1", status: "pending" });+ expect(mockEnqueueTask).toHaveBeenCalledWith("a1", "c1", "w1", "Hi there");+ });++ it("auto-titles conversation with truncated first message", async () => {+ const longContent = "A ".repeat(40).trim();+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };+ mockGetConversation.mockResolvedValue(conv);+ mockCreateMessage.mockResolvedValue({ id: "m1", content: longContent });+ mockUpdateConversationTitle.mockResolvedValue(undefined);+ mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });++ await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({ content: longContent }),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );++ const titleArg = mockUpdateConversationTitle.mock.calls[0][2] as string;+ expect(titleArg.endsWith("...")).toBe(true);+ expect(titleArg.length).toBeLessThanOrEqual(53);+ });++ it("short messages are not truncated", async () => {+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };+ mockGetConversation.mockResolvedValue(conv);+ mockCreateMessage.mockResolvedValue({ id: "m1", content: "short" });+ mockUpdateConversationTitle.mockResolvedValue(undefined);+ mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });++ await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({ content: "short" }),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );++ const titleArg = mockUpdateConversationTitle.mock.calls[0][2] as string;+ expect(titleArg).toBe("short");+ expect(titleArg.endsWith("...")).toBe(false);+ });++ it("returns 400 for missing content", async () => {+ const conv = { id: "c1", workspaceId: "w1", agentId: "a1" };+ mockGetConversation.mockResolvedValue(conv);++ const res = await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({}),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("content is required");+ });++ it("returns 404 when conversation not found", async () => {+ mockGetConversation.mockResolvedValue(null);++ const res = await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({ content: "hello" }),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });++ it("returns 404 when conversation workspace doesn't match", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other", agentId: "a1" });++ const res = await POST(+ new NextRequest("http://localhost/api/conversations/c1/messages", {+ method: "POST",+ body: JSON.stringify({ content: "hello" }),+ headers: { "Content-Type": "application/json" },+ }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });+});diff --git a/src/web/src/app/api/conversations/[id]/route.test.ts b/src/web/src/app/api/conversations/[id]/route.test.tsnew file mode 100644index 000000000..ee1cbd9b2--- /dev/null+++ b/src/web/src/app/api/conversations/[id]/route.test.ts@@ -0,0 +1,147 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetConversation = vi.fn();+const mockDeleteConversation = vi.fn();+const mockDeleteTasksByConversation = vi.fn();+const mockConversationToResponse = vi.fn((c: any) => ({ id: c.id, title: c.title }));++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ conversation: {+ getConversation: (...args: any[]) => mockGetConversation(...args),+ deleteConversation: (...args: any[]) => mockDeleteConversation(...args),+ },+ task: {+ deleteTasksByConversation: (...args: any[]) => mockDeleteTasksByConversation(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ conversationToResponse: (...args: any[]) => mockConversationToResponse(...args),+}));++import { GET, DELETE } from "./route";++const withParams = (id: string) => ({ params: Promise.resolve({ id }) });++describe("GET /api/conversations/[id]", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns conversation", async () => {+ const conv = { id: "c1", title: "Test", workspaceId: "w1" };+ mockGetConversation.mockResolvedValue(conv);++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "c1", title: "Test" });+ expect(mockGetConversation).toHaveBeenCalledWith({}, "c1");+ });++ it("returns 404 when not found", async () => {+ mockGetConversation.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });++ it("returns 404 when workspace mismatch", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other" });++ const res = await GET(+ new NextRequest("http://localhost/api/conversations/c1"),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });+});++describe("DELETE /api/conversations/[id]", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns 204 and removes conversation + tasks", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockDeleteTasksByConversation.mockResolvedValue(undefined);+ mockDeleteConversation.mockResolvedValue(undefined);++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),+ withParams("c1")+ );++ expect(res.status).toBe(204);+ expect(mockDeleteTasksByConversation).toHaveBeenCalled();+ expect(mockDeleteConversation).toHaveBeenCalled();+ });++ it("deletes tasks before conversation", async () => {+ const callOrder: string[] = [];+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockDeleteTasksByConversation.mockImplementation(async () => {+ callOrder.push("tasks");+ });+ mockDeleteConversation.mockImplementation(async () => {+ callOrder.push("conversation");+ });++ await DELETE(+ new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),+ withParams("c1")+ );++ expect(callOrder).toEqual(["tasks", "conversation"]);+ });++ it("returns 404 when conversation not found", async () => {+ mockGetConversation.mockResolvedValue(null);++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });++ it("returns 404 when workspace mismatch", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "other" });++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("conversation not found");+ });+});diff --git a/src/web/src/app/api/conversations/route.test.ts b/src/web/src/app/api/conversations/route.test.tsnew file mode 100644index 000000000..38c86974c--- /dev/null+++ b/src/web/src/app/api/conversations/route.test.ts@@ -0,0 +1,110 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockListConversations = vi.fn();+const mockCreateConversation = vi.fn();+const mockConversationToResponse = vi.fn((c: any) => ({ id: c.id, title: c.title }));++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ conversation: {+ listConversations: (...args: any[]) => mockListConversations(...args),+ createConversation: (...args: any[]) => mockCreateConversation(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ conversationToResponse: (...args: any[]) => mockConversationToResponse(...args),+}));++import { GET, POST } from "./route";++describe("GET /api/conversations", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists conversations", async () => {+ const convs = [+ { id: "c1", title: "Hello" },+ { id: "c2", title: "World" },+ ];+ mockListConversations.mockResolvedValue(convs);++ const res = await GET(new NextRequest("http://localhost/api/conversations"));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "c1", title: "Hello" },+ { id: "c2", title: "World" },+ ]);+ expect(mockListConversations).toHaveBeenCalledWith({}, "w1", "u1");+ });+});++describe("POST /api/conversations", () => {+ beforeEach(() => vi.clearAllMocks());++ it("creates a conversation with agent_id", async () => {+ const conv = { id: "c1", title: "" };+ mockCreateConversation.mockResolvedValue(conv);++ const res = await POST(+ new NextRequest("http://localhost/api/conversations", {+ method: "POST",+ body: JSON.stringify({ agent_id: "a1" }),+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(body).toEqual({ id: "c1", title: "" });+ expect(mockCreateConversation).toHaveBeenCalledWith({}, {+ workspaceId: "w1",+ agentId: "a1",+ userId: "u1",+ title: "",+ });+ });++ it("returns 400 for missing agent_id", async () => {+ const res = await POST(+ new NextRequest("http://localhost/api/conversations", {+ method: "POST",+ body: JSON.stringify({}),+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("agent_id is required");+ });++ it("returns 400 for invalid body", async () => {+ const res = await POST(+ new NextRequest("http://localhost/api/conversations", {+ method: "POST",+ body: "not json",+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+});diff --git a/src/web/src/app/api/daemon/deregister/route.test.ts b/src/web/src/app/api/daemon/deregister/route.test.tsnew file mode 100644index 000000000..ddf07d7aa--- /dev/null+++ b/src/web/src/app/api/daemon/deregister/route.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetAgentRuntimeForWorkspace = vi.fn();+const mockSetAgentRuntimeOffline = vi.fn();++function sharedMocks() {+ return {+ "@opennextjs/cloudflare": {+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ },+ "@alook/shared": async () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ getAgentRuntimeForWorkspace: (...a: any[]) =>+ mockGetAgentRuntimeForWorkspace(...a),+ setAgentRuntimeOffline: (...a: any[]) =>+ mockSetAgentRuntimeOffline(...a),+ },+ },+ DeregisterRequestSchema: (await import("@alook/shared"))+ .DeregisterRequestSchema,+ }),+ "@/lib/logger": {+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+ },+ };+}++function makeReq(body: unknown) {+ return new NextRequest("http://localhost/api/daemon/deregister", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ });+}++describe("POST /api/daemon/deregister", () => {+ beforeEach(() => vi.clearAllMocks());++ async function loadRoute(authCtx: Record<string, unknown>) {+ vi.resetModules();++ const mocks = sharedMocks();++ vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);+ vi.doMock("@alook/shared", mocks["@alook/shared"]);+ vi.doMock("@/lib/logger", () => mocks["@/lib/logger"]);+ vi.doMock("@/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, { ...authCtx, params });+ }),+ }));+ vi.doMock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+ });++ const { POST } = await import("./route");+ return POST;+ }++ const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ const jwtAuth = { userId: "u1", email: "[email protected]" };++ it("sets owned runtimes offline", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace+ .mockResolvedValueOnce({ id: "rt1" })+ .mockResolvedValueOnce({ id: "rt2" });+ mockSetAgentRuntimeOffline.mockResolvedValue(undefined);++ const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "ok" });+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledTimes(2);+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt2");+ });++ it("skips unowned runtimes", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace+ .mockResolvedValueOnce({ id: "rt1" })+ .mockResolvedValueOnce(null); // rt2 not owned+ mockSetAgentRuntimeOffline.mockResolvedValue(undefined);++ const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "ok" });+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledTimes(1);+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");+ });++ it("returns 200 with empty runtime_ids (no-op)", async () => {+ const POST = await loadRoute(daemonAuth);++ const res = await POST(makeReq({ runtime_ids: [] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "ok" });+ expect(mockGetAgentRuntimeForWorkspace).not.toHaveBeenCalled();+ expect(mockSetAgentRuntimeOffline).not.toHaveBeenCalled();+ });++ it("returns 403 when called without workspaceId", async () => {+ const POST = await loadRoute(jwtAuth);++ const res = await POST(makeReq({ runtime_ids: ["rt1"] }));+ const body = await res.json();++ expect(res.status).toBe(403);+ expect(body.error).toContain("machine token required");+ });++ it("continues processing remaining runtimes after DB error on one", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace+ .mockResolvedValueOnce({ id: "rt1" })+ .mockResolvedValueOnce({ id: "rt2" });+ mockSetAgentRuntimeOffline+ .mockRejectedValueOnce(new Error("DB connection lost"))+ .mockResolvedValueOnce(undefined);++ const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "ok" });+ expect(mockSetAgentRuntimeOffline).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.tsnew file mode 100644index 000000000..341aa6fcf--- /dev/null+++ b/src/web/src/app/api/daemon/heartbeat/route.test.ts@@ -0,0 +1,189 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++// ---------------------------------------------------------------------------+// Shared mock fns -- wired fresh on each test via vi.doMock+// ---------------------------------------------------------------------------+const mockGetAgentRuntimeForWorkspace = vi.fn();+const mockUpdateAgentRuntimeHeartbeat = vi.fn();+const mockMarkStaleRuntimesOffline = vi.fn();+const mockFailStaleDispatchedTasks = vi.fn();+const mockReconcileAgentStatus = vi.fn();++function makeReq(body: unknown) {+ return new NextRequest("http://localhost/api/daemon/heartbeat", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ });+}++describe("POST /api/daemon/heartbeat", () => {+ beforeEach(() => vi.clearAllMocks());++ async function loadRoute(authCtx: Record<string, unknown>) {+ vi.resetModules();++ const { HeartbeatRequestSchema } = await import("@alook/shared");++ vi.doMock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ }));+ vi.doMock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ getAgentRuntimeForWorkspace: (...a: any[]) =>+ mockGetAgentRuntimeForWorkspace(...a),+ updateAgentRuntimeHeartbeat: (...a: any[]) =>+ mockUpdateAgentRuntimeHeartbeat(...a),+ markStaleRuntimesOffline: (...a: any[]) =>+ mockMarkStaleRuntimesOffline(...a),+ },+ task: {+ failStaleDispatchedTasks: (...a: any[]) =>+ mockFailStaleDispatchedTasks(...a),+ },+ },+ HeartbeatRequestSchema,+ }));+ vi.doMock("@/lib/services/task", () => {+ const MockTaskService = function (this: any) {+ this.reconcileAgentStatus = (...a: any[]) =>+ mockReconcileAgentStatus(...a);+ } as any;+ return { TaskService: MockTaskService };+ });+ vi.doMock("@/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, { ...authCtx, params });+ }),+ }));+ vi.doMock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+ });++ const { POST } = await import("./route");+ return POST;+ }++ const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };+ const jwtAuth = { userId: "u1", email: "[email protected]" }; // no workspaceId++ it("succeeds for runtime in caller's workspace", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });+ mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);+ mockFailStaleDispatchedTasks.mockResolvedValue([]);++ const res = await POST(makeReq({ runtime_id: "rt1" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "ok" });+ });++ it("returns 404 when runtime not in caller's workspace", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq({ runtime_id: "rt-other" }));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("Runtime not found");+ });++ it("returns 404 when runtime ID doesn't exist", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq({ runtime_id: "nonexistent" }));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("Runtime not found");+ });++ it("returns 403 when called without workspaceId (JWT auth)", async () => {+ const POST = await loadRoute(jwtAuth);++ const res = await POST(makeReq({ runtime_id: "rt1" }));+ const body = await res.json();++ expect(res.status).toBe(403);+ expect(body.error).toContain("machine token required");+ });++ it("does NOT call heartbeat/stale functions when ownership fails", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ await POST(makeReq({ runtime_id: "rt1" }));++ expect(mockUpdateAgentRuntimeHeartbeat).not.toHaveBeenCalled();+ expect(mockMarkStaleRuntimesOffline).not.toHaveBeenCalled();+ expect(mockFailStaleDispatchedTasks).not.toHaveBeenCalled();+ });++ it("calls markStaleRuntimesOffline with workspaceId", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });+ mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);+ mockFailStaleDispatchedTasks.mockResolvedValue([]);++ await POST(makeReq({ runtime_id: "rt1" }));++ expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");+ });++ it("calls updateAgentRuntimeHeartbeat before markStaleRuntimesOffline", async () => {+ const POST = await loadRoute(daemonAuth);++ const callOrder: string[] = [];+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });+ mockUpdateAgentRuntimeHeartbeat.mockImplementation(async () => {+ callOrder.push("heartbeat");+ });+ mockMarkStaleRuntimesOffline.mockImplementation(async () => {+ callOrder.push("stale");+ });+ mockFailStaleDispatchedTasks.mockResolvedValue([]);++ await POST(makeReq({ runtime_id: "rt1" }));++ expect(callOrder).toEqual(["heartbeat", "stale"]);+ });++ it("calls failStaleDispatchedTasks and reconcile on happy path", async () => {+ const POST = await loadRoute(daemonAuth);++ mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1" });+ mockUpdateAgentRuntimeHeartbeat.mockResolvedValue(undefined);+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);+ mockFailStaleDispatchedTasks.mockResolvedValue([+ { agentId: "a1" },+ { agentId: "a2" },+ { agentId: "a1" },+ ]);++ await POST(makeReq({ runtime_id: "rt1" }));++ expect(mockFailStaleDispatchedTasks).toHaveBeenCalledOnce();+ // reconcile called for each unique agentId (a1 and a2)+ expect(mockReconcileAgentStatus).toHaveBeenCalledTimes(2);+ expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a1");+ expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a2");+ });+});diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.tsnew file mode 100644index 000000000..fec5577c1--- /dev/null+++ b/src/web/src/app/api/daemon/routes.test.ts@@ -0,0 +1,484 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++// ---------------------------------------------------------------------------+// Cross-route body-validation tests for daemon endpoints.+// Uses real Zod schemas (parseBody is NOT mocked) so we can assert that+// invalid payloads are rejected before hitting any DB logic.+// ---------------------------------------------------------------------------++const daemonAuth = { userId: "u1", email: "[email protected]", workspaceId: "w1" };++function baseMocks() {+ return {+ "@opennextjs/cloudflare": () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+ }),+ "@/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, { ...daemonAuth, params });+ }),+ }),+ "@/lib/middleware/helpers": async () =>+ await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ ),+ "@/lib/logger": () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+ }),+ };+}++function applyBase() {+ const m = baseMocks();+ vi.doMock("@opennextjs/cloudflare", m["@opennextjs/cloudflare"]);+ vi.doMock("@/lib/middleware/auth", m["@/lib/middleware/auth"]);+ vi.doMock("@/lib/middleware/helpers", m["@/lib/middleware/helpers"]);+ vi.doMock("@/lib/logger", m["@/lib/logger"]);+}++function postReq(url: string, body: unknown) {+ return new NextRequest(url, {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ });+}++function postRaw(url: string, raw: string) {+ return new NextRequest(url, {+ method: "POST",+ body: raw,+ headers: { "Content-Type": "application/json" },+ });+}++describe("daemon route body validation", () => {+ beforeEach(() => vi.clearAllMocks());++ // -----------------------------------------------------------------------+ // POST /daemon/register+ // -----------------------------------------------------------------------++ describe("POST /daemon/register", () => {+ async function loadRegister() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ member: {+ getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),+ },+ runtime: {+ upsertAgentRuntime: vi.fn().mockResolvedValue({ id: "rt1", workspaceId: "w1" }),+ },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ runtimeToResponse: (r: any) => r,+ }));++ return (await import("./register/route")).POST;+ }++ it("returns 400 when workspace_id is empty", async () => {+ const POST = await loadRegister();+ const res = await POST(+ postReq("http://localhost/api/daemon/register", {+ workspace_id: "",+ daemon_id: "d1",+ runtimes: [{ type: "claude" }],+ })+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 when runtimes is empty array", async () => {+ const POST = await loadRegister();+ const res = await POST(+ postReq("http://localhost/api/daemon/register", {+ workspace_id: "w1",+ daemon_id: "d1",+ runtimes: [],+ })+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 on malformed JSON", async () => {+ const POST = await loadRegister();+ const res = await POST(+ postRaw("http://localhost/api/daemon/register", "not json{{{")+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });++ it("stores deviceInfo correctly", async () => {+ const POST = await loadRegister();+ const upsertMock = vi.fn().mockResolvedValue({+ id: "rt1",+ workspaceId: "w1",+ deviceInfo: "MacBook Pro",+ });++ // Re-mock with a trackable upsert+ vi.resetModules();+ applyBase();+ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ member: {+ getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),+ },+ runtime: {+ upsertAgentRuntime: upsertMock,+ },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ runtimeToResponse: (r: any) => r,+ }));++ const POST2 = (await import("./register/route")).POST;+ await POST2(+ postReq("http://localhost/api/daemon/register", {+ workspace_id: "w1",+ daemon_id: "d1",+ device_name: "MacBook Pro",+ runtimes: [{ type: "claude" }],+ })+ );++ expect(upsertMock).toHaveBeenCalledWith(+ {},+ expect.objectContaining({ deviceInfo: "MacBook Pro" })+ );+ });++ it("stores version in metadata", async () => {+ vi.resetModules();+ applyBase();++ const upsertMock = vi.fn().mockResolvedValue({+ id: "rt1",+ workspaceId: "w1",+ });++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ member: {+ getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),+ },+ runtime: {+ upsertAgentRuntime: upsertMock,+ },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ runtimeToResponse: (r: any) => r,+ }));++ const POST = (await import("./register/route")).POST;+ await POST(+ postReq("http://localhost/api/daemon/register", {+ workspace_id: "w1",+ daemon_id: "d1",+ cli_version: "0.5.1",+ runtimes: [{ type: "claude", version: "3.5" }],+ })+ );++ expect(upsertMock).toHaveBeenCalledWith(+ {},+ expect.objectContaining({+ metadata: expect.objectContaining({ version: "3.5" }),+ })+ );+ });+ });++ // -----------------------------------------------------------------------+ // POST /daemon/heartbeat+ // -----------------------------------------------------------------------++ describe("POST /daemon/heartbeat", () => {+ async function loadHeartbeat() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ getAgentRuntimeForWorkspace: vi.fn().mockResolvedValue({ id: "rt1" }),+ updateAgentRuntimeHeartbeat: vi.fn(),+ markStaleRuntimesOffline: vi.fn(),+ },+ task: {+ failStaleDispatchedTasks: vi.fn().mockResolvedValue([]),+ },+ },+ };+ });+ vi.doMock("@/lib/services/task", () => ({+ TaskService: vi.fn().mockImplementation(() => ({+ reconcileAgentStatus: vi.fn(),+ })),+ }));++ return (await import("./heartbeat/route")).POST;+ }++ it("returns 400 when runtime_id is empty", async () => {+ const POST = await loadHeartbeat();+ const res = await POST(+ postReq("http://localhost/api/daemon/heartbeat", { runtime_id: "" })+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 when runtime_id is missing", async () => {+ const POST = await loadHeartbeat();+ const res = await POST(+ postReq("http://localhost/api/daemon/heartbeat", {})+ );+ expect(res.status).toBe(400);+ });+ });++ // -----------------------------------------------------------------------+ // POST /daemon/deregister+ // -----------------------------------------------------------------------++ describe("POST /daemon/deregister", () => {+ async function loadDeregister() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ getAgentRuntimeForWorkspace: vi.fn().mockResolvedValue({ id: "rt1" }),+ setAgentRuntimeOffline: vi.fn(),+ },+ },+ };+ });++ return (await import("./deregister/route")).POST;+ }++ it("returns 400 when runtime_ids contains non-strings", async () => {+ const POST = await loadDeregister();+ const res = await POST(+ postReq("http://localhost/api/daemon/deregister", {+ runtime_ids: [123, true],+ })+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 on malformed JSON", async () => {+ const POST = await loadDeregister();+ const res = await POST(+ postRaw("http://localhost/api/daemon/deregister", "{{bad")+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+ });++ // -----------------------------------------------------------------------+ // POST /daemon/tasks/:taskId/complete+ // -----------------------------------------------------------------------++ describe("POST /daemon/tasks/:taskId/complete", () => {+ async function loadComplete() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ };+ });+ vi.doMock("@/lib/services/task", () => ({+ TaskService: vi.fn().mockImplementation(() => ({+ completeTask: vi.fn().mockResolvedValue({+ id: "t1",+ agentId: "a1",+ runtimeId: "rt1",+ workspaceId: "w1",+ conversationId: "c1",+ prompt: "p",+ status: "completed",+ priority: 0,+ dispatchedAt: null,+ startedAt: null,+ completedAt: null,+ createdAt: new Date().toISOString(),+ }),+ })),+ }));+ vi.doMock("@/lib/api/responses", () => ({+ taskToResponse: (t: any) => ({ id: t.id, status: t.status }),+ }));++ return (await import("./tasks/[taskId]/complete/route")).POST;+ }++ it("returns 400 on malformed JSON", async () => {+ const POST = await loadComplete();+ const res = await POST(+ postRaw("http://localhost/api/daemon/tasks/t1/complete", "{bad}"),+ { params: Promise.resolve({ taskId: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+ });++ // -----------------------------------------------------------------------+ // POST /daemon/tasks/:taskId/fail+ // -----------------------------------------------------------------------++ describe("POST /daemon/tasks/:taskId/fail", () => {+ async function loadFail() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ };+ });+ vi.doMock("@/lib/services/task", () => ({+ TaskService: vi.fn().mockImplementation(() => ({+ failTask: vi.fn().mockResolvedValue({+ id: "t1",+ agentId: "a1",+ runtimeId: "rt1",+ workspaceId: "w1",+ conversationId: "c1",+ prompt: "p",+ status: "failed",+ priority: 0,+ dispatchedAt: null,+ startedAt: null,+ completedAt: null,+ createdAt: new Date().toISOString(),+ }),+ })),+ }));+ vi.doMock("@/lib/api/responses", () => ({+ taskToResponse: (t: any) => ({ id: t.id, status: t.status }),+ }));++ return (await import("./tasks/[taskId]/fail/route")).POST;+ }++ it("returns 400 on malformed JSON", async () => {+ const POST = await loadFail();+ const res = await POST(+ postRaw("http://localhost/api/daemon/tasks/t1/fail", "nope"),+ { params: Promise.resolve({ taskId: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+ });++ // -----------------------------------------------------------------------+ // POST /daemon/tasks/:taskId/messages+ // -----------------------------------------------------------------------++ describe("POST /daemon/tasks/:taskId/messages", () => {+ async function loadMessages() {+ vi.resetModules();+ applyBase();++ vi.doMock("@alook/shared", async () => {+ const real = await vi.importActual<typeof import("@alook/shared")>(+ "@alook/shared"+ );+ return {+ ...real,+ createDb: vi.fn(() => ({})),+ queries: {+ taskMessage: {+ createTaskMessage: vi.fn().mockResolvedValue(undefined),+ },+ },+ };+ });+ vi.doMock("@/lib/api/responses", () => ({+ taskMessageToResponse: (m: any) => m,+ }));++ return (await import("./tasks/[taskId]/messages/route")).POST;+ }++ it("returns 400 when message item missing seq/type", async () => {+ const POST = await loadMessages();+ const res = await POST(+ postReq("http://localhost/api/daemon/tasks/t1/messages", {+ messages: [{ content: "hello" }],+ }),+ { params: Promise.resolve({ taskId: "t1" }) }+ );++ expect(res.status).toBe(400);+ });+ });+});diff --git a/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.tsnew file mode 100644index 000000000..9a9677784--- /dev/null+++ b/src/web/src/app/api/daemon/runtimes/[runtimeId]/tasks/claim/route.test.ts@@ -0,0 +1,133 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockClaimTaskForRuntime = vi.fn();+const mockGetAgent = vi.fn();+const mockGetLastTaskSession = vi.fn();+const mockTaskToResponse = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ agent: {+ getAgent: (...args: any[]) => mockGetAgent(...args),+ },+ task: {+ getLastTaskSession: (...args: any[]) => mockGetLastTaskSession(...args),+ },+ },+}));+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]", workspaceId: "w1", params });+ }),+}));+vi.mock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+});+vi.mock("@/lib/services/task", () => {+ const MockTaskService = function (this: any) {+ this.claimTaskForRuntime = (...a: any[]) => mockClaimTaskForRuntime(...a);+ } as any;+ return { TaskService: MockTaskService };+});+vi.mock("@/lib/api/responses", () => ({+ taskToResponse: (...args: any[]) => mockTaskToResponse(...args),+}));++import { POST } from "./route";++const withParams = (runtimeId: string) => ({+ params: Promise.resolve({ runtimeId }),+});++describe("POST /api/daemon/runtimes/[runtimeId]/tasks/claim", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns { task: null } when no task available", async () => {+ mockClaimTaskForRuntime.mockResolvedValue(null);++ const res = await POST(+ new NextRequest("http://localhost/api/daemon/runtimes/rt1/tasks/claim", {+ method: "POST",+ }),+ withParams("rt1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ task: null });+ expect(mockClaimTaskForRuntime).toHaveBeenCalledWith("rt1");+ });++ it("returns task with agent data and prior session", async () => {+ const fakeTask = {+ id: "t1",+ agentId: "a1",+ conversationId: "conv1",+ runtimeId: "rt1",+ workspaceId: "w1",+ prompt: "do stuff",+ status: "dispatched",+ priority: 0,+ dispatchedAt: null,+ startedAt: null,+ completedAt: null,+ createdAt: new Date().toISOString(),+ };+ const fakeAgent = {+ id: "a1",+ name: "Agent 1",+ instructions: "be helpful",+ runtimeConfig: { model: "gpt-4" },+ };+ const fakeSession = { sessionId: "sess1", workDir: "/tmp/work" };++ mockClaimTaskForRuntime.mockResolvedValue(fakeTask);+ mockGetAgent.mockResolvedValue(fakeAgent);+ mockGetLastTaskSession.mockResolvedValue(fakeSession);+ mockTaskToResponse.mockReturnValue({+ id: "t1",+ agent_id: "a1",+ runtime_id: "rt1",+ conversation_id: "conv1",+ workspace_id: "w1",+ prompt: "do stuff",+ status: "dispatched",+ priority: 0,+ dispatched_at: null,+ started_at: null,+ completed_at: null,+ result: null,+ error: null,+ created_at: fakeTask.createdAt,+ });++ const res = await POST(+ new NextRequest("http://localhost/api/daemon/runtimes/rt1/tasks/claim", {+ method: "POST",+ }),+ withParams("rt1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.task).toBeTruthy();+ expect(body.task.agent).toEqual({+ instructions: "be helpful",+ name: "Agent 1",+ runtime_config: { model: "gpt-4" },+ });+ expect(body.task.prior_session_id).toBe("sess1");+ expect(body.task.prior_work_dir).toBe("/tmp/work");+ expect(mockGetAgent).toHaveBeenCalledWith({}, "a1");+ expect(mockGetLastTaskSession).toHaveBeenCalledWith({}, "a1", "conv1");+ });+});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.tsnew file mode 100644index 000000000..2aa6910eb--- /dev/null+++ b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts@@ -0,0 +1,80 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockStartTask = vi.fn();+const mockTaskToResponse = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+}));+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]", workspaceId: "w1", params });+ }),+}));+vi.mock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+});+vi.mock("@/lib/services/task", () => {+ const MockTaskService = function (this: any) {+ this.startTask = (...a: any[]) => mockStartTask(...a);+ } as any;+ return { TaskService: MockTaskService };+});+vi.mock("@/lib/api/responses", () => ({+ taskToResponse: (...args: any[]) => mockTaskToResponse(...args),+}));++import { POST } from "./route";++const withParams = (taskId: string) => ({+ params: Promise.resolve({ taskId }),+});++describe("POST /api/daemon/tasks/[taskId]/start", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns started task", async () => {+ const fakeTask = {+ id: "t1",+ agentId: "a1",+ status: "running",+ };+ mockStartTask.mockResolvedValue(fakeTask);+ mockTaskToResponse.mockReturnValue({ id: "t1", status: "running" });++ const res = await POST(+ new NextRequest("http://localhost/api/daemon/tasks/t1/start", {+ method: "POST",+ }),+ withParams("t1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "t1", status: "running" });+ expect(mockStartTask).toHaveBeenCalledWith("t1");+ });++ it("returns 400 when task not in dispatched status", async () => {+ mockStartTask.mockRejectedValue(new Error("task not in dispatched status"));++ const res = await POST(+ new NextRequest("http://localhost/api/daemon/tasks/t1/start", {+ method: "POST",+ }),+ withParams("t1")+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task not in dispatched status");+ });+});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.tsnew file mode 100644index 000000000..b1c4e494c--- /dev/null+++ b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts@@ -0,0 +1,65 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetTaskStatus = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ task: {+ getTaskStatus: (...args: any[]) => mockGetTaskStatus(...args),+ },+ },+}));+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]", workspaceId: "w1", params });+ }),+}));+vi.mock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+});++import { GET } from "./route";++const withParams = (taskId: string) => ({+ params: Promise.resolve({ taskId }),+});++describe("GET /api/daemon/tasks/[taskId]/status", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns task status", async () => {+ mockGetTaskStatus.mockResolvedValue("running");++ const res = await GET(+ new NextRequest("http://localhost/api/daemon/tasks/t1/status"),+ withParams("t1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ status: "running" });+ expect(mockGetTaskStatus).toHaveBeenCalledWith({}, "t1");+ });++ it("returns 404 when task not found", async () => {+ mockGetTaskStatus.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/daemon/tasks/t-missing/status"),+ withParams("t-missing")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("task not found");+ });+});diff --git a/src/web/src/app/api/machine-tokens/[id]/route.test.ts b/src/web/src/app/api/machine-tokens/[id]/route.test.tsnew file mode 100644index 000000000..ee215429e--- /dev/null+++ b/src/web/src/app/api/machine-tokens/[id]/route.test.ts@@ -0,0 +1,54 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockDeleteMachineToken = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ machineToken: {+ deleteMachineToken: (...args: unknown[]) => mockDeleteMachineToken(...args),+ },+ },+}));++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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server");+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++import { DELETE } from "./route";++describe("DELETE /api/machine-tokens/[id]", () => {+ beforeEach(() => vi.clearAllMocks());++ it("deletes token and returns 204", async () => {+ mockDeleteMachineToken.mockResolvedValue(undefined);++ const req = new NextRequest("http://localhost/api/machine-tokens/tok1", {+ method: "DELETE",+ });+ const res = await DELETE(req, { params: Promise.resolve({ id: "tok1" }) } as any);++ expect(res.status).toBe(204);+ expect(mockDeleteMachineToken).toHaveBeenCalledWith({}, "tok1", "u1");+ });+});diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsnew file mode 100644index 000000000..17cfa92f5--- /dev/null+++ b/src/web/src/app/api/machine-tokens/route.test.ts@@ -0,0 +1,129 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockListMachineTokens = vi.fn();+const mockCreateMachineToken = vi.fn();+const mockMachineTokenToResponse = vi.fn((mt: any) => ({+ id: mt.id,+ name: mt.name,+ last_used_at: null,+ created_at: "2025-01-01T00:00:00Z",+}));+const mockGenerateMachineToken = vi.fn(() => "al_abc123");+const mockHashToken = vi.fn(() => "hashed_abc123");++vi.mock("@/lib/middleware/helpers", () => ({+ writeJSON: (data: any, status = 200) =>+ new Response(JSON.stringify(data), {+ status,+ headers: { "content-type": "application/json" },+ }),+ writeError: (message: string, status: number) =>+ new Response(JSON.stringify({ error: message }), {+ status,+ headers: { "content-type": "application/json" },+ }),+}));+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ machineToken: {+ listMachineTokens: (...args: any[]) => mockListMachineTokens(...args),+ createMachineToken: (...args: any[]) => mockCreateMachineToken(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ machineTokenToResponse: (...args: any[]) => mockMachineTokenToResponse(...args),+}));+vi.mock("@/lib/token", () => ({+ generateMachineToken: (...args: any[]) => mockGenerateMachineToken(...args),+ hashToken: (...args: any[]) => mockHashToken(...args),+}));++import { GET, POST } from "./route";++describe("GET /api/machine-tokens", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists tokens", async () => {+ const tokens = [+ { id: "mt1", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" },+ { id: "mt2", name: "ci", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" },+ ];+ mockListMachineTokens.mockResolvedValue(tokens);++ const res = await GET(new NextRequest("http://localhost/api/machine-tokens"));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "mt1", name: "default", last_used_at: null, created_at: "2025-01-01T00:00:00Z" },+ { id: "mt2", name: "ci", last_used_at: null, created_at: "2025-01-01T00:00:00Z" },+ ]);+ expect(mockListMachineTokens).toHaveBeenCalledWith({}, "u1", "w1");+ });+});++describe("POST /api/machine-tokens", () => {+ beforeEach(() => vi.clearAllMocks());++ it("creates token and returns 201", async () => {+ const mt = { id: "mt1", name: "my-token", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };+ mockCreateMachineToken.mockResolvedValue(mt);++ const res = await POST(+ new NextRequest("http://localhost/api/machine-tokens", {+ method: "POST",+ body: JSON.stringify({ name: "my-token" }),+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(res.status).toBe(201);+ expect(body).toEqual({+ token: "al_abc123",+ id: "mt1",+ name: "my-token",+ last_used_at: null,+ created_at: "2025-01-01T00:00:00Z",+ });+ expect(mockCreateMachineToken).toHaveBeenCalledWith({}, {+ userId: "u1",+ workspaceId: "w1",+ tokenHash: "hashed_abc123",+ name: "my-token",+ });+ });++ it("returns the unhashed token in the response", async () => {+ const mt = { id: "mt2", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };+ mockCreateMachineToken.mockResolvedValue(mt);++ const res = await POST(+ new NextRequest("http://localhost/api/machine-tokens", {+ method: "POST",+ body: JSON.stringify({}),+ headers: { "Content-Type": "application/json" },+ })+ );+ const body = await res.json();++ expect(body.token).toBe("al_abc123");+ expect(body.token).not.toBe("hashed_abc123");+ expect(mockHashToken).toHaveBeenCalledWith("al_abc123");+ });+});diff --git a/src/web/src/app/api/me/route.test.ts b/src/web/src/app/api/me/route.test.tsnew file mode 100644index 000000000..4e4177994--- /dev/null+++ b/src/web/src/app/api/me/route.test.ts@@ -0,0 +1,51 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetUser = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ user: { getUser: (...args: unknown[]) => mockGetUser(...args) },+ },+}));++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/middleware/helpers", () => {+ const { NextResponse } = require("next/server");+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++vi.mock("@/lib/api/responses", () => ({+ userToResponse: vi.fn((u: any) => ({ id: u.id, name: u.name, email: u.email })),+}));++import { GET } from "./route";++describe("GET /api/me", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns user data when authenticated", async () => {+ mockGetUser.mockResolvedValue({ id: "u1", name: "Alice", email: "[email protected]" });++ const req = new NextRequest("http://localhost/api/me");+ const res = await GET(req, {} as any);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: "u1", name: "Alice", email: "[email protected]" });+ expect(mockGetUser).toHaveBeenCalledWith({}, "u1");+ });+});diff --git a/src/web/src/app/api/runtimes/machine/route.test.ts b/src/web/src/app/api/runtimes/machine/route.test.tsnew file mode 100644index 000000000..d07adaca6--- /dev/null+++ b/src/web/src/app/api/runtimes/machine/route.test.ts@@ -0,0 +1,137 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockDeleteRuntimesByDaemonId = vi.fn();+const mockGetMemberByUserAndWorkspace = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ deleteRuntimesByDaemonId: (...args: any[]) =>+ mockDeleteRuntimesByDaemonId(...args),+ },+ member: {+ getMemberByUserAndWorkspace: (...args: any[]) =>+ mockGetMemberByUserAndWorkspace(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async (req: any) => {+ const wsId = req.nextUrl.searchParams.get("workspace_id");+ if (!wsId) {+ const { NextResponse } = await import("next/server");+ return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });+ }+ // Check member mock+ const member = await mockGetMemberByUserAndWorkspace({}, "u1", wsId);+ if (!member) {+ const { NextResponse } = await import("next/server");+ return NextResponse.json({ error: "workspace not found" }, { status: 404 });+ }+ return { workspaceId: wsId };+ }),+}));+vi.mock("@/lib/logger", () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));++import { DELETE } from "./route";++function makeReq(params: Record<string, string>) {+ const url = new URL("http://localhost/api/runtimes/machine");+ for (const [k, v] of Object.entries(params)) {+ url.searchParams.set(k, v);+ }+ return new NextRequest(url.toString(), { method: "DELETE" });+}++describe("DELETE /api/runtimes/machine", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns 400 when daemon_id is missing", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });++ const res = await DELETE(makeReq({ workspace_id: "w1" }));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toContain("daemon_id");+ });++ it("returns 400 when workspace_id is missing", async () => {+ const res = await DELETE(makeReq({ daemon_id: "d1" }));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toContain("workspace_id");+ });++ it("returns 404 when user is not a workspace member", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue(null);++ const res = await DELETE(makeReq({ daemon_id: "d1", workspace_id: "w-other" }));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("workspace not found");+ });++ it("returns 204 on successful delete", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);++ const res = await DELETE(+ makeReq({ daemon_id: "d1", workspace_id: "w1" })+ );++ expect(res.status).toBe(204);+ });++ it("passes correct daemon_id with dots and dashes", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);++ const daemonId = "my-daemon.v2.host-01";+ await DELETE(makeReq({ daemon_id: daemonId, workspace_id: "w1" }));++ expect(mockDeleteRuntimesByDaemonId).toHaveBeenCalledWith(+ {},+ daemonId,+ "w1"+ );+ });++ it("calls deleteRuntimesByDaemonId exactly once", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);++ await DELETE(makeReq({ daemon_id: "d1", workspace_id: "w1" }));++ expect(mockDeleteRuntimesByDaemonId).toHaveBeenCalledOnce();+ });++ it("returns 500 when deleteRuntimesByDaemonId throws", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ mockDeleteRuntimesByDaemonId.mockRejectedValue(new Error("DB exploded"));++ const res = await DELETE(+ makeReq({ daemon_id: "d1", workspace_id: "w1" })+ );+ const body = await res.json();++ expect(res.status).toBe(500);+ expect(body.error).toContain("Failed to remove machine");+ });+});diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.tsnew file mode 100644index 000000000..8aa209807--- /dev/null+++ b/src/web/src/app/api/runtimes/route.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockMarkStaleRuntimesOffline = vi.fn();+const mockListAgentRuntimes = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ markStaleRuntimesOffline: (...args: unknown[]) => mockMarkStaleRuntimesOffline(...args),+ listAgentRuntimes: (...args: unknown[]) => mockListAgentRuntimes(...args),+ },+ },+}));++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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++vi.mock("@/lib/api/responses", () => ({+ runtimeToResponse: vi.fn((rt: any) => ({ id: rt.id, name: rt.name, status: rt.status })),+}));++vi.mock("@/lib/middleware/helpers", () => {+ const { NextResponse } = require("next/server");+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++import { GET } from "./route";++describe("GET /api/runtimes", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists runtimes in workspace", async () => {+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);+ mockListAgentRuntimes.mockResolvedValue([+ { id: "r1", name: "Runtime 1", status: "online" },+ { id: "r2", name: "Runtime 2", status: "offline" },+ ]);++ const req = new NextRequest("http://localhost/api/runtimes");+ const res = await GET(req, {} as any);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual([+ { id: "r1", name: "Runtime 1", status: "online" },+ { id: "r2", name: "Runtime 2", status: "offline" },+ ]);+ expect(mockListAgentRuntimes).toHaveBeenCalledWith({}, "w1");+ });++ it("marks stale runtimes offline before listing", async () => {+ mockMarkStaleRuntimesOffline.mockResolvedValue(undefined);+ mockListAgentRuntimes.mockResolvedValue([]);++ const req = new NextRequest("http://localhost/api/runtimes");+ await GET(req, {} as any);++ expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");+ expect(mockMarkStaleRuntimesOffline).toHaveBeenCalledBefore(mockListAgentRuntimes);+ });+});diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.tsnew file mode 100644index 000000000..f2ebae1b4--- /dev/null+++ b/src/web/src/app/api/tasks/[id]/messages/route.test.ts@@ -0,0 +1,131 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetTask = vi.fn();+const mockListTaskMessages = vi.fn();+const mockListTaskMessagesSince = vi.fn();+const mockTaskMessageToResponse = vi.fn((m: any) => ({+ id: m.id,+ task_id: m.taskId,+ seq: m.seq,+ type: m.type,+ content: m.content,+}));++vi.mock("@/lib/middleware/helpers", () => ({+ writeJSON: (data: any, status = 200) =>+ new Response(JSON.stringify(data), {+ status,+ headers: { "content-type": "application/json" },+ }),+ writeError: (message: string, status: number) =>+ new Response(JSON.stringify({ error: message }), {+ status,+ headers: { "content-type": "application/json" },+ }),+}));+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ task: {+ getTask: (...args: any[]) => mockGetTask(...args),+ },+ taskMessage: {+ listTaskMessages: (...args: any[]) => mockListTaskMessages(...args),+ listTaskMessagesSince: (...args: any[]) => mockListTaskMessagesSince(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ taskMessageToResponse: (...args: any[]) => mockTaskMessageToResponse(...args),+}));++import { GET } from "./route";++describe("GET /api/tasks/[id]/messages", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists all messages", async () => {+ const task = { id: "t1", workspaceId: "w1" };+ const messages = [+ { id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },+ { id: "m2", taskId: "t1", seq: 2, type: "text", content: "world" },+ ];+ mockGetTask.mockResolvedValue(task);+ mockListTaskMessages.mockResolvedValue(messages);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1/messages"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "m1", task_id: "t1", seq: 1, type: "text", content: "hello" },+ { id: "m2", task_id: "t1", seq: 2, type: "text", content: "world" },+ ]);+ expect(mockListTaskMessages).toHaveBeenCalledWith({}, "t1");+ });++ it("filters by since parameter", async () => {+ const task = { id: "t1", workspaceId: "w1" };+ const messages = [+ { id: "m3", taskId: "t1", seq: 6, type: "text", content: "new msg" },+ ];+ mockGetTask.mockResolvedValue(task);+ mockListTaskMessagesSince.mockResolvedValue(messages);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1/messages?since=5"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual([+ { id: "m3", task_id: "t1", seq: 6, type: "text", content: "new msg" },+ ]);+ expect(mockListTaskMessagesSince).toHaveBeenCalledWith({}, "t1", 5);+ expect(mockListTaskMessages).not.toHaveBeenCalled();+ });++ it("returns 400 for invalid since parameter", async () => {+ const task = { id: "t1", workspaceId: "w1" };+ mockGetTask.mockResolvedValue(task);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1/messages?since=abc"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid since parameter");+ });++ it("returns 404 when task not found", async () => {+ mockGetTask.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1/messages"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("task not found");+ });+});diff --git a/src/web/src/app/api/tasks/[id]/route.test.ts b/src/web/src/app/api/tasks/[id]/route.test.tsnew file mode 100644index 000000000..33c1e992c--- /dev/null+++ b/src/web/src/app/api/tasks/[id]/route.test.ts@@ -0,0 +1,113 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetTask = vi.fn();+const mockTaskToResponse = vi.fn((t: any) => ({+ id: t.id,+ agent_id: t.agentId,+ workspace_id: t.workspaceId,+ status: t.status,+ prompt: t.prompt,+}));++vi.mock("@/lib/middleware/helpers", () => ({+ writeJSON: (data: any, status = 200) =>+ new Response(JSON.stringify(data), {+ status,+ headers: { "content-type": "application/json" },+ }),+ writeError: (message: string, status: number) =>+ new Response(JSON.stringify({ error: message }), {+ status,+ headers: { "content-type": "application/json" },+ }),+}));+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ task: {+ getTask: (...args: any[]) => mockGetTask(...args),+ },+ },+}));+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/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));+vi.mock("@/lib/api/responses", () => ({+ taskToResponse: (...args: any[]) => mockTaskToResponse(...args),+}));++import { GET } from "./route";++describe("GET /api/tasks/[id]", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns task", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ workspaceId: "w1",+ status: "completed",+ prompt: "hello",+ };+ mockGetTask.mockResolvedValue(task);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({+ id: "t1",+ agent_id: "a1",+ workspace_id: "w1",+ status: "completed",+ prompt: "hello",+ });+ expect(mockGetTask).toHaveBeenCalledWith({}, "t1");+ });++ it("returns 404 when not found", async () => {+ mockGetTask.mockResolvedValue(null);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("task not found");+ });++ it("returns 404 when workspace mismatch", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ workspaceId: "other-workspace",+ status: "completed",+ prompt: "hello",+ };+ mockGetTask.mockResolvedValue(task);++ const res = await GET(+ new NextRequest("http://localhost/api/tasks/t1"),+ { params: Promise.resolve({ id: "t1" }) }+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("task not found");+ });+});diff --git a/src/web/src/app/api/workspaces/[id]/route.test.ts b/src/web/src/app/api/workspaces/[id]/route.test.tsnew file mode 100644index 000000000..8ddef0604--- /dev/null+++ b/src/web/src/app/api/workspaces/[id]/route.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockGetWorkspace = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ workspace: { getWorkspace: (...args: unknown[]) => mockGetWorkspace(...args) },+ },+}));++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/middleware/helpers", () => {+ const { NextResponse } = require("next/server");+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++vi.mock("@/lib/api/responses", () => ({+ workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name, slug: w.slug })),+}));++import { GET } from "./route";++describe("GET /api/workspaces/[id]", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns workspace", async () => {+ mockGetWorkspace.mockResolvedValue({ id: "w1", name: "Acme", slug: "acme" });++ const req = new NextRequest("http://localhost/api/workspaces/w1");+ const res = await GET(req, { params: Promise.resolve({ id: "w1" }) } as any);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ id: "w1", name: "Acme", slug: "acme" });+ expect(mockGetWorkspace).toHaveBeenCalledWith({}, "w1");+ });++ it("returns 404 when not found", async () => {+ mockGetWorkspace.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/workspaces/w999");+ const res = await GET(req, { params: Promise.resolve({ id: "w999" }) } as any);++ expect(res.status).toBe(404);+ expect(await res.json()).toEqual({ error: "workspace not found" });+ });+});diff --git a/src/web/src/app/api/workspaces/route.test.ts b/src/web/src/app/api/workspaces/route.test.tsnew file mode 100644index 000000000..159379a47--- /dev/null+++ b/src/web/src/app/api/workspaces/route.test.ts@@ -0,0 +1,128 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++const mockListWorkspaces = vi.fn();+const mockCreateWorkspace = vi.fn();+const mockCreateMember = vi.fn();++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ workspace: {+ listWorkspaces: (...args: unknown[]) => mockListWorkspaces(...args),+ createWorkspace: (...args: unknown[]) => mockCreateWorkspace(...args),+ },+ member: {+ createMember: (...args: unknown[]) => mockCreateMember(...args),+ },+ },+}));++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/middleware/helpers", () => {+ const { NextResponse } = require("next/server");+ return {+ writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),+ writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),+ };+});++vi.mock("@/lib/api/responses", () => ({+ workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name, slug: w.slug })),+}));++import { GET, POST } from "./route";++describe("GET /api/workspaces", () => {+ beforeEach(() => vi.clearAllMocks());++ it("lists user workspaces", async () => {+ mockListWorkspaces.mockResolvedValue([+ { id: "w1", name: "Acme", slug: "acme" },+ { id: "w2", name: "Beta", slug: "beta" },+ ]);++ const req = new NextRequest("http://localhost/api/workspaces");+ const res = await GET(req, {} as any);++ expect(res.status).toBe(200);+ expect(await res.json()).toEqual([+ { id: "w1", name: "Acme", slug: "acme" },+ { id: "w2", name: "Beta", slug: "beta" },+ ]);+ expect(mockListWorkspaces).toHaveBeenCalledWith({}, "u1");+ });+});++describe("POST /api/workspaces", () => {+ beforeEach(() => vi.clearAllMocks());++ it("creates workspace with member and returns 201", async () => {+ mockCreateWorkspace.mockResolvedValue({ id: "w-new", name: "New", slug: "new" });+ mockCreateMember.mockResolvedValue({});++ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name: "New", slug: "new" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(201);+ expect(await res.json()).toEqual({ id: "w-new", name: "New", slug: "new" });+ expect(mockCreateWorkspace).toHaveBeenCalledWith({}, { name: "New", slug: "new" });+ expect(mockCreateMember).toHaveBeenCalledWith({}, {+ workspaceId: "w-new",+ userId: "u1",+ role: "owner",+ });+ });++ it("returns 400 for missing name", async () => {+ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ slug: "test" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "name is required" });+ });++ it("returns 400 for missing slug", async () => {+ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name: "Test" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(400);+ expect(await res.json()).toEqual({ error: "slug is required" });+ });++ it("returns 409 on duplicate slug", async () => {+ mockCreateWorkspace.mockRejectedValue(new Error("UNIQUE constraint failed: workspaces.slug"));++ const req = new NextRequest("http://localhost/api/workspaces", {+ method: "POST",+ body: JSON.stringify({ name: "Dup", slug: "dup" }),+ headers: { "Content-Type": "application/json" },+ });+ const res = await POST(req, {} as any);++ expect(res.status).toBe(409);+ expect(await res.json()).toEqual({ error: "workspace slug already exists" });+ });+});diff --git a/src/web/lib/api.test.ts b/src/web/src/lib/api.test.tssimilarity index 100%rename from src/web/lib/api.test.tsrename to src/web/src/lib/api.test.tsdiff --git a/src/web/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tssimilarity index 100%rename from src/web/lib/api/responses.test.tsrename to src/web/src/lib/api/responses.test.tsdiff --git a/src/web/lib/logger.test.ts b/src/web/src/lib/logger.test.tssimilarity index 100%rename from src/web/lib/logger.test.tsrename to src/web/src/lib/logger.test.tsdiff --git a/src/web/src/lib/middleware/auth.test.ts b/src/web/src/lib/middleware/auth.test.tsnew file mode 100644index 000000000..cd0694319--- /dev/null+++ b/src/web/src/lib/middleware/auth.test.ts@@ -0,0 +1,174 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest, NextResponse } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}));++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ machineToken: {+ getMachineTokenByHash: vi.fn(),+ updateMachineTokenLastUsed: vi.fn(),+ },+ },+}));++const mockGetSession = vi.fn();+vi.mock("@/lib/auth", () => ({+ createAuth: vi.fn(() => ({+ api: { getSession: mockGetSession },+ })),+}));++import { withAuth } from "./auth";+import { queries } from "@alook/shared";++const mockGetMachineTokenByHash = queries.machineToken+ .getMachineTokenByHash as ReturnType<typeof vi.fn>;+const mockUpdateMachineTokenLastUsed = queries.machineToken+ .updateMachineTokenLastUsed as ReturnType<typeof vi.fn>;++const testHandler = vi.fn(async (_req: NextRequest, ctx: any) =>+ NextResponse.json({ ok: true, ctx })+);++describe("withAuth middleware", () => {+ beforeEach(() => vi.clearAllMocks());++ const wrapped = withAuth(testHandler);++ it("returns 401 when Authorization header is missing", async () => {+ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(401);+ expect(body.error).toBe("unauthorized");+ });++ it("returns 401 when Authorization format is not Bearer", async () => {+ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Basic abc123" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(401);+ expect(body.error).toBe("unauthorized");+ });++ it("returns 401 when Authorization has no token after Bearer", async () => {+ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer " },+ });++ mockGetSession.mockResolvedValue(null);++ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(401);+ expect(body.error).toBe("unauthorized");+ });++ it("authenticates valid Better Auth session and passes userId/email to handler", async () => {+ mockGetSession.mockResolvedValue({+ user: { id: "user-1", email: "[email protected]" },+ });++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer some-session-token" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.ctx.userId).toBe("user-1");+ expect(body.ctx.email).toBe("[email protected]");+ expect(testHandler).toHaveBeenCalledOnce();+ });++ it("returns 401 when Better Auth session is null", async () => {+ mockGetSession.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer some-session-token" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(401);+ expect(body.error).toBe("unauthorized");+ });++ it("authenticates machine token (al_ prefix) via hash lookup", async () => {+ mockGetMachineTokenByHash.mockResolvedValue({+ id: "mt-1",+ userId: "user-mt",+ userEmail: "[email protected]",+ workspaceId: "ws-1",+ });+ mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined);++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer al_secret_token" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ok).toBe(true);+ expect(body.ctx.userId).toBe("user-mt");+ expect(body.ctx.email).toBe("[email protected]");+ expect(body.ctx.workspaceId).toBe("ws-1");+ expect(mockGetMachineTokenByHash).toHaveBeenCalledOnce();+ });++ it("returns 401 for unknown machine token (getMachineTokenByHash returns null)", async () => {+ mockGetMachineTokenByHash.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer al_invalid_token" },+ });+ const res = await wrapped(req);+ const body = await res.json();++ expect(res.status).toBe(401);+ expect(body.error).toBe("invalid token");+ });++ it("updates lastUsedAt on machine token auth", async () => {+ mockGetMachineTokenByHash.mockResolvedValue({+ id: "mt-2",+ userId: "user-mt2",+ userEmail: "[email protected]",+ workspaceId: null,+ });+ mockUpdateMachineTokenLastUsed.mockResolvedValue(undefined);++ const req = new NextRequest("http://localhost/api/test", {+ headers: { Authorization: "Bearer al_another_token" },+ });+ await wrapped(req);++ expect(mockUpdateMachineTokenLastUsed).toHaveBeenCalledWith({}, "mt-2");+ });++ it("resolves dynamic params from context", async () => {+ mockGetSession.mockResolvedValue({+ user: { id: "user-p", email: "[email protected]" },+ });++ const req = new NextRequest("http://localhost/api/test");+ const res = await wrapped(req, {+ params: Promise.resolve({ id: "x" }),+ });+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.ctx.params).toEqual({ id: "x" });+ });+});diff --git a/src/web/lib/middleware/helpers.test.ts b/src/web/src/lib/middleware/helpers.test.tssimilarity index 89%rename from src/web/lib/middleware/helpers.test.tsrename to src/web/src/lib/middleware/helpers.test.tsindex 6fcca9fe2..570083ba1 100644--- a/src/web/lib/middleware/helpers.test.ts+++ b/src/web/src/lib/middleware/helpers.test.ts@@ -17,8 +17,6 @@ import {formatTimestamp,formatTimestampNullable,} from "./helpers";-import { z } from "zod";-describe("formatTimestamp", () => {it("strips milliseconds from ISO string", () => {const d = new Date("2024-01-15T10:30:00.000Z");@@ -77,7 +75,18 @@ describe("writeError", () => {// parseBody// ----------------------------------------------------------------------------const TestSchema = z.object({ name: z.string(), age: z.number() });+const TestSchema = {+ parse(data: unknown) {+ const obj = data as Record<string, unknown>;+ if (typeof obj?.name !== "string") {+ throw { issues: [{ path: ["name"], message: "Expected string" }] };+ }+ if (typeof obj?.age !== "number") {+ throw { issues: [{ path: ["age"], message: "Expected number" }] };+ }+ return obj as { name: string; age: number };+ },+};function fakeRequest(body: unknown, valid = true): Request {return {diff --git a/src/web/lib/middleware/request-id.test.ts b/src/web/src/lib/middleware/request-id.test.tssimilarity index 100%rename from src/web/lib/middleware/request-id.test.tsrename to src/web/src/lib/middleware/request-id.test.tsdiff --git a/src/web/lib/middleware/request-logger.test.ts b/src/web/src/lib/middleware/request-logger.test.tssimilarity index 100%rename from src/web/lib/middleware/request-logger.test.tsrename to src/web/src/lib/middleware/request-logger.test.tsdiff --git a/src/web/src/lib/middleware/workspace.test.ts b/src/web/src/lib/middleware/workspace.test.tsnew file mode 100644index 000000000..1f79b3cc8--- /dev/null+++ b/src/web/src/lib/middleware/workspace.test.ts@@ -0,0 +1,104 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest, NextResponse } from "next/server";++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),+}));++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ member: {+ getMemberByUserAndWorkspace: vi.fn(),+ },+ },+}));++import { withWorkspaceMember } from "./workspace";+import { queries } from "@alook/shared";+import type { AuthContext } from "./auth";++const mockGetMember = queries.member+ .getMemberByUserAndWorkspace as ReturnType<typeof vi.fn>;++describe("withWorkspaceMember", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns workspaceId from query param", async () => {+ mockGetMember.mockResolvedValue({ id: "m1" });++ const req = new NextRequest("http://localhost/api/test?workspace_id=w1");+ const auth: AuthContext = { userId: "u1", email: "[email protected]" };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toEqual({ workspaceId: "w1" });+ expect(mockGetMember).toHaveBeenCalledWith({}, "u1", "w1");+ });++ it("returns workspaceId from X-Workspace-ID header", async () => {+ mockGetMember.mockResolvedValue({ id: "m1" });++ const req = new NextRequest("http://localhost/api/test", {+ headers: { "X-Workspace-ID": "w-header" },+ });+ const auth: AuthContext = { userId: "u1", email: "[email protected]" };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toEqual({ workspaceId: "w-header" });+ });++ it("returns workspaceId from auth context (machine token has workspaceId)", async () => {+ mockGetMember.mockResolvedValue({ id: "m1" });++ const req = new NextRequest("http://localhost/api/test");+ const auth: AuthContext = {+ userId: "u1",+ email: "[email protected]",+ workspaceId: "w-auth",+ };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toEqual({ workspaceId: "w-auth" });+ });++ it("returns 400 when no workspace_id provided", async () => {+ const req = new NextRequest("http://localhost/api/test");+ const auth: AuthContext = { userId: "u1", email: "[email protected]" };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toBeInstanceOf(NextResponse);++ const res = result as NextResponse;+ const body = await res.json();+ expect(res.status).toBe(400);+ expect(body.error).toBe("workspace_id is required");+ });++ it("returns 404 when user is not a member", async () => {+ mockGetMember.mockResolvedValue(null);++ const req = new NextRequest("http://localhost/api/test?workspace_id=w1");+ const auth: AuthContext = { userId: "u1", email: "[email protected]" };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toBeInstanceOf(NextResponse);++ const res = result as NextResponse;+ const body = await res.json();+ expect(res.status).toBe(404);+ expect(body.error).toBe("workspace not found");+ });++ it("returns 401 when userId is missing", async () => {+ const req = new NextRequest("http://localhost/api/test?workspace_id=w1");+ const auth: AuthContext = { userId: "", email: "[email protected]" };++ const result = await withWorkspaceMember(req, auth);+ expect(result).toBeInstanceOf(NextResponse);++ const res = result as NextResponse;+ const body = await res.json();+ expect(res.status).toBe(401);+ expect(body.error).toBe("user not authenticated");+ });+});diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.tsnew file mode 100644index 000000000..be2b2d082--- /dev/null+++ b/src/web/src/lib/services/task.test.ts@@ -0,0 +1,347 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++vi.mock("@alook/shared", () => ({+ queries: {+ task: {+ createTask: vi.fn(),+ claimTask: vi.fn(),+ startTask: vi.fn(),+ completeTask: vi.fn(),+ failTask: vi.fn(),+ getTask: vi.fn(),+ countRunningTasks: vi.fn(),+ listPendingTasksByRuntime: vi.fn(),+ },+ agent: {+ getAgent: vi.fn(),+ updateAgentStatus: vi.fn(),+ },+ message: {+ createMessage: vi.fn(),+ },+ },+}));++vi.mock("@/lib/logger", () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },+}));++import { TaskService } from "./task";+import { queries } from "@alook/shared";++const taskQ = queries.task as {+ [K in keyof typeof queries.task]: ReturnType<typeof vi.fn>;+};+const agentQ = queries.agent as {+ [K in keyof typeof queries.agent]: ReturnType<typeof vi.fn>;+};+const messageQ = queries.message as {+ [K in keyof typeof queries.message]: ReturnType<typeof vi.fn>;+};++const service = new TaskService({} as any);++describe("TaskService", () => {+ beforeEach(() => vi.clearAllMocks());++ // ── enqueueTask ──────────────────────────────────────────────────++ describe("enqueueTask", () => {+ it("throws when agent not found", async () => {+ agentQ.getAgent.mockResolvedValue(null);++ await expect(+ service.enqueueTask("a1", "c1", "w1", "do stuff")+ ).rejects.toThrow("agent not found");+ });++ it("throws when agent has no runtime", async () => {+ agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: null });++ await expect(+ service.enqueueTask("a1", "c1", "w1", "do stuff")+ ).rejects.toThrow("agent has no runtime");+ });++ it("creates task with correct params on success", async () => {+ agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });+ taskQ.createTask.mockResolvedValue({ id: "t1" });++ const result = await service.enqueueTask("a1", "c1", "w1", "do stuff");++ expect(taskQ.createTask).toHaveBeenCalledWith({}, {+ agentId: "a1",+ runtimeId: "r1",+ workspaceId: "w1",+ conversationId: "c1",+ prompt: "do stuff",+ priority: 0,+ });+ expect(result).toEqual({ id: "t1" });+ });+ });++ // ── claimTask ────────────────────────────────────────────────────++ describe("claimTask", () => {+ it("returns null when agent not found", async () => {+ agentQ.getAgent.mockResolvedValue(null);++ const result = await service.claimTask("a1");+ expect(result).toBeNull();+ });++ it("returns null when at max capacity", async () => {+ agentQ.getAgent.mockResolvedValue({+ id: "a1",+ maxConcurrentTasks: 2,+ });+ taskQ.countRunningTasks.mockResolvedValue(2);++ const result = await service.claimTask("a1");+ expect(result).toBeNull();+ });++ it("returns null when no queued tasks", async () => {+ agentQ.getAgent.mockResolvedValue({+ id: "a1",+ maxConcurrentTasks: 5,+ });+ taskQ.countRunningTasks.mockResolvedValue(0);+ taskQ.claimTask.mockResolvedValue(null);++ const result = await service.claimTask("a1");+ expect(result).toBeNull();+ });++ it("claims task and updates agent to working on success", async () => {+ agentQ.getAgent.mockResolvedValue({+ id: "a1",+ maxConcurrentTasks: 5,+ });+ taskQ.countRunningTasks.mockResolvedValue(1);+ taskQ.claimTask.mockResolvedValue({ id: "t1", agentId: "a1" });++ const result = await service.claimTask("a1");++ expect(result).toEqual({ id: "t1", agentId: "a1" });+ expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(+ {},+ "a1",+ "working"+ );+ });+ });++ // ── claimTaskForRuntime ──────────────────────────────────────────++ describe("claimTaskForRuntime", () => {+ it("returns null when no pending tasks", async () => {+ taskQ.listPendingTasksByRuntime.mockResolvedValue([]);++ const result = await service.claimTaskForRuntime("r1");+ expect(result).toBeNull();+ });++ it("deduplicates by agent ID", async () => {+ taskQ.listPendingTasksByRuntime.mockResolvedValue([+ { agentId: "a1", id: "t1" },+ { agentId: "a1", id: "t2" },+ ]);+ agentQ.getAgent.mockResolvedValue({+ id: "a1",+ maxConcurrentTasks: 5,+ });+ taskQ.countRunningTasks.mockResolvedValue(0);+ taskQ.claimTask.mockResolvedValue({+ id: "t1",+ agentId: "a1",+ runtimeId: "r1",+ });++ const result = await service.claimTaskForRuntime("r1");++ expect(result).toEqual({ id: "t1", agentId: "a1", runtimeId: "r1" });+ // claimTask on the service calls agentQ internally, but the key point+ // is taskQ.claimTask should only have been called once (dedup by agentId)+ expect(taskQ.claimTask).toHaveBeenCalledTimes(1);+ });+ });++ // ── startTask ────────────────────────────────────────────────────++ describe("startTask", () => {+ it("throws when not in dispatched status", async () => {+ taskQ.startTask.mockResolvedValue(null);++ await expect(service.startTask("t1")).rejects.toThrow(+ "task not in dispatched status"+ );+ });++ it("returns started task on success", async () => {+ const task = { id: "t1", status: "running" };+ taskQ.startTask.mockResolvedValue(task);++ const result = await service.startTask("t1");+ expect(result).toEqual(task);+ });+ });++ // ── completeTask ─────────────────────────────────────────────────++ describe("completeTask", () => {+ it("creates assistant message from result.output", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "completed",+ };+ taskQ.completeTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(0);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.completeTask(+ "t1",+ JSON.stringify({ output: "Here is the answer" }),+ "sess-1",+ "/work"+ );++ expect(messageQ.createMessage).toHaveBeenCalledWith({}, {+ conversationId: "c1",+ role: "assistant",+ content: "Here is the answer",+ taskId: "t1",+ });+ });++ it("does not create message when result has no output", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "completed",+ };+ taskQ.completeTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(0);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.completeTask("t1", JSON.stringify({}), "sess-1", "/work");++ expect(messageQ.createMessage).not.toHaveBeenCalled();+ });++ it("calls reconcileAgentStatus", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "completed",+ };+ taskQ.completeTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(1);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.completeTask("t1", JSON.stringify({}), "sess-1", "/work");++ expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(+ {},+ "a1",+ "working"+ );+ });+ });++ // ── failTask ─────────────────────────────────────────────────────++ describe("failTask", () => {+ it("creates error message when error is non-empty", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "failed",+ };+ taskQ.failTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(0);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.failTask("t1", "something went wrong");++ expect(messageQ.createMessage).toHaveBeenCalledWith({}, {+ conversationId: "c1",+ role: "assistant",+ content: "Error: something went wrong",+ taskId: "t1",+ });+ });++ it("does not create message when error is empty", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "failed",+ };+ taskQ.failTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(0);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.failTask("t1", "");++ expect(messageQ.createMessage).not.toHaveBeenCalled();+ });++ it("calls reconcileAgentStatus", async () => {+ const task = {+ id: "t1",+ agentId: "a1",+ conversationId: "c1",+ status: "failed",+ };+ taskQ.failTask.mockResolvedValue(task);+ taskQ.countRunningTasks.mockResolvedValue(2);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.failTask("t1", "err");++ expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(+ {},+ "a1",+ "working"+ );+ });+ });++ // ── reconcileAgentStatus ─────────────────────────────────────────++ describe("reconcileAgentStatus", () => {+ it("sets working when running tasks > 0", async () => {+ taskQ.countRunningTasks.mockResolvedValue(3);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.reconcileAgentStatus("a1");++ expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(+ {},+ "a1",+ "working"+ );+ });++ it("sets idle when running tasks = 0", async () => {+ taskQ.countRunningTasks.mockResolvedValue(0);+ agentQ.updateAgentStatus.mockResolvedValue(undefined);++ await service.reconcileAgentStatus("a1");++ expect(agentQ.updateAgentStatus).toHaveBeenCalledWith(+ {},+ "a1",+ "idle"+ );+ });+ });+});diff --git a/src/web/vitest.config.ts b/src/web/vitest.config.tsindex 9b6f4cb1f..3f39e3d96 100644--- a/src/web/vitest.config.ts+++ b/src/web/vitest.config.ts@@ -1,11 +1,16 @@+import path from "path"import { defineConfig, mergeConfig } from "vitest/config"import shared from "../../vitest.shared"export default mergeConfig(shared, defineConfig({+ resolve: {+ alias: {+ "@": path.resolve(__dirname, "src"),+ },+ },test: {testTimeout: 30_000,hookTimeout: 30_000,- include: ["src/test/e2e/**/*.test.ts"],- setupFiles: ["src/test/setup.ts"],+ include: ["src/**/*.test.ts"],},}))