Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add template JSON endpoint and workspace init CLI command (#221)
Gener835777f4d249
diff --git a/src/cli/commands/workspace.test.ts b/src/cli/commands/workspace.test.tsnew file mode 100644index 000000000..4bfe75f51--- /dev/null+++ b/src/cli/commands/workspace.test.ts@@ -0,0 +1,232 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { mkdirSync, writeFileSync, rmSync } from "fs";+import { join } from "path";++const { getJSONMock, postJSONMock } = vi.hoisted(() => ({+ getJSONMock: vi.fn(),+ postJSONMock: vi.fn(),+}));++vi.mock("../lib/client.js", () => ({+ APIClient: class {+ getJSON(...a: unknown[]) { return getJSONMock(...a); }+ postJSON(...a: unknown[]) { return postJSONMock(...a); }+ },+}));++vi.mock("../lib/resolve-client.js", () => ({+ resolveClientOpts: vi.fn(() => ({+ serverUrl: "http://localhost:3000",+ token: "test-token",+ workspaceId: "ws_test",+ })),+}));++import { workspaceCommand } from "./workspace";++const TMP_DIR = "/tmp/alook-workspace-test";++describe("workspace init", () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let consoleErrSpy: ReturnType<typeof vi.spyOn>;+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;+ let mockExit: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ mkdirSync(TMP_DIR, { recursive: true });+ consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ mockExit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); });+ });++ afterEach(() => {+ rmSync(TMP_DIR, { recursive: true, force: true });+ consoleSpy.mockRestore();+ consoleErrSpy.mockRestore();+ consoleWarnSpy.mockRestore();+ mockExit.mockRestore();+ });++ function writeJson(filename: string, data: unknown) {+ const path = join(TMP_DIR, filename);+ writeFileSync(path, JSON.stringify(data));+ return path;+ }++ async function runInit(args: string[]) {+ const cmd = workspaceCommand();+ await cmd.parseAsync(["node", "workspace", "init", ...args]);+ }++ it("reads local JSON file and creates workspace", async () => {+ const jsonPath = writeJson("valid.json", {+ name: "Test WS",+ members: [+ { role: "leader", instructions: "You lead" },+ { role: "engineer", instructions: "You code", relationship: { leaderSees: "delegate", memberSees: "report" } },+ ],+ });++ getJSONMock+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes+ .mockResolvedValueOnce([]); // agents (empty = no existing agents)++ postJSONMock.mockResolvedValueOnce({+ studio: { name: "Test WS" },+ workspace: { id: "ws_test", name: "Test WS" },+ agents: [+ { id: "ag1", name: "Alice", email_handle: "alice" },+ { id: "ag2", name: "Bob", email_handle: "bob" },+ ],+ links: [],+ });++ await runInit(["--json-file", jsonPath]);++ expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({+ name: "Test WS",+ members: expect.arrayContaining([+ expect.objectContaining({ role: "leader", runtime_id: "rt1" }),+ ]),+ }));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("[email protected]"));+ });++ it("errors when JSON file does not exist", async () => {+ await expect(runInit(["--json-file", "/tmp/nonexistent-file.json"])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("cannot read file"));+ });++ it("errors when JSON is malformed", async () => {+ const path = join(TMP_DIR, "bad.json");+ writeFileSync(path, "not json {{{");++ await expect(runInit(["--json-file", path])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("invalid JSON"));+ });++ it("errors when members array is missing", async () => {+ const jsonPath = writeJson("no-members.json", { name: "Test" });++ await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("members"));+ });++ it("errors when no runtimes are registered", async () => {+ const jsonPath = writeJson("valid.json", {+ members: [{ role: "leader", instructions: "x" }],+ });++ getJSONMock.mockResolvedValueOnce([]); // empty runtimes++ await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("No daemon registered"));+ });++ it("creates new workspace when agents already exist", async () => {+ const jsonPath = writeJson("valid.json", {+ name: "New WS",+ members: [{ role: "leader", instructions: "x" }],+ });++ getJSONMock+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes+ .mockResolvedValueOnce([{ id: "existing-agent" }]); // existing agents++ postJSONMock+ .mockResolvedValueOnce({ id: "ws_new", name: "New WS" }) // POST /api/workspaces+ .mockResolvedValueOnce({ // POST /api/studios+ studio: { name: "New WS" },+ workspace: { id: "ws_new", name: "New WS" },+ agents: [{ id: "ag1", name: "Charlie", email_handle: "charlie" }],+ links: [],+ });++ await runInit(["--json-file", jsonPath]);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("existing agents"));+ expect(postJSONMock).toHaveBeenCalledWith("/api/workspaces", expect.objectContaining({ name: "New WS" }));+ });++ it("warns when agent existence check fails", async () => {+ const jsonPath = writeJson("valid.json", {+ members: [{ role: "leader", instructions: "x" }],+ });++ getJSONMock+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]) // runtimes+ .mockRejectedValueOnce(new Error("network error")); // agents check fails++ postJSONMock.mockResolvedValueOnce({+ studio: { name: "" },+ workspace: { id: "ws_test", name: "Workspace" },+ agents: [{ id: "ag1", name: "X", email_handle: "x" }],+ links: [],+ });++ await runInit(["--json-file", jsonPath]);++ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("could not check existing agents"));+ });++ it("errors when runtime fetch fails", async () => {+ const jsonPath = writeJson("valid.json", {+ members: [{ role: "leader", instructions: "x" }],+ });++ getJSONMock.mockRejectedValueOnce(new Error("connection refused"));++ await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("failed to fetch runtimes"));+ });++ it("errors when studios POST fails", async () => {+ const jsonPath = writeJson("valid.json", {+ members: [{ role: "leader", instructions: "x" }],+ });++ getJSONMock+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }])+ .mockResolvedValueOnce([]);++ postJSONMock.mockRejectedValueOnce(new Error("500 internal server error"));++ await expect(runInit(["--json-file", jsonPath])).rejects.toThrow("process.exit(1)");+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("failed to create workspace"));+ });++ it("selects online runtime over offline one", async () => {+ const jsonPath = writeJson("valid.json", {+ members: [{ role: "leader", instructions: "x" }],+ });++ const oldDate = new Date(Date.now() - 10 * 60 * 1000).toISOString(); // 10 min ago (offline)+ const recentDate = new Date().toISOString(); // now (online)++ getJSONMock+ .mockResolvedValueOnce([+ { id: "rt_offline", machineLastSeenAt: oldDate },+ { id: "rt_online", machineLastSeenAt: recentDate },+ ])+ .mockResolvedValueOnce([]); // no existing agents++ postJSONMock.mockResolvedValueOnce({+ studio: { name: "" },+ workspace: { id: "ws_test", name: "WS" },+ agents: [{ id: "ag1", name: "Y", email_handle: "y" }],+ links: [],+ });++ await runInit(["--json-file", jsonPath]);++ // The online runtime should be selected+ expect(postJSONMock).toHaveBeenCalledWith("/api/studios", expect.objectContaining({+ members: expect.arrayContaining([+ expect.objectContaining({ runtime_id: "rt_online" }),+ ]),+ }));+ });+});diff --git a/src/cli/commands/workspace.ts b/src/cli/commands/workspace.tsnew file mode 100644index 000000000..dd0574f28--- /dev/null+++ b/src/cli/commands/workspace.ts@@ -0,0 +1,133 @@+import { Command } from "commander";+import { readFileSync } from "fs";+import { APIClient } from "../lib/client.js";+import { printJSON } from "../lib/output.js";+import { resolveClientOpts } from "../lib/resolve-client.js";++interface RuntimeResponse {+ id: string;+ machineLastSeenAt?: string | null;+}++function slugify(name: string): string {+ return name+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "")+ .slice(0, 60);+}++interface StudioResponse {+ studio: { name: string };+ workspace: { id: string; name: string };+ agents: Array<{ id: string; name: string; email_handle: string | null }>;+}++export function workspaceCommand(): Command {+ const cmd = new Command("workspace").description("Manage workspaces");++ cmd+ .command("init")+ .description("Initialize a workspace from a JSON configuration file")+ .requiredOption("--json-file <path>", "Path to the JSON configuration file")+ .option("--name <name>", "Workspace name (overrides JSON)")+ .option("--json", "Output as JSON")+ .action(async (opts, command) => {+ const { serverUrl, token, workspaceId } = resolveClientOpts(command);+ const client = new APIClient(serverUrl, token, workspaceId);++ // Read local JSON file+ let configJson: string;+ try {+ configJson = readFileSync(opts.jsonFile, "utf-8");+ } catch (err) {+ console.error(`Error: cannot read file '${opts.jsonFile}': ${err instanceof Error ? err.message : err}`);+ process.exit(1);+ }++ let config: { name?: string; scenario?: string; members: Array<Record<string, unknown>> };+ try {+ config = JSON.parse(configJson);+ } catch {+ console.error("Error: invalid JSON in configuration file");+ process.exit(1);+ }++ if (!config.members || !Array.isArray(config.members) || config.members.length === 0) {+ console.error("Error: JSON must contain a 'members' array with at least one member");+ process.exit(1);+ }++ // Get runtimes for this workspace+ let runtimes: RuntimeResponse[];+ try {+ runtimes = await client.getJSON<RuntimeResponse[]>("/api/runtimes");+ } catch (err) {+ console.error(`Error: failed to fetch runtimes: ${err instanceof Error ? err.message : err}`);+ process.exit(1);+ }++ if (runtimes.length === 0) {+ console.error("Error: No daemon registered. Run 'npx @alook/cli daemon start' first.");+ process.exit(1);+ }++ // Pick the first online runtime, or first one if none are online+ const OFFLINE_THRESHOLD_MS = 5 * 60 * 1000;+ const now = Date.now();+ const onlineRuntime = runtimes.find((r) => {+ if (!r.machineLastSeenAt) return false;+ const lastSeen = new Date(r.machineLastSeenAt.includes("Z") ? r.machineLastSeenAt : r.machineLastSeenAt + "Z").getTime();+ return now - lastSeen < OFFLINE_THRESHOLD_MS;+ });+ const runtime = onlineRuntime || runtimes[0];++ // Check if workspace already has agents — if so, create a new workspace+ let targetWorkspaceId = workspaceId;+ let targetClient = client;+ try {+ const agents = await client.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${workspaceId}`);+ if (agents.length > 0) {+ console.log("Current workspace has existing agents. Creating a new workspace...");+ const wsName = opts.name || config.name || "New Workspace";+ const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: slugify(wsName) });+ targetWorkspaceId = newWs.id;+ targetClient = new APIClient(serverUrl, token, targetWorkspaceId);+ console.log(`Created workspace: ${newWs.name} (${newWs.id})`);+ }+ } catch (err) {+ console.warn(`Warning: could not check existing agents: ${err instanceof Error ? err.message : err}`);+ }++ // Inject runtime_id into each member+ const members = config.members.map((m) => ({+ ...m,+ runtime_id: runtime.id,+ }));++ const payload = {+ name: opts.name || config.name,+ scenario: config.scenario,+ members,+ };++ // POST to /api/studios+ try {+ const res = await targetClient.postJSON<StudioResponse>("/api/studios", payload);++ if (opts.json) return printJSON(res);++ console.log(`\nWorkspace initialized: ${res.studio.name || res.workspace.name}`);+ console.log("Agents created:");+ for (const agent of res.agents) {+ const email = agent.email_handle ? `${agent.email_handle}@alook.ai` : "no email";+ console.log(` - ${agent.name} (${email})`);+ }+ } catch (err) {+ console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);+ process.exit(1);+ }+ });++ return cmd;+}diff --git a/src/cli/src/index.ts b/src/cli/src/index.tsindex 8a80e6efa..380f21db7 100644--- a/src/cli/src/index.ts+++ b/src/cli/src/index.ts@@ -12,6 +12,7 @@ import { agentCommand } from "../commands/agent.js";import { versionCommand } from "../commands/version.js";import { updateCommand } from "../commands/update.js";import { syncCommand } from "../commands/sync.js";+import { workspaceCommand } from "../commands/workspace.js";const program = new Command();@@ -33,5 +34,6 @@ program.addCommand(configCommand());program.addCommand(versionCommand());program.addCommand(updateCommand());program.addCommand(syncCommand());+program.addCommand(workspaceCommand());program.parse();diff --git a/src/web/src/app/api/studios/route.test.ts b/src/web/src/app/api/studios/route.test.tsindex 46f7e8e3b..38bd32273 100644--- a/src/web/src/app/api/studios/route.test.ts+++ b/src/web/src/app/api/studios/route.test.ts@@ -297,4 +297,39 @@ describe("POST /api/studios", () => {expect(mockAddWhitelist).toHaveBeenCalledTimes(2);});++ it("creates agents with auto-generated names when name is omitted", async () => {+ mockListAgents+ .mockResolvedValueOnce([])+ .mockResolvedValueOnce([+ { id: "agent-1", name: "AutoName1", emailHandle: "auto1" },+ { id: "agent-2", name: "AutoName2", emailHandle: "auto2" },+ ]);++ const req = new NextRequest("http://localhost/api/studios", {+ method: "POST",+ body: JSON.stringify({+ members: [+ { role: "leader", runtime_id: "rt1", instructions: "You lead" },+ { role: "engineer", runtime_id: "rt1", instructions: "You code", relationship: { leaderSees: "delegate tasks", memberSees: "report results" } },+ ],+ }),+ });++ const res = await POST(req, {});+ expect(res.status).toBe(201);++ // Agents should be created with non-empty names+ expect(mockCreateAgent).toHaveBeenCalledTimes(2);+ const firstCall = mockCreateAgent.mock.calls[0][1];+ const secondCall = mockCreateAgent.mock.calls[1][1];+ expect(firstCall.name).toBeTruthy();+ expect(secondCall.name).toBeTruthy();++ // Links should still be created (index-based matching)+ expect(mockCreateLink).toHaveBeenCalledTimes(1);+ const linkCall = mockCreateLink.mock.calls[0][1];+ expect(linkCall.instruction).toContain("delegate tasks");+ expect(linkCall.instruction).toContain("report results");+ });});diff --git a/src/web/src/app/api/studios/route.ts b/src/web/src/app/api/studios/route.tsindex c561f2e99..a1fc2df39 100644--- a/src/web/src/app/api/studios/route.ts+++ b/src/web/src/app/api/studios/route.ts@@ -108,8 +108,15 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const allHandles = await cached(cacheKeys.allHandles(ws.workspaceId), 120, () => queries.agent.getAllHandlesForWorkspace(db, ws.workspaceId));const handleSet = new Set(allHandles.map((h) => h.emailHandle).filter(Boolean) as string[]);+ const usedNames = new Set<string>();for (const member of body.members) {- const agentName = member.name || `Agent-${nanoid(4)}`;+ let agentName = member.name;+ if (!agentName) {+ do {+ agentName = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });+ } while (usedNames.has(agentName));+ }+ usedNames.add(agentName);const handle = member.email_handle && isValidHandle(member.email_handle) && !handleSet.has(member.email_handle)? (handleSet.add(member.email_handle), member.email_handle): generateUniqueHandleFromSet(handleSet, agentName);@@ -153,10 +160,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const leaderAgent = createdAgents.find((a) => a.role === "leader")!;const specialists = createdAgents.filter((a) => a.role !== "leader");const createdLinks = [];- const memberPayloadMap = new Map(body.members.map((m) => [m.name, m]));for (const specialist of specialists) {- const memberPayload = memberPayloadMap.get(specialist.name);+ const specIndex = createdAgents.indexOf(specialist);+ const memberPayload = body.members[specIndex];if (!memberPayload?.relationship) continue;const leaderMention = `[@ id="${leaderAgent.id}" label="${leaderAgent.name}"]`;diff --git a/src/web/src/app/onboard.md/route.test.ts b/src/web/src/app/onboard.md/route.test.tsindex c18ae5cef..e9ec7a329 100644--- a/src/web/src/app/onboard.md/route.test.ts+++ b/src/web/src/app/onboard.md/route.test.ts@@ -29,14 +29,11 @@ describe("GET /onboard.md", () => {expect(body).toContain("workflow");});- it("contains agent recruit section with parameter table", async () => {+ it("contains workspace init section", async () => {const response = await GET();const body = await response.text();- expect(body).toContain("npx @alook/cli agent recruit");- expect(body).toContain("--instructions");- expect(body).toContain("--relationship");- expect(body).toContain("--name");- expect(body).toContain("--description");+ expect(body).toContain("npx @alook/cli workspace init --json-file");+ expect(body).toContain("workspace already has agents");});it("contains templates exploration section", async () => {diff --git a/src/web/src/app/onboard.md/route.ts b/src/web/src/app/onboard.md/route.tsindex afc6d098f..d4ab6dfdd 100644--- a/src/web/src/app/onboard.md/route.ts+++ b/src/web/src/app/onboard.md/route.ts@@ -33,25 +33,41 @@ Review your conversation history with this user. Summarize:Use this understanding to choose the best workspace setup.## 4. Explore Templates & Set Up Workspace+Visit https://alook.ai/templates to explore available workspace templates.-Choose the most appropriate template based on what you know about the user.+Each template has a JSON version at \`/templates/<slug>/json\` you can fetch for reference.++Based on what you learned about the user in Step 3, customize the template or create your own configuration:++\`\`\`json+{+ "name": "Workspace Name",+ "members": [+ {+ "role": "leader",+ "description": "Coordinates tasks and delegates",+ "instructions": "System prompt for this agent"+ },+ {+ "role": "engineer",+ "description": "Implements features and fixes bugs",+ "instructions": "System prompt for this agent",+ "relationship": {+ "leaderSees": "When/how the leader delegates to this agent",+ "memberSees": "How this agent reports back to the leader"+ }+ }+ ]+}+\`\`\`-Create agents using the CLI:+Write your customized JSON to a file, then run:\`\`\`bash-npx @alook/cli agent recruit \\- --instructions "<system_prompt>" \\- --relationship "<delegation_criteria>" \\- [--name "<name>"] \\- [--description "<text>"]+npx @alook/cli workspace init --json-file <path_to_json>\`\`\`-| Parameter | Required | Description |-|-----------|----------|-------------|-| \`--instructions\` | Yes | The agent's system prompt — defines what it does and how it behaves |-| \`--relationship\` | Yes | Delegation criteria — when and how you'll work with this agent |-| \`--name\` | No | Preferred name (auto-generated if omitted) |-| \`--description\` | No | Short description of the agent's role |+If the current workspace already has agents, a new workspace is created automatically.`;export async function GET() {diff --git a/src/web/src/app/templates/[id]/json/route.test.ts b/src/web/src/app/templates/[id]/json/route.test.tsnew file mode 100644index 000000000..d563036ab--- /dev/null+++ b/src/web/src/app/templates/[id]/json/route.test.ts@@ -0,0 +1,68 @@+import { describe, it, expect } from "vitest";+import { GET } from "./route";++function makeRequest(id: string) {+ return GET(+ new Request(`http://localhost/templates/${id}/json`),+ { params: Promise.resolve({ id }) },+ );+}++describe("GET /templates/[id]/json", () => {+ it("returns 200 with correct JSON structure for valid template", async () => {+ const res = await makeRequest("open-source-maintainer");+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toContain("application/json");++ const data = await res.json();+ expect(data.name).toBe("Open Source Maintainer");+ expect(data.scenario).toBe("software-dev");+ expect(Array.isArray(data.members)).toBe(true);+ expect(data.members.length).toBeGreaterThanOrEqual(2);+ });++ it("returns 404 JSON for nonexistent template slug", async () => {+ const res = await makeRequest("does-not-exist");+ expect(res.status).toBe(404);++ const data = await res.json();+ expect(data.error).toBe("Template not found");+ });++ it("does not include name field in member objects", async () => {+ const res = await makeRequest("open-source-maintainer");+ const data = await res.json();++ for (const member of data.members) {+ expect(member).not.toHaveProperty("name");+ }+ });++ it("leader member has no relationship, specialists have relationship", async () => {+ const res = await makeRequest("open-source-maintainer");+ const data = await res.json();++ const leader = data.members.find((m: { role: string }) => m.role === "leader");+ expect(leader).toBeTruthy();+ expect(leader).not.toHaveProperty("relationship");++ const specialists = data.members.filter((m: { role: string }) => m.role !== "leader");+ expect(specialists.length).toBeGreaterThanOrEqual(1);+ for (const spec of specialists) {+ expect(spec.relationship).toBeTruthy();+ expect(spec.relationship.leaderSees).toBeTruthy();+ expect(spec.relationship.memberSees).toBeTruthy();+ }+ });++ it("includes instructions for all members", async () => {+ const res = await makeRequest("open-source-maintainer");+ const data = await res.json();++ for (const member of data.members) {+ expect(member.instructions).toBeTruthy();+ expect(typeof member.instructions).toBe("string");+ expect(member.instructions.length).toBeGreaterThan(10);+ }+ });+});diff --git a/src/web/src/app/templates/[id]/json/route.ts b/src/web/src/app/templates/[id]/json/route.tsnew file mode 100644index 000000000..000dec18c--- /dev/null+++ b/src/web/src/app/templates/[id]/json/route.ts@@ -0,0 +1,30 @@+import { NextResponse } from "next/server";+import { getTemplateById } from "@/lib/templates";++export async function GET(+ _req: Request,+ { params }: { params: Promise<{ id: string }> },+) {+ const { id } = await params;+ const template = getTemplateById(id);++ if (!template) {+ return NextResponse.json(+ { error: "Template not found" },+ { status: 404 },+ );+ }++ const response = {+ name: template.name,+ scenario: template.baseScenario,+ members: template.members.map((m) => ({+ role: m.role,+ description: m.description,+ instructions: m.instructions,+ ...(m.relationship ? { relationship: m.relationship } : {}),+ })),+ };++ return NextResponse.json(response);+}diff --git a/src/web/src/test/e2e/workspace-init.test.ts b/src/web/src/test/e2e/workspace-init.test.tsnew file mode 100644index 000000000..9d3ab244e--- /dev/null+++ b/src/web/src/test/e2e/workspace-init.test.ts@@ -0,0 +1,220 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"++let seed: TestSeed+const createdAgentIds: string[] = []+let extraWorkspaceId: string | null = null++beforeAll(() => {+ seed = seedTestData()+})++afterAll(() => {+ for (const agentId of createdAgentIds) {+ sqlRun(`DELETE FROM agent_task_queue WHERE agent_id = ?`, agentId)+ sqlRun(`DELETE FROM message WHERE conversation_id IN (SELECT id FROM conversation WHERE agent_id = ?)`, agentId)+ sqlRun(`DELETE FROM conversation WHERE agent_id = ?`, agentId)+ sqlRun(`DELETE FROM agent_whitelist WHERE agent_id = ?`, agentId)+ sqlRun(`DELETE FROM agent_link WHERE source_agent_id = ? OR target_agent_id = ?`, agentId, agentId)+ sqlRun(`DELETE FROM agent_pin WHERE agent_id = ?`, agentId)+ sqlRun(`DELETE FROM agent WHERE id = ?`, agentId)+ }+ if (extraWorkspaceId) {+ sqlRun(`DELETE FROM agent_task_queue WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM conversation WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM agent_whitelist WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = ?)`, extraWorkspaceId)+ sqlRun(`DELETE FROM agent_link WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM agent_pin WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM agent WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM agent_runtime WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM member WHERE workspace_id = ?`, extraWorkspaceId)+ sqlRun(`DELETE FROM workspace WHERE id = ?`, extraWorkspaceId)+ }+ cleanupTestData(seed)+})++describe("workspace init flow", () => {+ describe("template JSON endpoint", () => {+ it("GET /templates/open-source-maintainer/json returns valid template JSON", async () => {+ const APP_URL = process.env.APP_URL || "http://localhost:3000"+ const res = await fetch(`${APP_URL}/templates/open-source-maintainer/json`)+ expect(res.status).toBe(200)+ expect(res.headers.get("content-type")).toContain("application/json")++ const data = await res.json() as Record<string, unknown>+ expect(data.name).toBe("Open Source Maintainer")+ expect(data.scenario).toBe("software-dev")+ expect(Array.isArray(data.members)).toBe(true)++ const members = data.members as Array<Record<string, unknown>>+ expect(members.length).toBeGreaterThanOrEqual(2)++ const leader = members.find(m => m.role === "leader")+ expect(leader).toBeTruthy()+ expect(leader!.instructions).toBeTruthy()+ expect(typeof leader!.instructions).toBe("string")++ const specialist = members.find(m => m.role !== "leader")+ expect(specialist).toBeTruthy()+ expect(specialist!.relationship).toBeTruthy()+ const rel = specialist!.relationship as Record<string, string>+ expect(rel.leaderSees).toBeTruthy()+ expect(rel.memberSees).toBeTruthy()+ })++ it("GET /templates/nonexistent-slug/json returns 404", async () => {+ const APP_URL = process.env.APP_URL || "http://localhost:3000"+ const res = await fetch(`${APP_URL}/templates/nonexistent-slug/json`)+ expect(res.status).toBe(404)+ const data = await res.json() as Record<string, unknown>+ expect(data.error).toBeTruthy()+ })+ })++ describe("studio creation (happy path)", () => {+ it("POST /api/studios creates agents from template-style JSON without names", async () => {+ const payload = {+ name: "E2E Init Test",+ scenario: "software-dev",+ members: [+ {+ role: "leader",+ runtime_id: seed.runtimeId,+ description: "Test leader agent",+ instructions: "You are the test leader",+ },+ {+ role: "engineer",+ runtime_id: seed.runtimeId,+ description: "Test engineer agent",+ instructions: "You are the test engineer",+ relationship: {+ leaderSees: "Delegate code tasks to this engineer",+ memberSees: "Report back with implementation results",+ },+ },+ ],+ }++ const res = await tokenRequest(+ `/api/studios?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(payload),+ },+ )+ expect(res.status).toBe(201)++ const data = await res.json() as {+ studio: { name: string }+ workspace: { id: string; name: string }+ agents: Array<{ id: string; name: string; email_handle: string | null }>+ links: Array<{ id: string; source_agent_id: string; target_agent_id: string }>+ }++ expect(data.studio.name).toBeTruthy()+ expect(data.agents.length).toBe(2)++ // Names should be auto-generated (not empty)+ for (const agent of data.agents) {+ expect(agent.name).toBeTruthy()+ expect(agent.name.length).toBeGreaterThan(0)+ expect(agent.email_handle).toBeTruthy()+ }++ createdAgentIds.push(...data.agents.map(a => a.id))++ // Verify agent links were created (index-based matching)+ expect(data.links.length).toBeGreaterThanOrEqual(1)+ const link = data.links[0]+ const linkAgentIds = [link.source_agent_id, link.target_agent_id]+ expect(linkAgentIds.length).toBe(2)+ })+ })++ describe("workspace with existing agents creates new workspace", () => {+ it("POST /api/workspaces creates a new workspace when agents already exist", async () => {+ // seed already has an agent in seed.workspaceId+ // Verify existing agents+ const listRes = await tokenRequest(+ `/api/agents?workspace_id=${seed.workspaceId}`,+ seed.machineToken,+ )+ expect(listRes.status).toBe(200)+ const existingAgents = await listRes.json() as Array<{ id: string }>+ expect(existingAgents.length).toBeGreaterThan(0)++ // Create a new workspace (simulates what CLI does when agents exist)+ const wsRes = await tokenRequest(+ `/api/workspaces`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "E2E New Workspace", slug: `e2e-new-ws-${Date.now()}` }),+ },+ )+ expect(wsRes.status).toBe(201)+ const newWs = await wsRes.json() as { id: string; name: string }+ expect(newWs.id).toBeTruthy()+ expect(newWs.name).toBe("E2E New Workspace")+ extraWorkspaceId = newWs.id++ // Register a runtime in the new workspace (POST /api/workspaces already adds user as member)+ const now = new Date().toISOString()+ const rtId = `rt_e2e_${Date.now()}`+ sqlRun(+ `INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ rtId, extraWorkspaceId, seed.daemonId, "local", "claude", "online", "test-device", now, now,+ )++ // Now create studio in the new workspace+ const studioRes = await tokenRequest(+ `/api/studios?workspace_id=${extraWorkspaceId}`,+ seed.machineToken,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ name: "E2E Init In New WS",+ members: [+ {+ role: "leader",+ name: "New WS Leader",+ runtime_id: rtId,+ instructions: "You lead the new workspace",+ },+ ],+ }),+ },+ )+ expect(studioRes.status).toBe(201)+ const studioData = await studioRes.json() as {+ agents: Array<{ id: string; name: string }>+ workspace: { id: string }+ }+ expect(studioData.agents.length).toBe(1)+ expect(studioData.agents[0].name).toBe("New WS Leader")+ expect(studioData.workspace.id).toBe(extraWorkspaceId)+ })+ })++ describe("agent links verification", () => {+ it("verifies leader-specialist links contain correct relationship text", async () => {+ // Query links directly from DB for the agents we created earlier+ if (createdAgentIds.length < 2) return++ const links = sqlQuery(+ `SELECT instruction FROM agent_link WHERE (source_agent_id = ? AND target_agent_id = ?) OR (source_agent_id = ? AND target_agent_id = ?)`,+ createdAgentIds[0], createdAgentIds[1], createdAgentIds[1], createdAgentIds[0],+ ) as Array<{ instruction: string }>++ expect(links.length).toBeGreaterThanOrEqual(1)+ const linkText = links[0].instruction+ expect(linkText).toContain("Delegate code tasks to this engineer")+ expect(linkText).toContain("Report back with implementation results")+ })+ })+})diff --git a/vitest.config.ts b/vitest.config.tsindex ca5758de8..dc5e27717 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -2,7 +2,7 @@ import { defineConfig } from "vitest/config"export default defineConfig({test: {- projects: ["src/shared", "src/web", "src/email-worker", "src/app", "tests/utils"],+ projects: ["src/shared", "src/web", "src/cli", "src/email-worker", "src/app", "tests/utils"],coverage: {provider: "v8",include: ["src/**/*.{ts,tsx,js,jsx}"],@@ -13,6 +13,7 @@ export default defineConfig({"**/.next/**","**/dist/**","**/bundled/**",+ "src/cli/src/index.ts",],},},