Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: killed status correct and restart daemon log

Gus6ee7c72fb155
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 3e0787590..535f43ef5 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -122,6 +122,10 @@ export class DaemonClient {
});
}
+ supersedeTask(token: string, taskId: string) {
+ return this.request("POST", `/api/daemon/tasks/${taskId}/supersede`, token);
+ }
+
async getArtifactMeta(
token: string,
artifactId: string,
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 3c548c841..8887297c1 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -11,6 +11,7 @@ const mockClientInstance = {
startTask: vi.fn(async () => ({})),
completeTask: vi.fn(async () => ({})),
failTask: vi.fn(async () => ({})),
+ supersedeTask: vi.fn(async () => ({})),
reportMessages: vi.fn(async () => ({})),
};
vi.mock("./client.js", () => {
@@ -37,6 +38,7 @@ vi.mock("./config.js", () => ({
cliVersion: "0.1.0",
})),
sessionRunnerLogDir: vi.fn(() => "/tmp/alook/daemon/session-runners"),
+ daemonLogFilePath: vi.fn(() => "/tmp/alook/daemon/logs/2026-01-01.log"),
lastUpdateMarkerPath: vi.fn((profile?: string) =>
profile ? `/tmp/alook/last_update_${profile}` : "/tmp/alook/last_update",
),
@@ -74,8 +76,23 @@ vi.mock("./update-handler.js", () => ({
}));
const mockFindRunningPidByTaskId = vi.fn();
+const mockFindRunningEntryByContextKey = vi.fn(() => null);
vi.mock("./execenv/timeline.js", () => ({
findRunningPidByTaskId: (...args: any[]) => mockFindRunningPidByTaskId(...args),
+ findRunningEntryByContextKey: (...args: any[]) => mockFindRunningEntryByContextKey(...args),
+}));
+
+const mockWriteKillIntent = vi.fn();
+const mockClearKillIntent = vi.fn();
+const mockAcquireSteeringLock = vi.fn(() => true);
+const mockReleaseSteeringLock = vi.fn();
+const mockCleanupStaleIntents = vi.fn();
+vi.mock("./execenv/steering.js", () => ({
+ writeKillIntent: (...args: any[]) => mockWriteKillIntent(...args),
+ clearKillIntent: (...args: any[]) => mockClearKillIntent(...args),
+ acquireSteeringLock: (...args: any[]) => mockAcquireSteeringLock(...args),
+ releaseSteeringLock: (...args: any[]) => mockReleaseSteeringLock(...args),
+ cleanupStaleIntents: (...args: any[]) => mockCleanupStaleIntents(...args),
}));
// Track spawned children
@@ -1281,6 +1298,82 @@ describe("daemon restart via update", () => {
expect(clearUpdateMarker).not.toHaveBeenCalled();
});
+
+});
+
+describe("daemon restart spawn", () => {
+ beforeEach(async () => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ spawnedChildren.length = 0;
+ nextPid = 50000;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+ mockOpenSync.mockReturnValue(99);
+
+ // Restore createHealthServer to the correct factory (previous tests may override it)
+ const { createHealthServer } = await import("./health.js");
+ vi.mocked(createHealthServer).mockReturnValue({
+ setRuntimeCount: vi.fn(),
+ server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },
+ } as any);
+
+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
+ mockClientInstance.deregister.mockResolvedValue(undefined as any);
+ mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ it("restart spawn uses process.execPath with log file fd for stdio", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
+ });
+
+ // Make handleCliUpdate immediately invoke the restart callback
+ vi.mocked(handleCliUpdate).mockImplementation((_version: string, onSuccess: () => void) => {
+ onSuccess();
+ });
+
+ mockClientInstance.poll.mockResolvedValue({
+ tasks: [],
+ evicted: false,
+ pending_update: { version: "2.0.0" },
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 200));
+
+ const spawnCalls = vi.mocked(spawn).mock.calls;
+ const restartCall = spawnCalls.find(
+ (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
+ );
+ expect(restartCall).toBeDefined();
+
+ const args = restartCall![1] as string[];
+ expect(args).toContain("daemon");
+ expect(args).toContain("start");
+ expect(args).toContain("--foreground");
+
+ const opts = restartCall![2] as any;
+ expect(opts.detached).toBe(true);
+ expect(opts.stdio).toEqual(["ignore", 99, 99]);
+
+ expect(mockMkdirSync).toHaveBeenCalledWith(
+ expect.stringContaining("logs"),
+ { recursive: true, mode: 0o700 },
+ );
+ expect(mockOpenSync).toHaveBeenCalledWith(
+ "/tmp/alook/daemon/logs/2026-01-01.log",
+ "a",
+ 0o600,
+ );
+ expect(mockCloseSync).toHaveBeenCalledWith(99);
+ });
});
describe("daemon kill_task handling", () => {
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 6c9b02084..e56504673 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -1,5 +1,5 @@
import { DaemonClient } from "./client.js";
-import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir } from "./config.js";
+import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir, daemonLogFilePath } from "./config.js";
import { createHealthServer } from "./health.js";
import { detectVersion } from "./agent/index.js";
import { type Task, type SessionRunnerInput, fromApiTask } from "./types.js";
@@ -8,7 +8,14 @@ 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 { findRunningPidByTaskId, findRunningEntryByContextKey } from "./execenv/timeline.js";
+import {
+ writeKillIntent,
+ clearKillIntent,
+ acquireSteeringLock,
+ releaseSteeringLock,
+ cleanupStaleIntents,
+} from "./execenv/steering.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";
@@ -364,15 +371,20 @@ export async function startDaemon(
releaseDaemonPid(profile);
health.server.close(() => {
if (restartRequested) {
- const args = ["daemon", "start", "--foreground"];
+ const entry = process.argv[1];
+ const args = [entry, "daemon", "start", "--foreground"];
if (profile) args.push("--profile", profile);
if (serverUrl) args.push("--server", serverUrl);
- const child = spawn("alook", args, {
+ const logPath = daemonLogFilePath();
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
+ const logFd = openSync(logPath, "a", 0o600);
+ const child = spawn(process.execPath, args, {
detached: true,
- stdio: ["ignore", "ignore", "ignore"],
+ stdio: ["ignore", logFd, logFd],
});
child.unref();
- log.info(`Spawned new daemon (pid=${child.pid})`);
+ closeSync(logFd);
+ log.info(`Spawned new daemon (pid=${child.pid}), logs: ${logPath}`);
}
clearTimeout(timeout);
process.exit(0);
@@ -421,10 +433,16 @@ async function handleTask(
return;
}
- const timelineDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir", ".context_timeline");
+ const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
+ const timelineDir = join(agentBaseDir, ".context_timeline");
const pid = findRunningPidByTaskId(timelineDir, targetTaskId);
if (pid != null) {
+ writeKillIntent(agentBaseDir, {
+ reason: "cancelled",
+ targetTaskId,
+ expectedPid: pid,
+ });
try {
process.kill(pid, "SIGTERM");
await client.failTask(token, task.id, "killed");
@@ -463,6 +481,67 @@ async function handleTask(
}
const provider = runtimeData.provider;
+
+ // --- Steering: supersede predecessor if same context_key + provider ---
+ if (task.contextKey) {
+ const agentBaseDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir");
+ cleanupStaleIntents(agentBaseDir);
+ const timelineDir = join(agentBaseDir, ".context_timeline");
+
+ const lockAcquired = acquireSteeringLock(agentBaseDir, task.contextKey);
+ if (!lockAcquired) {
+ log.warn(`Steering lock contention for context_key=${task.contextKey}, proceeding without steering`);
+ } else {
+ try {
+ const predecessor = findRunningEntryByContextKey(timelineDir, task.contextKey, provider);
+ if (predecessor && predecessor.task_id !== task.id) {
+ log.info(`Steering: task ${task.id} supersedes predecessor ${predecessor.task_id} (context_key=${task.contextKey})`);
+
+ if (predecessor.pid != null) {
+ writeKillIntent(agentBaseDir, {
+ reason: "superseded",
+ targetTaskId: predecessor.task_id,
+ expectedPid: predecessor.pid,
+ successorTaskId: task.id,
+ });
+ try {
+ process.kill(predecessor.pid, "SIGTERM");
+ log.info(`Steering: sent SIGTERM to predecessor pid=${predecessor.pid}`);
+ } catch (e: unknown) {
+ if ((e as NodeJS.ErrnoException)?.code === "ESRCH") {
+ log.info(`Steering: predecessor pid=${predecessor.pid} already exited`);
+ } else {
+ log.warn(`Steering: kill failed for pid=${predecessor.pid}`, e);
+ }
+ }
+ // Wait for predecessor to stop (poll timeline for up to 15 seconds)
+ const waitStart = Date.now();
+ const MAX_WAIT_MS = 15_000;
+ const POLL_MS = 200;
+ while (Date.now() - waitStart < MAX_WAIT_MS) {
+ const stillRunning = findRunningPidByTaskId(timelineDir, predecessor.task_id);
+ if (stillRunning == null) break;
+ await new Promise((r) => setTimeout(r, POLL_MS));
+ }
+ if (findRunningPidByTaskId(timelineDir, predecessor.task_id) != null) {
+ log.warn(`Steering: predecessor pid=${predecessor.pid} did not exit within ${MAX_WAIT_MS}ms, proceeding anyway`);
+ }
+ }
+
+ // Mark predecessor superseded server-side regardless of PID state
+ try {
+ await client.supersedeTask(token, predecessor.task_id);
+ log.info(`Steering: predecessor ${predecessor.task_id} marked superseded`);
+ } catch (e) {
+ log.warn(`Steering: failed to mark predecessor superseded server-side`, e);
+ }
+ }
+ } finally {
+ releaseSteeringLock(agentBaseDir, task.contextKey);
+ }
+ }
+ }
+
const cliPath =
provider === "claude"
? config.claudePath
diff --git a/src/cli/daemon/execenv/__tests__/steering.test.ts b/src/cli/daemon/execenv/__tests__/steering.test.ts
new file mode 100644
index 000000000..5f745565c
--- /dev/null
+++ b/src/cli/daemon/execenv/__tests__/steering.test.ts
@@ -0,0 +1,157 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { existsSync, readFileSync, mkdirSync, rmSync } from "fs";
+import { join } from "path";
+import { tmpdir } from "os";
+
+vi.mock("../../../lib/logger.js", () => ({
+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
+}));
+
+import {
+ writeKillIntent,
+ readKillIntent,
+ clearKillIntent,
+ cleanupStaleIntents,
+ acquireSteeringLock,
+ releaseSteeringLock,
+ type KillIntent,
+} from "../steering.js";
+
+describe("steering", () => {
+ let baseDir: string;
+
+ beforeEach(() => {
+ baseDir = join(tmpdir(), `steering-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(baseDir, { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ describe("kill intent files", () => {
+ it("writes and reads a superseded kill intent", () => {
+ const intent: KillIntent = {
+ reason: "superseded",
+ targetTaskId: "t_old",
+ expectedPid: 12345,
+ successorTaskId: "t_new",
+ };
+
+ writeKillIntent(baseDir, intent);
+ const read = readKillIntent(baseDir, "t_old");
+
+ expect(read).not.toBeNull();
+ expect(read!.reason).toBe("superseded");
+ expect(read!.targetTaskId).toBe("t_old");
+ expect(read!.expectedPid).toBe(12345);
+ expect(read!.successorTaskId).toBe("t_new");
+ });
+
+ it("writes and reads a cancelled kill intent", () => {
+ const intent: KillIntent = {
+ reason: "cancelled",
+ targetTaskId: "t_cancel",
+ expectedPid: 99999,
+ };
+
+ writeKillIntent(baseDir, intent);
+ const read = readKillIntent(baseDir, "t_cancel");
+
+ expect(read).not.toBeNull();
+ expect(read!.reason).toBe("cancelled");
+ expect(read!.targetTaskId).toBe("t_cancel");
+ expect(read!.expectedPid).toBe(99999);
+ });
+
+ it("returns null when no intent file exists", () => {
+ expect(readKillIntent(baseDir, "t_nonexistent")).toBeNull();
+ });
+
+ it("clears a kill intent", () => {
+ writeKillIntent(baseDir, {
+ reason: "cancelled",
+ targetTaskId: "t_clear",
+ });
+
+ expect(readKillIntent(baseDir, "t_clear")).not.toBeNull();
+ clearKillIntent(baseDir, "t_clear");
+ expect(readKillIntent(baseDir, "t_clear")).toBeNull();
+ });
+
+ it("clearKillIntent is a no-op when file does not exist", () => {
+ expect(() => clearKillIntent(baseDir, "t_nonexistent")).not.toThrow();
+ });
+
+ it("intent file is keyed by task id, not PID", () => {
+ writeKillIntent(baseDir, {
+ reason: "superseded",
+ targetTaskId: "t_abc",
+ expectedPid: 11111,
+ });
+
+ const intentPath = join(baseDir, ".kill_intents", "t_abc.json");
+ expect(existsSync(intentPath)).toBe(true);
+
+ const content = JSON.parse(readFileSync(intentPath, "utf-8"));
+ expect(content.expectedPid).toBe(11111);
+ });
+
+ it("multiple intents for different tasks coexist", () => {
+ writeKillIntent(baseDir, { reason: "superseded", targetTaskId: "t_1" });
+ writeKillIntent(baseDir, { reason: "cancelled", targetTaskId: "t_2" });
+
+ expect(readKillIntent(baseDir, "t_1")!.reason).toBe("superseded");
+ expect(readKillIntent(baseDir, "t_2")!.reason).toBe("cancelled");
+ });
+ });
+
+ describe("stale intent cleanup", () => {
+ it("does not throw when no intent directory exists", () => {
+ expect(() => cleanupStaleIntents(baseDir)).not.toThrow();
+ });
+
+ it("does not remove fresh intents", () => {
+ writeKillIntent(baseDir, { reason: "cancelled", targetTaskId: "t_fresh" });
+ cleanupStaleIntents(baseDir);
+ expect(readKillIntent(baseDir, "t_fresh")).not.toBeNull();
+ });
+ });
+
+ describe("steering lock", () => {
+ it("acquires and releases a steering lock", () => {
+ const acquired = acquireSteeringLock(baseDir, "email:<[email protected]>");
+ expect(acquired).toBe(true);
+
+ releaseSteeringLock(baseDir, "email:<[email protected]>");
+ });
+
+ it("cannot acquire the same lock twice", () => {
+ acquireSteeringLock(baseDir, "dm:conv_1");
+ const second = acquireSteeringLock(baseDir, "dm:conv_1");
+ expect(second).toBe(false);
+
+ releaseSteeringLock(baseDir, "dm:conv_1");
+ });
+
+ it("can re-acquire after release", () => {
+ acquireSteeringLock(baseDir, "dm:conv_1");
+ releaseSteeringLock(baseDir, "dm:conv_1");
+
+ const reacquired = acquireSteeringLock(baseDir, "dm:conv_1");
+ expect(reacquired).toBe(true);
+
+ releaseSteeringLock(baseDir, "dm:conv_1");
+ });
+
+ it("different context keys do not conflict", () => {
+ const first = acquireSteeringLock(baseDir, "dm:conv_1");
+ const second = acquireSteeringLock(baseDir, "dm:conv_2");
+ expect(first).toBe(true);
+ expect(second).toBe(true);
+
+ releaseSteeringLock(baseDir, "dm:conv_1");
+ releaseSteeringLock(baseDir, "dm:conv_2");
+ });
+ });
+});
diff --git a/src/cli/daemon/execenv/__tests__/timeline.test.ts b/src/cli/daemon/execenv/__tests__/timeline.test.ts
index 2aaf72701..bd71cb31a 100644
--- a/src/cli/daemon/execenv/__tests__/timeline.test.ts
+++ b/src/cli/daemon/execenv/__tests__/timeline.test.ts
@@ -16,6 +16,7 @@ import {
findResumableSessionId,
findResumableSessionByContextKey,
findRunningPidByTaskId,
+ findRunningEntryByContextKey,
_todayFilename,
_localISOString,
_filenameForDate,
@@ -717,4 +718,223 @@ describe("timeline", () => {
expect(findResumableSessionByContextKey(dir, "dm:conv_1", "claude")).toBe("sess_newer");
});
});
+
+ describe("findRunningPidByTaskId cross-day fix", () => {
+ 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("finds predecessor PID from yesterday's timeline file (cross-day fix)", () => {
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
+ writeEntry(_filenameForDate(yesterday), makeEntry({
+ task_id: "t_yesterday",
+ status: "running",
+ pid: 55555,
+ }));
+
+ expect(findRunningPidByTaskId(dir, "t_yesterday")).toBe(55555);
+ });
+
+ it("finds predecessor PID from 3 days ago", () => {
+ const threeDaysAgo = new Date();
+ threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
+ writeEntry(_filenameForDate(threeDaysAgo), makeEntry({
+ task_id: "t_old",
+ status: "running",
+ pid: 33333,
+ }));
+
+ expect(findRunningPidByTaskId(dir, "t_old")).toBe(33333);
+ });
+ });
+
+ describe("findRunningEntryByContextKey", () => {
+ 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 running entry for same context_key and provider", () => {
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_running",
+ status: "running",
+ pid: 12345,
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ }));
+
+ const entry = findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude");
+ expect(entry).not.toBeNull();
+ expect(entry!.task_id).toBe("t_running");
+ expect(entry!.pid).toBe(12345);
+ });
+
+ it("returns null when no running entries exist", () => {
+ expect(findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude")).toBeNull();
+ });
+
+ it("ignores non-running entries", () => {
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_done",
+ status: "completed",
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ }));
+
+ expect(findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude")).toBeNull();
+ });
+
+ it("ignores different provider", () => {
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_codex",
+ status: "running",
+ pid: 22222,
+ context_key: "email:<[email protected]>",
+ provider: "codex",
+ }));
+
+ expect(findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude")).toBeNull();
+ });
+
+ it("ignores different context_key", () => {
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_other",
+ status: "running",
+ pid: 33333,
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ }));
+
+ expect(findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude")).toBeNull();
+ });
+
+ it("returns the newest running entry for same context_key", () => {
+ const twoMinAgo = new Date(Date.now() - 2 * 60 * 1000);
+ const oneMinAgo = new Date(Date.now() - 1 * 60 * 1000);
+
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_older",
+ status: "running",
+ pid: 11111,
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ datetime: twoMinAgo.toISOString(),
+ }));
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_newer",
+ status: "running",
+ pid: 22222,
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ datetime: oneMinAgo.toISOString(),
+ }));
+
+ const entry = findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude");
+ expect(entry!.task_id).toBe("t_newer");
+ });
+
+ it("scans up to 7 days for running entries", () => {
+ const threeDaysAgo = new Date();
+ threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
+ writeEntry(_filenameForDate(threeDaysAgo), makeEntry({
+ task_id: "t_old_running",
+ status: "running",
+ pid: 44444,
+ context_key: "email:<[email protected]>",
+ provider: "claude",
+ datetime: threeDaysAgo.toISOString(),
+ }));
+
+ const entry = findRunningEntryByContextKey(dir, "email:<[email protected]>", "claude");
+ expect(entry!.task_id).toBe("t_old_running");
+ });
+
+ it("null context_key tasks are never matched", () => {
+ writeEntry(_todayFilename(), makeEntry({
+ task_id: "t_null_ctx",
+ status: "running",
+ pid: 55555,
+ context_key: null,
+ provider: "claude",
+ }));
+
+ expect(findRunningEntryByContextKey(dir, "dm:conv_1", "claude")).toBeNull();
+ });
+ });
+
+ describe("superseded timeline entry status", () => {
+ it("updateEntry can set status to superseded", () => {
+ const entry = createTimelineEntry("t_sup", "test", TASK_TYPES.USER_DM_MESSAGE);
+ initEntry(dir, entry);
+
+ updateEntry(dir, "t_sup", (e) => {
+ e.pid = null;
+ e.status = "superseded";
+ e.successor_task_id = "t_new";
+ e.supersede_reason = "superseded by newer task";
+ });
+
+ const entries = readEntries();
+ expect(entries[0].status).toBe("superseded");
+ expect(entries[0].successor_task_id).toBe("t_new");
+ expect(entries[0].supersede_reason).toBe("superseded by newer task");
+ });
+
+ it("updateEntry can set status to cancelled", () => {
+ const entry = createTimelineEntry("t_can", "test", TASK_TYPES.USER_DM_MESSAGE);
+ initEntry(dir, entry);
+
+ updateEntry(dir, "t_can", (e) => {
+ e.pid = null;
+ e.status = "cancelled";
+ e.errmsg = "cancelled by user";
+ });
+
+ const entries = readEntries();
+ expect(entries[0].status).toBe("cancelled");
+ expect(entries[0].errmsg).toBe("cancelled by user");
+ });
+ });
});
diff --git a/src/cli/daemon/execenv/steering.ts b/src/cli/daemon/execenv/steering.ts
new file mode 100644
index 000000000..eb3d640ee
--- /dev/null
+++ b/src/cli/daemon/execenv/steering.ts
@@ -0,0 +1,91 @@
+import { mkdirSync, writeFileSync, readFileSync, unlinkSync, readdirSync, statSync } from "fs";
+import { join } from "path";
+import { acquireLock, releaseLock } from "./filelock.js";
+import { log } from "../../lib/logger.js";
+
+export interface KillIntent {
+ reason: "superseded" | "cancelled";
+ targetTaskId: string;
+ expectedPid?: number | null;
+ successorTaskId?: string | null;
+}
+
+const INTENT_DIR_NAME = ".kill_intents";
+const STEERING_LOCK_DIR = ".steering_locks";
+const INTENT_STALE_MS = 10 * 60 * 1000; // 10 minutes
+
+function intentFilePath(baseDir: string, taskId: string): string {
+ return join(baseDir, INTENT_DIR_NAME, `${taskId}.json`);
+}
+
+function intentDirPath(baseDir: string): string {
+ return join(baseDir, INTENT_DIR_NAME);
+}
+
+function steeringLockPath(baseDir: string, contextKey: string): string {
+ const safeKey = contextKey.replace(/[^a-zA-Z0-9_:-]/g, "_");
+ return join(baseDir, STEERING_LOCK_DIR, safeKey);
+}
+
+export function writeKillIntent(baseDir: string, intent: KillIntent): void {
+ const dir = intentDirPath(baseDir);
+ try {
+ mkdirSync(dir, { recursive: true });
+ } catch { /* already exists */ }
+
+ const filePath = intentFilePath(baseDir, intent.targetTaskId);
+ writeFileSync(filePath, JSON.stringify(intent));
+}
+
+export function readKillIntent(baseDir: string, taskId: string): KillIntent | null {
+ const filePath = intentFilePath(baseDir, taskId);
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ return JSON.parse(content) as KillIntent;
+ } catch {
+ return null;
+ }
+}
+
+export function clearKillIntent(baseDir: string, taskId: string): void {
+ const filePath = intentFilePath(baseDir, taskId);
+ try {
+ unlinkSync(filePath);
+ } catch { /* already removed */ }
+}
+
+export function cleanupStaleIntents(baseDir: string): void {
+ const dir = intentDirPath(baseDir);
+ let files: string[];
+ try {
+ files = readdirSync(dir).filter((f) => f.endsWith(".json"));
+ } catch {
+ return;
+ }
+ const now = Date.now();
+ for (const file of files) {
+ const filePath = join(dir, file);
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ const intent = JSON.parse(content) as KillIntent;
+ const stat = statSync(filePath);
+ if (now - stat.mtimeMs > INTENT_STALE_MS) {
+ unlinkSync(filePath);
+ log.debug(`Cleaned up stale kill intent for task ${intent.targetTaskId}`);
+ }
+ } catch { /* best-effort */ }
+ }
+}
+
+export function acquireSteeringLock(baseDir: string, contextKey: string): boolean {
+ const lockPath = steeringLockPath(baseDir, contextKey);
+ try {
+ mkdirSync(join(baseDir, STEERING_LOCK_DIR), { recursive: true });
+ } catch { /* already exists */ }
+ return acquireLock(lockPath, 60_000);
+}
+
+export function releaseSteeringLock(baseDir: string, contextKey: string): void {
+ const lockPath = steeringLockPath(baseDir, contextKey);
+ releaseLock(lockPath);
+}
diff --git a/src/cli/daemon/execenv/timeline.ts b/src/cli/daemon/execenv/timeline.ts
index 69add1483..8383ce033 100644
--- a/src/cli/daemon/execenv/timeline.ts
+++ b/src/cli/daemon/execenv/timeline.ts
@@ -25,7 +25,9 @@ export interface ContextTimelineEntry {
context_key: string | null;
session_id: string | null;
pid: number | null;
- status: "running" | "completed" | "failed" | "killed";
+ status: "running" | "completed" | "failed" | "killed" | "superseded" | "cancelled";
+ successor_task_id?: string | null;
+ supersede_reason?: string | null;
datetime: string;
type: string;
prompt: string;
@@ -286,7 +288,7 @@ export function findRunningPidByTaskId(
timelineDir: string,
taskId: string,
): number | null {
- for (const filename of recentFilenames(1)) {
+ for (const filename of recentFilenames(7)) {
const entries = readJsonl(join(timelineDir, filename));
for (const entry of entries) {
if (entry.task_id === taskId && entry.status === "running" && entry.pid != null) {
@@ -297,6 +299,27 @@ export function findRunningPidByTaskId(
return null;
}
+export function findRunningEntryByContextKey(
+ timelineDir: string,
+ contextKey: string,
+ provider: string,
+): ContextTimelineEntry | null {
+ for (const filename of recentFilenames(7)) {
+ const dayEntries = readJsonl(join(timelineDir, filename));
+ for (let i = dayEntries.length - 1; i >= 0; i--) {
+ const entry = dayEntries[i];
+ if (
+ entry.status === "running" &&
+ entry.context_key === contextKey &&
+ entry.provider === provider
+ ) {
+ return entry;
+ }
+ }
+ }
+ return null;
+}
+
export { localISOString };
// Exported for testing
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
index 2a70ef333..0a0d720a1 100644
--- a/src/cli/daemon/session-runner.test.ts
+++ b/src/cli/daemon/session-runner.test.ts
@@ -5,6 +5,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
const mockClientInstance = {
completeTask: vi.fn(async () => ({})),
failTask: vi.fn(async () => ({})),
+ supersedeTask: vi.fn(async () => ({})),
reportMessages: vi.fn(async () => ({})),
};
vi.mock("./client.js", () => {
@@ -62,6 +63,13 @@ vi.mock("./execenv/timeline.js", () => ({
findResumableSessionByContextKey: (...args: any[]) => mockFindResumableSessionByContextKey(...args),
}));
+const mockReadKillIntent = vi.fn(() => null);
+const mockClearKillIntent = vi.fn();
+vi.mock("./execenv/steering.js", () => ({
+ readKillIntent: (...args: any[]) => mockReadKillIntent(...args),
+ clearKillIntent: (...args: any[]) => mockClearKillIntent(...args),
+}));
+
vi.mock("./prompt.js", () => ({
buildPrompt: vi.fn((task: any) => task.prompt),
}));
@@ -807,4 +815,141 @@ describe("session-runner runSession", () => {
);
});
});
+
+ describe("kill-intent handling", () => {
+ it("on SIGTERM with superseded intent: marks timeline superseded and calls supersedeTask", async () => {
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
+
+ mockReadKillIntent.mockReturnValueOnce({
+ reason: "superseded",
+ targetTaskId: "t1",
+ expectedPid: process.pid,
+ successorTaskId: "t_new",
+ });
+
+ let resolveMessage: (() => void) | null = null;
+ mockBackendExecute.mockReturnValue({
+ pid: 99999,
+ messages: (async function* () {
+ yield { type: "text", content: "working..." };
+ await new Promise<void>((resolve) => { resolveMessage = resolve; });
+ })(),
+ sessionId: Promise.resolve("sess-sup"),
+ result: new Promise(() => {}),
+ });
+
+ const sessionPromise = runSession(makeInput());
+ await new Promise((r) => setTimeout(r, 50));
+
+ process.emit("SIGTERM", "SIGTERM");
+ if (resolveMessage) resolveMessage();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Timeline should be updated to "superseded"
+ const supersedeCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
+ const updater = call[2];
+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[], successor_task_id: null as string | null, supersede_reason: null as string | null };
+ updater(entry);
+ return entry.status === "superseded";
+ });
+ expect(supersedeCalls.length).toBe(1);
+
+ // Should call supersedeTask, not failTask
+ expect(mockClientInstance.supersedeTask).toHaveBeenCalledWith("test_token", "t1");
+ expect(mockClientInstance.failTask).not.toHaveBeenCalled();
+
+ // Should clear the intent
+ expect(mockClearKillIntent).toHaveBeenCalled();
+
+ killSpy.mockRestore();
+ exitSpy.mockRestore();
+ });
+
+ it("on SIGTERM with cancelled intent: marks timeline cancelled and calls failTask", async () => {
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
+
+ mockReadKillIntent.mockReturnValueOnce({
+ reason: "cancelled",
+ targetTaskId: "t1",
+ expectedPid: process.pid,
+ });
+
+ let resolveMessage: (() => void) | null = null;
+ mockBackendExecute.mockReturnValue({
+ pid: 99999,
+ messages: (async function* () {
+ yield { type: "text", content: "working..." };
+ await new Promise<void>((resolve) => { resolveMessage = resolve; });
+ })(),
+ sessionId: Promise.resolve("sess-cancel"),
+ result: new Promise(() => {}),
+ });
+
+ const sessionPromise = runSession(makeInput());
+ await new Promise((r) => setTimeout(r, 50));
+
+ process.emit("SIGTERM", "SIGTERM");
+ if (resolveMessage) resolveMessage();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Timeline should be updated to "cancelled" (not "killed")
+ const cancelCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
+ const updater = call[2];
+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
+ updater(entry);
+ return entry.status === "cancelled";
+ });
+ expect(cancelCalls.length).toBe(1);
+
+ // Should call failTask with "cancelled by user"
+ expect(mockClientInstance.failTask).toHaveBeenCalledWith("test_token", "t1", "cancelled by user");
+ expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
+
+ killSpy.mockRestore();
+ exitSpy.mockRestore();
+ });
+
+ it("on SIGTERM without kill-intent file: preserves existing killed behavior", async () => {
+ const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
+
+ mockReadKillIntent.mockReturnValueOnce(null);
+
+ let resolveMessage: (() => void) | null = null;
+ mockBackendExecute.mockReturnValue({
+ pid: 99999,
+ messages: (async function* () {
+ yield { type: "text", content: "working..." };
+ await new Promise<void>((resolve) => { resolveMessage = resolve; });
+ })(),
+ sessionId: Promise.resolve("sess-kill"),
+ result: new Promise(() => {}),
+ });
+
+ const sessionPromise = runSession(makeInput());
+ await new Promise((r) => setTimeout(r, 50));
+
+ process.emit("SIGTERM", "SIGTERM");
+ if (resolveMessage) resolveMessage();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Timeline should be updated to "killed" (original behavior)
+ const killCalls = mockUpdateEntry.mock.calls.filter((call: any[]) => {
+ const updater = call[2];
+ const entry = { pid: 1, status: "running" as string, errmsg: null as string | null, agent_responses: [] as string[] };
+ updater(entry);
+ return entry.status === "killed";
+ });
+ expect(killCalls.length).toBe(1);
+
+ // Should call failTask with "killed by signal"
+ expect(mockClientInstance.failTask).toHaveBeenCalledWith("test_token", "t1", "killed by signal");
+ expect(mockClientInstance.supersedeTask).not.toHaveBeenCalled();
+
+ killSpy.mockRestore();
+ exitSpy.mockRestore();
+ });
+ });
});
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
index f2a6d95b5..61ba73b55 100644
--- a/src/cli/daemon/session-runner.ts
+++ b/src/cli/daemon/session-runner.ts
@@ -17,6 +17,7 @@ import {
createTimelineEntry,
findResumableSessionByContextKey,
} from "./execenv/timeline.js";
+import { readKillIntent, clearKillIntent } from "./execenv/steering.js";
import { buildPrompt } from "./prompt.js";
import { log } from "../lib/logger.js";
import type { SessionRunnerInput, Attachment } from "./types.js";
@@ -149,6 +150,7 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
// --- Graceful shutdown on SIGTERM/SIGINT ---
let killed = false;
+ const agentBaseDir = path.dirname(timelineDir);
const onKill = async () => {
if (killed) return;
killed = true;
@@ -166,17 +168,42 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
// 3. Cleanup attachments
await cleanupAttachments(task.id);
- // 4. Update timeline — status "killed"
- updateEntry(timelineDir, task.id, (entry) => {
- entry.pid = null;
- entry.status = "killed";
- entry.errmsg = "killed by signal";
- });
-
- // 5. Report to server
- try {
- await client.failTask(token, task.id, "killed by signal");
- } catch { /* best-effort */ }
+ // 4. Read kill-intent to determine reason
+ const intent = readKillIntent(agentBaseDir, task.id);
+ clearKillIntent(agentBaseDir, task.id);
+
+ if (intent?.reason === "superseded") {
+ // Superseded: update timeline and report via dedicated API
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "superseded";
+ entry.successor_task_id = intent.successorTaskId ?? null;
+ entry.supersede_reason = "superseded by newer task";
+ });
+ try {
+ await client.supersedeTask(token, task.id);
+ } catch { /* best-effort — daemon steering may have already marked it */ }
+ } else if (intent?.reason === "cancelled") {
+ // User cancel: update timeline to cancelled (not killed)
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "cancelled";
+ entry.errmsg = "cancelled by user";
+ });
+ try {
+ await client.failTask(token, task.id, "cancelled by user");
+ } catch { /* best-effort */ }
+ } else {
+ // No intent file: preserve existing behavior
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "killed";
+ entry.errmsg = "killed by signal";
+ });
+ try {
+ await client.failTask(token, task.id, "killed by signal");
+ } catch { /* best-effort */ }
+ }
process.exit(1);
};
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index 62ba2a562..76a9488f6 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -22,8 +22,20 @@ export const TaskStatus = {
COMPLETED: "completed",
FAILED: "failed",
CANCELLED: "cancelled",
+ SUPERSEDED: "superseded",
} as const;
+export const TERMINAL_TASK_STATUSES: readonly TaskStatusType[] = [
+ TaskStatus.COMPLETED,
+ TaskStatus.FAILED,
+ TaskStatus.CANCELLED,
+ TaskStatus.SUPERSEDED,
+] as const;
+
+export function isTerminalTaskStatus(status: string): boolean {
+ return (TERMINAL_TASK_STATUSES as readonly string[]).includes(status);
+}
+
export type TaskStatusType = (typeof TaskStatus)[keyof typeof TaskStatus];
export const TASK_TYPES = {
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index 87d39969d..068371760 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -55,10 +55,57 @@ export async function getTaskStatus(db: Database, id: string, workspaceId?: stri
return rows[0]?.status ?? null;
}
+export async function findSteerableReplacement(
+ db: Database,
+ agentId: string,
+ workspaceId: string,
+): Promise<{ predecessorId: string; contextKey: string } | null> {
+ const activeTasks = await db
+ .select({
+ id: agentTaskQueue.id,
+ conversationId: agentTaskQueue.conversationId,
+ contextKey: agentTaskQueue.contextKey,
+ })
+ .from(agentTaskQueue)
+ .where(
+ and(
+ eq(agentTaskQueue.agentId, agentId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.status, ["dispatched", "running"]),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)
+ )
+ );
+
+ for (const active of activeTasks) {
+ if (!active.contextKey) continue;
+ const candidates = await db
+ .select({ id: agentTaskQueue.id })
+ .from(agentTaskQueue)
+ .where(
+ and(
+ eq(agentTaskQueue.agentId, agentId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ eq(agentTaskQueue.status, "queued"),
+ eq(agentTaskQueue.conversationId, active.conversationId),
+ eq(agentTaskQueue.contextKey, active.contextKey)
+ )
+ )
+ .limit(1);
+
+ if (candidates.length > 0) {
+ return { predecessorId: active.id, contextKey: active.contextKey };
+ }
+ }
+ return null;
+}
+
export async function claimTask(db: Database, agentId: string, workspaceId: string) {
- // Step 1: Get conversations that have active (dispatched/running) tasks
- const activeConversations = await db
- .select({ conversationId: agentTaskQueue.conversationId })
+ // Step 1: Get conversations that have active (dispatched/running) tasks, with their context keys
+ const activeTasks = await db
+ .select({
+ conversationId: agentTaskQueue.conversationId,
+ contextKey: agentTaskQueue.contextKey,
+ })
.from(agentTaskQueue)
.where(
and(
@@ -69,9 +116,28 @@ export async function claimTask(db: Database, agentId: string, workspaceId: stri
)
);
- const activeConvIds = activeConversations.map((r) => r.conversationId);
+ // Conversations fully blocked (active task with null contextKey, or any active task)
+ // Steering-eligible conversations have a non-null contextKey on the active task
+ const blockedConvIds: string[] = [];
+ const steerableConvContextKeys = new Map<string, string>(); // conversationId -> contextKey
- // Step 2: Find queued tasks not in those conversations
+ for (const t of activeTasks) {
+ if (t.contextKey) {
+ steerableConvContextKeys.set(t.conversationId, t.contextKey);
+ } else {
+ blockedConvIds.push(t.conversationId);
+ }
+ }
+
+ // Step 2: Find queued tasks not in blocked conversations.
+ // For steerable conversations, only allow if the queued task has the same non-null contextKey.
+ const allBlockedConvIds = [...blockedConvIds];
+ // Also block steerable conversations for the general query — we'll query them separately
+ for (const convId of steerableConvContextKeys.keys()) {
+ allBlockedConvIds.push(convId);
+ }
+
+ // Try non-steerable candidates first
const candidateQuery = db
.select({ id: agentTaskQueue.id })
.from(agentTaskQueue)
@@ -80,15 +146,40 @@ export async function claimTask(db: Database, agentId: string, workspaceId: stri
eq(agentTaskQueue.agentId, agentId),
eq(agentTaskQueue.workspaceId, workspaceId),
eq(agentTaskQueue.status, "queued"),
- ...(activeConvIds.length > 0
- ? [notInArray(agentTaskQueue.conversationId, activeConvIds)]
+ ...(allBlockedConvIds.length > 0
+ ? [notInArray(agentTaskQueue.conversationId, allBlockedConvIds)]
: [])
)
)
.orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt))
.limit(1);
- const candidates = await candidateQuery;
+ let candidates = await candidateQuery;
+
+ // If no non-steerable candidate, try steerable conversations
+ if (candidates.length === 0 && steerableConvContextKeys.size > 0) {
+ for (const [convId, activeContextKey] of steerableConvContextKeys) {
+ const steerCandidates = await db
+ .select({ id: agentTaskQueue.id })
+ .from(agentTaskQueue)
+ .where(
+ and(
+ eq(agentTaskQueue.agentId, agentId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ eq(agentTaskQueue.status, "queued"),
+ eq(agentTaskQueue.conversationId, convId),
+ eq(agentTaskQueue.contextKey, activeContextKey)
+ )
+ )
+ .orderBy(desc(agentTaskQueue.priority), asc(agentTaskQueue.createdAt))
+ .limit(1);
+
+ if (steerCandidates.length > 0) {
+ candidates = steerCandidates;
+ break;
+ }
+ }
+ }
if (candidates.length === 0) return null;
@@ -199,6 +290,21 @@ export async function hasPendingTaskForConversation(
return rows.length > 0;
}
+export async function supersedeTask(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .update(agentTaskQueue)
+ .set({ status: "superseded", completedAt: new Date().toISOString() })
+ .where(
+ and(
+ eq(agentTaskQueue.id, id),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.status, ["dispatched", "running"])
+ )
+ )
+ .returning();
+ return rows[0] ?? null;
+}
+
export async function cancelTask(db: Database, id: string, workspaceId: string) {
const rows = await db
.update(agentTaskQueue)
@@ -248,18 +354,20 @@ export async function deleteTasksByConversation(
.returning({ id: agentTaskQueue.id });
}
-export async function countRunningTasks(db: Database, agentId: string, workspaceId: string) {
+export async function countRunningTasks(db: Database, agentId: string, workspaceId: string, excludeTaskId?: string) {
+ const conditions = [
+ eq(agentTaskQueue.agentId, agentId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.status, ["dispatched", "running"]),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),
+ ];
+ if (excludeTaskId) {
+ conditions.push(ne(agentTaskQueue.id, excludeTaskId));
+ }
const rows = await db
.select({ value: count() })
.from(agentTaskQueue)
- .where(
- and(
- eq(agentTaskQueue.agentId, agentId),
- eq(agentTaskQueue.workspaceId, workspaceId),
- inArray(agentTaskQueue.status, ["dispatched", "running"]),
- ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)
- )
- );
+ .where(and(...conditions));
return Number(rows[0]?.value ?? 0);
}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index b72ee16ae..d8f11ba81 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -55,6 +55,8 @@ export {
AgentStatus,
RuntimeStatus,
TaskStatus,
+ TERMINAL_TASK_STATUSES,
+ isTerminalTaskStatus,
TASK_TYPES,
MessageRole,
POLL_INTERVAL_MS,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 401a0325a..0e879f79b 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -12,6 +12,7 @@ export const TaskStatusSchema = z.enum([
"completed",
"failed",
"cancelled",
+ "superseded",
]);
// ---------------------------------------------------------------------------
diff --git a/src/shared/test/constants.test.ts b/src/shared/test/constants.test.ts
index 85b6646fa..2b54f1944 100644
--- a/src/shared/test/constants.test.ts
+++ b/src/shared/test/constants.test.ts
@@ -1,8 +1,43 @@
import { describe, it, expect } from "vitest"
-import { POLL_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH } from "../src/constants"
+import {
+ POLL_INTERVAL_MS, OFFLINE_THRESHOLD_MS, EVENT_POLL_INTERVAL_MS, AGENT_HANDLE_MIN_LENGTH,
+ TaskStatus, TERMINAL_TASK_STATUSES, isTerminalTaskStatus,
+} from "../src/constants"
describe("constants", () => {
it("OFFLINE_THRESHOLD_MS is 3x POLL_INTERVAL", () => expect(OFFLINE_THRESHOLD_MS).toBe(POLL_INTERVAL_MS * 3))
it("AGENT_HANDLE_MIN_LENGTH is 4", () => expect(AGENT_HANDLE_MIN_LENGTH).toBe(4))
it("EVENT_POLL < POLL_INTERVAL", () => expect(EVENT_POLL_INTERVAL_MS).toBeLessThan(POLL_INTERVAL_MS))
})
+
+describe("TaskStatus", () => {
+ it("includes superseded", () => {
+ expect(TaskStatus.SUPERSEDED).toBe("superseded")
+ })
+
+ it("TERMINAL_TASK_STATUSES includes all terminal statuses", () => {
+ expect(TERMINAL_TASK_STATUSES).toContain("completed")
+ expect(TERMINAL_TASK_STATUSES).toContain("failed")
+ expect(TERMINAL_TASK_STATUSES).toContain("cancelled")
+ expect(TERMINAL_TASK_STATUSES).toContain("superseded")
+ })
+
+ it("TERMINAL_TASK_STATUSES does not include active statuses", () => {
+ expect(TERMINAL_TASK_STATUSES).not.toContain("queued")
+ expect(TERMINAL_TASK_STATUSES).not.toContain("dispatched")
+ expect(TERMINAL_TASK_STATUSES).not.toContain("running")
+ })
+
+ it("isTerminalTaskStatus returns true for terminal statuses", () => {
+ expect(isTerminalTaskStatus("completed")).toBe(true)
+ expect(isTerminalTaskStatus("failed")).toBe(true)
+ expect(isTerminalTaskStatus("cancelled")).toBe(true)
+ expect(isTerminalTaskStatus("superseded")).toBe(true)
+ })
+
+ it("isTerminalTaskStatus returns false for active statuses", () => {
+ expect(isTerminalTaskStatus("queued")).toBe(false)
+ expect(isTerminalTaskStatus("dispatched")).toBe(false)
+ expect(isTerminalTaskStatus("running")).toBe(false)
+ })
+})
diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.ts b/src/web/src/app/api/agents/[id]/chat-init/route.ts
index 546baa075..aa767ba34 100644
--- a/src/web/src/app/api/agents/[id]/chat-init/route.ts
+++ b/src/web/src/app/api/agents/[id]/chat-init/route.ts
@@ -61,8 +61,7 @@ export const POST = withAuth(async (req, ctx) => {
let taskMessages: unknown[] = [];
if (
activeTask &&
- activeTask.status !== "completed" &&
- activeTask.status !== "failed"
+ !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status)
) {
try {
const tmsgs = await queries.taskMessage.listTaskMessages(
diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts
new file mode 100644
index 000000000..a5e09cc48
--- /dev/null
+++ b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts
@@ -0,0 +1,31 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { getDb } from "@/lib/db";
+import { withAuth } from "@/lib/middleware/auth";
+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: NextRequest, ctx) => {
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const taskId = ctx.params?.taskId;
+ if (!taskId) {
+ return writeError("task_id is required", 400);
+ }
+
+ const taskService = new TaskService(db);
+ try {
+ const task = await taskService.supersedeTask(taskId, ctx.workspaceId);
+ broadcastToUser(ctx.userId, { type: "task.updated", taskId, status: "superseded" }).catch(() => {});
+ return writeJSON(taskToResponse(task));
+ } 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.tsx
index 31ff23bb8..aa55dba5a 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -251,7 +251,7 @@ export function AgentChatView() {
setTaskMessages(data.task_messages);
lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));
}
- if (!["completed", "failed", "cancelled"].includes(data.active_task.status)) {
+ if (!["completed", "failed", "cancelled", "superseded"].includes(data.active_task.status)) {
startPollingRef.current(data.active_task.id, data.conversation.id, lastSeqRef.current);
}
}
@@ -384,7 +384,7 @@ export function AgentChatView() {
);
}
- if (task.status === "completed" || task.status === "failed" || task.status === "cancelled") {
+ if (task.status === "completed" || task.status === "failed" || task.status === "cancelled" || task.status === "superseded") {
if (isStale) {
// Stale poll — still merge messages but don't touch activeTask or polling
listMessages(conversationId, workspaceId)
@@ -597,7 +597,7 @@ export function AgentChatView() {
setPendingFiles([]);
setSending(true);
- const taskActive = !!activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status);
+ const taskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
if (taskActive) {
// Buffer mode: queue message for later dispatch
@@ -745,7 +745,7 @@ export function AgentChatView() {
}
};
- const isTaskActive = !!activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status);
+ const isTaskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);
if (loading) {
return (
@@ -873,7 +873,7 @@ export function AgentChatView() {
})}
{/* Show trace while task is in progress (no assistant message yet) */}
- {activeTask && !["completed", "failed", "cancelled"].includes(activeTask.status) && (
+ {activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status) && (
<TaskStream
task={activeTask}
messages={taskMessages}
diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsx
index f8616ad55..c634b4c33 100644
--- a/src/web/src/components/task-stream.tsx
+++ b/src/web/src/components/task-stream.tsx
@@ -252,7 +252,7 @@ export function TaskStream({
connectionLost?: boolean;
}) {
const allItems = useMemo(() => groupMessages(messages), [messages]);
- const isRunning = task.status !== "completed" && task.status !== "failed";
+ const isRunning = task.status !== "completed" && task.status !== "failed" && task.status !== "cancelled" && task.status !== "superseded";
const toolItems = allItems.filter((i) => i.kind !== "text");
const textItems = allItems.filter((i): i is TextItem => i.kind === "text");
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index cc63e9972..5f0fbe123 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -17,12 +17,14 @@ vi.mock("@alook/shared", () => ({
startTask: vi.fn(),
completeTask: vi.fn(),
failTask: vi.fn(),
+ supersedeTask: vi.fn(),
getTask: vi.fn(),
countRunningTasks: vi.fn(),
listPendingTasksByRuntimes: vi.fn(),
claimKillTasks: vi.fn().mockResolvedValue([]),
getActiveTaskByConversation: vi.fn(),
cancelTask: vi.fn(),
+ findSteerableReplacement: vi.fn().mockResolvedValue(null),
},
agent: {
getAgent: vi.fn(),
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index 62953aed0..3093f578b 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -49,7 +49,12 @@ export class TaskService {
const running = await taskQueries.countRunningTasks(this.db, agentId, workspaceId);
if (running >= agent.maxConcurrentTasks) {
- return null;
+ // At max capacity — check if a steerable replacement exists to bypass the limit
+ const steerable = await taskQueries.findSteerableReplacement(this.db, agentId, workspaceId);
+ if (!steerable) return null;
+ // Re-check excluding the predecessor being replaced
+ const runningExcluding = await taskQueries.countRunningTasks(this.db, agentId, workspaceId, steerable.predecessorId);
+ if (runningExcluding >= agent.maxConcurrentTasks) return null;
}
const task = await taskQueries.claimTask(this.db, agentId, workspaceId);
@@ -168,6 +173,21 @@ export class TaskService {
return task;
}
+ async supersedeTask(taskId: string, workspaceId: string) {
+ const task = await taskQueries.supersedeTask(this.db, taskId, workspaceId);
+
+ if (!task) {
+ const existing = await taskQueries.getTask(this.db, taskId);
+ const status = existing?.status ?? "unknown";
+ log.warn(`supersedeTask failed: task is in '${status}' status`, { taskId });
+ throw new Error(`cannot supersede task in '${status}' status`);
+ }
+
+ await this.reconcileAgentStatus(task.agentId, task.workspaceId);
+ await this.dispatchNextBufferedMessage(task.conversationId, task.workspaceId);
+ return task;
+ }
+
async cancelActiveTask(conversationId: string, workspaceId: string) {
const activeTask = await taskQueries.getActiveTaskByConversation(this.db, conversationId, workspaceId);
if (!activeTask) return null;