Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: improve session-runner resilience and remove chat auto-fetch overhead

Gus871551d96246
diff --git a/src/cli/daemon/agent/claude.ts b/src/cli/daemon/agent/claude.ts
index 00e1c8a8e..7b33f4811 100644
--- a/src/cli/daemon/agent/claude.ts
+++ b/src/cli/daemon/agent/claude.ts
@@ -35,6 +35,13 @@ export class ClaudeBackend implements AgentBackend {
env: { ...process.env, ...options.env },
});
+ if (!proc.pid) {
+ const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'claude' installed and on PATH?`;
+ const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
+ const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
+ return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
+ }
+
let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
@@ -168,6 +175,25 @@ export class ClaudeBackend implements AgentBackend {
}
});
+ proc.on("error", (err: Error) => {
+ resultStatus = "failed";
+ lastError = `spawn error: ${err.message}`;
+ resolveSessionId(lastSessionId);
+ messageDone = true;
+ if (messageResolve) {
+ const r = messageResolve;
+ messageResolve = null;
+ r();
+ }
+ resolve({
+ status: "failed",
+ output: "",
+ error: lastError,
+ durationMs: Date.now() - startTime,
+ sessionId: lastSessionId,
+ });
+ });
+
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
diff --git a/src/cli/daemon/agent/codex.ts b/src/cli/daemon/agent/codex.ts
index b61486b69..24f50d407 100644
--- a/src/cli/daemon/agent/codex.ts
+++ b/src/cli/daemon/agent/codex.ts
@@ -52,6 +52,13 @@ export class CodexBackend implements AgentBackend {
env: { ...process.env, ...options.env },
});
+ if (!proc.pid) {
+ const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'codex' installed and on PATH?`;
+ const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
+ const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
+ return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
+ }
+
let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
@@ -502,6 +509,26 @@ export class CodexBackend implements AgentBackend {
startHandshake();
+ proc.on("error", (err: Error) => {
+ resultStatus = "failed";
+ lastError = `spawn error: ${err.message}`;
+ closeAllPending("spawn error");
+ resolveSessionId(sessionId);
+ messageDone = true;
+ if (messageResolve) {
+ const r = messageResolve;
+ messageResolve = null;
+ r();
+ }
+ resolve({
+ status: "failed",
+ output: "",
+ error: lastError,
+ durationMs: Date.now() - startTime,
+ sessionId,
+ });
+ });
+
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
diff --git a/src/cli/daemon/agent/opencode.ts b/src/cli/daemon/agent/opencode.ts
index d74c35e64..ec246895e 100644
--- a/src/cli/daemon/agent/opencode.ts
+++ b/src/cli/daemon/agent/opencode.ts
@@ -27,6 +27,13 @@ export class OpenCodeBackend implements AgentBackend {
env: { ...process.env, ...options.env, OPENCODE_PERMISSION: '{"*":"allow"}' },
});
+ if (!proc.pid) {
+ const error = `Failed to start ${this.cliPath}: binary not found or not executable. Is 'opencode' installed and on PATH?`;
+ const failedResult: AgentResult = { status: "failed", output: "", error, durationMs: 0, sessionId: "" };
+ const emptyMessages: AsyncIterable<AgentMessage> = { [Symbol.asyncIterator]() { return { async next() { return { value: undefined as unknown as AgentMessage, done: true }; } }; } };
+ return { pid: undefined, messages: emptyMessages, sessionId: Promise.resolve(""), result: Promise.resolve(failedResult) };
+ }
+
let timedOut = false;
let timeoutTimer: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
@@ -199,6 +206,25 @@ export class OpenCodeBackend implements AgentBackend {
}
});
+ proc.on("error", (err: Error) => {
+ resultStatus = "failed";
+ lastError = `spawn error: ${err.message}`;
+ resolveSessionId(lastSessionId);
+ messageDone = true;
+ if (messageResolve) {
+ const r = messageResolve;
+ messageResolve = null;
+ r();
+ }
+ resolve({
+ status: "failed",
+ output: "",
+ error: lastError,
+ durationMs: Date.now() - startTime,
+ sessionId: lastSessionId,
+ });
+ });
+
proc.on("close", (code: number | null) => {
if (timeoutTimer) clearTimeout(timeoutTimer);
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 6b086e5ef..d0e0fe9db 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -3,7 +3,7 @@ import { type DaemonConfig, loadDaemonConfig, sessionRunnerLogDir, daemonLogFile
import { createHealthServer } from "./health.js";
import { detectVersion } from "./agent/index.js";
import { type Task, type SessionRunnerInput, fromApiTask } from "./types.js";
-import type { MarkerData } from "./session-runner.js";
+import { type MarkerData, writeMarkerFile } from "./session-runner.js";
import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { createLogger } from "../lib/logger.js";
@@ -11,7 +11,7 @@ const log = createLogger({ module: "daemon" });
import { cmdPrefix } from "../lib/env.js";
import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";
import { handleCliUpdate, isUpdating, readUpdateMarker, clearUpdateMarker } from "./update-handler.js";
-import { findRunningPidByTaskId, findRunningEntryByContextKey } from "./execenv/timeline.js";
+import { findRunningPidByTaskId, findRunningEntryByContextKey, updateEntry } from "./execenv/timeline.js";
import {
writeKillIntent,
acquireSteeringLock,
@@ -865,6 +865,42 @@ async function handleTask(
};
const child = spawnSessionRunner(input);
- child.on("close", () => activeTasks.delete(task.id));
+ child.on("close", async (code) => {
+ activeTasks.delete(task.id);
+ if (code !== 0) {
+ const msg = code === null
+ ? `session-runner killed by signal (task ${task.id})`
+ : `session-runner crashed (exit code ${code}, task ${task.id})`;
+ log.warn(msg);
+
+ // Update timeline JSONL as fallback
+ const timelineDir = join(config.workspacesRoot, task.workspaceId, task.agentId, "workdir", ".context_timeline");
+ updateEntry(timelineDir, task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "failed";
+ entry.errmsg = msg;
+ });
+
+ try {
+ await client.failTask(token, task.id, msg);
+ } catch (e) {
+ if (isClientError(e)) {
+ log.info(`Backstop: task ${task.id} already in terminal state`);
+ return;
+ }
+ log.error(`Backstop: failed to report crash for task ${task.id}`, e);
+ try {
+ await writeMarkerFile(config.workspacesRoot, {
+ taskId: task.id,
+ type: "fail",
+ payload: { error: msg },
+ token,
+ serverURL: config.serverURL,
+ createdAt: new Date().toISOString(),
+ });
+ } catch { /* best-effort */ }
+ }
+ }
+ });
log.info(`Task ${task.id} dispatched to session-runner (pid=${child.pid})`);
}
diff --git a/src/cli/daemon/session-runner.test.ts b/src/cli/daemon/session-runner.test.ts
index e3806e0bd..17d35f721 100644
--- a/src/cli/daemon/session-runner.test.ts
+++ b/src/cli/daemon/session-runner.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import path from "path";
// --- Mocks ---
@@ -265,7 +265,7 @@ describe("session-runner runSession", () => {
undefined,
);
expect(mockInitEntryAsync).toHaveBeenCalledWith(
- "/tmp/ws/ws1/agent1/workdir/.context_timeline",
+ "/tmp/ws/ws1/a1/workdir/.context_timeline",
expect.objectContaining({ task_id: "t1", pid: process.pid, session_id: null }),
);
});
@@ -283,7 +283,7 @@ describe("session-runner runSession", () => {
// The first updateEntry call should set session_id
const firstCall = mockUpdateEntry.mock.calls[0];
- expect(firstCall[0]).toBe("/tmp/ws/ws1/agent1/workdir/.context_timeline");
+ expect(firstCall[0]).toBe("/tmp/ws/ws1/a1/workdir/.context_timeline");
expect(firstCall[1]).toBe("t1");
const entry = { session_id: null as string | null };
firstCall[2](entry);
@@ -430,7 +430,7 @@ describe("session-runner runSession", () => {
await runSession(makeInput());
expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/agent1/workdir/.context_timeline",
+ "/tmp/ws/ws1/a1/workdir/.context_timeline",
"c1",
"claude",
);
@@ -751,7 +751,7 @@ describe("session-runner runSession", () => {
await runSession(makeInput({ provider: "codex" }));
expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/agent1/workdir/.context_timeline",
+ "/tmp/ws/ws1/a1/workdir/.context_timeline",
"c1",
"codex",
);
@@ -790,7 +790,7 @@ describe("session-runner runSession", () => {
await runSession(makeInput({ provider: "opencode" }));
expect(mockFindResumableSessionByContextKey).toHaveBeenCalledWith(
- "/tmp/ws/ws1/agent1/workdir/.context_timeline",
+ "/tmp/ws/ws1/a1/workdir/.context_timeline",
"c1",
"opencode",
);
@@ -1240,6 +1240,11 @@ describe("writeMarkerFile", () => {
describe("reportToServer", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
});
const marker: MarkerData = {
@@ -1257,7 +1262,9 @@ describe("reportToServer", () => {
});
it("writes marker on fn failure", async () => {
- await reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
+ const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
+ await vi.runAllTimersAsync();
+ await promise;
expect(mockWriteFile).toHaveBeenCalled();
const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
expect(written.taskId).toBe("t1");
@@ -1265,26 +1272,49 @@ describe("reportToServer", () => {
});
it("does not throw when fn fails", async () => {
- await expect(
- reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws"),
- ).resolves.toBeUndefined();
+ const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toBeUndefined();
});
it("does not throw when both fn and marker write fail", async () => {
mockWriteFile.mockRejectedValueOnce(new Error("ENOSPC"));
- await expect(
- reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws"),
- ).resolves.toBeUndefined();
+ const promise = reportToServer(async () => { throw new Error("network"); }, marker, "/tmp/ws");
+ await vi.runAllTimersAsync();
+ await expect(promise).resolves.toBeUndefined();
+ });
+
+ it("does not retry on HTTP 4xx (client error)", async () => {
+ await reportToServer(async () => { throw new Error("HTTP 400: bad request"); }, marker, "/tmp/ws");
+ expect(mockWriteFile).not.toHaveBeenCalled();
+ });
+
+ it("retries on retryable error and succeeds on 2nd attempt", async () => {
+ let attempt = 0;
+ const fn = async () => {
+ attempt++;
+ if (attempt === 1) throw new Error("ECONNREFUSED");
+ };
+ const promise = reportToServer(fn, marker, "/tmp/ws");
+ await vi.runAllTimersAsync();
+ await promise;
+ expect(attempt).toBe(2);
+ expect(mockWriteFile).not.toHaveBeenCalled();
});
});
describe("session-runner marker integration", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
});
it("completeTask failure writes 'complete' marker", async () => {
- mockClientInstance.completeTask.mockRejectedValueOnce(new Error("server down"));
+ mockClientInstance.completeTask.mockRejectedValue(new Error("server down"));
setupBackend([], {
status: "completed",
output: "Done!",
@@ -1293,17 +1323,20 @@ describe("session-runner marker integration", () => {
sessionId: "sess-1",
});
- await runSession(makeInput());
+ const promise = runSession(makeInput());
+ await vi.runAllTimersAsync();
+ await promise;
expect(mockWriteFile).toHaveBeenCalled();
const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
expect(written.type).toBe("complete");
expect(written.taskId).toBe("t1");
expect(written.payload.output).toBe("Done!");
+ mockClientInstance.completeTask.mockResolvedValue({});
});
it("failTask failure writes 'fail' marker", async () => {
- mockClientInstance.failTask.mockRejectedValueOnce(new Error("server down"));
+ mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
setupBackend([], {
status: "failed",
output: "",
@@ -1312,19 +1345,22 @@ describe("session-runner marker integration", () => {
sessionId: "sess-1",
});
- await runSession(makeInput());
+ const promise = runSession(makeInput());
+ await vi.runAllTimersAsync();
+ await promise;
expect(mockWriteFile).toHaveBeenCalled();
const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
expect(written.type).toBe("fail");
expect(written.taskId).toBe("t1");
expect(written.payload.error).toBe("something broke");
+ mockClientInstance.failTask.mockResolvedValue({});
});
it("onKill cancel writes marker on failure", async () => {
const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
- mockClientInstance.failTask.mockRejectedValueOnce(new Error("server down"));
+ mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
mockReadKillIntent.mockReturnValueOnce({ reason: "cancelled", targetTaskId: "t1", expectedPid: process.pid });
let resolveMessage: (() => void) | null = null;
@@ -1339,10 +1375,10 @@ describe("session-runner marker integration", () => {
});
const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
+ await vi.advanceTimersByTimeAsync(50);
process.emit("SIGTERM", "SIGTERM");
if (resolveMessage) resolveMessage();
- await new Promise((r) => setTimeout(r, 50));
+ await vi.runAllTimersAsync();
expect(mockWriteFile).toHaveBeenCalled();
const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
@@ -1351,12 +1387,13 @@ describe("session-runner marker integration", () => {
killSpy.mockRestore();
exitSpy.mockRestore();
+ mockClientInstance.failTask.mockResolvedValue({});
});
it("onKill kill writes marker on failure", async () => {
const killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);
const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
- mockClientInstance.failTask.mockRejectedValueOnce(new Error("server down"));
+ mockClientInstance.failTask.mockRejectedValue(new Error("server down"));
mockReadKillIntent.mockReturnValueOnce(null);
let resolveMessage: (() => void) | null = null;
@@ -1371,10 +1408,10 @@ describe("session-runner marker integration", () => {
});
const sessionPromise = runSession(makeInput());
- await new Promise((r) => setTimeout(r, 50));
+ await vi.advanceTimersByTimeAsync(50);
process.emit("SIGTERM", "SIGTERM");
if (resolveMessage) resolveMessage();
- await new Promise((r) => setTimeout(r, 50));
+ await vi.runAllTimersAsync();
expect(mockWriteFile).toHaveBeenCalled();
const written = JSON.parse(mockWriteFile.mock.calls[0][1] as string);
@@ -1383,6 +1420,7 @@ describe("session-runner marker integration", () => {
killSpy.mockRestore();
exitSpy.mockRestore();
+ mockClientInstance.failTask.mockResolvedValue({});
});
});
diff --git a/src/cli/daemon/session-runner.ts b/src/cli/daemon/session-runner.ts
index 3387430f6..029626c0a 100644
--- a/src/cli/daemon/session-runner.ts
+++ b/src/cli/daemon/session-runner.ts
@@ -7,6 +7,7 @@
*/
import { mkdir, writeFile, rm, rename } from "fs/promises";
+import { mkdirSync } from "fs";
import path from "path";
import { DaemonClient } from "./client.js";
import { createBackend } from "./agent/index.js";
@@ -59,21 +60,60 @@ export async function writeMarkerFile(
await rename(tmpPath, finalPath);
}
+function isRetryableError(e: unknown): boolean {
+ if (!(e instanceof Error)) return true;
+ const msg = e.message;
+ if (/ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|EAI_AGAIN/.test(msg)) return true;
+ const httpMatch = msg.match(/^HTTP (\d+):/);
+ if (httpMatch) {
+ const status = Number(httpMatch[1]);
+ if (status >= 500) return true;
+ if (status === 408 || status === 429) return true;
+ return false;
+ }
+ return true;
+}
+
+function isClientError(e: unknown): boolean {
+ if (!(e instanceof Error)) return false;
+ const match = e.message.match(/^HTTP (\d+):/);
+ if (!match) return false;
+ const status = Number(match[1]);
+ if (status === 408 || status === 429) return false;
+ return status >= 400 && status < 500;
+}
+
export async function reportToServer(
fn: () => Promise<unknown>,
markerData: MarkerData,
workspacesRoot: string,
): Promise<void> {
- try {
- await fn();
- } catch (e) {
- log.warn(`server report failed for task ${markerData.taskId}, writing marker: ${e}`);
+ const RETRY_DELAYS = [1000, 3000, 9000];
+ let lastErr: unknown;
+
+ for (let attempt = 0; attempt <= RETRY_DELAYS.length; attempt++) {
try {
- await writeMarkerFile(workspacesRoot, markerData);
- } catch (writeErr) {
- log.error(`marker write also failed for task ${markerData.taskId}: ${writeErr}`);
+ await fn();
+ return;
+ } catch (e) {
+ lastErr = e;
+ if (isClientError(e)) {
+ log.info(`server report for task ${markerData.taskId}: task already in terminal state (${e})`);
+ return;
+ }
+ if (attempt < RETRY_DELAYS.length && isRetryableError(e)) {
+ log.debug(`server report attempt ${attempt + 1} failed for task ${markerData.taskId}, retrying in ${RETRY_DELAYS[attempt]}ms`);
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt]));
+ }
}
}
+
+ log.warn(`server report failed for task ${markerData.taskId} after retries, writing marker: ${lastErr}`);
+ try {
+ await writeMarkerFile(workspacesRoot, markerData);
+ } catch (writeErr) {
+ log.error(`marker write also failed for task ${markerData.taskId}: ${writeErr}`);
+ }
}
function sanitizeFilename(name: string): string {
@@ -122,12 +162,10 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
const client = new DaemonClient(serverURL);
const backend = createBackend(provider, cliPath);
- const { workDir, timelineDir, env } = prepare(
- { workspacesRoot },
- task,
- );
-
- const agentBaseDir = path.dirname(timelineDir);
+ // Compute timelineDir before prepare() so timeline entry exists even on early crashes
+ const agentBaseDir = path.join(workspacesRoot, task.workspaceId, task.agentId, "workdir");
+ const timelineDir = path.join(agentBaseDir, ".context_timeline");
+ mkdirSync(timelineDir, { recursive: true });
// Timeline entry: write IMMEDIATELY so KILL_TASK can find our PID
await initEntryAsync(
@@ -135,6 +173,11 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
createTimelineEntry(task.id, task.prompt, task.type, undefined, process.pid, provider, task.contextKey, input.logFilePath),
);
+ const { workDir, env } = prepare(
+ { workspacesRoot },
+ task,
+ );
+
let killed = false;
// Early signal handler (before agent starts — no agentPid/flushTimer yet)
@@ -204,7 +247,11 @@ export async function runSession(input: SessionRunnerInput): Promise<void> {
entry.status = "failed";
entry.errmsg = errMsg;
});
- await client.failTask(token, task.id, errMsg);
+ await reportToServer(
+ () => client.failTask(token, task.id, errMsg),
+ { taskId: task.id, type: "fail", payload: { error: errMsg }, token, serverURL, createdAt: new Date().toISOString() },
+ workspacesRoot,
+ );
process.removeListener("SIGTERM", earlyOnKill);
process.removeListener("SIGINT", earlyOnKill);
return;
@@ -491,6 +538,15 @@ async function main(): Promise<void> {
} catch (e) {
log.error(`session-runner: unhandled error for task ${input.task.id}`, e);
await cleanupAttachments(input.task.id);
+
+ // Update timeline entry to reflect failure
+ const timelineDir = path.join(input.workspacesRoot, input.task.workspaceId, input.task.agentId, "workdir", ".context_timeline");
+ updateEntry(timelineDir, input.task.id, (entry) => {
+ entry.pid = null;
+ entry.status = "failed";
+ entry.errmsg = `session-runner crash: ${e}`;
+ });
+
const errorMsg = `session-runner crash: ${e}`;
await reportToServer(
() => client.failTask(input.token, input.task.id, errorMsg),
diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsx
index 77e627972..67c08affc 100644
--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx
@@ -35,7 +35,6 @@ import { Button } from "@/components/ui/button";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { AgentPreviewCard } from "@/components/agent-preview-card";
import {
- listAgentLinks,
createAgentLink,
updateAgentLink,
deleteAgentLink,
@@ -77,36 +76,24 @@ function savePositions(workspaceId: string, nodes: Node[]) {
function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }) {
const router = useRouter();
- const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();
+ const { agents, runtimes, loading, activeTaskCounts, agentLinks } = useAgentContext();
const { slug, workspaceId } = useWorkspace();
const { zoomIn, zoomOut, fitView } = useReactFlow();
const [nodes, setNodes] = useState<Node[]>([]);
const [edges, setEdges] = useState<Edge[]>([]);
const [links, setLinks] = useState<AgentLink[]>([]);
- const [linksLoaded, setLinksLoaded] = useState(false);
+ const linksLoaded = !loading;
const [sidecarLink, setSidecarLink] = useState<AgentLink | null>(null);
const [sidecarOpen, setSidecarOpen] = useState(false);
const [showHint, setShowHint] = useState(false);
const initialLayoutDone = useRef(false);
const handleMap = useRef<Record<string, { sourceHandle: string; targetHandle: string }>>({});
- // Fetch links
+ // Sync links from context
useEffect(() => {
- if (!workspaceId || loading || agents.length === 0) return;
- let cancelled = false;
- listAgentLinks(workspaceId)
- .then((data) => {
- if (!cancelled) {
- setLinks(data);
- setLinksLoaded(true);
- }
- })
- .catch(() => {
- if (!cancelled) setLinksLoaded(true);
- });
- return () => { cancelled = true; };
- }, [workspaceId, loading, agents.length]);
+ if (!loading) setLinks(agentLinks);
+ }, [agentLinks, loading]);
// Build edges from links
useEffect(() => {
@@ -190,6 +177,14 @@ function AgentCanvas({ onAgentClick }: { onAgentClick?: (agent: Agent) => void }
const hasAnyPosition = Object.keys(validPositions).length > 0;
const newAgentIds = agents.filter((a) => !validPositions[a.id]).map((a) => a.id);
+ // Case 1: No saved positions and links not loaded yet — wait for links before setting nodes
+ if (!hasAnyPosition && !linksLoaded) return;
+
+ // Case 2: Some saved positions but new agents need layout — only show positioned nodes until links load
+ if (hasAnyPosition && newAgentIds.length > 0 && !linksLoaded) {
+ newNodes = newNodes.filter((n) => validPositions[n.id]);
+ }
+
if (!hasAnyPosition) {
// First visit — auto-layout all
if (linksLoaded) {
diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.ts
index 533831057..41c6671ab 100644
--- a/src/web/src/app/api/agent-links/[id]/route.ts
+++ b/src/web/src/app/api/agent-links/[id]/route.ts
@@ -25,7 +25,10 @@ export const PATCH = withAuth(async (req, ctx) => {
});
if (!updated) return writeError("agent link not found", 404);
- await invalidate(cacheKeys.allColleagues(ws.workspaceId));
+ await Promise.all([
+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),
+ invalidate(cacheKeys.agentLinks(ws.workspaceId)),
+ ]);
return writeJSON(agentLinkToResponse(updated));
});
@@ -43,7 +46,10 @@ export const DELETE = withAuth(async (req, ctx) => {
const deleted = await queries.agentLink.remove(db, id, ws.workspaceId);
if (!deleted) return writeError("agent link not found", 404);
- await invalidate(cacheKeys.allColleagues(ws.workspaceId));
+ await Promise.all([
+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),
+ invalidate(cacheKeys.agentLinks(ws.workspaceId)),
+ ]);
return writeJSON(agentLinkToResponse(deleted));
});
diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.ts
index 370c50f89..997788d54 100644
--- a/src/web/src/app/api/agent-links/route.ts
+++ b/src/web/src/app/api/agent-links/route.ts
@@ -10,7 +10,7 @@ import { withAuth } from "@/lib/middleware/auth";
import { withWorkspaceMember } from "@/lib/middleware/workspace";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { agentLinkToResponse } from "@/lib/api/responses";
-import { invalidate, cacheKeys } from "@/lib/cache";
+import { cached, invalidate, cacheKeys } from "@/lib/cache";
export const GET = withAuth(async (req: NextRequest, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -23,6 +23,14 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {
const limit = Math.min(Number(url.searchParams.get("limit")) || 200, 500);
const offset = Number(url.searchParams.get("offset")) || 0;
+ if (offset === 0 && !url.searchParams.has("limit")) {
+ const data = await cached(cacheKeys.agentLinks(ws.workspaceId), 120, async () => {
+ const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId, { limit, offset });
+ return rows.map(agentLinkToResponse);
+ });
+ return writeJSON(data);
+ }
+
const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId, { limit, offset });
return writeJSON(rows.map(agentLinkToResponse));
});
@@ -55,7 +63,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
targetAgentId: body.target_agent_id,
instruction: body.instruction,
});
- await invalidate(cacheKeys.allColleagues(ws.workspaceId));
+ await Promise.all([
+ invalidate(cacheKeys.allColleagues(ws.workspaceId)),
+ invalidate(cacheKeys.agentLinks(ws.workspaceId)),
+ ]);
return writeJSON(agentLinkToResponse(created), 201);
} catch (e) {
if (isUniqueConstraintError(e)) {
diff --git a/src/web/src/components/agent-chat/historical-task-steps.tsx b/src/web/src/components/agent-chat/historical-task-steps.tsx
index 242716327..0556dff45 100644
--- a/src/web/src/components/agent-chat/historical-task-steps.tsx
+++ b/src/web/src/components/agent-chat/historical-task-steps.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useEffect } from "react";
+import { useState, useCallback } from "react";
import { TaskStream } from "@/components/task-stream";
import { getTaskMessages } from "@/lib/api";
import type { TaskMessage, TaskApi } from "@alook/shared";
@@ -50,9 +50,6 @@ export function HistoricalTaskSteps({
}
}, [fetched, loading, taskId, workspaceId]);
- // Auto-load messages so intermediate text ("Thinking") is available
- useEffect(() => { fetchMessages(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
-
return (
<TaskStream
task={COMPLETED_STUB}
diff --git a/src/web/src/components/canvas/agent-node.tsx b/src/web/src/components/canvas/agent-node.tsx
index 0ffb497a3..922005b2b 100644
--- a/src/web/src/components/canvas/agent-node.tsx
+++ b/src/web/src/components/canvas/agent-node.tsx
@@ -30,7 +30,7 @@ function AgentNodeInner({ data, selected, dragging }: NodeProps) {
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className={cn(
- "bg-background rounded-xl ring-1 ring-foreground/8 shadow-sm transition-all duration-200 py-3 px-3.5 group",
+ "bg-background rounded-xl ring-1 ring-foreground/8 shadow-sm transition-[box-shadow,ring-color,opacity,transform] duration-200 py-3 px-3.5 group",
selected && "ring-2 ring-primary/30 shadow-md",
!selected && "hover:ring-foreground/15 hover:shadow-md",
dragging && "shadow-lg scale-[1.02] cursor-grabbing",
diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.ts
index 1efc23f80..9ce417f49 100644
--- a/src/web/src/lib/cache.ts
+++ b/src/web/src/lib/cache.ts
@@ -149,6 +149,7 @@ export const cacheKeys = {
allAgents: (workspaceId: string) => `agents:${workspaceId}`,
allEmailAccounts: (workspaceId: string) => `ea:${workspaceId}`,
allColleagues: (workspaceId: string) => `col:${workspaceId}`,
+ agentLinks: (workspaceId: string) => `al:${workspaceId}`,
allHandles: (workspaceId: string) => `handles:${workspaceId}`,
overviewEmailStats: (workspaceId: string) => `ov_email:${workspaceId}`,
overviewTaskStats: (workspaceId: string, dateStr: string) => `ov_task:${workspaceId}:${dateStr}`,