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
feat: add retry button for failed tasks (replace mode) (#34)
Gener1fefdbcfe489
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.tsindex ffdaec8e1..8e2491a9e 100644--- a/src/shared/src/db/queries/task.ts+++ b/src/shared/src/db/queries/task.ts@@ -305,6 +305,21 @@ export async function supersedeTask(db: Database, id: string, workspaceId: strinreturn rows[0] ?? null;}+export async function markFailedAsSuperseded(db: Database, id: string, workspaceId: string) {+ const rows = await db+ .update(agentTaskQueue)+ .set({ status: "superseded" })+ .where(+ and(+ eq(agentTaskQueue.id, id),+ eq(agentTaskQueue.workspaceId, workspaceId),+ eq(agentTaskQueue.status, "failed")+ )+ )+ .returning();+ return rows[0] ?? null;+}+export async function cancelTask(db: Database, id: string, workspaceId: string) {const rows = await db.update(agentTaskQueue)diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsxindex 89f7d7316..f8096dea6 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx@@ -4,7 +4,7 @@ import { useState, useEffect, useCallback, useRef } from "react";import { useParams, useRouter, useSearchParams } from "next/navigation";import Link from "next/link";import { useWorkspace } from "@/contexts/workspace-context";-import { listAgentActivity, type ActivityTask } from "@/lib/api";+import { listAgentActivity, retryTask, type ActivityTask } from "@/lib/api";import { Skeleton } from "@/components/ui/skeleton";import {Select,@@ -19,6 +19,8 @@ import {CalendarDays,CircleDot,History,+ RotateCw,+ Loader2,} from "lucide-react";const ACTIVITY_LIMIT = 30;@@ -101,11 +103,26 @@ function StatusDot({ status }: { status: string }) {return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;}-function ActivityRow({ task, slug, agentId }: { task: ActivityTask; slug: string; agentId: string }) {+function ActivityRow({ task, slug, agentId, workspaceId, onRetry }: { task: ActivityTask; slug: string; agentId: string; workspaceId: string; onRetry: () => void }) {const Icon = TYPE_ICONS[task.type] ?? CircleDot;const duration = TERMINAL_STATUSES.has(task.status)? formatDuration(task.started_at, task.completed_at): null;+ const [retrying, setRetrying] = useState(false);++ const handleRetry = async (e: React.MouseEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setRetrying(true);+ try {+ await retryTask(task.id, workspaceId);+ onRetry();+ } catch {+ // silently fail+ } finally {+ setRetrying(false);+ }+ };return (<Link@@ -143,6 +160,19 @@ function ActivityRow({ task, slug, agentId }: { task: ActivityTask; slug: string</span></>)}+ {task.status === "failed" && (+ <button+ type="button"+ onClick={handleRetry}+ disabled={retrying}+ className="ml-auto shrink-0 text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:opacity-50"+ title="Retry task"+ >+ {retrying+ ? <Loader2 className="size-3 animate-spin" />+ : <RotateCw className="size-3" />}+ </button>+ )}</div></Link>);@@ -344,6 +374,8 @@ export default function AgentActivityPage() {task={task}slug={slug}agentId={agentId}+ workspaceId={workspaceId}+ onRetry={loadInitial}/>))}</div>diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsxindex ea9c2a4c0..e5c813864 100644--- a/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx@@ -1,15 +1,18 @@"use client";+import { useState } from "react";import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";import { Badge } from "@/components/ui/badge";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";-import { MessageSquare, Mail, CalendarDays } from "lucide-react";-import type { WorkspaceOverview } from "@/lib/api";+import { MessageSquare, Mail, CalendarDays, RotateCw, Loader2 } from "lucide-react";+import { retryTask, type WorkspaceOverview } from "@/lib/api";import type { Agent } from "@alook/shared";interface RecentActivityProps {overview: WorkspaceOverview;agents: Agent[];+ workspaceId: string;+ onRefresh: () => void;}const TYPE_CONFIG: Record<string, { icon: React.ElementType; label: string }> = {@@ -30,7 +33,8 @@ function timeAgo(dateStr: string | null): string {return `${days}d ago`;}-export function RecentActivity({ overview, agents }: RecentActivityProps) {+export function RecentActivity({ overview, agents, workspaceId, onRefresh }: RecentActivityProps) {+ const [retryingId, setRetryingId] = useState<string | null>(null);const { recent_tasks } = overview;const agentMap = new Map(agents.map((a) => [a.id, a.name]));@@ -87,6 +91,26 @@ export function RecentActivity({ overview, agents }: RecentActivityProps) {>{task.status}</Badge>+ {task.status === "failed" && (+ <button+ type="button"+ onClick={async () => {+ setRetryingId(task.id);+ try {+ await retryTask(task.id, workspaceId);+ onRefresh();+ } catch { /* silently fail */ }+ finally { setRetryingId(null); }+ }}+ disabled={retryingId === task.id}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:opacity-50"+ title="Retry task"+ >+ {retryingId === task.id+ ? <Loader2 className="size-3 animate-spin" />+ : <RotateCw className="size-3" />}+ </button>+ )}<span className="text-[10px] text-muted-foreground w-14 text-right">{timeAgo(task.completed_at)}</span>diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex c427deb58..53783d922 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -1,6 +1,6 @@"use client";-import { useEffect, useState } from "react";+import { useCallback, useEffect, useState } from "react";import { useRouter } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";import { useWorkspace } from "@/contexts/workspace-context";@@ -35,6 +35,12 @@ export default function HomePage() {return () => { cancelled = true; };}, [loading, agents.length, workspaceId]);+ const refreshOverview = useCallback(() => {+ getWorkspaceOverview(workspaceId)+ .then((data) => setOverview(data))+ .catch(() => {});+ }, [workspaceId]);+if (loading) {return (<div className="flex flex-1 items-center justify-center">@@ -111,7 +117,7 @@ export default function HomePage() {overview={overview}/><div className="grid gap-4 lg:grid-cols-2 lg:flex-1 lg:min-h-0 lg:auto-rows-fr">- <RecentActivity overview={overview} agents={agents} />+ <RecentActivity overview={overview} agents={agents} workspaceId={workspaceId} onRefresh={refreshOverview} /><CalendarOverview overview={overview} agents={agents} /></div><div className="shrink-0">diff --git a/src/web/src/app/api/tasks/[id]/retry/route.test.ts b/src/web/src/app/api/tasks/[id]/retry/route.test.tsnew file mode 100644index 000000000..fee346aa5--- /dev/null+++ b/src/web/src/app/api/tasks/[id]/retry/route.test.ts@@ -0,0 +1,98 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockRetryTask = 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("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));+vi.mock("@/lib/services/task", () => {+ const MockTaskService = function (this: any) {+ this.retryTask = (...a: any[]) => mockRetryTask(...a);+ } as any;+ return { TaskService: MockTaskService };+});+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),+}));+vi.mock("@/lib/broadcast", () => ({+ broadcastToUser: vi.fn().mockResolvedValue(undefined),+}));++import { POST } from "./route";++describe("POST /api/tasks/[id]/retry", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns new task on success", async () => {+ const oldTask = { id: "t1", agentId: "a1", workspaceId: "w1", status: "superseded", prompt: "hello" };+ const newTask = { id: "t2", agentId: "a1", workspaceId: "w1", status: "queued", prompt: "hello" };+ mockRetryTask.mockResolvedValue({ oldTask, newTask });++ const res = await POST(+ new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),+ { params: Promise.resolve({ id: "t1" }) },+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.status).toBe("queued");+ expect(body.prompt).toBe("hello");+ expect(mockRetryTask).toHaveBeenCalledWith("t1", "w1");+ });++ it("returns 400 when task is not failed", async () => {+ mockRetryTask.mockRejectedValue(new Error("only failed tasks can be retried"));++ const res = await POST(+ new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),+ { params: Promise.resolve({ id: "t1" }) },+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("only failed tasks can be retried");+ });++ it("returns 400 when task not found", async () => {+ mockRetryTask.mockRejectedValue(new Error("task not found"));++ const res = await POST(+ new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),+ { params: Promise.resolve({ id: "t1" }) },+ );+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task not found");+ });+});diff --git a/src/web/src/app/api/tasks/[id]/retry/route.ts b/src/web/src/app/api/tasks/[id]/retry/route.tsnew file mode 100644index 000000000..d2296cb2c--- /dev/null+++ b/src/web/src/app/api/tasks/[id]/retry/route.ts@@ -0,0 +1,31 @@+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { getDb } from "@/lib/db";+import { withAuth } from "@/lib/middleware/auth";+import { withWorkspaceMember } from "@/lib/middleware/workspace";+import { writeJSON, writeError } from "@/lib/middleware/helpers";+import { taskToResponse } from "@/lib/api/responses";+import { TaskService } from "@/lib/services/task";+import { broadcastToUser } from "@/lib/broadcast";++export const POST = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const id = ctx.params?.id;+ if (!id) {+ return writeError("task id is required", 400);+ }++ const taskService = new TaskService(db);+ try {+ const { oldTask, newTask } = await taskService.retryTask(id, ws.workspaceId);+ broadcastToUser(ctx.userId, { type: "task.updated", taskId: oldTask.id, agentId: oldTask.agentId, status: "superseded" }).catch(() => {});+ broadcastToUser(ctx.userId, { type: "task.updated", taskId: newTask.id, agentId: newTask.agentId, status: "queued" }).catch(() => {});+ return writeJSON(taskToResponse(newTask));+ } catch (e: unknown) {+ return writeError(e instanceof Error ? e.message : "Unknown error", 400);+ }+});diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex be94ecaa5..e91973a0e 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -20,6 +20,7 @@ import {deleteBufferedMessage,cancelActiveTask,getActiveTask,+ retryTask,} from "@/lib/api";import type { Artifact, Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";@@ -765,6 +766,14 @@ export function AgentChatView() {}};+ const handleRetryTask = useCallback(async () => {+ if (!activeTask || !conversation) return;+ const newTask = await retryTask(activeTask.id, workspaceId);+ setActiveTask(newTask);+ setTaskMessages([]);+ startPolling(newTask.id, conversation.id);+ }, [activeTask, conversation, workspaceId, startPolling]);+const [resetConfirmOpen, setResetConfirmOpen] = useState(false);const [resetting, setResetting] = useState(false);const [resetDontAsk, setResetDontAsk] = useState(false);@@ -946,6 +955,7 @@ export function AgentChatView() {task={activeTask}messages={taskMessages}connectionLost={connectionLost}+ onRetry={handleRetryTask}/>)}{msg.role === "user" ? (() => {diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsxindex 5251eecea..20d47b0ff 100644--- a/src/web/src/components/task-stream.tsx+++ b/src/web/src/components/task-stream.tsx@@ -9,6 +9,8 @@ import {ChevronRight,Brain,AlertCircle,+ RotateCw,+ Loader2,} from "lucide-react";import { Streamdown } from "streamdown";@@ -274,11 +276,14 @@ export function TaskStream({task,messages,connectionLost,+ onRetry,}: {task: Task;messages: TaskMessage[];connectionLost?: boolean;+ onRetry?: () => void;}) {+ const [retrying, setRetrying] = useState(false);const allItems = useMemo(() => groupMessages(messages), [messages]);const isRunning = task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled" && task.status !== "superseded";@@ -377,10 +382,26 @@ export function TaskStream({{/* Error display */}{task.status === "failed" && task.error && (- <p className="text-sm text-destructive flex items-center gap-1.5 mt-2">- <AlertCircle className="size-3.5 shrink-0" />- {task.error}- </p>+ <div className="flex items-center gap-2 mt-2">+ <p className="text-sm text-destructive flex items-center gap-1.5">+ <AlertCircle className="size-3.5 shrink-0" />+ {task.error}+ </p>+ {onRetry && (+ <button+ type="button"+ onClick={async () => {+ setRetrying(true);+ try { await onRetry(); } finally { setRetrying(false); }+ }}+ disabled={retrying}+ className="shrink-0 text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:opacity-50 flex items-center gap-1"+ >+ {retrying ? <Loader2 className="size-3 animate-spin" /> : <RotateCw className="size-3" />}+ Retry+ </button>+ )}+ </div>)}{connectionLost && (diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex e9bea78f0..6ad774264 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -416,6 +416,11 @@ export const getTaskMessages = (id: string, workspaceId: string, since?: number)`/api/tasks/${id}/messages${wsQuery(workspaceId, since ? { since: String(since) } : undefined)}`);+export const retryTask = (id: string, workspaceId: string) =>+ apiFetch<TaskApi>(`/api/tasks/${id}/retry${wsQuery(workspaceId)}`, {+ method: "POST",+ });+// Emailsexport const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string) =>apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`);diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.tsindex 5f0fbe123..f3efc9cb6 100644--- a/src/web/src/lib/services/task.test.ts+++ b/src/web/src/lib/services/task.test.ts@@ -18,6 +18,7 @@ vi.mock("@alook/shared", () => ({completeTask: vi.fn(),failTask: vi.fn(),supersedeTask: vi.fn(),+ markFailedAsSuperseded: vi.fn(),getTask: vi.fn(),countRunningTasks: vi.fn(),listPendingTasksByRuntimes: vi.fn(),@@ -735,6 +736,80 @@ describe("TaskService", () => {});});+ // ── retryTask ──────────────────────────────────────────────++ describe("retryTask", () => {+ const failedTask = {+ id: "t1",+ agentId: "a1",+ workspaceId: "w1",+ conversationId: "c1",+ prompt: "do stuff",+ type: "user_dm_message",+ status: "failed",+ context: null,+ };++ it("throws when task not found", async () => {+ taskQ.getTask.mockResolvedValue(null);++ await expect(service.retryTask("t1", "w1")).rejects.toThrow("task not found");+ });++ it("throws when workspace mismatch", async () => {+ taskQ.getTask.mockResolvedValue({ ...failedTask, workspaceId: "other" });++ await expect(service.retryTask("t1", "w1")).rejects.toThrow("task not found");+ });++ it("throws when task is not failed", async () => {+ taskQ.getTask.mockResolvedValue({ ...failedTask, status: "completed" });++ await expect(service.retryTask("t1", "w1")).rejects.toThrow("only failed tasks can be retried");+ });++ it("marks old task as superseded and creates new task", async () => {+ taskQ.getTask.mockResolvedValue(failedTask);+ taskQ.markFailedAsSuperseded.mockResolvedValue({ ...failedTask, status: "superseded" });+ agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });+ taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });++ const { oldTask, newTask } = await service.retryTask("t1", "w1");++ expect(taskQ.markFailedAsSuperseded).toHaveBeenCalledWith({}, "t1", "w1");+ expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({+ agentId: "a1",+ conversationId: "c1",+ workspaceId: "w1",+ prompt: "do stuff",+ type: "user_dm_message",+ }));+ expect(oldTask.status).toBe("superseded");+ expect(newTask.status).toBe("queued");+ });++ it("throws when markFailedAsSuperseded fails", async () => {+ taskQ.getTask.mockResolvedValue(failedTask);+ taskQ.markFailedAsSuperseded.mockResolvedValue(null);++ await expect(service.retryTask("t1", "w1")).rejects.toThrow("failed to mark task as superseded");+ });++ it("preserves context from original task", async () => {+ const taskWithContext = { ...failedTask, context: { attachment_ids: ["a1"] } };+ taskQ.getTask.mockResolvedValue(taskWithContext);+ taskQ.markFailedAsSuperseded.mockResolvedValue({ ...taskWithContext, status: "superseded" });+ agentQ.getAgent.mockResolvedValue({ id: "a1", runtimeId: "r1" });+ taskQ.createTask.mockResolvedValue({ id: "t2", status: "queued" });++ await service.retryTask("t1", "w1");++ expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({+ context: { attachment_ids: ["a1"] },+ }));+ });+ });+// ── claimTasksForRuntimes with kill_tasks ───────────────────describe("claimTasksForRuntimes with kill_tasks", () => {diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.tsindex 3093f578b..74eb8255e 100644--- a/src/web/src/lib/services/task.ts+++ b/src/web/src/lib/services/task.ts@@ -188,6 +188,27 @@ export class TaskService {return task;}+ async retryTask(taskId: string, workspaceId: string) {+ const original = await taskQueries.getTask(this.db, taskId);+ if (!original) throw new Error("task not found");+ if (original.workspaceId !== workspaceId) throw new Error("task not found");+ if (original.status !== "failed") throw new Error("only failed tasks can be retried");++ const marked = await taskQueries.markFailedAsSuperseded(this.db, taskId, workspaceId);+ if (!marked) throw new Error("failed to mark task as superseded");++ const newTask = await this.enqueueTask(+ original.agentId,+ original.conversationId,+ workspaceId,+ original.prompt,+ original.type,+ { context: original.context as Record<string, unknown> | undefined },+ );++ return { oldTask: marked, newTask };+ }+async cancelActiveTask(conversationId: string, workspaceId: string) {const activeTask = await taskQueries.getActiveTaskByConversation(this.db, conversationId, workspaceId);if (!activeTask) return null;diff --git a/src/web/src/test/e2e/task-lifecycle.test.ts b/src/web/src/test/e2e/task-lifecycle.test.tsindex 583eea133..c8e6a9a52 100644--- a/src/web/src/test/e2e/task-lifecycle.test.ts+++ b/src/web/src/test/e2e/task-lifecycle.test.ts@@ -352,7 +352,7 @@ describe("context_key resume contract", () => {})})-describe("task failure", () => {+describe("task failure and retry", () => {let failTaskId: stringbeforeAll(async () => {@@ -414,4 +414,39 @@ describe("task failure", () => {expect(data.status).toBe("failed")expect(data.error).toBe("Timeout exceeded")})++ it("POST /api/tasks/:id/retry retries a failed task", async () => {+ const res = await tokenRequest(+ `/api/tasks/${failTaskId}/retry?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ { method: "POST" },+ )+ expect(res.status).toBe(200)+ const data = await res.json() as Record<string, unknown>+ expect(data.status).toBe("queued")+ expect(data.prompt).toBe("This will fail")+ expect(data.id).not.toBe(failTaskId)+ })++ it("original task is now superseded", async () => {+ const res = await tokenRequest(+ `/api/tasks/${failTaskId}?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ )+ expect(res.status).toBe(200)+ const data = await res.json() as Record<string, unknown>+ expect(data.status).toBe("superseded")+ })++ it("retrying a non-failed task returns 400", async () => {+ // failTaskId is now superseded, not failed+ const res = await tokenRequest(+ `/api/tasks/${failTaskId}/retry?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ { method: "POST" },+ )+ expect(res.status).toBe(400)+ const data = await res.json() as Record<string, unknown>+ expect(data.error).toBe("only failed tasks can be retried")+ })})