Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: sync agent_ids to local config from daemon tasks and CLI commands

Generb7a96a6ab0f3
diff --git a/src/cli/commands/agent.test.ts b/src/cli/commands/agent.test.ts
new file mode 100644
index 000000000..a0e59fd62
--- /dev/null
+++ b/src/cli/commands/agent.test.ts
@@ -0,0 +1,257 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import type { WatchedWorkspace, ProfileConfig } from "../lib/config.js";
+
+// ── mocks ──────────────────────────────────────────────────────────
+let mockProfileConfig: ProfileConfig;
+
+vi.mock("../lib/config.js", () => ({
+ loadCLIConfigForProfile: vi.fn(() => mockProfileConfig),
+ saveCLIConfigForProfile: vi.fn(),
+}));
+
+// Stub the Commander parent chain so resolveClientOpts can read --profile/--server
+function fakeCommand(workspaceOpt?: string) {
+ return {
+ parent: { parent: { opts: () => ({}) } },
+ opts: () => ({ workspace: workspaceOpt }),
+ };
+}
+
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
+import { APIClient } from "../lib/client.js";
+
+// ── helpers ────────────────────────────────────────────────────────
+function makeWorkspace(overrides?: Partial<WatchedWorkspace>): WatchedWorkspace {
+ return {
+ id: "ws_1",
+ name: "Test",
+ token: "al_test",
+ agent_ids: [],
+ ...overrides,
+ };
+}
+
+function mockFetchJSON(body: unknown, status = 200) {
+ return vi.fn().mockResolvedValue({
+ ok: status >= 200 && status < 300,
+ status,
+ json: async () => body,
+ text: async () => JSON.stringify(body),
+ });
+}
+
+// ── tests ──────────────────────────────────────────────────────────
+
+describe("agent list — config sync", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("syncs agent_ids to local config after listing agents", async () => {
+ const ws = makeWorkspace({ agent_ids: [] });
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ const agents = [
+ { id: "ag_1", name: "Agent 1", runtime: "claude", status: "active", created_at: "2024-01-01" },
+ { id: "ag_2", name: "Agent 2", runtime: "codex", status: "active", created_at: "2024-01-02" },
+ ];
+ globalThis.fetch = mockFetchJSON(agents);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const result = await client.getJSON<typeof agents>("/api/agents?workspace_id=ws_1");
+
+ // Simulate the sync logic from the list action
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ configWs.agent_ids = result.map((a) => a.id);
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ expect(saveCLIConfigForProfile).toHaveBeenCalledOnce();
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual(["ag_1", "ag_2"]);
+ });
+
+ it("replaces stale agent_ids with current server state", async () => {
+ const ws = makeWorkspace({ agent_ids: ["ag_old", "ag_deleted"] });
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ const agents = [
+ { id: "ag_new", name: "New Agent", runtime: "claude", status: "active", created_at: "2024-01-01" },
+ ];
+ globalThis.fetch = mockFetchJSON(agents);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const result = await client.getJSON<typeof agents>("/api/agents?workspace_id=ws_1");
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ configWs.agent_ids = result.map((a) => a.id);
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual(["ag_new"]);
+ expect(savedConfig.watched_workspaces![0].agent_ids).not.toContain("ag_old");
+ expect(savedConfig.watched_workspaces![0].agent_ids).not.toContain("ag_deleted");
+ });
+
+ it("handles empty agent list from server", async () => {
+ const ws = makeWorkspace({ agent_ids: ["ag_stale"] });
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ globalThis.fetch = mockFetchJSON([]);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const result = await client.getJSON<{ id: string }[]>("/api/agents?workspace_id=ws_1");
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ configWs.agent_ids = result.map((a) => a.id);
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual([]);
+ });
+
+ it("does not save if workspace is not found in config", async () => {
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [] };
+
+ const agents = [{ id: "ag_1", name: "A", runtime: "claude", status: "active", created_at: "" }];
+ globalThis.fetch = mockFetchJSON(agents);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_missing");
+ const result = await client.getJSON<typeof agents>("/api/agents?workspace_id=ws_missing");
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_missing");
+ if (configWs) {
+ configWs.agent_ids = result.map((a) => a.id);
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
+ });
+});
+
+describe("agent create — config sync", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("appends new agent ID to config after creation", async () => {
+ const ws = makeWorkspace({ agent_ids: ["ag_existing"] });
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ const created = { id: "ag_new", name: "New", runtime: "claude", status: "active", created_at: "" };
+ globalThis.fetch = mockFetchJSON(created);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const agent = await client.postJSON<typeof created>("/api/agents", {
+ name: "New",
+ runtime: "claude",
+ workspace_id: "ws_1",
+ });
+
+ // Simulate the create action's config sync logic
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ if (!configWs.agent_ids) configWs.agent_ids = [];
+ if (!configWs.agent_ids.includes(agent.id)) {
+ configWs.agent_ids.push(agent.id);
+ }
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual(["ag_existing", "ag_new"]);
+ });
+
+ it("does not duplicate agent ID if already in config", async () => {
+ const ws = makeWorkspace({ agent_ids: ["ag_1"] });
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ const created = { id: "ag_1", name: "Dup", runtime: "claude", status: "active", created_at: "" };
+ globalThis.fetch = mockFetchJSON(created);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const agent = await client.postJSON<typeof created>("/api/agents", {
+ name: "Dup",
+ runtime: "claude",
+ workspace_id: "ws_1",
+ });
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ if (!configWs.agent_ids) configWs.agent_ids = [];
+ if (!configWs.agent_ids.includes(agent.id)) {
+ configWs.agent_ids.push(agent.id);
+ }
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual(["ag_1"]);
+ });
+
+ it("initializes agent_ids when undefined in config", async () => {
+ const ws = makeWorkspace();
+ delete (ws as any).agent_ids;
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [ws] };
+
+ const created = { id: "ag_first", name: "First", runtime: "claude", status: "active", created_at: "" };
+ globalThis.fetch = mockFetchJSON(created);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_1");
+ const agent = await client.postJSON<typeof created>("/api/agents", {
+ name: "First",
+ runtime: "claude",
+ workspace_id: "ws_1",
+ });
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_1");
+ if (configWs) {
+ if (!configWs.agent_ids) configWs.agent_ids = [];
+ if (!configWs.agent_ids.includes(agent.id)) {
+ configWs.agent_ids.push(agent.id);
+ }
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1] as ProfileConfig;
+ expect(savedConfig.watched_workspaces![0].agent_ids).toEqual(["ag_first"]);
+ });
+
+ it("does not save if workspace is not found in config", async () => {
+ mockProfileConfig = { server_url: "http://localhost", watched_workspaces: [] };
+
+ const created = { id: "ag_1", name: "A", runtime: "claude", status: "active", created_at: "" };
+ globalThis.fetch = mockFetchJSON(created);
+
+ const client = new APIClient("http://localhost", "al_test", "ws_missing");
+ const agent = await client.postJSON<typeof created>("/api/agents", {
+ name: "A",
+ runtime: "claude",
+ workspace_id: "ws_missing",
+ });
+
+ const profileCfg = loadCLIConfigForProfile(undefined);
+ const configWs = profileCfg.watched_workspaces?.find((w) => w.id === "ws_missing");
+ if (configWs) {
+ if (!configWs.agent_ids) configWs.agent_ids = [];
+ if (!configWs.agent_ids.includes(agent.id)) {
+ configWs.agent_ids.push(agent.id);
+ }
+ saveCLIConfigForProfile(undefined, profileCfg);
+ }
+
+ expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts
index c8bcadcbd..a2904488e 100644
--- a/src/cli/commands/agent.ts
+++ b/src/cli/commands/agent.ts
@@ -1,6 +1,6 @@
import { Command } from "commander";
import { APIClient } from "../lib/client.js";
-import { loadCLIConfigForProfile } from "../lib/config.js";
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { printTable, printJSON } from "../lib/output.js";
import { cmdPrefix } from "../lib/env.js";
@@ -42,7 +42,7 @@ export function agentCommand(): Command {
.option("--workspace <id>", "Workspace ID")
.option("--json", "Output as JSON")
.action(async (opts, command) => {
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.workspace);
+ const { serverUrl, token, workspaceId, profile } = resolveClientOpts(command, opts.workspace);
const client = new APIClient(serverUrl, token, workspaceId);
try {
@@ -53,6 +53,14 @@ export function agentCommand(): Command {
`/api/agents${queryParam}`,
);
+ // Sync agent_ids to local config
+ const profileCfg = loadCLIConfigForProfile(profile);
+ const ws = profileCfg.watched_workspaces?.find((w) => w.id === workspaceId);
+ if (ws) {
+ ws.agent_ids = agents.map((a) => a.id);
+ saveCLIConfigForProfile(profile, profileCfg);
+ }
+
if (opts.json) {
printJSON(agents);
return;
@@ -82,7 +90,7 @@ export function agentCommand(): Command {
.requiredOption("--runtime <runtime>", "Agent runtime")
.option("--workspace <id>", "Workspace ID")
.action(async (opts, command) => {
- const { serverUrl, token, workspaceId } = resolveClientOpts(command, opts.workspace);
+ const { serverUrl, token, workspaceId, profile } = resolveClientOpts(command, opts.workspace);
const client = new APIClient(serverUrl, token, workspaceId);
if (!opts.name) {
@@ -100,6 +108,19 @@ export function agentCommand(): Command {
runtime: opts.runtime,
workspace_id: workspaceId,
});
+
+ // Update local config with new agent ID
+ const profileCfg = loadCLIConfigForProfile(profile);
+ const watched = profileCfg.watched_workspaces || [];
+ const ws = watched.find((w) => w.id === workspaceId);
+ if (ws) {
+ if (!ws.agent_ids) ws.agent_ids = [];
+ if (!ws.agent_ids.includes(agent.id)) {
+ ws.agent_ids.push(agent.id);
+ }
+ saveCLIConfigForProfile(profile, profileCfg);
+ }
+
console.log(`Agent created: ${agent.name} (${agent.id})`);
} catch (err) {
console.error(
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 471f5b847..e7098c164 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -54,6 +54,7 @@ vi.mock("../lib/config.js", () => ({
server_url: null,
watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
})),
+ saveCLIConfigForProfile: vi.fn(),
}));
vi.mock("./pidfile.js", () => ({
@@ -125,7 +126,7 @@ vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {
}) as any);
import { spawn } from "child_process";
-import { loadCLIConfigForProfile } from "../lib/config.js";
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { startDaemon, spawnSessionRunner } from "./daemon.js";
function decodeSpawnInput(call: any[]): any {
@@ -535,6 +536,111 @@ describe("daemon shutdown", () => {
});
});
+describe("daemon agent_ids lazy sync", () => {
+ beforeEach(() => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ spawnedChildren.length = 0;
+ nextPid = 50000;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+
+ // Restore default mock implementations after clearAllMocks
+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
+ mockClientInstance.startTask.mockResolvedValue({});
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ function makeFakeTask(overrides?: Record<string, unknown>) {
+ return {
+ id: "t1",
+ agent_id: "a1",
+ runtime_id: "rt1",
+ conversation_id: "c1",
+ workspace_id: "ws1",
+ prompt: "do stuff",
+ status: "dispatched",
+ priority: 0,
+ dispatched_at: null,
+ started_at: null,
+ completed_at: null,
+ created_at: "2026-01-01T00:00:00Z",
+ type: "user_dm_message",
+ result: null,
+ error: null,
+ agent: { name: "Agent 1", instructions: "be helpful" },
+ ...overrides,
+ };
+ }
+
+ it("syncs unknown agent_id to config when task is received", async () => {
+ // Config has no agent_ids — agent was created on the web
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: [] }],
+ });
+
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation(async () => {
+ if (!claimed) { claimed = true; return [makeFakeTask()]; }
+ return [];
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(saveCLIConfigForProfile).toHaveBeenCalledOnce();
+ const savedConfig = vi.mocked(saveCLIConfigForProfile).mock.calls[0][1];
+ expect(savedConfig.watched_workspaces![0].agent_ids).toContain("a1");
+ });
+
+ it("does not save config when agent_id is already known", async () => {
+ // Config already has agent "a1"
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: ["a1"] }],
+ });
+
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation(async () => {
+ if (!claimed) { claimed = true; return [makeFakeTask()]; }
+ return [];
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ expect(saveCLIConfigForProfile).not.toHaveBeenCalled();
+ });
+
+ it("deduplicates: multiple tasks with same new agent_id only save once", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token", agent_ids: [] }],
+ });
+
+ let claimed = false;
+ mockClientInstance.poll.mockImplementation(async () => {
+ if (!claimed) {
+ claimed = true;
+ // Two tasks from the same agent
+ return [makeFakeTask({ id: "t1" }), makeFakeTask({ id: "t2" })];
+ }
+ return [];
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 50));
+
+ // Only one save — the in-memory set deduplicates
+ expect(saveCLIConfigForProfile).toHaveBeenCalledOnce();
+ });
+});
+
describe("spawnSessionRunner", () => {
beforeEach(() => {
spawnedChildren.length = 0;
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 719b17b8d..083b00154 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -3,7 +3,7 @@ import { type DaemonConfig, loadDaemonConfig } from "./config.js";
import { createHealthServer } from "./health.js";
import { detectVersion } from "./agent/index.js";
import { type Task, type SessionRunnerInput, fromApiTask } from "./types.js";
-import { loadCLIConfigForProfile } from "../lib/config.js";
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { log } from "../lib/logger.js";
import { cmdPrefix } from "../lib/env.js";
import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";
@@ -136,6 +136,28 @@ export async function startDaemon(
const activeTasks = new Set<string>();
+ // Seed known agent IDs from config so we only write on genuinely new ones
+ const knownAgentIds = new Set<string>(
+ workspaces.flatMap((ws) => ws.agent_ids ?? []),
+ );
+
+ function syncAgentId(agentId: string, workspaceId: string): void {
+ if (knownAgentIds.has(agentId)) return;
+ knownAgentIds.add(agentId);
+ try {
+ const cfg = loadCLIConfigForProfile(profile);
+ const ws = cfg.watched_workspaces?.find((w) => w.id === workspaceId);
+ if (!ws) return;
+ if (!ws.agent_ids) ws.agent_ids = [];
+ if (!ws.agent_ids.includes(agentId)) {
+ ws.agent_ids.push(agentId);
+ saveCLIConfigForProfile(profile, cfg);
+ }
+ } catch {
+ // Non-fatal — config sync is best-effort
+ }
+ }
+
// Staggered per-workspace polling
const pollCycle = async () => {
let remaining = config.maxConcurrentTasks - activeTasks.size;
@@ -156,6 +178,7 @@ export async function startDaemon(
const tasks = await client.poll(ws.token, config.daemonId, remaining);
for (const apiTask of tasks) {
const task = fromApiTask(apiTask);
+ syncAgentId(task.agentId, ws.workspaceId);
activeTasks.add(task.id);
remaining--;
handleTask(client, config, runtimeIndex, task, ws.token, activeTasks)