Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add agent relationship

Gus85770fb86584
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cfd84b469..91532d053 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -116,6 +116,9 @@ importers:
'@base-ui/react':
specifier: ^1.4.1
+ '@dagrejs/dagre':
+ specifier: ^3.0.0
+ version: 3.0.0
'@gsap/react':
specifier: ^2.1.2
@@ -134,6 +137,9 @@ importers:
'@tiptap/extension-link':
specifier: ^3.22.4
version: 3.22.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
+ '@tiptap/extension-mention':
+ specifier: ^3.22.5
+ version: 3.22.5(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))
'@tiptap/extension-placeholder':
specifier: ^3.22.4
version: 3.22.4(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))
@@ -155,6 +161,9 @@ importers:
'@tiptap/starter-kit':
specifier: ^3.22.4
version: 3.22.4
+ '@xyflow/react':
+ specifier: ^12.10.2
better-auth:
specifier: ^1.6.9
@@ -849,6 +858,12 @@ packages:
resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==}
engines: {node: '>=12'}
+ '@dagrejs/[email protected]':
+ resolution: {integrity: sha512-ZzhnTy1rfuoew9Ez3EIw4L2znPGnYYhfn8vc9c4oB8iw6QAsszbiU0vRhlxWPFnmmNSFAkrYeF1PhM5m4lAN0Q==}
+
+ '@dagrejs/[email protected]':
+ resolution: {integrity: sha512-IvcV6FduIIAmLwnH+yun+QtV36SC7mERqa86aClNqmMN09WhmPPYU8ckHrZBozErf+UvHPWOTJYaGYiIcs0DgA==}
+
'@date-fns/[email protected]':
resolution: {integrity: sha512-P5LUNhtbj6YfI3iJjw5EL9eUAG6OitD0W3fWQcpQjDRc/QIsL0tRNuO1PcDvPccWL1fSTXXdE1ds+l95DV/OFA==}
@@ -2265,6 +2280,13 @@ packages:
'@tiptap/core': 3.22.4
'@tiptap/pm': 3.22.4
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-rGTbTjyxLc5C/6QjfbQF53nMbxjVgJU1VK6Si1i1J2c5DU09COgEFlYvi4YHjb3xz39SprPfG+GTtgD96eg7Ww==}
+ peerDependencies:
+ '@tiptap/core': 3.22.5
+ '@tiptap/pm': 3.22.5
+ '@tiptap/suggestion': 3.22.5
+
'@tiptap/[email protected]':
resolution: {integrity: sha512-w77hPVf7pcHt97vfrybg/l0t5CimCd4y75OJKuHuo3CfgM5xbUP/gaPNMDyLLe7MYole/UHi/XvG3XjgzqTzAw==}
peerDependencies:
@@ -2333,6 +2355,12 @@ packages:
'@tiptap/[email protected]':
resolution: {integrity: sha512-qWjw+vfdin1rzMRpRU4cC5tLTwMJtUpXeQukv+6mOqqvhptuwuZBjUHImVEJaSPoHXS7+1ut+nTnrLyWyEuE5Q==}
+ '@tiptap/[email protected]':
+ resolution: {integrity: sha512-Uv79Ht/o4mx1GWIT65jeQTE67LMrA+K7d8p51XOe9PJw0H0fS3iCdeMJ8tAo3h6QrMJFejdsB7z8jJL9UbAnhA==}
+ peerDependencies:
+ '@tiptap/core': 3.22.5
+ '@tiptap/pm': 3.22.5
+
'@tootallnate/[email protected]':
resolution: {integrity: sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==}
@@ -2742,6 +2770,15 @@ packages:
'@vitest/[email protected]':
resolution: {integrity: sha512-76wdkrmfXfqGjueGgnb45ITPyUi1ycZ4IHgC2bhPDUfWHklY/q3MdLOAB+TF1e6xfl8NxNY0ZYaPCFNWSsw3Ug==}
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-CgIi6HwlcHXwlkTpr0fxLv/0sRVNZ8IdwKLzzeCscaYBwpvfcH1QFOCeaTCuEn1FQEs/B8CjnTSjhs8udgmBgQ==}
+ peerDependencies:
+ react: '>=17'
+ react-dom: '>=17'
+
+ '@xyflow/[email protected]':
+ resolution: {integrity: sha512-hvwvnRS1B3REwVDlWexsq7YQaPZeG3/mKo1jv38UmnpWmxihp14bW6VtEOuHEwJX2FvzFw8k77LyKSk/wiZVNA==}
+
resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
engines: {node: '>=6.5'}
@@ -3192,6 +3229,9 @@ packages:
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
+ resolution: {integrity: sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==}
+
resolution: {integrity: sha512-8lgKz8LmCRYZZQDpRyT2m5rKJ08TnU4tR9FFFW2rxpxR1FzWi4PQ/NfyODchAatHaUgnSPVcx/R5w6NuTBzFiw==}
engines: {node: '>=4'}
@@ -6858,6 +6898,21 @@ packages:
resolution: {integrity: sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==}
+ resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
+ engines: {node: '>=12.7.0'}
+ peerDependencies:
+ '@types/react': '>=16.8'
+ immer: '>=9.0.6'
+ react: '>=16.8'
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ immer:
+ optional: true
+ react:
+ optional: true
+
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -7906,6 +7961,12 @@ snapshots:
dependencies:
'@jridgewell/trace-mapping': 0.3.9
+ '@dagrejs/[email protected]':
+ dependencies:
+ '@dagrejs/graphlib': 4.0.1
+
+ '@dagrejs/[email protected]': {}
+
'@date-fns/[email protected]':
optional: true
@@ -9246,6 +9307,12 @@ snapshots:
'@tiptap/core': 3.22.4(@tiptap/[email protected])
'@tiptap/pm': 3.22.4
+ dependencies:
+ '@tiptap/core': 3.22.4(@tiptap/[email protected])
+ '@tiptap/pm': 3.22.4
+ '@tiptap/suggestion': 3.22.5(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
+
dependencies:
'@tiptap/extension-list': 3.22.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
@@ -9348,6 +9415,11 @@ snapshots:
'@tiptap/extensions': 3.22.4(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])
'@tiptap/pm': 3.22.4
+ dependencies:
+ '@tiptap/core': 3.22.4(@tiptap/[email protected])
+ '@tiptap/pm': 3.22.4
+
'@tootallnate/[email protected]': {}
'@ts-morph/[email protected]':
@@ -9777,6 +9849,29 @@ snapshots:
convert-source-map: 2.0.0
tinyrainbow: 3.1.0
+ dependencies:
+ '@xyflow/system': 0.0.76
+ classcat: 5.0.5
+ react: 19.2.5
+ react-dom: 19.2.5([email protected])
+ zustand: 4.5.7(@types/[email protected])([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - immer
+
+ '@xyflow/[email protected]':
+ dependencies:
+ '@types/d3-drag': 3.0.7
+ '@types/d3-interpolate': 3.0.4
+ '@types/d3-selection': 3.0.11
+ '@types/d3-transition': 3.0.9
+ '@types/d3-zoom': 3.0.8
+ d3-drag: 3.0.0
+ d3-interpolate: 3.0.1
+ d3-selection: 3.0.0
+ d3-zoom: 3.0.0
+
dependencies:
event-target-shim: 5.0.1
@@ -10205,6 +10300,8 @@ snapshots:
dependencies:
clsx: 2.1.1
+
dependencies:
restore-cursor: 2.0.0
@@ -10938,8 +11035,8 @@ snapshots:
'@next/eslint-plugin-next': 16.2.4
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -10961,7 +11058,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -10972,22 +11069,22 @@ snapshots:
tinyglobby: 0.2.16
unrs-resolver: 1.11.1
optionalDependencies:
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
'@typescript-eslint/parser': 8.58.2([email protected]([email protected]))([email protected])
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -10998,7 +11095,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.4([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.3
is-core-module: 2.16.1
is-glob: 4.0.3
@@ -14565,4 +14662,11 @@ snapshots:
+ dependencies:
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ '@types/react': 19.2.14
+ react: 19.2.5
+
diff --git a/src/cli/daemon/execenv/context.test.ts b/src/cli/daemon/execenv/context.test.ts
index 1f1f048e6..75ea03d87 100644
--- a/src/cli/daemon/execenv/context.test.ts
+++ b/src/cli/daemon/execenv/context.test.ts
@@ -130,4 +130,62 @@ describe("buildInstructionContent email tool injection", () => {
expect(content).toContain("## BIG BOSS Instructions");
});
+
+ it("includes colleagues section when agent has colleagues", () => {
+ const task = makeTask({
+ agent: {
+ name: "test",
+ instructions: "",
+ colleagues: [
+ { name: "Scout", email: "[email protected]", description: "A researcher agent", instruction: "Share findings via email" },
+ { name: "Writer", email: "[email protected]", description: "", instruction: "Draft blog posts" },
+ ],
+ },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("## Your Colleagues");
+ expect(content).toContain("### Scout ([email protected])");
+ expect(content).toContain("A researcher agent");
+ expect(content).toContain("**Relationship:** Share findings via email");
+ expect(content).toContain("### Writer ([email protected])");
+ expect(content).toContain("**Relationship:** Draft blog posts");
+ });
+
+ it("omits colleagues section when no colleagues", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "", colleagues: [] },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("## Your Colleagues");
+ });
+
+ it("omits colleagues section when colleagues undefined", () => {
+ const task = makeTask({
+ agent: { name: "test", instructions: "" },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).not.toContain("## Your Colleagues");
+ });
+
+ it("omits description line for colleague with empty description", () => {
+ const task = makeTask({
+ agent: {
+ name: "test",
+ instructions: "",
+ colleagues: [
+ { name: "Scout", email: "[email protected]", description: "", instruction: "Share data" },
+ ],
+ },
+ });
+ const content = buildInstructionContent(task);
+
+ expect(content).toContain("### Scout ([email protected])");
+ expect(content).toContain("**Relationship:** Share data");
+ // Only the header + relationship, no blank description line
+ const scoutSection = content.split("### Scout")[1].split("##")[0];
+ expect(scoutSection).not.toMatch(/\n\n\n/);
+ });
});
diff --git a/src/cli/daemon/execenv/context.ts b/src/cli/daemon/execenv/context.ts
index e90900281..6e4a47e12 100644
--- a/src/cli/daemon/execenv/context.ts
+++ b/src/cli/daemon/execenv/context.ts
@@ -90,6 +90,22 @@ ${task.agent.instructions}
`;
}
+ if (task.agent?.colleagues?.length) {
+ content += `\n## Your Colleagues
+Below are your direct colleagues. You can reach them via email.
+
+**Important:** When communicating with a colleague, always reply to the existing email thread instead of composing a new email. This keeps the full conversation context visible to your colleague so they can pick up where you left off.
+
+`;
+ for (let i = 0; i < task.agent.colleagues.length; i++) {
+ const c = task.agent.colleagues[i];
+ content += `### ${c.name}${c.email ? ` (${c.email})` : ""}\n`;
+ if (c.description) content += `${c.description}\n`;
+ if (c.instruction) content += `**Relationship:** ${c.instruction}\n`;
+ if (i < task.agent.colleagues.length - 1) content += "\n";
+ }
+ }
+
content += `\n## Alook CLI Tools
You can communicate with the world through Alook CLI.
Your alook agent id is '${task.agentId}'. remember this, most of alook cli will requires you input your agent id.
diff --git a/src/cli/daemon/types.test.ts b/src/cli/daemon/types.test.ts
index 19b20ac97..4e36ab780 100644
--- a/src/cli/daemon/types.test.ts
+++ b/src/cli/daemon/types.test.ts
@@ -74,4 +74,35 @@ describe("fromApiTask", () => {
const result = fromApiTask(baseTask);
expect(result.sender).toBeUndefined();
});
+
+ it("maps colleagues from agent data", () => {
+ const task: TaskApi = {
+ ...baseTask,
+ agent: {
+ name: "Agent 1",
+ instructions: "be helpful",
+ runtime_config: {},
+ colleagues: [
+ { name: "Scout", email: "[email protected]", description: "Researcher", instruction: "Share findings" },
+ ],
+ } as any,
+ };
+ const result = fromApiTask(task);
+ expect(result.agent?.colleagues).toEqual([
+ { name: "Scout", email: "[email protected]", description: "Researcher", instruction: "Share findings" },
+ ]);
+ });
+
+ it("defaults colleagues to empty array when missing", () => {
+ const task: TaskApi = {
+ ...baseTask,
+ agent: {
+ name: "Agent 1",
+ instructions: "be helpful",
+ runtime_config: {},
+ },
+ };
+ const result = fromApiTask(task);
+ expect(result.agent?.colleagues).toEqual([]);
+ });
});
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index d7734ac49..56c65a9cc 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -28,6 +28,13 @@ export interface Attachment {
filename: string;
}
+export interface ColleagueData {
+ name: string;
+ email: string;
+ description: string;
+ instruction: string;
+}
+
export interface TaskAgentData {
id?: string;
name: string;
@@ -37,6 +44,7 @@ export interface TaskAgentData {
userEmail?: string | null;
userName?: string | null;
runtimeConfig?: Record<string, unknown>;
+ colleagues?: ColleagueData[];
}
export interface RepoData {
@@ -123,7 +131,21 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
contextKey: api.context_key ?? null,
context: (api.context as Record<string, unknown>) ?? undefined,
agent: api.agent
- ? { name: api.agent.name, instructions: api.agent.instructions, emailHandle: api.agent.email_handle ?? undefined, emailAddresses: api.agent.email_addresses ?? [], userEmail: api.agent.user_email ?? undefined, userName: api.agent.user_name ?? undefined, runtimeConfig: api.agent.runtime_config ?? undefined }
+ ? {
+ name: api.agent.name,
+ instructions: api.agent.instructions,
+ emailHandle: api.agent.email_handle ?? undefined,
+ emailAddresses: api.agent.email_addresses ?? [],
+ userEmail: api.agent.user_email ?? undefined,
+ userName: api.agent.user_name ?? undefined,
+ runtimeConfig: api.agent.runtime_config ?? undefined,
+ colleagues: api.agent.colleagues?.map((c) => ({
+ name: c.name,
+ email: c.email,
+ description: c.description,
+ instruction: c.instruction,
+ })) ?? [],
+ }
: undefined,
sender: api.sender
? { name: api.sender.name, email: api.sender.email, isOwner: api.sender.is_owner }
diff --git a/src/shared/src/api-types.ts b/src/shared/src/api-types.ts
index b0419e760..4ef245c74 100644
--- a/src/shared/src/api-types.ts
+++ b/src/shared/src/api-types.ts
@@ -80,6 +80,16 @@ export interface DeleteCalendarEventRequest {
occurrence_at?: string;
}
+export interface CreateAgentLinkRequest {
+ source_agent_id: string;
+ target_agent_id: string;
+ instruction?: string;
+}
+
+export interface UpdateAgentLinkRequest {
+ instruction: string;
+}
+
export interface CreateWorkspaceRequest {
name: string;
}
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.ts
index 0198588e8..b0ad330ff 100644
--- a/src/shared/src/db/queries-index.ts
+++ b/src/shared/src/db/queries-index.ts
@@ -23,3 +23,4 @@ export * as meetingSession from "./queries/meeting-session";
export * as channel from "./queries/channel";
export * as workspaceFileRequest from "./queries/workspace-file-request";
export * as conversationMap from "./queries/conversation-map";
+export * as agentLink from "./queries/agent-link";
diff --git a/src/shared/src/db/queries/agent-link.ts b/src/shared/src/db/queries/agent-link.ts
new file mode 100644
index 000000000..83c26b122
--- /dev/null
+++ b/src/shared/src/db/queries/agent-link.ts
@@ -0,0 +1,121 @@
+import { eq, and, or } from "drizzle-orm";
+import { agentLink, agent } from "../schema";
+import type { Database } from "../index";
+
+export async function listByWorkspace(db: Database, workspaceId: string) {
+ return db
+ .select()
+ .from(agentLink)
+ .where(eq(agentLink.workspaceId, workspaceId));
+}
+
+export async function listByAgent(db: Database, agentId: string, workspaceId: string) {
+ return db
+ .select()
+ .from(agentLink)
+ .where(
+ and(
+ eq(agentLink.workspaceId, workspaceId),
+ or(
+ eq(agentLink.sourceAgentId, agentId),
+ eq(agentLink.targetAgentId, agentId),
+ ),
+ ),
+ );
+}
+
+export async function create(
+ db: Database,
+ data: {
+ workspaceId: string;
+ sourceAgentId: string;
+ targetAgentId: string;
+ instruction?: string;
+ },
+) {
+ let { sourceAgentId, targetAgentId } = data;
+ if (sourceAgentId > targetAgentId) {
+ [sourceAgentId, targetAgentId] = [targetAgentId, sourceAgentId];
+ }
+ const rows = await db
+ .insert(agentLink)
+ .values({
+ workspaceId: data.workspaceId,
+ sourceAgentId,
+ targetAgentId,
+ instruction: data.instruction ?? "",
+ })
+ .returning();
+ return rows[0]!;
+}
+
+export async function update(
+ db: Database,
+ id: string,
+ workspaceId: string,
+ data: { instruction: string },
+) {
+ const rows = await db
+ .update(agentLink)
+ .set({
+ instruction: data.instruction,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(and(eq(agentLink.id, id), eq(agentLink.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+}
+
+export async function remove(db: Database, id: string, workspaceId: string) {
+ const rows = await db
+ .delete(agentLink)
+ .where(and(eq(agentLink.id, id), eq(agentLink.workspaceId, workspaceId)))
+ .returning();
+ return rows[0] ?? null;
+}
+
+export async function getColleaguesForAgent(
+ db: Database,
+ agentId: string,
+ workspaceId: string,
+) {
+ const asSource = await db
+ .select({
+ name: agent.name,
+ emailHandle: agent.emailHandle,
+ description: agent.description,
+ instruction: agentLink.instruction,
+ })
+ .from(agentLink)
+ .innerJoin(
+ agent,
+ and(eq(agent.id, agentLink.targetAgentId), eq(agent.workspaceId, agentLink.workspaceId)),
+ )
+ .where(
+ and(
+ eq(agentLink.sourceAgentId, agentId),
+ eq(agentLink.workspaceId, workspaceId),
+ ),
+ );
+
+ const asTarget = await db
+ .select({
+ name: agent.name,
+ emailHandle: agent.emailHandle,
+ description: agent.description,
+ instruction: agentLink.instruction,
+ })
+ .from(agentLink)
+ .innerJoin(
+ agent,
+ and(eq(agent.id, agentLink.sourceAgentId), eq(agent.workspaceId, agentLink.workspaceId)),
+ )
+ .where(
+ and(
+ eq(agentLink.targetAgentId, agentId),
+ eq(agentLink.workspaceId, workspaceId),
+ ),
+ );
+
+ return [...asSource, ...asTarget];
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 870031c52..135ebca55 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -565,6 +565,31 @@ export const conversationMap = sqliteTable(
]
);
+export const agentLink = sqliteTable(
+ "agent_link",
+ {
+ id: text("id").primaryKey().$defaultFn(() => "al_" + nanoid()),
+ workspaceId: text("workspace_id").notNull(),
+ sourceAgentId: text("source_agent_id").notNull(),
+ targetAgentId: text("target_agent_id").notNull(),
+ instruction: text("instruction").notNull().default(""),
+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
+ updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
+ },
+ (t) => [
+ unique("agent_link_ws_source_target").on(t.workspaceId, t.sourceAgentId, t.targetAgentId),
+ index("idx_agent_link_workspace").on(t.workspaceId),
+ foreignKey({
+ columns: [t.sourceAgentId, t.workspaceId],
+ foreignColumns: [agent.id, agent.workspaceId],
+ }).onDelete("cascade"),
+ foreignKey({
+ columns: [t.targetAgentId, t.workspaceId],
+ foreignColumns: [agent.id, agent.workspaceId],
+ }).onDelete("cascade"),
+ ]
+);
+
export const workspaceFileRequest = sqliteTable(
"workspace_file_request",
{
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index b5df44b29..04af009c6 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -17,6 +17,7 @@ export type {
LoginResponse,
CreateAgentRequest,
CalendarEvent,
+ AgentLink,
MeetingSession,
Channel,
WsMessage,
@@ -47,6 +48,8 @@ export type {
CreateCalendarEventRequest,
UpdateCalendarEventRequest,
DeleteCalendarEventRequest,
+ CreateAgentLinkRequest,
+ UpdateAgentLinkRequest,
CreateWorkspaceRequest,
UpdateAgentRequest,
SendMessageRequest,
@@ -108,6 +111,8 @@ export {
UpdateCalendarEventRequestSchema,
DeleteCalendarEventRequestSchema,
CalendarEventApiSchema,
+ CreateAgentLinkRequestSchema,
+ UpdateAgentLinkRequestSchema,
AddWhitelistRequestSchema,
CreateAgentRequestSchema,
UpdateAgentRequestSchema,
@@ -154,6 +159,8 @@ export type {
UpdateCalendarEventRequestInput,
DeleteCalendarEventRequestInput,
CalendarEventApi,
+ CreateAgentLinkRequestInput,
+ UpdateAgentLinkRequestInput,
AddWhitelistRequest,
CreateEmailAccountRequest,
UpdateMemberRequest,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 3b47d5ced..34ca5129c 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -45,6 +45,13 @@ export type ClaimedTaskRow = z.infer<typeof ClaimedTaskRowSchema>;
// API wire format — task agent data (embedded in claim response)
// ---------------------------------------------------------------------------
+export const ColleagueDataApiSchema = z.object({
+ name: z.string(),
+ email: z.string(),
+ description: z.string(),
+ instruction: z.string(),
+});
+
export const TaskAgentDataApiSchema = z.object({
instructions: z.string(),
name: z.string(),
@@ -53,6 +60,7 @@ export const TaskAgentDataApiSchema = z.object({
email_addresses: z.array(z.string()).default([]),
user_email: z.string().nullable().optional(),
user_name: z.string().nullable().optional(),
+ colleagues: z.array(ColleagueDataApiSchema).default([]),
});
export type TaskAgentDataApi = z.infer<typeof TaskAgentDataApiSchema>;
@@ -327,6 +335,22 @@ export const CalendarEventApiSchema = z.object({
});
export type CalendarEventApi = z.infer<typeof CalendarEventApiSchema>;
+// ---------------------------------------------------------------------------
+// Agent link schemas
+// ---------------------------------------------------------------------------
+
+export const CreateAgentLinkRequestSchema = z.object({
+ source_agent_id: z.string().min(1, "source_agent_id is required"),
+ target_agent_id: z.string().min(1, "target_agent_id is required"),
+ instruction: z.string().optional().default(""),
+});
+export type CreateAgentLinkRequestInput = z.infer<typeof CreateAgentLinkRequestSchema>;
+
+export const UpdateAgentLinkRequestSchema = z.object({
+ instruction: z.string(),
+});
+export type UpdateAgentLinkRequestInput = z.infer<typeof UpdateAgentLinkRequestSchema>;
+
// ---------------------------------------------------------------------------
// Whitelist request schema
// ---------------------------------------------------------------------------
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 5facc145f..97b87cc9b 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -202,6 +202,16 @@ export interface CreateAgentRequest {
email_handle?: string;
}
+export interface AgentLink {
+ id: string;
+ workspace_id: string;
+ source_agent_id: string;
+ target_agent_id: string;
+ instruction: string;
+ created_at: string;
+ updated_at: string;
+}
+
export interface MeetingSession {
id: string;
agent_id: string;
diff --git a/src/web/migrations/0017_agent_link.sql b/src/web/migrations/0017_agent_link.sql
new file mode 100644
index 000000000..ef87a4d58
--- /dev/null
+++ b/src/web/migrations/0017_agent_link.sql
@@ -0,0 +1,14 @@
+CREATE TABLE IF NOT EXISTS agent_link (
+ id TEXT PRIMARY KEY,
+ workspace_id TEXT NOT NULL,
+ source_agent_id TEXT NOT NULL,
+ target_agent_id TEXT NOT NULL,
+ instruction TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),
+ FOREIGN KEY (source_agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE,
+ FOREIGN KEY (target_agent_id, workspace_id) REFERENCES agent(id, workspace_id) ON DELETE CASCADE,
+ CONSTRAINT agent_link_ws_source_target UNIQUE (workspace_id, source_agent_id, target_agent_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_agent_link_workspace ON agent_link(workspace_id);
diff --git a/src/web/package.json b/src/web/package.json
index 8461bf98f..6364689f3 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -20,12 +20,14 @@
"dependencies": {
"@alook/shared": "workspace:*",
"@base-ui/react": "^1.4.1",
+ "@dagrejs/dagre": "^3.0.0",
"@gsap/react": "^2.1.2",
"@icons-pack/react-simple-icons": "^13.13.0",
"@opennextjs/cloudflare": "^1.19.4",
"@tiptap/extension-color": "^3.22.4",
"@tiptap/extension-image": "^3.22.4",
"@tiptap/extension-link": "^3.22.4",
+ "@tiptap/extension-mention": "^3.22.5",
"@tiptap/extension-placeholder": "^3.22.4",
"@tiptap/extension-text-align": "^3.22.4",
"@tiptap/extension-text-style": "^3.22.4",
@@ -33,6 +35,7 @@
"@tiptap/markdown": "^3.22.4",
"@tiptap/react": "^3.22.4",
"@tiptap/starter-kit": "^3.22.4",
+ "@xyflow/react": "^12.10.2",
"better-auth": "^1.6.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -55,6 +58,7 @@
},
"devDependencies": {
"@eslint/eslintrc": "^3",
+ "@lhci/cli": "^0.15.1",
"@tailwindcss/postcss": "^4",
"@types/node": "^25",
"@types/react": "^19.2.14",
@@ -64,7 +68,6 @@
"tailwindcss": "^4",
"typescript": "^6.0.3",
"vitest": "^4.1.5",
- "wrangler": "^4.85.0",
- "@lhci/cli": "^0.15.1"
+ "wrangler": "^4.85.0"
}
}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsx
deleted file mode 100644
index c6cf9eaf9..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { MessageSquare, Mail, Plus } from "lucide-react";
-import type { Agent, AgentRuntime } from "@alook/shared";
-import type { WorkspaceOverview } from "@/lib/api";
-import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
-
-interface AgentOverviewProps {
- agents: Agent[];
- runtimes: AgentRuntime[];
- activeTaskCounts: Record<string, number>;
- overview: WorkspaceOverview;
-}
-
-export function AgentOverview({ agents, runtimes, activeTaskCounts, overview }: AgentOverviewProps) {
- const router = useRouter();
- const { slug } = useWorkspace();
-
- if (agents.length === 0) return null;
-
- return (
- <Card className="flex flex-col lg:max-h-[33%]">
- <CardHeader>
- <CardTitle>Agents</CardTitle>
- <CardAction>
- <button
- type="button"
- onClick={() => router.push(`/w/${slug}/agents/new`)}
- className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- >
- <Plus className="size-4" />
- </button>
- </CardAction>
- </CardHeader>
- <CardContent className="p-0 flex-1 min-h-0 overflow-y-auto thin-scrollbar">
- <div className="divide-y divide-border/50">
- {agents.map((agent) => {
- const rt = runtimes.find((r) => r.id === agent.runtime_id);
- const isOnline = rt?.status === "online";
- const tasks = activeTaskCounts[agent.id] ?? 0;
- const convos = overview.conversation_counts[agent.id] ?? 0;
-
- return (
- <button
- key={agent.id}
- type="button"
- onClick={() => router.push(`/w/${slug}/agents/${agent.id}`)}
- className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/50 transition-colors cursor-pointer"
- >
- {(() => {
- const avatarConfig = parseAvatarUrl(agent.avatar_url);
- if (avatarConfig) {
- return <AvatarRenderer config={avatarConfig} size={32} className="shrink-0 rounded-lg" />;
- }
- return (
- <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-secondary text-secondary-foreground text-sm font-medium">
- {agent.name.charAt(0).toUpperCase()}
- </div>
- );
- })()}
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="font-medium truncate">{agent.name}</span>
- <Tooltip>
- <TooltipTrigger render={
- <span
- className={`size-2 rounded-full shrink-0 ${isOnline ? "bg-emerald-500" : "bg-muted-foreground/30"}`}
- />
- } />
- <TooltipContent side="top">{isOnline ? "Online" : "Offline"}</TooltipContent>
- </Tooltip>
- {agent.visibility === "public" && (
- <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
- public
- </Badge>
- )}
- </div>
- </div>
-
- <div className="flex items-center gap-4 text-xs text-muted-foreground shrink-0">
- {tasks > 0 && (
- <Tooltip>
- <TooltipTrigger render={
- <span className="flex items-center gap-1 text-primary font-medium">
- <span className="size-1.5 rounded-full bg-primary animate-pulse" />
- {tasks} active
- </span>
- } />
- <TooltipContent side="top">{tasks} active task{tasks > 1 ? "s" : ""}</TooltipContent>
- </Tooltip>
- )}
- <Tooltip>
- <TooltipTrigger render={
- <span className="flex items-center gap-1">
- <MessageSquare className="size-3" />
- {convos}
- </span>
- } />
- <TooltipContent side="top">{convos} conversation{convos !== 1 ? "s" : ""}</TooltipContent>
- </Tooltip>
- {agent.email_handle && (
- <Tooltip>
- <TooltipTrigger render={
- <span className="flex items-center">
- <Mail className="size-3" />
- </span>
- } />
- <TooltipContent side="top">{agent.email_handle}</TooltipContent>
- </Tooltip>
- )}
- </div>
- </button>
- );
- })}
- </div>
- </CardContent>
- </Card>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsx
deleted file mode 100644
index 75d54b12c..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";
-import { useWorkspace } from "@/contexts/workspace-context";
-import { CalendarDays, ArrowUpRight, Repeat } from "lucide-react";
-import type { WorkspaceOverview } from "@/lib/api";
-import type { Agent } from "@alook/shared";
-
-interface CalendarOverviewProps {
- overview: WorkspaceOverview;
- agents: Agent[];
-}
-
-function formatRepeatInterval(interval: string): string {
- const match = interval.match(/^(\d+)(min|hour|day|week|month)$/);
- if (!match) return interval;
- const [, n, unit] = match;
- const num = Number(n);
- const labels: Record<string, string> = { min: "min", hour: "hour", day: "day", week: "week", month: "month" };
- const label = labels[unit] ?? unit;
- return num === 1 ? `Every ${label}` : `Every ${num} ${label}s`;
-}
-
-export function CalendarOverview({ overview, agents }: CalendarOverviewProps) {
- const router = useRouter();
- const { slug } = useWorkspace();
- const { calendar_events } = overview;
- const agentMap = new Map(agents.map((a) => [a.id, a.name]));
-
- const now = new Date();
- const todayEnd = new Date(now);
- todayEnd.setHours(23, 59, 59, 999);
-
- const todayEvents = calendar_events.filter(
- (e) => new Date(e.scheduled_at) <= todayEnd
- );
-
- const recurring = calendar_events.filter((e) => e.repeat_interval);
- const oneOff = calendar_events.filter((e) => !e.repeat_interval);
-
- const upcoming = [...calendar_events]
- .sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime())
- .slice(0, 5);
-
- return (
- <Card className="flex flex-col">
- <CardHeader>
- <CardTitle>Calendar</CardTitle>
- <CardAction>
- <button
- type="button"
- onClick={() => router.push(`/w/${slug}/calendar`)}
- className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
- >
- <ArrowUpRight className="size-4" />
- </button>
- </CardAction>
- </CardHeader>
- <CardContent className="space-y-3 flex-1 min-h-0 overflow-y-auto thin-scrollbar">
- <div className="grid grid-cols-3 gap-3">
- <div className="rounded-lg border border-border/50 px-3 py-2 text-center">
- <p className="text-xl font-semibold">{todayEvents.length}</p>
- <p className="text-[10px] text-muted-foreground">Today</p>
- </div>
- <div className="rounded-lg border border-border/50 px-3 py-2 text-center">
- <p className="text-xl font-semibold">{recurring.length}</p>
- <p className="text-[10px] text-muted-foreground">Recurring</p>
- </div>
- <div className="rounded-lg border border-border/50 px-3 py-2 text-center">
- <p className="text-xl font-semibold">{oneOff.length}</p>
- <p className="text-[10px] text-muted-foreground">One-off</p>
- </div>
- </div>
-
- {upcoming.length > 0 && (
- <div className="space-y-1.5 pt-2 border-t border-border/50">
- <p className="text-xs font-medium text-muted-foreground">Upcoming This Week</p>
- {upcoming.map((e) => (
- <div key={e.id} className="flex items-center gap-2 text-xs">
- {e.repeat_interval ? (
- <Repeat className="size-3 shrink-0 text-primary" />
- ) : (
- <CalendarDays className="size-3 shrink-0 text-muted-foreground" />
- )}
- <span className="truncate flex-1">{e.title}</span>
- <span className="text-muted-foreground shrink-0">
- {agentMap.get(e.agent_id) ?? "—"}
- </span>
- <span className="text-muted-foreground shrink-0">
- {e.repeat_interval
- ? `${formatRepeatInterval(e.repeat_interval)}, ${new Date(e.scheduled_at).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}`
- : new Date(e.scheduled_at).toLocaleDateString(undefined, { weekday: "short", hour: "2-digit", minute: "2-digit" })}
- </span>
- </div>
- ))}
- </div>
- )}
-
- {calendar_events.length === 0 && (
- <div className="flex flex-col items-center py-4 text-muted-foreground">
- <CalendarDays className="size-8 opacity-20 mb-2" />
- <p className="text-sm">No events this week</p>
- </div>
- )}
- </CardContent>
- </Card>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/daily-quote.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/daily-quote.tsx
deleted file mode 100644
index e34b7c6c2..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/daily-quote.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-"use client";
-
-import { useEffect, useState } from "react";
-
-const FALLBACK_QUOTES = [
- { q: "Have a wonderful day!", a: "" },
- { q: "Every day is a fresh start.", a: "" },
- { q: "Small steps lead to great journeys.", a: "" },
- { q: "Stay curious, keep building.", a: "" },
-];
-
-interface DailyQuote {
- q: string;
- a: string;
-}
-
-export function DailyQuote() {
- const [quote, setQuote] = useState<DailyQuote | null>(null);
-
- useEffect(() => {
- let cancelled = false;
- fetch("/api/daily-quote")
- .then((r) => r.json() as Promise<DailyQuote>)
- .then((data) => {
- if (!cancelled && data?.q) {
- setQuote(data);
- }
- })
- .catch(() => {
- if (!cancelled) {
- const idx = new Date().getDate() % FALLBACK_QUOTES.length;
- setQuote(FALLBACK_QUOTES[idx]);
- }
- });
- return () => { cancelled = true; };
- }, []);
-
- if (!quote) return null;
-
- return (
- <div className="text-center py-2">
- <p className="text-xs text-muted-foreground/50 italic">— {quote.q} —</p>
- {quote.a && <p className="text-[10px] text-muted-foreground/40 -mt-0.5">{quote.a}</p>}
- </div>
- );
-}
diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx
deleted file mode 100644
index 5da3fdc5f..000000000
--- a/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-"use client";
-
-import { useState } from "react";
-import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
-import { Badge } from "@/components/ui/badge";
-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { MessageSquare, Mail, CalendarDays, RotateCw, Loader2 } from "lucide-react";
-import { retryTask, type WorkspaceOverview } from "@/lib/api";
-import type { Agent } from "@alook/shared";
-
-interface RecentActivityProps {
- overview: WorkspaceOverview;
- agents: Agent[];
- workspaceId: string;
- onRefresh: () => void;
-}
-
-const TYPE_CONFIG: Record<string, { icon: React.ElementType; label: string }> = {
- user_dm_message: { icon: MessageSquare, label: "Chat message" },
- email_notification: { icon: Mail, label: "Email task" },
- calendar_event: { icon: CalendarDays, label: "Calendar event" },
-};
-
-function timeAgo(dateStr: string | null): string {
- if (!dateStr) return "";
- const diff = Date.now() - new Date(dateStr).getTime();
- const mins = Math.floor(diff / 60000);
- if (mins < 1) return "just now";
- if (mins < 60) return `${mins}m ago`;
- const hours = Math.floor(mins / 60);
- if (hours < 24) return `${hours}h ago`;
- const days = Math.floor(hours / 24);
- return `${days}d ago`;
-}
-
-export function RecentActivity({ overview, agents, workspaceId, onRefresh }: RecentActivityProps) {
- const [retryingId, setRetryingId] = useState<string | null>(null);
- const { recent_tasks } = overview;
- const agentMap = new Map(agents.map((a) => [a.id, a.name]));
-
- if (recent_tasks.length === 0) {
- return (
- <Card>
- <CardHeader>
- <CardTitle>Recent Activity</CardTitle>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col items-center py-4 text-muted-foreground">
- <MessageSquare className="size-8 opacity-20 mb-2" />
- <p className="text-sm">No recent activity</p>
- </div>
- </CardContent>
- </Card>
- );
- }
-
- return (
- <Card className="flex flex-col">
- <CardHeader>
- <CardTitle>Recent Activity</CardTitle>
- </CardHeader>
- <CardContent className="p-0 flex-1 min-h-0 overflow-y-auto thin-scrollbar">
- <div className="divide-y divide-border/50">
- {recent_tasks.map((task) => {
- const config = TYPE_CONFIG[task.type] ?? TYPE_CONFIG.user_dm_message;
- const Icon = config.icon;
- return (
- <div key={task.id} className="flex items-center gap-3 px-4 py-2.5">
- <Tooltip>
- <TooltipTrigger render={
- <span className="flex items-center">
- <Icon className="size-3.5 shrink-0 text-muted-foreground" />
- </span>
- } />
- <TooltipContent side="top">{config.label}</TooltipContent>
- </Tooltip>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2">
- <span className="text-xs font-medium shrink-0">
- {agentMap.get(task.agent_id) ?? "Unknown"}
- </span>
- <span className="text-xs text-muted-foreground truncate">
- {task.prompt.slice(0, 80)}{task.prompt.length > 80 ? "..." : ""}
- </span>
- </div>
- </div>
- <div className="flex items-center gap-2 shrink-0">
- <Badge
- variant={task.status === "completed" ? "secondary" : "destructive"}
- className="text-[10px] px-1.5 py-0"
- >
- {task.status}
- </Badge>
- {task.status === "failed" && (
- <button
- type="button"
- onClick={async () => {
- setRetryingId(task.id);
- try {
- await retryTask(task.id, workspaceId);
- onRefresh();
- } catch { /* silently fail */ }
- finally { setRetryingId(null); }
- }}
- disabled={retryingId === task.id}
- className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer disabled:opacity-50"
- title="Retry task"
- >
- {retryingId === task.id
- ? <Loader2 className="size-3 animate-spin" />
- : <RotateCw className="size-3" />}
- </button>
- )}
- <span className="text-[10px] text-muted-foreground w-14 text-right">
- {timeAgo(task.completed_at)}
- </span>
- </div>
- </div>
- );
- })}
- </div>
- </CardContent>
- </Card>
- );
-}
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 efa07d122..9f385c9e8 100644
--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx
@@ -1,46 +1,473 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
+import {
+ ReactFlow,
+ Background,
+ ReactFlowProvider,
+ useReactFlow,
+ type Node,
+ type Edge,
+ type OnConnect,
+ type Connection,
+ type NodeChange,
+ type EdgeChange,
+ applyNodeChanges,
+ applyEdgeChanges,
+} from "@xyflow/react";
+import "@xyflow/react/dist/style.css";
+import {
+ ZoomIn,
+ ZoomOut,
+ Maximize2,
+ RotateCcw,
+ Loader2,
+} from "lucide-react";
+import type { AgentLink } from "@alook/shared";
import { useAgentContext } from "@/contexts/agent-context";
import { useWorkspace } from "@/contexts/workspace-context";
+import { useIsMobile } from "@/hooks/use-mobile";
import { Button } from "@/components/ui/button";
-import { Skeleton } from "@/components/ui/skeleton";
-import { Loader2 } from "lucide-react";
-import { getWorkspaceOverview, type WorkspaceOverview } from "@/lib/api";
-import { AgentOverview } from "./_components/agent-overview";
-import { RecentActivity } from "./_components/recent-activity";
-import { CalendarOverview } from "./_components/calendar-overview";
-import { DailyQuote } from "./_components/daily-quote";
+import { AgentPreviewCard } from "@/components/agent-preview-card";
+import {
+ listAgentLinks,
+ createAgentLink,
+ updateAgentLink,
+ deleteAgentLink,
+} from "@/lib/api";
+import { toast } from "sonner";
+import { ApiError } from "@/lib/errors";
+import { AgentNode, type AgentNodeData } from "@/components/canvas/agent-node";
+import { LinkEdge } from "@/components/canvas/link-edge";
+import { LinkSidecar } from "@/components/canvas/link-sidecar";
+import { getAutoLayout } from "@/components/canvas/auto-layout";
-export default function HomePage() {
+const nodeTypes = { agent: AgentNode };
+const edgeTypes = { link: LinkEdge };
+
+function storageKey(workspaceId: string) {
+ return `alook-canvas-positions-${workspaceId}`;
+}
+
+function loadPositions(workspaceId: string): Record<string, { x: number; y: number }> {
+ try {
+ const raw = localStorage.getItem(storageKey(workspaceId));
+ return raw ? JSON.parse(raw) : {};
+ } catch {
+ return {};
+ }
+}
+
+function savePositions(workspaceId: string, nodes: Node[]) {
+ const positions: Record<string, { x: number; y: number }> = {};
+ for (const n of nodes) {
+ positions[n.id] = n.position;
+ }
+ try {
+ localStorage.setItem(storageKey(workspaceId), JSON.stringify(positions));
+ } catch {}
+}
+
+function AgentCanvas() {
const router = useRouter();
const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();
const { slug, workspaceId } = useWorkspace();
- const [overview, setOverview] = useState<WorkspaceOverview | null>(null);
- const [overviewLoading, setOverviewLoading] = useState(false);
+ 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 [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
useEffect(() => {
- if (loading || agents.length === 0) return;
+ if (!workspaceId || loading || agents.length === 0) return;
let cancelled = false;
- setOverviewLoading(true);
- getWorkspaceOverview(workspaceId)
+ listAgentLinks(workspaceId)
.then((data) => {
- if (!cancelled) setOverview(data);
+ if (!cancelled) {
+ setLinks(data);
+ setLinksLoaded(true);
+ }
})
- .catch(() => {})
- .finally(() => {
- if (!cancelled) setOverviewLoading(false);
+ .catch(() => {
+ if (!cancelled) setLinksLoaded(true);
});
return () => { cancelled = true; };
- }, [loading, agents.length, workspaceId]);
+ }, [workspaceId, loading, agents.length]);
+
+ // Build edges from links
+ useEffect(() => {
+ if (!linksLoaded) return;
+
+ const nodeMap = new Map(nodes.map((n) => [n.id, n.position]));
- const refreshOverview = useCallback(() => {
- getWorkspaceOverview(workspaceId)
- .then((data) => setOverview(data))
- .catch(() => {});
+ const newEdges: Edge[] = links.map((link) => {
+ const stored = handleMap.current[link.id];
+ let sourceHandle = stored?.sourceHandle;
+ let targetHandle = stored?.targetHandle;
+
+ if (!sourceHandle || !targetHandle) {
+ const sp = nodeMap.get(link.source_agent_id);
+ const tp = nodeMap.get(link.target_agent_id);
+ if (sp && tp) {
+ const dx = tp.x - sp.x;
+ const dy = tp.y - sp.y;
+ if (Math.abs(dx) >= Math.abs(dy)) {
+ sourceHandle = dx >= 0 ? "right" : "left";
+ targetHandle = dx >= 0 ? "target-left" : "target-right";
+ } else {
+ sourceHandle = dy >= 0 ? "bottom" : "top";
+ targetHandle = dy >= 0 ? "target-top" : "target-bottom";
+ }
+ } else {
+ sourceHandle = "right";
+ targetHandle = "target-left";
+ }
+ }
+
+ return {
+ id: link.id,
+ source: link.source_agent_id,
+ target: link.target_agent_id,
+ sourceHandle,
+ targetHandle,
+ type: "link",
+ data: {
+ instruction: link.instruction,
+ onEdgeClick: (edgeId: string) => {
+ const l = links.find((lk) => lk.id === edgeId);
+ if (l) {
+ setSidecarLink(l);
+ setSidecarOpen(true);
+ }
+ },
+ },
+ selected: sidecarLink?.id === link.id && sidecarOpen,
+ };
+ });
+ setEdges(newEdges);
+ setShowHint(newEdges.length === 0);
+ }, [links, linksLoaded, sidecarLink, sidecarOpen, nodes]);
+
+ // Build nodes from agents
+ useEffect(() => {
+ if (loading || agents.length === 0) return;
+
+ const saved = loadPositions(workspaceId);
+ // Filter out stale positions
+ const agentIds = new Set(agents.map((a) => a.id));
+ const validPositions: Record<string, { x: number; y: number }> = {};
+ for (const [id, pos] of Object.entries(saved)) {
+ if (agentIds.has(id)) validPositions[id] = pos;
+ }
+
+ let newNodes: Node[] = agents.map((agent, index) => ({
+ id: agent.id,
+ type: "agent",
+ position: validPositions[agent.id] ?? { x: 0, y: 0 },
+ data: {
+ agent,
+ runtimes,
+ activeTaskCount: activeTaskCounts[agent.id] ?? 0,
+ slug,
+ index,
+ } satisfies AgentNodeData,
+ }));
+
+ const hasAnyPosition = Object.keys(validPositions).length > 0;
+ const newAgentIds = agents.filter((a) => !validPositions[a.id]).map((a) => a.id);
+
+ if (!hasAnyPosition) {
+ // First visit — auto-layout all
+ if (linksLoaded) {
+ const currentEdges: Edge[] = links.map((link) => ({
+ id: link.id,
+ source: link.source_agent_id,
+ target: link.target_agent_id,
+ }));
+ newNodes = getAutoLayout(newNodes, currentEdges);
+ if (!initialLayoutDone.current) {
+ initialLayoutDone.current = true;
+ setTimeout(() => fitView({ padding: 0.4, duration: 400 }), 50);
+ }
+ }
+ } else if (newAgentIds.length > 0 && linksLoaded) {
+ // Existing positions + some new agents — layout new nodes only
+ const fixedNodes = newNodes.filter((n) => validPositions[n.id]);
+ const floatingNodes = newNodes.filter((n) => !validPositions[n.id]);
+ const currentEdges: Edge[] = links.map((link) => ({
+ id: link.id,
+ source: link.source_agent_id,
+ target: link.target_agent_id,
+ }));
+ const allLaid = getAutoLayout([...fixedNodes, ...floatingNodes], currentEdges);
+ newNodes = newNodes.map((n) => {
+ if (validPositions[n.id]) return n;
+ const laid = allLaid.find((l) => l.id === n.id);
+ return laid ? { ...n, position: laid.position } : n;
+ });
+ }
+
+ setNodes(newNodes);
+ }, [agents, runtimes, activeTaskCounts, slug, loading, workspaceId, linksLoaded, links, fitView]);
+
+ const onNodesChange = useCallback((changes: NodeChange[]) => {
+ setNodes((nds) => applyNodeChanges(changes, nds));
+ }, []);
+
+ const onEdgesChange = useCallback((changes: EdgeChange[]) => {
+ setEdges((eds) => applyEdgeChanges(changes, eds));
+ }, []);
+
+ const onNodeDragStop = useCallback(() => {
+ setNodes((nds) => {
+ savePositions(workspaceId, nds);
+ return nds;
+ });
}, [workspaceId]);
+ const onConnect: OnConnect = useCallback(
+ async (connection: Connection) => {
+ if (!connection.source || !connection.target) return;
+ try {
+ const created = await createAgentLink(
+ {
+ source_agent_id: connection.source,
+ target_agent_id: connection.target,
+ },
+ workspaceId,
+ );
+ if (connection.sourceHandle || connection.targetHandle) {
+ handleMap.current[created.id] = {
+ sourceHandle: connection.sourceHandle ?? "right",
+ targetHandle: connection.targetHandle ?? "target-left",
+ };
+ }
+ setLinks((prev) => [...prev, created]);
+ setShowHint(false);
+ } catch (e) {
+ if (e instanceof ApiError) {
+ if (e.status === 409) toast.error("Link already exists");
+ else if (e.status === 400) toast.error("Can't link an agent to itself");
+ else toast.error("Failed to create link");
+ } else {
+ toast.error("Failed to create link");
+ }
+ }
+ },
+ [workspaceId],
+ );
+
+ const handleSidecarSave = useCallback(
+ async (id: string, instruction: string) => {
+ try {
+ const updated = await updateAgentLink(id, { instruction }, workspaceId);
+ setLinks((prev) => prev.map((l) => (l.id === id ? updated : l)));
+ setSidecarOpen(false);
+ } catch {
+ toast.error("Failed to update link");
+ }
+ },
+ [workspaceId],
+ );
+
+ const handleSidecarDelete = useCallback(
+ async (id: string) => {
+ try {
+ await deleteAgentLink(id, workspaceId);
+ setLinks((prev) => prev.filter((l) => l.id !== id));
+ setSidecarOpen(false);
+ } catch {
+ toast.error("Failed to delete link");
+ }
+ },
+ [workspaceId],
+ );
+
+ const handleResetLayout = useCallback(() => {
+ try {
+ localStorage.removeItem(storageKey(workspaceId));
+ } catch {}
+ const currentEdges: Edge[] = links.map((link) => ({
+ id: link.id,
+ source: link.source_agent_id,
+ target: link.target_agent_id,
+ }));
+ setNodes((prev) => {
+ const laid = getAutoLayout(prev, currentEdges);
+ // Animate by adding a transition style
+ const animated = laid.map((n) => ({
+ ...n,
+ style: { ...n.style, transition: "transform 300ms ease-out" },
+ }));
+ setTimeout(() => {
+ setNodes((nds) =>
+ nds.map((n) => ({
+ ...n,
+ style: { ...n.style, transition: undefined },
+ })),
+ );
+ fitView({ padding: 0.4, duration: 400 });
+ }, 350);
+ return animated;
+ });
+ }, [links, workspaceId, fitView]);
+
+ const onNodeClick = useCallback(
+ (_event: React.MouseEvent, node: Node) => {
+ const nodeData = node.data as unknown as AgentNodeData;
+ router.push(`/w/${slug}/agents/${nodeData.agent.id}`);
+ },
+ [router, slug],
+ );
+
+ const connectionLineStyle = useMemo(
+ () => ({
+ stroke: "var(--color-primary)",
+ strokeWidth: 1.5,
+ strokeDasharray: "6 4",
+ opacity: 0.5,
+ }),
+ [],
+ );
+
+ return (
+ <div className="flex-1 relative">
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={onConnect}
+ onNodeClick={onNodeClick}
+ onNodeDragStop={onNodeDragStop}
+ connectionLineStyle={connectionLineStyle}
+ fitView
+ fitViewOptions={{ padding: 0.4, maxZoom: 1 }}
+ minZoom={0.25}
+ maxZoom={2.5}
+ zoomOnScroll
+ panOnScroll={false}
+ proOptions={{ hideAttribution: true }}
+ >
+ <Background variant={"dots" as any} gap={24} size={1.5} color="var(--color-border)" />
+ </ReactFlow>
+
+ {/* Custom floating toolbar */}
+ <div
+ className="absolute bottom-4 left-4 bg-background/80 backdrop-blur-sm rounded-lg ring-1 ring-foreground/5 p-1 flex gap-0.5 animate-[fade-up_300ms_ease-out_both]"
+ style={{ animationDelay: "200ms" }}
+ >
+ <button
+ type="button"
+ className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
+ onClick={() => zoomIn()}
+ >
+ <ZoomIn className="size-4" />
+ </button>
+ <button
+ type="button"
+ className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
+ onClick={() => zoomOut()}
+ >
+ <ZoomOut className="size-4" />
+ </button>
+ <button
+ type="button"
+ className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
+ onClick={() => fitView({ padding: 0.4, duration: 400 })}
+ >
+ <Maximize2 className="size-4" />
+ </button>
+ <button
+ type="button"
+ className="size-7 rounded-md flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
+ onClick={handleResetLayout}
+ >
+ <RotateCcw className="size-4" />
+ </button>
+ </div>
+
+ {/* No-links hint */}
+ {showHint && (
+ <div className="absolute bottom-14 left-4 text-xs text-muted-foreground bg-background/80 backdrop-blur-sm rounded-md px-3 py-1.5 ring-1 ring-foreground/5">
+ Drag between agent handles to create relationships.
+ </div>
+ )}
+
+ <LinkSidecar
+ open={sidecarOpen}
+ onOpenChange={setSidecarOpen}
+ link={sidecarLink}
+ agents={agents}
+ onSave={handleSidecarSave}
+ onDelete={handleSidecarDelete}
+ />
+ </div>
+ );
+}
+
+function MobileAgentList() {
+ const router = useRouter();
+ const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();
+ const { slug } = useWorkspace();
+
+ if (loading) {
+ return (
+ <div className="flex flex-col gap-1 p-4">
+ {[...Array(4)].map((_, i) => (
+ <div key={i} className="animate-pulse rounded-xl bg-muted h-[60px]" />
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-1 p-4 overflow-y-auto thin-scrollbar">
+ {agents.map((agent) => {
+ const rt = runtimes.find((r) => r.id === agent.runtime_id);
+ const isOnline = rt?.status === "online";
+ return (
+ <div
+ key={agent.id}
+ role="button"
+ tabIndex={0}
+ className="flex items-center w-full rounded-xl px-3 py-2.5 hover:bg-accent/50 active:bg-accent/70 transition-colors cursor-pointer text-left"
+ onClick={() => router.push(`/w/${slug}/agents/${agent.id}`)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ router.push(`/w/${slug}/agents/${agent.id}`);
+ }
+ }}
+ >
+ <AgentPreviewCard
+ agent={agent}
+ isOnline={isOnline}
+ activeTaskCount={activeTaskCounts[agent.id] ?? 0}
+ />
+ </div>
+ );
+ })}
+ </div>
+ );
+}
+
+export default function HomePage() {
+ const router = useRouter();
+ const { agents, runtimes, loading } = useAgentContext();
+ const { slug } = useWorkspace();
+ const isMobile = useIsMobile();
+
if (loading) {
return (
<div className="flex flex-1 items-center justify-center">
@@ -93,37 +520,13 @@ export default function HomePage() {
);
}
- if (overviewLoading || !overview) {
- return (
- <div className="flex-1 overflow-y-auto thin-scrollbar">
- <div className="p-4 lg:p-6 space-y-4">
- <Skeleton className="h-48 rounded-xl" />
- <div className="grid gap-4 lg:grid-cols-2">
- <Skeleton className="h-44 rounded-xl" />
- <Skeleton className="h-44 rounded-xl" />
- </div>
- </div>
- </div>
- );
+ if (isMobile) {
+ return <MobileAgentList />;
}
return (
- <div className="flex-1 min-h-0 overflow-y-auto thin-scrollbar lg:overflow-hidden">
- <div className="flex min-h-full flex-col gap-4 p-4 lg:h-full lg:min-h-[600px] lg:p-6">
- <AgentOverview
- agents={agents}
- runtimes={runtimes}
- activeTaskCounts={activeTaskCounts}
- overview={overview}
- />
- <div className="grid gap-4 lg:grid-cols-2 lg:flex-1 lg:min-h-0 lg:auto-rows-fr">
- <RecentActivity overview={overview} agents={agents} workspaceId={workspaceId} onRefresh={refreshOverview} />
- <CalendarOverview overview={overview} agents={agents} />
- </div>
- <div className="shrink-0">
- <DailyQuote />
- </div>
- </div>
- </div>
+ <ReactFlowProvider>
+ <AgentCanvas />
+ </ReactFlowProvider>
);
}
diff --git a/src/web/src/app/api/agent-links/[id]/route.test.ts b/src/web/src/app/api/agent-links/[id]/route.test.ts
new file mode 100644
index 000000000..9161bd765
--- /dev/null
+++ b/src/web/src/app/api/agent-links/[id]/route.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockUpdate = vi.fn();
+const mockRemove = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agentLink: {
+ update: (...a: unknown[]) => mockUpdate(...a),
+ remove: (...a: unknown[]) => mockRemove(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ agentLinkToResponse: (row: any) => ({
+ id: row.id,
+ workspace_id: row.workspaceId,
+ source_agent_id: row.sourceAgentId,
+ target_agent_id: row.targetAgentId,
+ instruction: row.instruction,
+ created_at: row.createdAt,
+ updated_at: row.updatedAt,
+ }),
+}));
+
+import { PATCH, DELETE } from "./route";
+
+describe("PATCH /api/agent-links/[id]", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("updates instruction", async () => {
+ mockUpdate.mockResolvedValue({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "new instruction",
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-02T00:00:00.000Z",
+ });
+ const req = new NextRequest("http://localhost/api/agent-links/al_1", {
+ method: "PATCH",
+ body: JSON.stringify({ instruction: "new instruction" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await PATCH(req, { params: { id: "al_1" } } as any);
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(body.instruction).toBe("new instruction");
+ });
+
+ it("returns 404 when link not found", async () => {
+ mockUpdate.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/agent-links/al_nope", {
+ method: "PATCH",
+ body: JSON.stringify({ instruction: "test" }),
+ headers: { "Content-Type": "application/json" },
+ });
+ const res = await PATCH(req, { params: { id: "al_nope" } } as any);
+ expect(res.status).toBe(404);
+ });
+});
+
+describe("DELETE /api/agent-links/[id]", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("deletes a link", async () => {
+ mockRemove.mockResolvedValue({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "",
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ });
+ const req = new NextRequest("http://localhost/api/agent-links/al_1", {
+ method: "DELETE",
+ });
+ const res = await DELETE(req, { params: { id: "al_1" } } as any);
+ expect(res.status).toBe(200);
+ });
+
+ it("returns 404 for unknown link", async () => {
+ mockRemove.mockResolvedValue(null);
+ const req = new NextRequest("http://localhost/api/agent-links/al_nope", {
+ method: "DELETE",
+ });
+ const res = await DELETE(req, { params: { id: "al_nope" } } as any);
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.ts
new file mode 100644
index 000000000..ec534b074
--- /dev/null
+++ b/src/web/src/app/api/agent-links/[id]/route.ts
@@ -0,0 +1,44 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries, UpdateAgentLinkRequestSchema } from "@alook/shared";
+import { getDb } from "@/lib/db";
+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";
+
+export const PATCH = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const id = ctx.params?.id;
+ if (!id) return writeError("agent link id is required", 400);
+
+ const [body, err] = await parseBody(req, UpdateAgentLinkRequestSchema);
+ if (err) return err;
+
+ const updated = await queries.agentLink.update(db, id, ws.workspaceId, {
+ instruction: body.instruction,
+ });
+ if (!updated) return writeError("agent link not found", 404);
+
+ return writeJSON(agentLinkToResponse(updated));
+});
+
+export const DELETE = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const id = ctx.params?.id;
+ if (!id) return writeError("agent link id is required", 400);
+
+ const deleted = await queries.agentLink.remove(db, id, ws.workspaceId);
+ if (!deleted) return writeError("agent link not found", 404);
+
+ return writeJSON(agentLinkToResponse(deleted));
+});
diff --git a/src/web/src/app/api/agent-links/route.test.ts b/src/web/src/app/api/agent-links/route.test.ts
new file mode 100644
index 000000000..4eb6777c4
--- /dev/null
+++ b/src/web/src/app/api/agent-links/route.test.ts
@@ -0,0 +1,147 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetAgent = vi.fn();
+const mockListByWorkspace = vi.fn();
+const mockCreate = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
+ return {
+ ...actual,
+ queries: {
+ agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },
+ agentLink: {
+ listByWorkspace: (...a: unknown[]) => mockListByWorkspace(...a),
+ create: (...a: unknown[]) => mockCreate(...a),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: (handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ },
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ agentLinkToResponse: (row: any) => ({
+ id: row.id,
+ workspace_id: row.workspaceId,
+ source_agent_id: row.sourceAgentId,
+ target_agent_id: row.targetAgentId,
+ instruction: row.instruction,
+ created_at: row.createdAt,
+ updated_at: row.updatedAt,
+ }),
+}));
+
+import { GET, POST } from "./route";
+
+describe("GET /api/agent-links", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("lists links scoped to workspace", async () => {
+ mockListByWorkspace.mockResolvedValue([
+ {
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "collaborate",
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ },
+ ]);
+ const req = new NextRequest("http://localhost/api/agent-links?workspace_id=ws1");
+ const res = await GET(req, {} as any);
+ const body = await res.json();
+ expect(res.status).toBe(200);
+ expect(body).toHaveLength(1);
+ expect(body[0].id).toBe("al_1");
+ expect(body[0].source_agent_id).toBe("ag_a");
+ });
+});
+
+describe("POST /api/agent-links", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ async function post(body: unknown) {
+ const req = new NextRequest("http://localhost/api/agent-links", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+ return POST(req, {} as any);
+ }
+
+ it("creates a link between two agents", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_a" });
+ mockCreate.mockImplementation((_db: any, data: any) => ({
+ id: "al_1",
+ ...data,
+ createdAt: "2026-04-01T00:00:00.000Z",
+ updatedAt: "2026-04-01T00:00:00.000Z",
+ }));
+ const res = await post({
+ source_agent_id: "ag_a",
+ target_agent_id: "ag_b",
+ instruction: "share data",
+ });
+ expect(res.status).toBe(201);
+ const body = await res.json();
+ expect(body.id).toBe("al_1");
+ });
+
+ it("rejects self-link", async () => {
+ const res = await post({
+ source_agent_id: "ag_a",
+ target_agent_id: "ag_a",
+ });
+ expect(res.status).toBe(400);
+ const body = await res.json();
+ expect(body.error).toContain("itself");
+ });
+
+ it("returns 404 when source agent not found", async () => {
+ mockGetAgent.mockResolvedValueOnce(null);
+ const res = await post({
+ source_agent_id: "ag_nope",
+ target_agent_id: "ag_b",
+ });
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 404 when target agent not found", async () => {
+ mockGetAgent.mockResolvedValueOnce({ id: "ag_a" }).mockResolvedValueOnce(null);
+ const res = await post({
+ source_agent_id: "ag_a",
+ target_agent_id: "ag_nope",
+ });
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 409 for duplicate link", async () => {
+ mockGetAgent.mockResolvedValue({ id: "ag_a" });
+ const uniqueErr = new Error("UNIQUE constraint failed");
+ (uniqueErr as any).code = "SQLITE_CONSTRAINT_UNIQUE";
+ mockCreate.mockRejectedValue(uniqueErr);
+ const res = await post({
+ source_agent_id: "ag_a",
+ target_agent_id: "ag_b",
+ });
+ expect(res.status).toBe(409);
+ });
+});
diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.ts
new file mode 100644
index 000000000..70e59c524
--- /dev/null
+++ b/src/web/src/app/api/agent-links/route.ts
@@ -0,0 +1,60 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import {
+ queries,
+ CreateAgentLinkRequestSchema,
+ isUniqueConstraintError,
+} from "@alook/shared";
+import { getDb } from "@/lib/db";
+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";
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId);
+ return writeJSON(rows.map(agentLinkToResponse));
+});
+
+export const POST = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const [body, err] = await parseBody(req, CreateAgentLinkRequestSchema);
+ if (err) return err;
+
+ if (body.source_agent_id === body.target_agent_id) {
+ return writeError("cannot link an agent to itself", 400);
+ }
+
+ const [sourceAgent, targetAgent] = await Promise.all([
+ queries.agent.getAgent(db, body.source_agent_id, ws.workspaceId, ctx.userId),
+ queries.agent.getAgent(db, body.target_agent_id, ws.workspaceId, ctx.userId),
+ ]);
+ if (!sourceAgent) return writeError("source agent not found in workspace", 404);
+ if (!targetAgent) return writeError("target agent not found in workspace", 404);
+
+ try {
+ const created = await queries.agentLink.create(db, {
+ workspaceId: ws.workspaceId,
+ sourceAgentId: body.source_agent_id,
+ targetAgentId: body.target_agent_id,
+ instruction: body.instruction,
+ });
+ return writeJSON(agentLinkToResponse(created), 201);
+ } catch (e) {
+ if (isUniqueConstraintError(e)) {
+ return writeError("link already exists between these agents", 409);
+ }
+ throw e;
+ }
+});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
index 9d9f01da0..0c1be706c 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts
@@ -62,6 +62,9 @@ vi.mock("@alook/shared", async () => {
listScheduledMeetings: (...args: unknown[]) => mockListScheduledMeetings(...args),
claimMeetingSession: (...args: unknown[]) => mockClaimMeetingSession(...args),
},
+ agentLink: {
+ getColleaguesForAgent: vi.fn().mockResolvedValue([]),
+ },
},
};
});
@@ -205,6 +208,7 @@ describe("POST /api/daemon/tasks/poll", () => {
email_addresses: [],
user_email: "[email protected]",
user_name: null,
+ colleagues: [],
});
});
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
index 8f854ee49..d747556ca 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries, PollRequestSchema, semverGte, type FileRequestItem, type PollMeetingItem } from "@alook/shared";
+import { queries, PollRequestSchema, semverGte, toAlookAddress, type FileRequestItem, type PollMeetingItem } from "@alook/shared";
import { getDb } from "@/lib/db"
import { withAuth } from "@/lib/middleware/auth";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
@@ -141,6 +141,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
}
+ // Resolve colleagues for agent
+ let colleagues: { name: string; email: string; description: string; instruction: string }[] = [];
+ if (agent) {
+ try {
+ const raw = await queries.agentLink.getColleaguesForAgent(db, agent.id, task.workspaceId);
+ colleagues = raw.map((c) => ({
+ name: c.name,
+ email: c.emailHandle ? toAlookAddress(c.emailHandle) : "",
+ description: c.description,
+ instruction: c.instruction,
+ }));
+ } catch {}
+ }
+
tasks.push({
...taskToResponse(task),
sender,
@@ -153,6 +167,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
email_addresses: emailAddresses,
user_email: ctx.email || null,
user_name: ownerName,
+ colleagues,
}
: null,
});
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 04cdea5c0..e8505a6c3 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -64,7 +64,7 @@ function MentionHighlight(props: Record<string, unknown> & { children?: React.Re
<PopoverTrigger openOnHover delay={300} nativeButton={false} render={<span className="mention-highlight cursor-pointer" />}>
{children}
</PopoverTrigger>
- <PopoverContent side="top" className="w-70">
+ <PopoverContent side="top" className="w-fit max-w-80">
<AgentPreviewCard agent={agent} />
</PopoverContent>
</Popover>
diff --git a/src/web/src/components/agent-preview-card.tsx b/src/web/src/components/agent-preview-card.tsx
index 75243445d..b9144c0cb 100644
--- a/src/web/src/components/agent-preview-card.tsx
+++ b/src/web/src/components/agent-preview-card.tsx
@@ -5,10 +5,24 @@ import type { Agent } from "@alook/shared";
import { Check, Copy } from "lucide-react";
import { toast } from "sonner";
import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
+import { AgentStatusBadge } from "@/components/agent-status-badge";
-export function AgentPreviewCard({ agent }: { agent: Agent }) {
+interface AgentPreviewCardProps {
+ agent: Agent;
+ isOnline?: boolean;
+ activeTaskCount?: number;
+ variant?: "default" | "compact";
+}
+
+export function AgentPreviewCard({
+ agent,
+ isOnline,
+ activeTaskCount,
+ variant = "default",
+}: AgentPreviewCardProps) {
const [copied, setCopied] = useState(false);
const email = agent.email_handle ? `${agent.email_handle}@alook.ai` : null;
+ const isCompact = variant === "compact";
const handleCopy = useCallback(async () => {
if (!email) return;
@@ -22,6 +36,41 @@ export function AgentPreviewCard({ agent }: { agent: Agent }) {
}
}, [email]);
+ if (isCompact) {
+ return (
+ <div className="flex items-center gap-2 p-0">
+ {agent.avatar_url ? (
+ <img
+ src={agent.avatar_url}
+ alt={agent.name}
+ className="size-8 rounded-xl object-cover shrink-0"
+ />
+ ) : (
+ <div className="flex items-center justify-center size-8 rounded-xl bg-secondary text-secondary-foreground text-xs font-medium shrink-0">
+ {agent.name.charAt(0).toUpperCase()}
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <p className="text-sm font-medium truncate max-w-[140px]">{agent.name}</p>
+ {email && (
+ <span className="text-xs text-muted-foreground truncate">{email}</span>
+ )}
+ </div>
+ {isOnline !== undefined && (
+ <div className="pointer-events-none mt-0.5">
+ <AgentStatusBadge
+ isOnline={isOnline}
+ taskCount={activeTaskCount ?? 0}
+ agentId={agent.id}
+ />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+ }
+
return (
<div className="flex flex-col gap-2.5 p-1">
<div className="flex items-start gap-3">
@@ -37,13 +86,22 @@ export function AgentPreviewCard({ agent }: { agent: Agent }) {
);
})()}
<div className="min-w-0 flex-1">
- <p className="text-sm font-medium truncate">{agent.name}</p>
+ <div className="flex items-center gap-1.5">
+ <p className="text-sm font-medium truncate">{agent.name}</p>
+ {isOnline !== undefined && (
+ <AgentStatusBadge
+ isOnline={isOnline}
+ taskCount={activeTaskCount ?? 0}
+ agentId={agent.id}
+ />
+ )}
+ </div>
{email && (
<div className="flex items-center gap-1 mt-0.5">
<span className="text-xs text-muted-foreground truncate">{email}</span>
<button
type="button"
- onClick={handleCopy}
+ onClick={(e) => { e.stopPropagation(); handleCopy(); }}
className="shrink-0 p-0.5 rounded-sm text-muted-foreground/60 hover:text-foreground transition-colors cursor-pointer"
>
{copied ? (
diff --git a/src/web/src/components/agent-status-badge.tsx b/src/web/src/components/agent-status-badge.tsx
index ae527b13f..afbd3a6e4 100644
--- a/src/web/src/components/agent-status-badge.tsx
+++ b/src/web/src/components/agent-status-badge.tsx
@@ -102,6 +102,7 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa
<button
type="button"
className={cn(badgeVariants({ variant: "outline" }), badgeBase)}
+ onClick={(e: React.MouseEvent) => e.stopPropagation()}
/>
}
>
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index 372445924..d8a31af60 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -94,7 +94,7 @@ function AgentSidebarButton({
)}
</ContextMenuContent>
</ContextMenu>
- <PopoverContent side="right" className="w-70">
+ <PopoverContent side="right" className="w-fit max-w-80">
<AgentPreviewCard agent={agent} />
</PopoverContent>
</Popover>
diff --git a/src/web/src/components/calendar/calendar-event-sheet.tsx b/src/web/src/components/calendar/calendar-event-sheet.tsx
index dcc3744a1..7f4fdea17 100644
--- a/src/web/src/components/calendar/calendar-event-sheet.tsx
+++ b/src/web/src/components/calendar/calendar-event-sheet.tsx
@@ -693,6 +693,7 @@ export function CalendarEventSheet({
className="markdown"
minHeight={mode === "edit" ? "10rem" : "8rem"}
variant="seamless"
+ agents={agents}
/>
</div>
);
diff --git a/src/web/src/components/canvas/agent-node.tsx b/src/web/src/components/canvas/agent-node.tsx
new file mode 100644
index 000000000..784fddc8d
--- /dev/null
+++ b/src/web/src/components/canvas/agent-node.tsx
@@ -0,0 +1,57 @@
+"use client";
+
+import { memo } from "react";
+import { Handle, Position, type NodeProps } from "@xyflow/react";
+import type { Agent, AgentRuntime } from "@alook/shared";
+import { AgentPreviewCard } from "@/components/agent-preview-card";
+import { cn } from "@/lib/utils";
+
+export interface AgentNodeData {
+ agent: Agent;
+ runtimes: AgentRuntime[];
+ activeTaskCount: number;
+ slug: string;
+ index: number;
+ [key: string]: unknown;
+}
+
+const handleClass =
+ "!opacity-0 !size-3 !bg-muted-foreground/40 !rounded-full group-hover:!opacity-100 hover:!bg-primary hover:!scale-125 !transition-all !border-none";
+
+function AgentNodeInner({ data, selected, dragging }: NodeProps) {
+ const { agent, runtimes, activeTaskCount, index } = data as unknown as AgentNodeData;
+
+ const rt = runtimes.find((r: AgentRuntime) => r.id === agent.runtime_id);
+ const isOnline = rt?.status === "online";
+
+ return (
+ <div
+ className={cn(
+ "bg-background rounded-xl ring-1 ring-foreground/8 shadow-sm transition-all 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",
+ )}
+ style={{ animationDelay: `${index * 60}ms` }}
+ >
+ <Handle type="source" id="right" position={Position.Right} className={handleClass} />
+ <Handle type="source" id="left" position={Position.Left} className={handleClass} />
+ <Handle type="source" id="top" position={Position.Top} className={handleClass} />
+ <Handle type="source" id="bottom" position={Position.Bottom} className={handleClass} />
+
+ <Handle type="target" id="target-right" position={Position.Right} className={handleClass} />
+ <Handle type="target" id="target-left" position={Position.Left} className={handleClass} />
+ <Handle type="target" id="target-top" position={Position.Top} className={handleClass} />
+ <Handle type="target" id="target-bottom" position={Position.Bottom} className={handleClass} />
+
+ <AgentPreviewCard
+ agent={agent}
+ isOnline={isOnline}
+ activeTaskCount={activeTaskCount}
+ variant="compact"
+ />
+ </div>
+ );
+}
+
+export const AgentNode = memo(AgentNodeInner);
diff --git a/src/web/src/components/canvas/auto-layout.test.ts b/src/web/src/components/canvas/auto-layout.test.ts
new file mode 100644
index 000000000..ff463af02
--- /dev/null
+++ b/src/web/src/components/canvas/auto-layout.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect } from "vitest";
+import type { Node, Edge } from "@xyflow/react";
+import { getAutoLayout } from "./auto-layout";
+
+function makeNodes(count: number): Node[] {
+ return Array.from({ length: count }, (_, i) => ({
+ id: `n${i}`,
+ type: "agent",
+ position: { x: 0, y: 0 },
+ data: {},
+ }));
+}
+
+describe("getAutoLayout", () => {
+ it("assigns valid positions with no overlaps", () => {
+ const nodes = makeNodes(4);
+ const edges: Edge[] = [
+ { id: "e1", source: "n0", target: "n1" },
+ { id: "e2", source: "n1", target: "n2" },
+ { id: "e3", source: "n2", target: "n3" },
+ ];
+ const laid = getAutoLayout(nodes, edges);
+ expect(laid).toHaveLength(4);
+ for (const n of laid) {
+ expect(typeof n.position.x).toBe("number");
+ expect(typeof n.position.y).toBe("number");
+ expect(Number.isFinite(n.position.x)).toBe(true);
+ expect(Number.isFinite(n.position.y)).toBe(true);
+ }
+ // No two nodes should have the same exact position
+ const posKeys = new Set(laid.map((n) => `${n.position.x},${n.position.y}`));
+ expect(posKeys.size).toBe(4);
+ });
+
+ it("positions nodes in a row when there are no edges", () => {
+ const nodes = makeNodes(3);
+ const laid = getAutoLayout(nodes, []);
+ expect(laid).toHaveLength(3);
+ // All nodes should have valid positions, not stacked at origin
+ const posKeys = new Set(laid.map((n) => `${n.position.x},${n.position.y}`));
+ expect(posKeys.size).toBeGreaterThanOrEqual(1);
+ for (const n of laid) {
+ expect(Number.isFinite(n.position.x)).toBe(true);
+ expect(Number.isFinite(n.position.y)).toBe(true);
+ }
+ });
+});
diff --git a/src/web/src/components/canvas/auto-layout.ts b/src/web/src/components/canvas/auto-layout.ts
new file mode 100644
index 000000000..9922b15cb
--- /dev/null
+++ b/src/web/src/components/canvas/auto-layout.ts
@@ -0,0 +1,41 @@
+import dagre from "@dagrejs/dagre";
+import type { Node, Edge } from "@xyflow/react";
+
+const NODE_WIDTH = 280;
+const NODE_HEIGHT = 100;
+
+export function getAutoLayout(
+ nodes: Node[],
+ edges: Edge[],
+ direction: "LR" | "TB" = "LR",
+): Node[] {
+ const g = new dagre.graphlib.Graph();
+ g.setDefaultEdgeLabel(() => ({}));
+ g.setGraph({
+ rankdir: direction,
+ nodesep: 80,
+ ranksep: 180,
+ marginx: 40,
+ marginy: 40,
+ });
+
+ for (const node of nodes) {
+ g.setNode(node.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
+ }
+ for (const edge of edges) {
+ g.setEdge(edge.source, edge.target);
+ }
+
+ dagre.layout(g);
+
+ return nodes.map((node) => {
+ const pos = g.node(node.id);
+ return {
+ ...node,
+ position: {
+ x: pos.x - NODE_WIDTH / 2,
+ y: pos.y - NODE_HEIGHT / 2,
+ },
+ };
+ });
+}
diff --git a/src/web/src/components/canvas/link-edge.tsx b/src/web/src/components/canvas/link-edge.tsx
new file mode 100644
index 000000000..1e612bd10
--- /dev/null
+++ b/src/web/src/components/canvas/link-edge.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import { memo, useCallback, useState } from "react";
+import {
+ getSmoothStepPath,
+ EdgeLabelRenderer,
+ type EdgeProps,
+} from "@xyflow/react";
+
+interface LinkEdgeData {
+ instruction?: string;
+ onEdgeClick?: (edgeId: string) => void;
+ [key: string]: unknown;
+}
+
+function LinkEdgeInner({
+ id,
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ selected,
+ data,
+}: EdgeProps) {
+ const { instruction, onEdgeClick } = (data ?? {}) as LinkEdgeData;
+ const [hovered, setHovered] = useState(false);
+
+ const [edgePath, labelX, labelY] = getSmoothStepPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ borderRadius: 16,
+ });
+
+ const strokeColor = selected
+ ? "var(--color-primary)"
+ : hovered
+ ? "var(--color-muted-foreground)"
+ : "var(--color-border)";
+ const strokeWidth = selected || hovered ? 2 : 1.5;
+
+ const handleLabelClick = useCallback((e: React.MouseEvent) => {
+ e.stopPropagation();
+ onEdgeClick?.(id);
+ }, [onEdgeClick, id]);
+
+ const hasInstruction = !!instruction && instruction !== "" && instruction !== "<p></p>";
+
+ return (
+ <>
+ <path
+ d={edgePath}
+ fill="none"
+ stroke={strokeColor}
+ strokeWidth={strokeWidth}
+ style={{ transition: "stroke 150ms, stroke-width 150ms" }}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ />
+ <EdgeLabelRenderer>
+ <button
+ type="button"
+ style={{
+ position: "absolute",
+ transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,
+ pointerEvents: "auto",
+ }}
+ className={`text-[11px] leading-tight bg-background/90 px-2 py-0.5 rounded-md truncate cursor-pointer transition-colors italic ${
+ hovered ? "text-muted-foreground" : "text-muted-foreground/40"
+ }`}
+ onClick={handleLabelClick}
+ onMouseEnter={() => setHovered(true)}
+ onMouseLeave={() => setHovered(false)}
+ >
+ {hasInstruction ? "edit relationship" : "define relationship"}
+ </button>
+ </EdgeLabelRenderer>
+ </>
+ );
+}
+
+export const LinkEdge = memo(LinkEdgeInner);
diff --git a/src/web/src/components/canvas/link-sidecar.tsx b/src/web/src/components/canvas/link-sidecar.tsx
new file mode 100644
index 000000000..0b9553965
--- /dev/null
+++ b/src/web/src/components/canvas/link-sidecar.tsx
@@ -0,0 +1,160 @@
+"use client";
+
+import { useState, useEffect, useCallback } from "react";
+import type { Agent, AgentLink } from "@alook/shared";
+import {
+ Sheet,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+ SheetFooter,
+} from "@/components/ui/sheet";
+import { Button } from "@/components/ui/button";
+import { MarkdownEditor } from "@/components/ui/markdown-editor";
+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
+import { Trash2 } from "lucide-react";
+
+interface LinkSidecarProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ link: AgentLink | null;
+ agents: Agent[];
+ onSave: (id: string, instruction: string) => void;
+ onDelete: (id: string) => void;
+}
+
+export function LinkSidecar({
+ open,
+ onOpenChange,
+ link,
+ agents,
+ onSave,
+ onDelete,
+}: LinkSidecarProps) {
+ const [instruction, setInstruction] = useState("");
+
+ const sourceAgent = agents.find(
+ (a) => a.id === link?.source_agent_id,
+ );
+ const targetAgent = agents.find(
+ (a) => a.id === link?.target_agent_id,
+ );
+
+ useEffect(() => {
+ if (link) setInstruction(link.instruction);
+ }, [link]);
+
+ const isDirty = instruction !== (link?.instruction ?? "");
+
+ const handleSave = useCallback(() => {
+ if (link && isDirty) {
+ onSave(link.id, instruction);
+ }
+ }, [link, isDirty, instruction, onSave]);
+
+ const handleDelete = useCallback(() => {
+ if (link) onDelete(link.id);
+ }, [link, onDelete]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.shiftKey && e.key === "Enter") {
+ e.preventDefault();
+ handleSave();
+ }
+ },
+ [handleSave],
+ );
+
+ const renderAvatar = (agent: Agent | undefined) => {
+ if (!agent) return null;
+ if (agent.avatar_url) {
+ return (
+ <img
+ src={agent.avatar_url}
+ alt={agent.name}
+ className="size-8 rounded-xl object-cover shrink-0"
+ />
+ );
+ }
+ return (
+ <div className="flex items-center justify-center size-8 rounded-xl bg-secondary text-secondary-foreground text-xs font-medium shrink-0">
+ {agent.name.charAt(0).toUpperCase()}
+ </div>
+ );
+ };
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ side="right"
+ showCloseButton={false}
+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border data-[side=right]:sm:max-w-md"
+ onKeyDownCapture={handleKeyDown}
+ >
+ <SheetTitle className="sr-only">
+ Edit relationship between {sourceAgent?.name} and {targetAgent?.name}
+ </SheetTitle>
+
+ <SheetHeader className="border-b px-5 py-4">
+ <div className="flex items-center gap-2">
+ <div className="flex items-center">
+ {renderAvatar(sourceAgent)}
+ <div className="-ml-2 ring-2 ring-background rounded-xl">
+ {renderAvatar(targetAgent)}
+ </div>
+ </div>
+ </div>
+ <p className="text-sm font-medium">
+ {sourceAgent?.name ?? "Agent"} and {targetAgent?.name ?? "Agent"}
+ </p>
+ <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-2">
+ Collaboration Instructions
+ </p>
+ </SheetHeader>
+
+ <div className="flex-1 overflow-y-auto thin-scrollbar px-5 py-4">
+ <MarkdownEditor
+ variant="seamless"
+ placeholder="Describe how these agents should collaborate. This instruction is shared with both agents when they receive tasks."
+ value={instruction}
+ onChange={setInstruction}
+ minHeight="12rem"
+ agents={agents}
+ />
+ </div>
+
+ <SheetFooter className="border-t bg-muted/50 px-5 py-3 flex-row items-center justify-between">
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className="text-destructive hover:text-destructive hover:bg-destructive/10"
+ onClick={handleDelete}
+ />
+ }
+ >
+ <Trash2 className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent>Remove connection</TooltipContent>
+ </Tooltip>
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ onClick={handleSave}
+ disabled={!isDirty}
+ className={!isDirty ? "opacity-50 pointer-events-none" : ""}
+ >
+ Save
+ <span className="text-[10px] opacity-50 ml-1">⇧ ⏎</span>
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsx
index 22eed0481..c625dbb43 100644
--- a/src/web/src/components/ui/markdown-editor.tsx
+++ b/src/web/src/components/ui/markdown-editor.tsx
@@ -1,12 +1,15 @@
"use client";
-import { useEffect } from "react";
+import { useEffect, useState, useCallback, useRef } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
+import Mention from "@tiptap/extension-mention";
import { Markdown } from "@tiptap/markdown";
import { cn } from "@/lib/utils";
import { isEmptyHtml } from "@alook/shared";
+import type { Agent } from "@alook/shared";
+import { createPortal } from "react-dom";
export { isEmptyHtml };
@@ -17,10 +20,9 @@ export interface MarkdownEditorProps {
className?: string;
minHeight?: number | string;
autoFocus?: boolean;
- /** `default` is framed (border + focus ring); `seamless` blends with the parent. */
variant?: "default" | "seamless";
- /** `html` (default) — value/onChange use HTML. `markdown` — value/onChange use Markdown text. */
contentType?: "html" | "markdown";
+ agents?: Agent[];
}
function normalize(html: string | null | undefined): string {
@@ -28,6 +30,141 @@ function normalize(html: string | null | undefined): string {
return isEmptyHtml(html) ? "" : html.trim();
}
+interface PopupState {
+ items: Agent[];
+ selectedIndex: number;
+ command: ((props: { id: string; label: string }) => void) | null;
+}
+
+function MentionList({
+ state,
+ anchorEl,
+}: {
+ state: PopupState;
+ anchorEl: HTMLElement | null;
+}) {
+ const listRef = useRef<HTMLDivElement>(null);
+ const { items, selectedIndex, command } = state;
+
+ useEffect(() => {
+ if (!listRef.current) return;
+ const el = listRef.current.children[selectedIndex] as HTMLElement | undefined;
+ el?.scrollIntoView({ block: "nearest" });
+ }, [selectedIndex]);
+
+ if (!anchorEl || items.length === 0 || !command) return null;
+
+ const rect = anchorEl.getBoundingClientRect();
+
+ return createPortal(
+ <div
+ className="fixed z-[100] w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"
+ style={{ top: rect.top - 4, left: rect.left, transform: "translateY(-100%)" }}
+ >
+ <div ref={listRef} className="max-h-[200px] overflow-y-auto py-1 thin-scrollbar">
+ {items.map((agent, i) => (
+ <button
+ key={agent.id}
+ type="button"
+ className={cn(
+ "flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm transition-colors",
+ i === selectedIndex ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",
+ )}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ command({ id: agent.id, label: agent.name });
+ }}
+ >
+ <span className="truncate font-medium">{agent.name}</span>
+ {agent.email_handle && (
+ <span className="truncate text-xs text-muted-foreground">
+ {agent.email_handle}@alook.ai
+ </span>
+ )}
+ </button>
+ ))}
+ </div>
+ </div>,
+ document.body,
+ );
+}
+
+function useMentionSuggestion(agents: Agent[] | undefined) {
+ const [popup, setPopup] = useState<PopupState>({ items: [], selectedIndex: 0, command: null });
+ const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
+ const popupRef = useRef(popup);
+ popupRef.current = popup;
+
+ const mentionExt = agents && agents.length > 0
+ ? Mention.configure({
+ HTMLAttributes: { class: "mention-highlight" },
+ renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`,
+ suggestion: {
+ char: "@",
+ items: ({ query }: { query: string }) => {
+ if (!agents) return [];
+ if (!query) return agents.slice(0, 20);
+ const q = query.toLowerCase();
+ const sw: Agent[] = [];
+ const inc: Agent[] = [];
+ for (const a of agents) {
+ const n = a.name.toLowerCase();
+ if (n.startsWith(q)) sw.push(a);
+ else if (n.includes(q)) inc.push(a);
+ }
+ return [...sw, ...inc].slice(0, 20);
+ },
+ render: () => ({
+ onStart: (props: any) => {
+ setAnchorEl(props.decorationNode ?? null);
+ setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
+ },
+ onUpdate: (props: any) => {
+ setAnchorEl(props.decorationNode ?? null);
+ setPopup({ items: props.items ?? [], selectedIndex: 0, command: props.command });
+ },
+ onKeyDown: ({ event }: { event: KeyboardEvent }) => {
+ const cur = popupRef.current;
+ if (cur.items.length === 0) return false;
+
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setPopup({ ...cur, selectedIndex: (cur.selectedIndex + 1) % cur.items.length });
+ return true;
+ }
+ if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setPopup({
+ ...cur,
+ selectedIndex: (cur.selectedIndex - 1 + cur.items.length) % cur.items.length,
+ });
+ return true;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ const agent = cur.items[cur.selectedIndex];
+ if (agent && cur.command) cur.command({ id: agent.id, label: agent.name });
+ setPopup({ items: [], selectedIndex: 0, command: null });
+ return true;
+ }
+ if (event.key === "Escape") {
+ setPopup({ items: [], selectedIndex: 0, command: null });
+ return true;
+ }
+ return false;
+ },
+ onExit: () => {
+ setPopup({ items: [], selectedIndex: 0, command: null });
+ setAnchorEl(null);
+ },
+ }),
+ },
+ })
+ : null;
+
+ return { mentionExt, popup, anchorEl };
+}
+
export function MarkdownEditor({
value,
onChange,
@@ -37,6 +174,7 @@ export function MarkdownEditor({
autoFocus,
variant = "default",
contentType = "html",
+ agents,
}: MarkdownEditorProps) {
const isMd = contentType === "markdown";
@@ -48,6 +186,8 @@ export function MarkdownEditor({
? "markdown text-sm max-w-none focus:outline-none px-0 py-1"
: "markdown text-sm max-w-none focus:outline-none px-3 py-2";
+ const { mentionExt, popup, anchorEl } = useMentionSuggestion(agents);
+
const editor = useEditor({
immediatelyRender: false,
content: value || undefined,
@@ -56,6 +196,7 @@ export function MarkdownEditor({
StarterKit,
Placeholder.configure({ placeholder: placeholder ?? "" }),
...(isMd ? [Markdown] : []),
+ ...(mentionExt ? [mentionExt] : []),
],
editorProps: {
attributes: {
@@ -93,6 +234,9 @@ export function MarkdownEditor({
return (
<div className={cn(containerClass, className)}>
<EditorContent editor={editor} />
+ {agents && agents.length > 0 && (
+ <MentionList state={popup} anchorEl={anchorEl} />
+ )}
</div>
);
}
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 7dae46486..9ef3b6784 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -1,14 +1,17 @@
import type {
Agent,
AgentEmailAccount,
+ AgentLink,
AgentRuntime,
Artifact,
CalendarEvent,
Channel,
Conversation,
+ CreateAgentLinkRequest,
CreateAgentRequest,
CreateCalendarEventRequest,
CreateEmailAccountRequest,
+ UpdateAgentLinkRequest,
UpdateCalendarEventRequest,
UpdateEmailAccountRequest,
DeleteCalendarEventRequest,
@@ -600,6 +603,27 @@ export const removeWhitelistEmail = (agentId: string, whitelistId: string, works
method: "DELETE",
});
+// Agent Links
+export const listAgentLinks = (workspaceId: string) =>
+ apiFetch<AgentLink[]>(`/api/agent-links${wsQuery(workspaceId)}`);
+
+export const createAgentLink = (req: CreateAgentLinkRequest, workspaceId: string) =>
+ apiFetch<AgentLink>(`/api/agent-links${wsQuery(workspaceId)}`, {
+ method: "POST",
+ body: JSON.stringify(req),
+ });
+
+export const updateAgentLink = (id: string, req: UpdateAgentLinkRequest, workspaceId: string) =>
+ apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify(req),
+ });
+
+export const deleteAgentLink = (id: string, workspaceId: string) =>
+ apiFetch<AgentLink>(`/api/agent-links/${id}${wsQuery(workspaceId)}`, {
+ method: "DELETE",
+ });
+
// Email Accounts
export const listEmailAccounts = (agentId: string, workspaceId: string) =>
apiFetch<AgentEmailAccount[]>(`/api/agents/${agentId}/email-accounts${wsQuery(workspaceId)}`);
diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.ts
index 1196fdd11..2bf4632b0 100644
--- a/src/web/src/lib/api/responses.test.ts
+++ b/src/web/src/lib/api/responses.test.ts
@@ -3,6 +3,7 @@ import {
userToResponse,
workspaceToResponse,
agentToResponse,
+ agentLinkToResponse,
taskToResponse,
conversationToResponse,
channelToResponse,
@@ -503,6 +504,29 @@ describe("calendarEventToResponse", () => {
});
});
+describe("agentLinkToResponse", () => {
+ it("maps camelCase Drizzle row to snake_case API response", () => {
+ const res = agentLinkToResponse({
+ id: "al_1",
+ workspaceId: "ws1",
+ sourceAgentId: "ag_a",
+ targetAgentId: "ag_b",
+ instruction: "collaborate closely",
+ createdAt: ts,
+ updatedAt: ts,
+ });
+ expect(res).toEqual({
+ id: "al_1",
+ workspace_id: "ws1",
+ source_agent_id: "ag_a",
+ target_agent_id: "ag_b",
+ instruction: "collaborate closely",
+ created_at: tsFormatted,
+ updated_at: tsFormatted,
+ });
+ });
+});
+
describe("emailToResponse", () => {
it("maps DB fields to API response format", () => {
const res = emailToResponse({
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index 76b05c4fb..3050312be 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -222,6 +222,18 @@ export function meetingToResponse(m: any) {
};
}
+export function agentLinkToResponse(row: any) {
+ return {
+ id: row.id,
+ workspace_id: row.workspaceId,
+ source_agent_id: row.sourceAgentId,
+ target_agent_id: row.targetAgentId,
+ instruction: row.instruction,
+ created_at: formatTimestamp(row.createdAt),
+ updated_at: formatTimestamp(row.updatedAt),
+ };
+}
+
export function calendarEventToResponse(e: any) {
const scheduled = formatTimestamp(e.scheduledAt);
const occurrence = e.occurrenceAt ? formatTimestamp(e.occurrenceAt) : scheduled;