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 cancel button
Gus04b6dbbd48bf
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex de4ce33cb..3c548c841 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -73,6 +73,11 @@ vi.mock("./update-handler.js", () => ({clearUpdateMarker: vi.fn(),}));+const mockFindRunningPidByTaskId = vi.fn();+vi.mock("./execenv/timeline.js", () => ({+ findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...args),+}));+// Track spawned childreninterface MockChild extends EventEmitter {pid: number;@@ -1277,3 +1282,128 @@ describe("daemon restart via update", () => {expect(clearUpdateMarker).not.toHaveBeenCalled();});});++describe("daemon kill_task handling", () => {+ beforeEach(() => {+ signalHandlers.clear();+ intervalTimers.length = 0;+ clearedTimers.length = 0;+ spawnedChildren.length = 0;+ nextPid = 50000;+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);+ mockOpenSync.mockReturnValue(42);+ });++ afterEach(() => {+ for (const t of intervalTimers) realClearInterval(t);+ });++ function makeKillTask(targetTaskId: string) {+ return {+ id: "kt1",+ agent_id: "a1",+ runtime_id: "rt1",+ conversation_id: "c1",+ workspace_id: "ws1",+ prompt: "",+ status: "dispatched",+ priority: 0,+ dispatched_at: null,+ started_at: null,+ completed_at: null,+ created_at: "2026-01-01T00:00:00Z",+ type: "kill_task",+ result: null,+ error: null,+ agent: null,+ context: { target_task_id: targetTaskId },+ };+ }++ function setupKillTaskClaim(targetTaskId: string) {+ let claimed = false;+ mockClientInstance.poll.mockImplementation(async () => {+ if (!claimed) {+ claimed = true;+ return { tasks: [makeKillTask(targetTaskId)], evicted: false };+ }+ return { tasks: [], evicted: false };+ });+ }++ it("sends SIGTERM when target PID is found in timeline", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(99999);+ const mockKill = vi.spyOn(process, "kill").mockImplementation((() => {}) as any);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ expect(mockKill).toHaveBeenCalledWith(99999, "SIGTERM");+ expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "killed");+ expect(spawn).not.toHaveBeenCalled();++ mockKill.mockRestore();+ });++ it("reports 'target not found' when PID not in timeline", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(null);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "target not found in timeline");+ expect(spawn).not.toHaveBeenCalled();+ });++ it("handles ESRCH when target process already exited", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(12345);+ const esrchError = Object.assign(new Error("kill ESRCH"), { code: "ESRCH" });+ const mockKill = vi.spyOn(process, "kill").mockImplementation(() => { throw esrchError; });++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ expect(mockClientInstance.failTask).toHaveBeenCalledWith("al_test_token", "kt1", "target process already exited");+ expect(spawn).not.toHaveBeenCalled();++ mockKill.mockRestore();+ });++ it("does not call startTask for kill_tasks", async () => {+ setupKillTaskClaim("target_t1");+ mockFindRunningPidByTaskId.mockReturnValue(null);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ await startDaemon();+ await new Promise((r) => setTimeout(r, 50));++ expect(mockClientInstance.startTask).not.toHaveBeenCalled();+ });+});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 479980b76..6c9b02084 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -8,6 +8,8 @@ import { log } from "../lib/logger.js";import { cmdPrefix } from "../lib/env.js";import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";+import { findRunningPidByTaskId } from "./execenv/timeline.js";+import { TASK_TYPES } from "@alook/shared";import { existsSync, mkdirSync, openSync, closeSync, readdirSync, statSync, unlinkSync } from "fs";import { execSync, spawn, type ChildProcess } from "child_process";import { fileURLToPath } from "url";@@ -411,6 +413,39 @@ async function handleTask(): Promise<void> {log.info(`Task ${task.id} claimed agent=${task.agentId}`);+ if (task.type === TASK_TYPES.KILL_TASK) {+ const targetTaskId = (task.context as Record<string, unknown>)?.target_task_id as string | undefined;+ if (!targetTaskId) {+ await client.failTask(token, task.id, "missing target_task_id in context");+ activeTasks.delete(task.id);+ return;+ }++ const timelineDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir", ".context_timeline");+ const pid = findRunningPidByTaskId(timelineDir, targetTaskId);++ if (pid != null) {+ try {+ process.kill(pid, "SIGTERM");+ await client.failTask(token, task.id, "killed");+ log.info(`Kill task ${task.id}: sent SIGTERM to pid=${pid} for target=${targetTaskId}`);+ } catch (e: unknown) {+ if ((e as NodeJS.ErrnoException)?.code === "ESRCH") {+ await client.failTask(token, task.id, "target process already exited");+ log.info(`Kill task ${task.id}: target pid=${pid} already exited`);+ } else {+ await client.failTask(token, task.id, `kill failed: ${e}`);+ }+ }+ } else {+ await client.failTask(token, task.id, "target not found in timeline");+ log.info(`Kill task ${task.id}: target ${targetTaskId} not found in timeline`);+ }++ activeTasks.delete(task.id);+ return;+ }+try {await client.startTask(token, task.id);} catch (e) {diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.tsindex f761b26e8..2aaf72701 100644--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts@@ -15,6 +15,7 @@ import {createTimelineEntry,findResumableSessionId,findResumableSessionByContextKey,+ findRunningPidByTaskId,_todayFilename,_localISOString,_filenameForDate,@@ -517,6 +518,77 @@ describe("timeline", () => {});});+ describe("findRunningPidByTaskId", () => {+ function writeEntry(filename: string, entry: ContextTimelineEntry) {+ const filePath = join(dir, filename);+ let existing = "";+ try { existing = readFileSync(filePath, "utf-8"); } catch { /* new file */ }+ writeFileSync(filePath, existing + JSON.stringify(entry) + "\n");+ }++ function makeEntry(overrides: Partial<ContextTimelineEntry>): ContextTimelineEntry {+ return {+ task_id: "t_1",+ context_key: null,+ session_id: null,+ pid: null,+ status: "running",+ datetime: new Date().toISOString(),+ type: "user_dm_message",+ prompt: "test",+ agent_responses: [],+ errmsg: null,+ provider: "claude",+ detailed_log: null,+ ...overrides,+ };+ }++ it("returns PID for running task", () => {+ writeEntry(_todayFilename(), makeEntry({+ task_id: "t_running",+ status: "running",+ pid: 12345,+ }));++ expect(findRunningPidByTaskId(dir, "t_running")).toBe(12345);+ });++ it("returns null for completed task", () => {+ writeEntry(_todayFilename(), makeEntry({+ task_id: "t_done",+ status: "completed",+ pid: null,+ }));++ expect(findRunningPidByTaskId(dir, "t_done")).toBeNull();+ });++ it("returns null when task not in timeline", () => {+ expect(findRunningPidByTaskId(dir, "t_nonexistent")).toBeNull();+ });++ it("returns null for running task with null pid", () => {+ writeEntry(_todayFilename(), makeEntry({+ task_id: "t_nopid",+ status: "running",+ pid: null,+ }));++ expect(findRunningPidByTaskId(dir, "t_nopid")).toBeNull();+ });++ it("returns null for killed task even with pid", () => {+ writeEntry(_todayFilename(), makeEntry({+ task_id: "t_killed",+ status: "killed",+ pid: 99999,+ }));++ expect(findRunningPidByTaskId(dir, "t_killed")).toBeNull();+ });+ });+describe("findResumableSessionByContextKey", () => {function writeEntry(filename: string, entry: ContextTimelineEntry) {const filePath = join(dir, filename);diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.tsindex b10614c45..d523bd8b1 100644--- a/src/cli/daemon/execenv/context.ts+++ b/src/cli/daemon/execenv/context.ts@@ -55,12 +55,14 @@ those json are sorted by datetime in asc order.- When you recall the timelines, don't say "I find ... in my timeline jsonl". Just say "I can recall..."- User don't know about the context timeline jsonl, this is your secret weapon.- Act and response like you're human and actually have memory, not a file reading machine.+- Don't report your agent id and workspace id when not asked, it will break the image that you're a human colleague.## RULES- Read @memory.md(if exists) before your action.- When you start a new task, read the last ~10 lines of today's timeline to understand what has been asked and done recently.- if you don't know the current datetime, obtain the current datetime first.- When user ask you something you don't have in your current context, try to read the timeline jsonl files for answer (today or previous days).+ - Use grep tool to search in the context timeline jsonls if you have clean and focus keywords to recall.- When access other local projects, make sure you read the CLAUDE.md/AGENTS.md file under the project root dir to understand the requirements.`;diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.tsindex cc64c660c..69add1483 100644--- a/src/cli/daemon/execenv/timeline.ts+++ b/src/cli/daemon/execenv/timeline.ts@@ -282,6 +282,21 @@ export function findResumableSessionByContextKey(return null;}+export function findRunningPidByTaskId(+ timelineDir: string,+ taskId: string,+): number | null {+ for (const filename of recentFilenames(1)) {+ const entries = readJsonl(join(timelineDir, filename));+ for (const entry of entries) {+ if (entry.task_id === taskId && entry.status === "running" && entry.pid != null) {+ return entry.pid;+ }+ }+ }+ return null;+}+export { localISOString };// Exported for testingdiff --git a/src/shared/src/constants.ts b/src/shared/src/constants.tsindex 4e47eb2d7..62ba2a562 100644--- a/src/shared/src/constants.ts+++ b/src/shared/src/constants.ts@@ -30,6 +30,7 @@ export const TASK_TYPES = {USER_DM_MESSAGE: "user_dm_message",EMAIL_NOTIFICATION: "email_notification",CALENDAR_EVENT: "calendar_event",+ KILL_TASK: "kill_task",} as const;export type TaskType = (typeof TASK_TYPES)[keyof typeof TASK_TYPES];diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.tsindex 8b8d3cb1f..87d39969d 100644--- a/src/shared/src/db/queries/task.ts+++ b/src/shared/src/db/queries/task.ts@@ -1,4 +1,4 @@-import { eq, and, desc, asc, inArray, notInArray, count, lt } from "drizzle-orm";+import { eq, and, desc, asc, inArray, notInArray, ne, count, lt } from "drizzle-orm";import { agentTaskQueue } from "../schema";import type { Database } from "../index";import { ClaimedTaskRowSchema } from "../../schemas";@@ -64,7 +64,8 @@ export async function claimTask(db: Database, agentId: string, workspaceId: striand(eq(agentTaskQueue.agentId, agentId),eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.status, ["dispatched", "running"])+ inArray(agentTaskQueue.status, ["dispatched", "running"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)));@@ -173,7 +174,8 @@ export async function listPendingTasksByRuntimes(and(eq(agentTaskQueue.workspaceId, workspaceId),inArray(agentTaskQueue.runtimeId, runtimeIds),- inArray(agentTaskQueue.status, ["queued", "dispatched"])+ inArray(agentTaskQueue.status, ["queued", "dispatched"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK))).orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt));@@ -189,20 +191,22 @@ export async function hasPendingTaskForConversation(.where(and(eq(agentTaskQueue.conversationId, conversationId),- inArray(agentTaskQueue.status, ["queued", "dispatched"])+ inArray(agentTaskQueue.status, ["queued", "dispatched"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK))).limit(1);return rows.length > 0;}-export async function cancelTask(db: Database, id: string) {+export async function cancelTask(db: Database, id: string, workspaceId: string) {const rows = await db.update(agentTaskQueue).set({ status: "cancelled", completedAt: new Date().toISOString() }).where(and(eq(agentTaskQueue.id, id),+ eq(agentTaskQueue.workspaceId, workspaceId),inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])))@@ -225,6 +229,7 @@ export async function failStaleDispatchedTasks(db: Database, workspaceId: stringand(eq(agentTaskQueue.workspaceId, workspaceId),eq(agentTaskQueue.status, "dispatched"),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),lt(agentTaskQueue.dispatchedAt, threshold)))@@ -251,7 +256,8 @@ export async function countRunningTasks(db: Database, agentId: string, workspaceand(eq(agentTaskQueue.agentId, agentId),eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.status, ["dispatched", "running"])+ inArray(agentTaskQueue.status, ["dispatched", "running"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)));return Number(rows[0]?.value ?? 0);@@ -270,7 +276,8 @@ export async function listActiveTaskCountsByWorkspace(.where(and(eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK))).groupBy(agentTaskQueue.agentId);@@ -293,7 +300,8 @@ export async function listActiveTasksByAgent(and(eq(agentTaskQueue.agentId, agentId),eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK))).orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt))@@ -312,10 +320,74 @@ export async function getActiveTaskByConversation(and(eq(agentTaskQueue.conversationId, conversationId),eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"]),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK))).orderBy(desc(agentTaskQueue.createdAt)).limit(1);return rows[0] ?? null;}++export async function claimKillTasks(+ db: Database,+ runtimeIds: string[],+ workspaceId: string,+ limit: number+) {+ if (runtimeIds.length === 0 || limit <= 0) return [];++ const candidates = await db+ .select({ id: agentTaskQueue.id })+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ eq(agentTaskQueue.type, TASK_TYPES.KILL_TASK),+ eq(agentTaskQueue.status, "queued"),+ inArray(agentTaskQueue.runtimeId, runtimeIds)+ )+ )+ .orderBy(asc(agentTaskQueue.createdAt))+ .limit(limit);++ const claimed = [];+ for (const candidate of candidates) {+ const rows = await db+ .update(agentTaskQueue)+ .set({ status: "dispatched", dispatchedAt: new Date().toISOString() })+ .where(+ and(+ eq(agentTaskQueue.id, candidate.id),+ eq(agentTaskQueue.status, "queued")+ )+ )+ .returning();+ const row = rows[0];+ if (row) claimed.push(ClaimedTaskRowSchema.parse(row));+ }+ return claimed;+}++const KILL_TASK_STALE_SECONDS = 30;++export async function failStaleKillTasks(db: Database, workspaceId: string) {+ const threshold = new Date(Date.now() - KILL_TASK_STALE_SECONDS * 1000).toISOString();+ const rows = await db+ .update(agentTaskQueue)+ .set({+ status: "failed",+ completedAt: new Date().toISOString(),+ error: "kill_task timed out (daemon likely offline)",+ })+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ eq(agentTaskQueue.type, TASK_TYPES.KILL_TASK),+ inArray(agentTaskQueue.status, ["queued", "dispatched"]),+ lt(agentTaskQueue.createdAt, threshold)+ )+ )+ .returning({ id: agentTaskQueue.id });+ return rows;+}diff --git a/src/web/src/app/(app)/w/[slug]/settings/page.tsx b/src/web/src/app/(app)/w/[slug]/settings/page.tsxindex 330b6de3f..f723cb058 100644--- a/src/web/src/app/(app)/w/[slug]/settings/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/page.tsx@@ -5,19 +5,58 @@ import { toast } from "sonner";import { useWorkspace } from "@/contexts/workspace-context";import { getMemberMe, updateMemberMe } from "@/lib/api";import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";-import { Button } from "@/components/ui/button";-import { Label } from "@/components/ui/label";import { MarkdownEditor } from "@/components/ui/markdown-editor";import { Skeleton } from "@/components/ui/skeleton";+import { cn } from "@/lib/utils";const MAX_LENGTH = 50_000;+const DEBOUNCE_MS = 500;++const TABS = [+ { id: "global-instruction", label: "Global Instruction" },+] as const;++type TabId = (typeof TABS)[number]["id"];++function UsageRing({ ratio, size = 16, stroke = 1.5 }: { ratio: number; size?: number; stroke?: number }) {+ const r = (size - stroke) / 2;+ const circ = 2 * Math.PI * r;+ const visual = ratio <= 0 ? 0 : ratio >= 1 ? 1 : Math.log1p(ratio * 99) / Math.log(100);+ const filled = visual * circ;+ return (+ <svg width={size} height={size} className="shrink-0 -rotate-90" aria-hidden>+ <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="currentColor" strokeWidth={stroke} className="text-border" />+ <circle+ cx={size / 2}+ cy={size / 2}+ r={r}+ fill="none"+ stroke="currentColor"+ strokeWidth={stroke}+ strokeDasharray={`${filled} ${circ - filled}`}+ strokeLinecap="round"+ className={cn(+ "transition-all duration-300",+ ratio > 0.9 ? "text-destructive/70" : ratio > 0.7 ? "text-yellow-500/50" : "text-muted-foreground/30"+ )}+ />+ </svg>+ );+}export default function SettingsPage() {const { workspaceId } = useWorkspace();+ const [activeTab, setActiveTab] = useState<TabId>("global-instruction");const [value, setValue] = useState("");const [savedValue, setSavedValue] = useState("");const [loading, setLoading] = useState(true);- const [saving, setSaving] = useState(false);++ const valueRef = useRef(value);+ valueRef.current = value;+ const savedValueRef = useRef(savedValue);+ savedValueRef.current = savedValue;+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const savingRef = useRef(false);const fetchInstruction = useCallback(async () => {setLoading(true);@@ -36,45 +75,61 @@ export default function SettingsPage() {fetchInstruction();}, [fetchInstruction]);- const handleSave = async () => {- setSaving(true);+ const flushSave = useCallback(async () => {+ if (savingRef.current) return;+ const current = valueRef.current;+ if (current === savedValueRef.current) return;+ savingRef.current = true;try {- const data = await updateMemberMe(workspaceId, value);+ const data = await updateMemberMe(workspaceId, current);setSavedValue(data.global_instruction);- toast.success("Settings saved");} catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to save settings");+ toast.error(err instanceof Error ? err.message : "Failed to save");} finally {- setSaving(false);+ savingRef.current = false;}- };+ }, [workspaceId]);++ const scheduleSave = useCallback(() => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ debounceRef.current = setTimeout(flushSave, DEBOUNCE_MS);+ }, [flushSave]);- const isDirty = value !== savedValue;- const isDirtyRef = useRef(isDirty);- isDirtyRef.current = isDirty;- const handleSaveRef = useRef(handleSave);- handleSaveRef.current = handleSave;+ const handleChange = useCallback(+ (next: string) => {+ setValue(next);+ scheduleSave();+ },+ [scheduleSave],+ );- // Warn on unsaved changes when navigating awayuseEffect(() => {- const onBeforeUnload = (e: BeforeUnloadEvent) => {- if (isDirtyRef.current) e.preventDefault();+ const onBeforeUnload = () => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ if (valueRef.current !== savedValueRef.current) {+ const params = new URLSearchParams({ workspace_id: workspaceId });+ fetch(`/api/members/me?${params}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ global_instruction: valueRef.current }),+ keepalive: true,+ });+ }};window.addEventListener("beforeunload", onBeforeUnload);return () => window.removeEventListener("beforeunload", onBeforeUnload);- }, []);+ }, [workspaceId]);- // Cmd+S / Ctrl+S to saveuseEffect(() => {- const onKeyDown = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && e.key === "s") {- e.preventDefault();- if (isDirtyRef.current) handleSaveRef.current();+ return () => {+ if (debounceRef.current) clearTimeout(debounceRef.current);+ if (valueRef.current !== savedValueRef.current) {+ void flushSave();}};- window.addEventListener("keydown", onKeyDown);- return () => window.removeEventListener("keydown", onKeyDown);- }, []);+ }, [flushSave]);++ const ratio = value.length / MAX_LENGTH;return (<>@@ -82,47 +137,80 @@ export default function SettingsPage() {<div className="flex items-center gap-3 min-w-0"><MobileSidebarLogo /><h1 className="text-sm font-medium">Settings</h1>- <p className="text-xs text-muted-foreground hidden md:block">- Instructions shared across all your agents- </p></div></div>- <div className="flex-1 overflow-y-auto px-5 py-5">- {loading ? (- <div className="mx-auto max-w-md space-y-4">- <Skeleton className="h-4 w-32" />- <Skeleton className="h-40 w-full" />- </div>- ) : (- <div className="mx-auto max-w-md space-y-4">- <Label htmlFor="global-instruction">Global Instruction</Label>- <MarkdownEditor- value={value}- onChange={setValue}- placeholder="Write instructions that every agent you own will follow..."- minHeight="240px"- contentType="markdown"- />- <div className="flex items-center justify-between">- <p className="text-xs text-muted-foreground/70">- This markdown instruction is prepended to every agent's individual instruction.- </p>- <span className="text-xs text-muted-foreground tabular-nums shrink-0 ml-4">- {value.length.toLocaleString()} / {MAX_LENGTH.toLocaleString()}- </span>- </div>- <div className="flex items-center gap-2 pt-2">- <Button- size="sm"- onClick={handleSave}- disabled={!isDirty || saving}+ <div className="flex flex-1 min-h-0">+ <nav className="w-48 shrink-0 border-r border-border/50 py-3 px-2 hidden md:block">+ {TABS.map((tab) => (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id)}+ className={cn(+ "w-full rounded-md px-2.5 py-1.5 text-left text-sm transition-colors",+ activeTab === tab.id+ ? "bg-accent text-foreground font-medium"+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"+ )}+ >+ {tab.label}+ </button>+ ))}+ </nav>++ <div className="flex-1 min-w-0 flex flex-col">+ <div className="flex items-center gap-1 border-b border-border/50 px-4 md:hidden">+ {TABS.map((tab) => (+ <button+ key={tab.id}+ onClick={() => setActiveTab(tab.id)}+ className={cn(+ "relative px-3 py-2.5 text-sm transition-colors",+ activeTab === tab.id+ ? "text-foreground font-medium"+ : "text-muted-foreground hover:text-foreground"+ )}>- {saving ? "Saving…" : "Save"}- </Button>- </div>+ {tab.label}+ {activeTab === tab.id && (+ <span className="absolute inset-x-3 -bottom-px h-px bg-foreground" />+ )}+ </button>+ ))}</div>- )}++ <div className="flex-1 overflow-y-auto thin-scrollbar">+ {activeTab === "global-instruction" && (+ <div className="flex flex-col h-full">+ {loading ? (+ <div className="px-6 py-6 space-y-4">+ <Skeleton className="h-4 w-48" />+ <Skeleton className="h-40 w-full" />+ </div>+ ) : (+ <div className="flex flex-col flex-1 min-h-0">+ <div className="flex-1 px-6 pt-4 pb-4">+ <MarkdownEditor+ value={value}+ onChange={handleChange}+ placeholder="Write instructions that every agent you own will follow..."+ minHeight="calc(100vh - 240px)"+ contentType="markdown"+ variant="seamless"+ />+ </div>+ <div className="flex items-center gap-2 px-6 py-3">+ <UsageRing ratio={ratio} />+ <p className="text-xs text-muted-foreground">+ This instruction is prepended to every agent's individual instruction.+ </p>+ </div>+ </div>+ )}+ </div>+ )}+ </div>+ </div></div></>);diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.tsindex 879d118e7..bedf16979 100644--- a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/active-task/route.test.ts@@ -12,15 +12,40 @@ vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));vi.mock("@alook/shared", () => ({createDb: vi.fn(() => ({})),+ createLogger: vi.fn(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })),+ TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", KILL_TASK: "kill_task" },+ buildContextKey: () => "ctx:test",queries: {conversation: {getConversation: (...args: any[]) => mockGetConversation(...args),},task: {getActiveTaskByConversation: (...args: any[]) => mockGetActiveTaskByConversation(...args),+ createTask: vi.fn(),+ claimTask: vi.fn(),+ countRunningTasks: vi.fn(),+ failTask: vi.fn(),+ getTask: vi.fn(),+ cancelTask: vi.fn(),+ claimKillTasks: vi.fn(),+ },+ agent: {+ getAgent: vi.fn(),+ updateAgentStatus: vi.fn(),+ },+ message: {+ createMessage: vi.fn(),+ activateNextBufferedMessage: vi.fn(),+ revertToBuffered: vi.fn(),},},}));+vi.mock("@/lib/logger", () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));+vi.mock("@/lib/broadcast", () => ({+ broadcastToUser: vi.fn().mockResolvedValue(undefined),+}));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;@@ -34,7 +59,17 @@ vi.mock("@/lib/api/responses", () => ({taskToResponse: (...args: any[]) => mockTaskToResponse(...args),}));-import { GET } from "./route";+const mockCancelActiveTask = vi.fn();+vi.mock("@/lib/services/task", () => {+ return {+ TaskService: class {+ cancelActiveTask(...args: any[]) { return mockCancelActiveTask(...args); }+ },+ };+});++import { GET, DELETE } from "./route";+import { broadcastToUser } from "@/lib/broadcast";const withParams = (id: string) => ({ params: Promise.resolve({ id }) });@@ -81,3 +116,64 @@ describe("GET /api/conversations/[id]/active-task", () => {expect(body.error).toBe("conversation not found");});});++describe("DELETE /api/conversations/[id]/active-task", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns cancelled task", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ id: "t1", status: "cancelled" });+ });++ it("returns 404 when no active task", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockCancelActiveTask.mockResolvedValue(null);++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),+ withParams("c1")+ );+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("no active task to cancel");+ });++ it("broadcasts task.updated on cancel", async () => {+ mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1" });+ mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });++ await DELETE(+ new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),+ withParams("c1")+ );++ expect(broadcastToUser).toHaveBeenCalledWith("u1", {+ type: "task.updated",+ taskId: "t1",+ status: "cancelled",+ });+ });++ it("returns 404 when conversation not found", async () => {+ mockGetConversation.mockResolvedValue(null);++ const res = await DELETE(+ new NextRequest("http://localhost/api/conversations/c1/active-task", { 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/[id]/active-task/route.ts b/src/web/src/app/api/conversations/[id]/active-task/route.tsindex ffb23ef10..6a3714510 100644--- a/src/web/src/app/api/conversations/[id]/active-task/route.ts+++ b/src/web/src/app/api/conversations/[id]/active-task/route.ts@@ -5,6 +5,8 @@ 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 GET = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -30,3 +32,35 @@ export const GET = withAuth(async (req, ctx) => {return writeJSON(taskToResponse(task));});++export const DELETE = 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("conversation id is required", 400);+ }++ const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);+ if (!conversation) {+ return writeError("conversation not found", 404);+ }++ const taskService = new TaskService(db);+ const cancelled = await taskService.cancelActiveTask(id, ws.workspaceId);+ if (!cancelled) {+ return writeError("no active task to cancel", 404);+ }++ broadcastToUser(ctx.userId, {+ type: "task.updated",+ taskId: cancelled.id,+ status: "cancelled",+ }).catch(() => {});++ return writeJSON(taskToResponse(cancelled));+});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 909fdc65f..3a57ce4e2 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -79,6 +79,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {// Per-request cache: avoids duplicate DB reads when multiple agents share the same ownerconst memberCache = new Map<string, { globalInstruction: string } | null>();for (const task of claimed) {+ if (task.type === "kill_task") {+ tasks.push({ ...taskToResponse(task), agent: null });+ continue;+ }+const agent = await queries.agent.getAgent(db, task.agentId, task.workspaceId);let emailAddresses: string[] = [];if (agent) {diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex 1f91c03e8..31ff23bb8 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -17,13 +17,14 @@ import {listBufferedMessages,createBufferedMessage,deleteBufferedMessage,+ cancelActiveTask,} from "@/lib/api";import type { Artifact, Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";import { toast } from "sonner";import { cn } from "@/lib/utils";import { Skeleton } from "@/components/ui/skeleton";-import { ArrowUp, Box, FileText, Loader2, Mic, Paperclip, RotateCcw, X } from "lucide-react";+import { ArrowUp, Box, FileText, Loader2, Mic, Paperclip, RotateCcw, Square, X } from "lucide-react";import { useSpeechRecognition } from "@/hooks/use-speech-recognition";import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";@@ -164,6 +165,7 @@ export function AgentChatView() {return localStorage.getItem(`chat-draft:${agentId}`) ?? "";});const [sending, setSending] = useState(false);+ const [cancelling, setCancelling] = useState(false);const [activeTask, setActiveTask] = useState<Task | null>(null);const [taskMessages, setTaskMessages] = useState<TaskMessage[]>([]);const [loading, setLoading] = useState(true);@@ -249,7 +251,7 @@ export function AgentChatView() {setTaskMessages(data.task_messages);lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));}- if (data.active_task.status !== "completed" && data.active_task.status !== "failed") {+ if (!["completed", "failed", "cancelled"].includes(data.active_task.status)) {startPollingRef.current(data.active_task.id, data.conversation.id, lastSeqRef.current);}}@@ -382,7 +384,7 @@ export function AgentChatView() {);}- if (task.status === "completed" || task.status === "failed") {+ if (task.status === "completed" || task.status === "failed" || task.status === "cancelled") {if (isStale) {// Stale poll — still merge messages but don't touch activeTask or pollinglistMessages(conversationId, workspaceId)@@ -562,6 +564,26 @@ export function AgentChatView() {}}, []);+ const handleStop = async () => {+ if (!conversation || cancelling) return;+ setCancelling(true);+ try {+ const cancelled = await cancelActiveTask(conversation.id, workspaceId);+ if (cancelled) {+ if (pollRef.current) clearInterval(pollRef.current);+ pollRef.current = null;+ const latest = await listMessages(conversation.id, workspaceId);+ setMessages((prev) => mergeMessages(prev, latest));+ setActiveTask(cancelled as Task);+ setTaskMessages([]);+ }+ } catch {+ toast.error("Failed to cancel task");+ } finally {+ setCancelling(false);+ }+ };+const handleSend = async () => {const content = input.trim();if ((!content && pendingFiles.length === 0) || sending || !conversation) return;@@ -575,7 +597,7 @@ export function AgentChatView() {setPendingFiles([]);setSending(true);- const taskActive = !!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed";+ const taskActive = !!activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status);if (taskActive) {// Buffer mode: queue message for later dispatch@@ -723,7 +745,7 @@ export function AgentChatView() {}};- const isTaskActive = !!activeTask && activeTask.status !== "completed" && activeTask.status !== "failed";+ const isTaskActive = !!activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status);if (loading) {return (@@ -851,7 +873,7 @@ export function AgentChatView() {})}{/* Show trace while task is in progress (no assistant message yet) */}- {activeTask && activeTask.status !== "completed" && activeTask.status !== "failed" && (+ {activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status) && (<TaskStreamtask={activeTask}messages={taskMessages}@@ -998,21 +1020,36 @@ export function AgentChatView() {<Mic className={cn("size-3.5", listening && "animate-pulse")} /></Button>)}- <Button- size="icon-sm"- onClick={handleSend}- disabled={!input.trim() || sending}- 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>+ {isTaskActive && !input.trim() && !sending ? (+ <Button+ size="icon-sm"+ onClick={handleStop}+ disabled={cancelling}+ className="rounded-lg bg-red-500/10 text-red-500 hover:bg-red-500/20 transition-colors duration-200"+ >+ {cancelling ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <Square className="size-3.5 fill-current" />+ )}+ </Button>+ ) : (+ <Button+ size="icon-sm"+ onClick={handleSend}+ disabled={!input.trim() || sending}+ 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>diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 53b654e6d..a5b608ec0 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -334,6 +334,11 @@ export const deleteAllBufferedMessages = (conversationId: string, workspaceId: sexport const getActiveTask = (conversationId: string, workspaceId: string) =>apiFetch<TaskApi | undefined>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`);+export const cancelActiveTask = (conversationId: string, workspaceId: string) =>+ apiFetch<TaskApi>(`/api/conversations/${conversationId}/active-task${wsQuery(workspaceId)}`, {+ method: "DELETE",+ });+// Machine tokensexport const createMachineToken = (name?: string, workspaceId?: string) =>apiFetch<{ token: string; id: string; name: string; created_at: string }>(diff --git a/src/web/src/lib/services/sweep.test.ts b/src/web/src/lib/services/sweep.test.tsindex 554ea4912..276a3fbea 100644--- a/src/web/src/lib/services/sweep.test.ts+++ b/src/web/src/lib/services/sweep.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest";const mockFailStaleDispatchedTasks = vi.fn();+const mockFailStaleKillTasks = vi.fn();const mockCountRunningTasks = vi.fn();const mockUpdateAgentStatus = vi.fn();const mockActivateNextBufferedMessage = vi.fn();@@ -14,6 +15,7 @@ vi.mock("@alook/shared", () => ({queries: {task: {failStaleDispatchedTasks: (...args: unknown[]) => mockFailStaleDispatchedTasks(...args),+ failStaleKillTasks: (...args: unknown[]) => mockFailStaleKillTasks(...args),countRunningTasks: (...args: unknown[]) => mockCountRunningTasks(...args),createTask: (...args: unknown[]) => mockCreateTask(...args),},@@ -29,7 +31,7 @@ vi.mock("@alook/shared", () => ({getConversation: (...args: unknown[]) => mockGetConversation(...args),},},- TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message" },+ TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", KILL_TASK: "kill_task" },buildContextKey: () => "ctx:test",}));@@ -53,6 +55,7 @@ const db = {} as any;describe("sweepStaleState", () => {beforeEach(() => {vi.clearAllMocks();+ mockFailStaleKillTasks.mockResolvedValue([]);mockActivateNextBufferedMessage.mockResolvedValue(null);});@@ -129,4 +132,12 @@ describe("sweepStaleState", () => {expect(mockActivateNextBufferedMessage).toHaveBeenCalledTimes(1);});++ it("calls failStaleKillTasks with workspace", async () => {+ mockFailStaleDispatchedTasks.mockResolvedValue([]);++ await sweepStaleState(db, "w1");++ expect(mockFailStaleKillTasks).toHaveBeenCalledWith(db, "w1");+ });});diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.tsindex 5f2f439a1..b6f5dc458 100644--- a/src/web/src/lib/services/sweep.ts+++ b/src/web/src/lib/services/sweep.ts@@ -10,6 +10,9 @@ export async function sweepStaleState(db: Database, workspaceId: string) {// 1. Fail tasks stuck in "dispatched" for >20s (daemon crashed between claim and start)const stale = await queries.task.failStaleDispatchedTasks(db, workspaceId);+ // 1b. Fail kill_tasks stuck for >30s (daemon offline or crashed after claim)+ await queries.task.failStaleKillTasks(db, workspaceId);+// 2. Reconcile agent status for any agents affected by step 1if (stale.length > 0) {const taskService = new TaskService(db);diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.tsindex cab9d2b63..cc63e9972 100644--- a/src/web/src/lib/services/task.test.ts+++ b/src/web/src/lib/services/task.test.ts@@ -7,6 +7,7 @@ vi.mock("@alook/shared", () => ({USER_DM_MESSAGE: "user_dm_message",EMAIL_NOTIFICATION: "email_notification",CALENDAR_EVENT: "calendar_event",+ KILL_TASK: "kill_task",},buildContextKey: (...a: unknown[]) => `ctx:${(a[1] as Record<string, unknown>)?.conversationId}`,queries: {@@ -19,6 +20,9 @@ vi.mock("@alook/shared", () => ({getTask: vi.fn(),countRunningTasks: vi.fn(),listPendingTasksByRuntimes: vi.fn(),+ claimKillTasks: vi.fn().mockResolvedValue([]),+ getActiveTaskByConversation: vi.fn(),+ cancelTask: vi.fn(),},agent: {getAgent: vi.fn(),@@ -72,6 +76,8 @@ describe("TaskService", () => {vi.clearAllMocks();// Default: no buffered messages to dispatchmessageQ.activateNextBufferedMessage.mockResolvedValue(null);+ // Default: no kill tasks to claim+ taskQ.claimKillTasks.mockResolvedValue([]);});// ── enqueueTask ──────────────────────────────────────────────────@@ -633,4 +639,129 @@ describe("TaskService", () => {expect(messageQ.activateNextBufferedMessage).toHaveBeenCalledWith({}, "c1");});});++ // ── failTask skips side-effects for kill_task ──────────────────++ describe("failTask kill_task guard", () => {+ it("skips message creation and reconciliation for kill_task type", async () => {+ const task = {+ id: "kt1",+ agentId: "a1",+ workspaceId: "w1",+ conversationId: "c1",+ status: "failed",+ type: "kill_task",+ };+ taskQ.failTask.mockResolvedValue(task);++ const result = await service.failTask("kt1", "w1", "killed");++ expect(result).toEqual(task);+ expect(messageQ.createMessage).not.toHaveBeenCalled();+ expect(taskQ.countRunningTasks).not.toHaveBeenCalled();+ expect(agentQ.updateAgentStatus).not.toHaveBeenCalled();+ expect(messageQ.activateNextBufferedMessage).not.toHaveBeenCalled();+ });+ });++ // ── cancelActiveTask ─────────────────────────────────────────++ describe("cancelActiveTask", () => {+ it("returns null when no active task", async () => {+ taskQ.getActiveTaskByConversation.mockResolvedValue(null);++ const result = await service.cancelActiveTask("c1", "w1");+ expect(result).toBeNull();+ });++ it("cancels queued task without creating kill_task", async () => {+ const task = { id: "t1", status: "queued", agentId: "a1", runtimeId: "r1", conversationId: "c1" };+ taskQ.getActiveTaskByConversation.mockResolvedValue(task);+ taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });+ taskQ.countRunningTasks.mockResolvedValue(0);++ const result = await service.cancelActiveTask("c1", "w1");++ expect(result!.status).toBe("cancelled");+ expect(taskQ.createTask).not.toHaveBeenCalled();+ expect(messageQ.createMessage).toHaveBeenCalledWith({}, expect.objectContaining({+ content: "Task cancelled by user",+ taskId: "t1",+ }));+ });++ it("creates kill_task for running task", async () => {+ const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };+ taskQ.getActiveTaskByConversation.mockResolvedValue(task);+ taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });+ taskQ.countRunningTasks.mockResolvedValue(0);++ await service.cancelActiveTask("c1", "w1");++ expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({+ type: "kill_task",+ agentId: "a1",+ runtimeId: "r1",+ conversationId: "c1",+ context: { target_task_id: "t1" },+ }));+ });++ it("creates kill_task for dispatched task", async () => {+ const task = { id: "t1", status: "dispatched", agentId: "a1", runtimeId: "r1", conversationId: "c1" };+ taskQ.getActiveTaskByConversation.mockResolvedValue(task);+ taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });+ taskQ.countRunningTasks.mockResolvedValue(0);++ await service.cancelActiveTask("c1", "w1");++ expect(taskQ.createTask).toHaveBeenCalledWith({}, expect.objectContaining({+ type: "kill_task",+ context: { target_task_id: "t1" },+ }));+ });++ it("dispatches next buffered message after cancel", async () => {+ const task = { id: "t1", status: "running", agentId: "a1", runtimeId: "r1", conversationId: "c1" };+ taskQ.getActiveTaskByConversation.mockResolvedValue(task);+ taskQ.cancelTask.mockResolvedValue({ ...task, status: "cancelled" });+ taskQ.countRunningTasks.mockResolvedValue(0);++ await service.cancelActiveTask("c1", "w1");++ expect(messageQ.activateNextBufferedMessage).toHaveBeenCalledWith({}, "c1");+ });+ });++ // ── claimTasksForRuntimes with kill_tasks ───────────────────++ describe("claimTasksForRuntimes with kill_tasks", () => {+ it("claims kill_tasks before normal tasks", async () => {+ const killTask = { id: "kt1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", type: "kill_task" };+ taskQ.claimKillTasks.mockResolvedValue([killTask]);+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([]);++ const result = await service.claimTasksForRuntimes(["r1"], 2, "w1");++ expect(result).toEqual([killTask]);+ expect(taskQ.claimKillTasks).toHaveBeenCalledWith({}, ["r1"], "w1", 2);+ });++ it("subtracts kill_tasks from remaining capacity", async () => {+ const killTask = { id: "kt1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", type: "kill_task" };+ taskQ.claimKillTasks.mockResolvedValue([killTask]);+ taskQ.listPendingTasksByRuntimes.mockResolvedValue([+ { agentId: "a2", workspaceId: "w1", id: "t2", runtimeId: "r1" },+ ]);+ agentQ.getAgent.mockResolvedValue({ id: "a2", maxConcurrentTasks: 5 });+ taskQ.countRunningTasks.mockResolvedValue(0);+ taskQ.claimTask.mockResolvedValue({ id: "t2", agentId: "a2", runtimeId: "r1" });++ const result = await service.claimTasksForRuntimes(["r1"], 1, "w1");++ // Only the kill_task — maxTasks=1 is fully consumed+ expect(result).toHaveLength(1);+ expect(result[0].id).toBe("kt1");+ });+ });});diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.tsindex fd7b5f8cc..62953aed0 100644--- a/src/web/src/lib/services/task.ts+++ b/src/web/src/lib/services/task.ts@@ -62,17 +62,18 @@ export class TaskService {}async claimTasksForRuntimes(runtimeIds: string[], maxTasks: number, workspaceId: string) {- const tasks = await taskQueries.listPendingTasksByRuntimes(- this.db,- runtimeIds,- workspaceId- );+ const killTasks = await taskQueries.claimKillTasks(this.db, runtimeIds, workspaceId, maxTasks);+ let remaining = maxTasks - killTasks.length;++ const tasks = remaining > 0+ ? await taskQueries.listPendingTasksByRuntimes(this.db, runtimeIds, workspaceId)+ : [];const runtimeIdSet = new Set(runtimeIds);const triedAgents = new Set<string>();- const claimed: NonNullable<Awaited<ReturnType<typeof this.claimTask>>>[] = [];+ const claimed: NonNullable<Awaited<ReturnType<typeof this.claimTask>>>[] = [...killTasks];for (const candidate of tasks) {- if (claimed.length >= maxTasks) break;+ if (remaining <= 0) break;const key = `${candidate.agentId}:${candidate.workspaceId}`;if (triedAgents.has(key)) continue;@@ -81,6 +82,7 @@ export class TaskService {const task = await this.claimTask(candidate.agentId, candidate.workspaceId);if (task && runtimeIdSet.has(task.runtimeId)) {claimed.push(task);+ remaining--;}}@@ -148,6 +150,10 @@ export class TaskService {throw new Error(`cannot fail task in '${status}' status`);}+ if (task.type === TASK_TYPES.KILL_TASK) {+ return task;+ }+if (error) {await messageQueries.createMessage(this.db, {conversationId: task.conversationId,@@ -162,6 +168,37 @@ export class TaskService {return task;}+ async cancelActiveTask(conversationId: string, workspaceId: string) {+ const activeTask = await taskQueries.getActiveTaskByConversation(this.db, conversationId, workspaceId);+ if (!activeTask) return null;++ const cancelled = await taskQueries.cancelTask(this.db, activeTask.id, workspaceId);+ if (!cancelled) return null;++ if (activeTask.status === "dispatched" || activeTask.status === "running") {+ await taskQueries.createTask(this.db, {+ agentId: activeTask.agentId,+ runtimeId: activeTask.runtimeId,+ workspaceId,+ conversationId,+ prompt: "",+ type: TASK_TYPES.KILL_TASK,+ context: { target_task_id: activeTask.id },+ });+ }++ await messageQueries.createMessage(this.db, {+ conversationId,+ role: "assistant",+ content: "Task cancelled by user",+ taskId: activeTask.id,+ });++ await this.reconcileAgentStatus(activeTask.agentId, workspaceId);+ await this.dispatchNextBufferedMessage(conversationId, workspaceId);+ return cancelled;+ }+async reconcileAgentStatus(agentId: string, workspaceId: string) {const running = await taskQueries.countRunningTasks(this.db, agentId, workspaceId);const status = running > 0 ? "working" : "idle";