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 templates page and refactor studio creation flow (#69)
Gener942d82e480e0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3e409a0c6..852bd96f4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -26,6 +26,7 @@ jobs:cache: pnpm- run: pnpm install --frozen-lockfile- run: pnpm typecheck+ - run: pnpm linttest:name: Tests (${{ matrix.os }})diff --git a/package.json b/package.jsonindex a40e3864b..8277fc3e2 100644--- a/package.json+++ b/package.json@@ -11,6 +11,7 @@"clean:builds": "rm -rf src/*/dist src/web/.next src/web/.open-next .turbo src/*/.turbo","reinstall": "pnpm run clean && pnpm install","typecheck": "turbo run typecheck",+ "lint": "turbo run lint","dev:web": "pnpm --filter @alook/web dev","dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev","dev:email": "pnpm --filter @alook/email-worker dev",@@ -32,7 +33,7 @@"prepare": "simple-git-hooks"},"simple-git-hooks": {- "pre-commit": "pnpm test"+ "pre-commit": "pnpm lint && pnpm test"},"devDependencies": {"simple-git-hooks": "^2.13.1",@@ -46,6 +47,7 @@"esbuild","msw","sharp",+ "simple-git-hooks","unrs-resolver","workerd"]diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8703bb914..884261b52 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -249,6 +249,9 @@ importers:'@lhci/cli':specifier: ^0.15.1version: 0.15.1+ '@tailwindcss/node':+ specifier: ^4.3.0+ version: 4.3.0'@tailwindcss/postcss':specifier: ^4version: 4.3.0@@ -267,6 +270,9 @@ importers:eslint-config-next:specifier: 16.2.6version: 16.2.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ eslint-plugin-tailwind-canonical-classes:+ specifier: ^1.3.3+ version: 1.3.3([email protected]([email protected]))tailwindcss:specifier: ^4version: 4.3.0@@ -1757,6 +1763,10 @@ packages:'@paulirish/[email protected]':resolution: {integrity: sha512-PUl/vlfo08Oj804VI5nDPeSk9vyslnBlVzDDwFt8SUVxY8+KdGMkra/vrXjEEHe8gb7+RqVTfOIlGw0nyrEelA==}+ '@pkgr/[email protected]':+ resolution: {integrity: sha512-fdDH1LSGfZdTH2sxdpVMw31BanV28K/Gry0cVFxaNP77neJSkd82mM8ErPNYs9e+0O7SdHBLTDzDgwUuy18RnQ==}+ engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}+'@poppinss/[email protected]':resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}@@ -4081,6 +4091,12 @@ packages:peerDependencies:eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7+ resolution: {integrity: sha512-JNnbtGVEydbdi27qKOdZ/qgJPpdKwFymn+MEAWuiXy1KxNlB4duly9Xq4/6AnqBGrW1IE5iC47AVpXyu3KZMfw==}+ engines: {node: '>=18.0.0'}+ peerDependencies:+ eslint: ^8.0.0 || ^9.0.0 || ^10.0.0+resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -6323,6 +6339,10 @@ packages:resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}engines: {node: '>= 0.4'}+ resolution: {integrity: sha512-JJoOEKTfL1urb1mDoEblhD9NhEbWmq9jHEMEnxoC4ujUaZ4itA8vKgwkFAyNClgxplLi9tsUKX+EduK0p/l7sg==}+ engines: {node: ^14.18.0 || >=16.0.0}+resolution: {integrity: sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==}engines: {node: '>=20'}@@ -8783,6 +8803,8 @@ snapshots:legacy-javascript: 0.0.1third-party-web: 0.29.0+ '@pkgr/[email protected]': {}+'@poppinss/[email protected]':dependencies:kleur: 4.1.5@@ -11132,7 +11154,7 @@ snapshots:'@next/eslint-plugin-next': 16.2.6eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([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]))@@ -11155,7 +11177,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -11170,14 +11192,14 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))transitivePeerDependencies:- supports-color@@ -11192,7 +11214,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))hasown: 2.0.3is-core-module: 2.16.2is-glob: 4.0.3@@ -11262,6 +11284,12 @@ snapshots:string.prototype.matchall: 4.0.12string.prototype.repeat: 1.0.0+ dependencies:+ '@tailwindcss/node': 4.3.0+ eslint: 9.39.4([email protected])+ synckit: 0.9.3+dependencies:esrecurse: 4.3.0@@ -14114,6 +14142,11 @@ snapshots:+ dependencies:+ '@pkgr/core': 0.1.2+ tslib: 2.8.1+diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex bfdec16ed..0b334ff2a 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -95,21 +95,6 @@ export function registerCommand(): Command {process.exit(1);}- let workspaces: Workspace[];- try {- workspaces = await client.getJSON<Workspace[]>("/api/workspaces");- } catch (err) {- console.error(- `Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`,- );- process.exit(1);- }-- if (!workspaces.length) {- console.error("Error: no workspaces found for this user");- process.exit(1);- }-// Detect local runtimesconsole.log("Scanning for AI runtimes...");const runtimes = detectRuntimes();@@ -123,7 +108,7 @@ export function registerCommand(): Command {`Found: ${runtimes.map((r) => r.type).join(", ")}`,);- // Activate token — no auth header needed, token in body+ // Activate token — may create workspace if none existsconst host = hostname();console.log("Registering runtime...");let activateResp: ActivateResponse;@@ -146,6 +131,22 @@ export function registerCommand(): Command {process.exit(1);}+ // Fetch workspaces after activation (activation may have created one)+ let workspaces: Workspace[];+ try {+ workspaces = await client.getJSON<Workspace[]>("/api/workspaces");+ } catch (err) {+ console.error(+ `Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`,+ );+ process.exit(1);+ }++ if (!workspaces.length) {+ console.error("Error: no workspaces found for this user");+ process.exit(1);+ }+// Use the workspace_id from activate response to find the correct workspaceconst ws = workspaces.find((w) => w.id === activateResp.workspace_id) || workspaces[0];diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.tsindex 49eca7f99..251a1ad69 100644--- a/src/shared/src/db/queries/machine-token.ts+++ b/src/shared/src/db/queries/machine-token.ts@@ -1,4 +1,4 @@-import { eq, and, desc } from "drizzle-orm";+import { eq, and, desc, isNull } from "drizzle-orm";import { machineToken, user } from "../schema";import type { Database } from "../index";@@ -6,7 +6,7 @@ export async function createMachineToken(db: Database,data: {userId: string;- workspaceId: string;+ workspaceId?: string | null;token: string;name: string;status?: string;@@ -16,7 +16,7 @@ export async function createMachineToken(.insert(machineToken).values({userId: data.userId,- workspaceId: data.workspaceId,+ workspaceId: data.workspaceId ?? null,token: data.token,name: data.name,status: data.status ?? "active",@@ -47,26 +47,29 @@ export async function getMachineTokenByToken(db: Database, token: string) {export async function getPendingMachineToken(db: Database,userId: string,- workspaceId: string+ workspaceId?: string | null) {+ const conditions = [+ eq(machineToken.userId, userId),+ eq(machineToken.status, "pending"),+ ];+ if (workspaceId) {+ conditions.push(eq(machineToken.workspaceId, workspaceId));+ } else {+ conditions.push(isNull(machineToken.workspaceId));+ }const rows = await db.select().from(machineToken)- .where(- and(- eq(machineToken.userId, userId),- eq(machineToken.workspaceId, workspaceId),- eq(machineToken.status, "pending")- )- )+ .where(and(...conditions)).limit(1);return rows[0] ?? null;}-export async function activateMachineToken(db: Database, id: string) {+export async function activateMachineToken(db: Database, id: string, workspaceId?: string) {await db.update(machineToken)- .set({ status: "active" })+ .set({ status: "active", ...(workspaceId ? { workspaceId } : {}) }).where(eq(machineToken.id, id));}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex aee581043..d86312cfc 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -630,7 +630,6 @@ export const machineToken = sqliteTable(.notNull().references(() => user.id, { onDelete: "cascade" }),workspaceId: text("workspace_id")- .notNull().references(() => workspace.id, { onDelete: "cascade" }),token: text("token").unique().notNull(),name: text("name").notNull().default(""),diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 014b3865b..062eed0c2 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -231,4 +231,5 @@ export type { PromptAgent, PromptMention, ParseResult } from "./utils/prompt-parexport { isValidToken, isValidEmail } from "./utils/validation";export { isOnline, formatStatus } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";+export { generateWorkspaceSlug } from "./utils/slug";export { semverGte } from "./semver";diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 0157d2cc6..8b34ba936 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -186,7 +186,7 @@ export const ActivateTokenRequestSchema = z.object({export type ActivateTokenRequest = z.infer<typeof ActivateTokenRequestSchema>;export const RegisterDaemonRequestSchema = z.object({- workspace_id: z.string().min(1),+ workspace_id: z.string().min(1).optional(),daemon_id: z.string().min(1),device_name: z.string().optional().default(""),cli_version: z.string().optional().default(""),diff --git a/src/shared/src/utils/slug.ts b/src/shared/src/utils/slug.tsnew file mode 100644index 000000000..d26b3e7fe--- /dev/null+++ b/src/shared/src/utils/slug.ts@@ -0,0 +1,5 @@+import { nanoid } from "nanoid";++export function generateWorkspaceSlug(): string {+ return `studio-${nanoid(8)}`;+}diff --git a/src/web/eslint.config.mjs b/src/web/eslint.config.mjsindex 697cbcdd2..c0884667d 100644--- a/src/web/eslint.config.mjs+++ b/src/web/eslint.config.mjs@@ -1,10 +1,12 @@import { defineConfig, globalIgnores } from "eslint/config";import nextVitals from "eslint-config-next/core-web-vitals";import nextTs from "eslint-config-next/typescript";+import tailwindCanonicalClasses from "eslint-plugin-tailwind-canonical-classes";const eslintConfig = defineConfig([...nextVitals,...nextTs,+ ...tailwindCanonicalClasses.configs["flat/recommended"],// Override default ignores of eslint-config-next.globalIgnores([// Default ignores of eslint-config-next:@@ -18,6 +20,12 @@ const eslintConfig = defineConfig([rules: {"react-hooks/set-state-in-effect": "off","react-hooks/preserve-manual-memoization": "off",+ "react-hooks/refs": "warn",+ "@typescript-eslint/no-explicit-any": "warn",+ "tailwind-canonical-classes/tailwind-canonical-classes": [+ "warn",+ { cssPath: "./src/app/globals.css" },+ ],"@next/next/no-img-element": "off","@next/next/no-before-interactive-script-outside-document": "off",},diff --git a/src/web/migrations/0026_machine_token_nullable_workspace.sql b/src/web/migrations/0026_machine_token_nullable_workspace.sqlnew file mode 100644index 000000000..a24c31050--- /dev/null+++ b/src/web/migrations/0026_machine_token_nullable_workspace.sql@@ -0,0 +1,19 @@+-- Make machine_token.workspace_id nullable so tokens can be created before workspace exists.+-- The workspace is created when the daemon actually registers.++-- SQLite doesn't support ALTER COLUMN, so we recreate the table.+CREATE TABLE machine_token_new (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,+ workspace_id TEXT REFERENCES workspace(id) ON DELETE CASCADE,+ token TEXT UNIQUE NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT 'active',+ last_used_at TEXT,+ created_at TEXT NOT NULL+);++INSERT INTO machine_token_new SELECT * FROM machine_token;+DROP TABLE machine_token;+ALTER TABLE machine_token_new RENAME TO machine_token;+CREATE INDEX idx_machine_token ON machine_token(token);diff --git a/src/web/package.json b/src/web/package.jsonindex e31d2b54f..deed0cd3e 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -6,7 +6,7 @@"dev": "next dev","build": "next build","start": "next start",- "lint": "next lint",+ "lint": "eslint src/","deploy": "opennextjs-cloudflare build && opennextjs-cloudflare deploy","upload": "opennextjs-cloudflare build && opennextjs-cloudflare upload","preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",@@ -65,12 +65,14 @@"devDependencies": {"@eslint/eslintrc": "^3","@lhci/cli": "^0.15.1",+ "@tailwindcss/node": "^4.3.0","@tailwindcss/postcss": "^4","@types/node": "^25","@types/react": "^19.2.14","@types/react-dom": "^19.2.3","eslint": "^9","eslint-config-next": "16.2.6",+ "eslint-plugin-tailwind-canonical-classes": "^1.3.3","tailwindcss": "^4","tsx": "^4.21.0","typescript": "^6.0.3",diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex f94ba9fba..9f44ee128 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect } from "react";+import { useState, useCallback, useEffect, useRef } from "react";import { useRouter } from "next/navigation";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";@@ -21,22 +21,33 @@ import type { AgentRuntime as Runtime } from "@alook/shared";import type { WsMessage } from "@alook/shared";import { listRuntimes, createMachineToken } from "@/lib/api";import { useUserWs } from "@/lib/use-user-ws";+import type { TemplatePreset } from "@/lib/templates";export function StudioOnboardingClient({- workspaceId,+ workspaceId: initialWorkspaceId,workspaceSlug,workspaceName,+ initialTemplate,}: {- workspaceId: string;+ workspaceId: string | null;workspaceSlug: string;workspaceName: string;+ initialTemplate?: TemplatePreset;}) {const router = useRouter();+ const isNewWorkspace = !initialWorkspaceId;+ const [workspaceId, setWorkspaceId] = useState<string | null>(initialWorkspaceId);+ const workspaceIdRef = useRef(workspaceId);+ useEffect(() => { workspaceIdRef.current = workspaceId; }, [workspaceId]);const [runtimes, setRuntimes] = useState<Runtime[]>([]);- const [loadingRuntimes, setLoadingRuntimes] = useState(true);- const [scenarioId, setScenarioId] = useState<ScenarioId | null>(null);- const [studioName, setStudioName] = useState(workspaceName === "Personal" ? "" : workspaceName);+ const [loadingRuntimes, setLoadingRuntimes] = useState(!!initialWorkspaceId);+ const [scenarioId, setScenarioId] = useState<ScenarioId | null>(+ initialTemplate ? initialTemplate.baseScenario : null,+ );+ const [studioName, setStudioName] = useState(+ isNewWorkspace ? "" : (workspaceName === "Personal" ? "" : workspaceName),+ );const [nameAvailable, setNameAvailable] = useState<boolean | null>(null);const [checkingName, setCheckingName] = useState(false);const [members, setMembers] = useState<TeamMember[]>([]);@@ -52,8 +63,9 @@ export function StudioOnboardingClient({const hasOnlineRuntime = onlineRuntimes.length > 0;const onlineMachineCount = new Set(onlineRuntimes.map((r) => r.daemon_id).filter(Boolean)).size;- // Fetch runtimes on mount+ // Fetch runtimes on mount (only if workspace exists)useEffect(() => {+ if (!workspaceId) return;listRuntimes(workspaceId).then(setRuntimes).catch(() => {})@@ -62,14 +74,25 @@ export function StudioOnboardingClient({// WebSocket for runtime registration eventsconst handleWsMessage = useCallback((msg: WsMessage) => {- if (- msg.type === "runtime.registered" ||- (msg.type === "runtime.status" && (msg as any).payload?.status === "online")- ) {+ const currentWsId = workspaceIdRef.current;+ const extra = msg as WsMessage & { workspaceId?: string; payload?: { status?: string } };+ if (msg.type === "runtime.registered") {+ setMachineRegistered(true);+ const eventWsId = extra.workspaceId;+ if (eventWsId && !currentWsId) {+ setWorkspaceId(eventWsId);+ listRuntimes(eventWsId).then(setRuntimes).catch(() => {});+ } else if (currentWsId) {+ listRuntimes(currentWsId).then(setRuntimes).catch(() => {});+ }+ } else if (msg.type === "runtime.status" && extra.payload?.status === "online") {setMachineRegistered(true);- listRuntimes(workspaceId).then(setRuntimes).catch(() => {});+ const wsId = workspaceIdRef.current;+ if (wsId) {+ listRuntimes(wsId).then(setRuntimes).catch(() => {});+ }}- }, [workspaceId]);+ }, []);useUserWs(handleWsMessage);@@ -99,6 +122,34 @@ export function StudioOnboardingClient({}}, []);+ // Initialize from template when runtimes are loaded+ useEffect(() => {+ if (!initialTemplate || loadingRuntimes) return;+ if (members.length > 0) return;+ const generated = shuffleMembers(initialTemplate.members.length);+ const defaultRuntimeId = onlineRuntimes[0]?.id || "";+ const newMembers = initialTemplate.members.map((m, i) => ({+ name: generated[i].name,+ role: m.role,+ description: m.description,+ instructions: m.instructions,+ avatarUrl: generated[i].avatarUrl,+ runtimeId: defaultRuntimeId,+ }));+ setMembers(newMembers);+ resolveHandles(newMembers.map((m) => m.name)).then((handles) => {+ if (handles) {+ setMembers((prev) =>+ prev.map((m) => {+ const h = handles.find((r) => r.name === m.name);+ return h ? { ...m, emailHandle: h.handle } : m;+ }),+ );+ }+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [initialTemplate, loadingRuntimes]);+const handleScenarioSelect = async (id: ScenarioId) => {setScenarioId(id);const preset = SCENARIO_PRESETS.find((s) => s.id === id)!;@@ -140,9 +191,10 @@ export function StudioOnboardingClient({setCheckingName(true);setNameAvailable(null);try {- const res = await fetch(- `/api/studios/check-name?name=${encodeURIComponent(studioName.trim())}&workspace_id=${workspaceId}`,- );+ const url = workspaceId+ ? `/api/studios/check-name?name=${encodeURIComponent(studioName.trim())}&workspace_id=${workspaceId}`+ : `/api/studios/check-name?name=${encodeURIComponent(studioName.trim())}`;+ const res = await fetch(url);const data = (await res.json()) as { available: boolean };setNameAvailable(data.available);} catch {@@ -156,7 +208,7 @@ export function StudioOnboardingClient({const handleGenerateToken = useCallback(async () => {setGeneratingToken(true);try {- const res = await createMachineToken("cli", workspaceId);+ const res = await createMachineToken("cli", workspaceId || undefined);setGeneratedToken(res.token);} catch {toast.error("Failed to generate token");@@ -174,6 +226,11 @@ export function StudioOnboardingClient({const handleCreate = async () => {setCreating(true);try {+ if (!workspaceId) {+ toast.error("Please connect a computer first");+ setCreating(false);+ return;+ }const res = await fetch("/api/studios", {method: "POST",headers: {@@ -209,11 +266,16 @@ export function StudioOnboardingClient({}};+ const nameValid =+ isNewWorkspace+ ? studioName.trim() && nameAvailable === true+ : nameAvailable !== false;+const canCreate =scenarioId &&members.length > 0 &&members.every((m) => m.runtimeId) &&- nameAvailable !== false &&+ nameValid &&(hasOnlineRuntime || machineRegistered);// Page 1: Scenario selection@@ -240,14 +302,26 @@ export function StudioOnboardingClient({</Button><div className="w-full max-w-3xl space-y-8">- <div className="text-center space-y-1">- <h1 className="text-lg font-semibold">What will your studio focus on?</h1>- <p className="text-xs text-muted-foreground">- Pick a scenario to assemble the right team.- </p>+ <div className="text-center">+ <h1 className="text-lg font-semibold">Pick a scenario to get started</h1></div>- <ScenarioPicker selected={scenarioId} onSelect={handleScenarioSelect} />+ <ScenarioPicker selected={scenarioId} onSelect={handleScenarioSelect} onBrowseTemplates={() => router.push(workspaceId ? `/templates?workspace_id=${workspaceId}` : "/templates")} />++ {workspaceId && (+ <div className="flex justify-center pt-2">+ <button+ type="button"+ onClick={() => {+ document.cookie = `skip_init=${workspaceId};path=/;max-age=86400`;+ router.push(`/w/${workspaceSlug}/home`);+ }}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ Skip+ </button>+ </div>+ )}</div></div>);@@ -290,7 +364,9 @@ export function StudioOnboardingClient({<div className="w-full max-w-3xl space-y-8 py-12">{/* Header */}<div className="text-center space-y-1">- <h1 className="text-lg font-semibold">Build your AI studio</h1>+ <h1 className="text-lg font-semibold">+ {!isNewWorkspace ? "Set up your AI team" : "Create a new studio"}+ </h1><p className="text-xs text-muted-foreground">Name your team, connect a machine, and start working.</p>@@ -338,7 +414,11 @@ export function StudioOnboardingClient({</span>)}{nameAvailable === true && <span>·</span>}- <span>Optional — you can always rename later.</span>+ {!isNewWorkspace ? (+ <span>Optional — you can always rename later.</span>+ ) : (+ <span>Required — pick a name for your new studio.</span>+ )}</p></div>@@ -402,6 +482,8 @@ export function StudioOnboardingClient({<Loader2 className="size-4 animate-spin mr-2" />Creating studio...</>+ ) : isNewWorkspace && studioName.trim() && nameAvailable !== true ? (+ "Check studio name first") : ("Create studio")}diff --git a/src/web/src/app/(app)/studio/new/page.tsx b/src/web/src/app/(app)/studio/new/page.tsxindex 35cc3e7a5..493b79c9b 100644--- a/src/web/src/app/(app)/studio/new/page.tsx+++ b/src/web/src/app/(app)/studio/new/page.tsx@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries } from "@alook/shared";import { getDb } from "@/lib/db";import { requireSession } from "@/lib/session";+import { getTemplateById } from "@/lib/templates";import { StudioOnboardingClient } from "./client";export default async function StudioNewPage({@@ -15,29 +16,33 @@ export default async function StudioNewPage({const db = getDb((env as Env).DB);const params = await searchParams;- let workspaceId = params.workspace_id;+ const templateId = params.template;+ const initialTemplate = templateId ? getTemplateById(templateId) : undefined;- if (!workspaceId) {- const workspaces = await queries.workspace.listWorkspaces(db, session.user.id);- if (workspaces.length === 0) redirect("/workspaces");- workspaceId = workspaces[workspaces.length - 1].id;- }+ const workspaceId = params.workspace_id ?? null;+ let workspaceName = "";+ let workspaceSlug = "";- const membership = await queries.member.getMemberByUserAndWorkspace(- db,- session.user.id,- workspaceId,- );- if (!membership) redirect("/workspaces");+ if (workspaceId) {+ const membership = await queries.member.getMemberByUserAndWorkspace(+ db,+ session.user.id,+ workspaceId,+ );+ if (!membership) redirect("/workspaces");- const workspace = await queries.workspace.getWorkspace(db, workspaceId, session.user.id);- if (!workspace) redirect("/workspaces");+ const workspace = await queries.workspace.getWorkspace(db, workspaceId, session.user.id);+ if (!workspace) redirect("/workspaces");+ workspaceName = workspace.name;+ workspaceSlug = workspace.slug;+ }return (<StudioOnboardingClientworkspaceId={workspaceId}- workspaceSlug={workspace.slug}- workspaceName={workspace.name}+ workspaceSlug={workspaceSlug}+ workspaceName={workspaceName}+ initialTemplate={initialTemplate}/>);}diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsxindex b00de039b..dca63debc 100644--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx@@ -142,7 +142,7 @@ function ActivityRow({ task, slug, agentId, workspaceId, onRetry }: { task: Acti{relativeTime(task.created_at)}</span></div>- <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">+ <div className="flex items-center gap-1.5 mt-1 ml-5.5"><StatusDot status={task.status} /><span className="text-xs text-muted-foreground">{STATUS_LABELS[task.status] ?? task.status}@@ -187,7 +187,7 @@ function SkeletonRow({ promptWidth }: { promptWidth: string }) {<Skeleton className={`h-3.5 rounded`} style={{ width: promptWidth }} /><Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" /></div>- <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">+ <div className="flex items-center gap-1.5 mt-1 ml-5.5"><Skeleton className="h-2.5 w-20 rounded-full" /><Skeleton className="h-2.5 w-8 rounded" /></div>diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex ae4894297..1bd214766 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -493,8 +493,8 @@ function MobileAgentList() {export default function HomePage() {const router = useRouter();- const { agents, runtimes, loading } = useAgentContext();- const { slug, workspaceId } = useWorkspace();+ const { agents, loading } = useAgentContext();+ const { workspaceId } = useWorkspace();const isMobile = useIsMobile();if (loading) {diff --git a/src/web/src/app/(app)/w/[slug]/issues/page.tsx b/src/web/src/app/(app)/w/[slug]/issues/page.tsxindex 1a76fc54c..087b9a0f3 100644--- a/src/web/src/app/(app)/w/[slug]/issues/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/issues/page.tsx@@ -490,7 +490,7 @@ export default function IssuesPage() {} finally {pendingStatusUpdate.current = null;}- }, [workspaceId, issues, detail]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [workspaceId, issues, detail]);const handleDeleteIssue = useCallback(async (issueId: string) => {diff --git a/src/web/src/app/(app)/w/[slug]/layout.tsx b/src/web/src/app/(app)/w/[slug]/layout.tsxindex 7147ea686..af96d7c20 100644--- a/src/web/src/app/(app)/w/[slug]/layout.tsx+++ b/src/web/src/app/(app)/w/[slug]/layout.tsx@@ -1,3 +1,4 @@+import { headers } from "next/headers"import { redirect } from "next/navigation"import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"@@ -35,7 +36,17 @@ export default async function WorkspaceLayout({const agents = await queries.agent.listAgents(db, ws.id, session.user.id)if (agents.length === 0) {- redirect(`/studio/new?workspace_id=${ws.id}`)+ const hdrs = await headers()+ const cookieHeader = hdrs.get("cookie") || ""+ const cookies = Object.fromEntries(+ cookieHeader.split(";").map((c) => {+ const [k, ...v] = c.trim().split("=")+ return [k, v.join("=")]+ })+ )+ if (!cookies["skip_init"] || cookies["skip_init"] !== ws.id) {+ redirect(`/studio/new?workspace_id=${ws.id}`)+ }}return (diff --git a/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx b/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsxindex cfa20aa6c..d25c25db5 100644--- a/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx@@ -204,7 +204,7 @@ export default function TraceDetailPage() {<Skeleton className="h-3.5 rounded" style={{ width: `${w}%` }} /><Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" /></div>- <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">+ <div className="flex items-center gap-1.5 mt-1 ml-5.5"><Skeleton className="h-2.5 w-20 rounded-full" /></div></div>diff --git a/src/web/src/app/(app)/w/[slug]/threads/page.tsx b/src/web/src/app/(app)/w/[slug]/threads/page.tsxindex 67ae4d874..54a3e88ba 100644--- a/src/web/src/app/(app)/w/[slug]/threads/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/threads/page.tsx@@ -147,7 +147,7 @@ function SkeletonRow({ promptWidth }: { promptWidth: string }) {<Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} /><Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" /></div>- <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">+ <div className="flex items-center gap-1.5 mt-1 ml-5.5"><Skeleton className="h-2.5 w-20 rounded-full" /><Skeleton className="h-2.5 w-8 rounded" /></div>diff --git a/src/web/src/app/(app)/workspaces/client.tsx b/src/web/src/app/(app)/workspaces/client.tsxindex a7ca8a2dd..26ba13612 100644--- a/src/web/src/app/(app)/workspaces/client.tsx+++ b/src/web/src/app/(app)/workspaces/client.tsx@@ -1,19 +1,12 @@"use client"-import { useState } from "react"import { useRouter } from "next/navigation"import { Button } from "@/components/ui/button"import { Card, CardContent } from "@/components/ui/card"-import { Input } from "@/components/ui/input"import { GradientBackground } from "@/components/gradient-background"import { Logo } from "@/components/logo"-import { Plus, ArrowRight, Loader2, LogOut } from "lucide-react"+import { Plus, ArrowRight, LogOut } from "lucide-react"import { signOut } from "@/lib/auth-client"-import {- type WorkspaceFormErrors,- hasWorkspaceFormErrors,- validateWorkspaceForm,-} from "@/lib/form-validation"interface WorkspaceItem {id: string@@ -21,57 +14,12 @@ interface WorkspaceItem {slug: string}-function deriveSlug(name: string): string {- return name- .toLowerCase()- .replace(/[^a-z0-9-]/g, "-")- .replace(/-+/g, "-")- .replace(/^-|-$/g, "")- .slice(0, 48)-}-export function WorkspaceListClient({workspaces,}: {workspaces: WorkspaceItem[]}) {const router = useRouter()- const [showForm, setShowForm] = useState(false)- const [name, setName] = useState("")- const [creating, setCreating] = useState(false)- const [error, setError] = useState("")- const [fieldErrors, setFieldErrors] = useState<WorkspaceFormErrors>({})-- const slug = deriveSlug(name)-- async function handleCreate(e: React.FormEvent) {- e.preventDefault()- const nextErrors = validateWorkspaceForm({ name, slug })- setFieldErrors(nextErrors)- if (hasWorkspaceFormErrors(nextErrors)) return-- setError("")- setCreating(true)- try {- const res = await fetch("/api/workspaces", {- method: "POST",- credentials: "include",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: name.trim(), slug }),- })- if (!res.ok) {- const body = await res.json().catch(() => ({}))- setError((body as { error?: string }).error || "Failed to create workspace")- return- }- const ws = (await res.json()) as WorkspaceItem- router.push(`/studio/new?workspace_id=${ws.id}`)- } catch {- setError("Failed to create workspace")- } finally {- setCreating(false)- }- }return (<div className="relative flex min-h-dvh flex-col items-center justify-center p-6">@@ -116,78 +64,14 @@ export function WorkspaceListClient({))}</div>- {showForm ? (- <form onSubmit={handleCreate} className="space-y-3">- <div className="space-y-2">- <Input- placeholder="Workspace name"- value={name}- onChange={(e) => {- const nextName = e.target.value- setName(nextName)- const nextSlug = deriveSlug(nextName)- if (fieldErrors.name && nextName.trim()) {- setFieldErrors((prev) => ({ ...prev, name: undefined }))- }- if (fieldErrors.slug && nextSlug) {- setFieldErrors((prev) => ({ ...prev, slug: undefined }))- }- }}- autoFocus- aria-invalid={Boolean(fieldErrors.name || fieldErrors.slug)}- aria-describedby={fieldErrors.name || fieldErrors.slug ? "workspace-name-error" : undefined}- />- {slug && (- <p className="text-xs text-muted-foreground pl-1">- Slug: {slug}- </p>- )}- {(fieldErrors.name || fieldErrors.slug) && (- <p id="workspace-name-error" className="text-xs text-destructive">- {fieldErrors.name || fieldErrors.slug}- </p>- )}- </div>- {error && (- <p className="text-xs text-destructive">{error}</p>- )}- <div className="flex gap-2">- <Button- type="button"- variant="ghost"- size="sm"- onClick={() => {- setShowForm(false)- setName("")- setError("")- }}- >- Cancel- </Button>- <Button- type="submit"- size="sm"- disabled={creating}- className="flex-1"- >- {creating ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- "Create"- )}- </Button>- </div>- </form>- ) : (- <Button- variant="outline"- className="w-full"- onClick={() => setShowForm(true)}- >- <Plus className="size-4" />- New workspace- </Button>- )}+ <Button+ variant="outline"+ className="w-full"+ onClick={() => router.push("/studio/new")}+ >+ <Plus className="size-4" />+ New workspace+ </Button></div></div>)diff --git a/src/web/src/app/api/daemon/register/route.test.ts b/src/web/src/app/api/daemon/register/route.test.tsindex ada296519..45317ed33 100644--- a/src/web/src/app/api/daemon/register/route.test.ts+++ b/src/web/src/app/api/daemon/register/route.test.ts@@ -57,6 +57,10 @@ describe("POST /api/daemon/register", () => {vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);vi.doMock("@/lib/api/responses", () => mocks["@/lib/api/responses"]);+ vi.doMock("@/lib/cache", () => ({+ invalidate: vi.fn(),+ cacheKeys: { runtimeIds: (...a: any[]) => a.join(":") },+ }));vi.doMock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params =@@ -98,7 +102,7 @@ describe("POST /api/daemon/register", () => {const body = await res.json();expect(res.status).toBe(200);- expect(body).toEqual({ runtimes: [{ id: "r1" }] });+ expect(body).toEqual({ runtimes: [{ id: "r1" }], workspaceId: "w1" });expect(mockUpsertMachine).toHaveBeenCalledTimes(1);expect(mockUpsertAgentRuntime).toHaveBeenCalledTimes(1);});diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex 620f3f847..c43d1ded9 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -5,7 +5,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { writeJSON, parseBody } from "@/lib/middleware/helpers";import { runtimeToResponse } from "@/lib/api/responses";-import { RegisterDaemonRequestSchema } from "@alook/shared";+import { RegisterDaemonRequestSchema, generateWorkspaceSlug } from "@alook/shared";import { broadcastToUser } from "@/lib/broadcast";import { invalidate, cacheKeys } from "@/lib/cache";@@ -16,7 +16,32 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const [body, err] = await parseBody(req, RegisterDaemonRequestSchema);if (err) return err;- const { workspace_id: workspaceId, daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, runtimes } = body;+ const { daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, runtimes } = body;+ let workspaceId = body.workspace_id;++ // Resolve workspace: use provided, fall back to auth context, or create new+ if (!workspaceId && ctx.workspaceId) {+ workspaceId = ctx.workspaceId;+ }++ if (!workspaceId) {+ // Check if user already has a workspace before creating a new one+ const existing = await queries.workspace.listWorkspaces(db, ctx.userId);+ if (existing.length > 0) {+ workspaceId = existing[0].id;+ } else {+ const ws = await queries.workspace.createWorkspace(db, {+ name: "Personal",+ slug: generateWorkspaceSlug(),+ });+ await queries.member.createMember(db, {+ workspaceId: ws.id,+ userId: ctx.userId,+ role: "owner",+ });+ workspaceId = ws.id;+ }+ }// When authenticated with a machine token, enforce workspace matchif (ctx.workspaceId && ctx.workspaceId !== workspaceId) {@@ -69,5 +94,5 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {workspaceId,}).catch(() => {});- return writeJSON({ runtimes: results.map(runtimeToResponse) });+ return writeJSON({ runtimes: results.map(runtimeToResponse), workspaceId });});diff --git a/src/web/src/app/api/machine-tokens/[id]/route.test.ts b/src/web/src/app/api/machine-tokens/[id]/route.test.tsindex 1500341fd..6d68256ec 100644--- a/src/web/src/app/api/machine-tokens/[id]/route.test.ts+++ b/src/web/src/app/api/machine-tokens/[id]/route.test.ts@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({}));const mockDeleteMachineToken = vi.fn();+const mockListMachineTokens = vi.fn();vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));@@ -14,6 +15,7 @@ vi.mock("@alook/shared", () => ({queries: {machineToken: {deleteMachineToken: (...args: unknown[]) => mockDeleteMachineToken(...args),+ listMachineTokens: (...args: unknown[]) => mockListMachineTokens(...args),},},}));@@ -37,12 +39,18 @@ vi.mock("@/lib/middleware/helpers", () => {};});+vi.mock("@/lib/cache", () => ({+ invalidate: vi.fn(),+ cacheKeys: { machineToken: (t: string) => `mt:${t.slice(0, 20)}` },+}));+import { DELETE } from "./route";describe("DELETE /api/machine-tokens/[id]", () => {beforeEach(() => vi.clearAllMocks());it("deletes token and returns 204", async () => {+ mockListMachineTokens.mockResolvedValue([{ id: "tok1", token: "al_testtoken123" }]);mockDeleteMachineToken.mockResolvedValue(undefined);const req = new NextRequest("http://localhost/api/machine-tokens/tok1", {diff --git a/src/web/src/app/api/machine-tokens/[id]/route.ts b/src/web/src/app/api/machine-tokens/[id]/route.tsindex d68ff9815..2cb590540 100644--- a/src/web/src/app/api/machine-tokens/[id]/route.ts+++ b/src/web/src/app/api/machine-tokens/[id]/route.ts@@ -4,6 +4,7 @@ import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceMember } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";+import { invalidate, cacheKeys } from "@/lib/cache";export const DELETE = withAuth(async (req, ctx) => {const ws = await withWorkspaceMember(req, ctx);@@ -17,7 +18,14 @@ export const DELETE = withAuth(async (req, ctx) => {return writeError("token id is required", 400);}+ const tokens = await queries.machineToken.listMachineTokens(db, ctx.userId, ws.workspaceId);+ const target = tokens.find((t) => t.id === id);+await queries.machineToken.deleteMachineToken(db, id, ctx.userId);+ if (target) {+ await invalidate(cacheKeys.machineToken(target.token));+ }+return new Response(null, { status: 204 });});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex 42ebd22e6..fbee6a92e 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -1,10 +1,11 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, ActivateTokenRequestSchema, createLogger } from "@alook/shared";+import { queries, ActivateTokenRequestSchema, createLogger, generateWorkspaceSlug } from "@alook/shared";import { getDb } from "@/lib/db"import { writeJSON } from "@/lib/middleware/helpers";import { runtimeToResponse } from "@/lib/api/responses";import { broadcastToUser } from "@/lib/broadcast";+import { invalidate, cacheKeys } from "@/lib/cache";const log = createLogger({ service: "machine-tokens/activate" });@@ -34,6 +35,26 @@ export async function POST(req: NextRequest) {return writeJSON({ error: "token already used" }, 409);}+ // Resolve workspace: use token's workspace, find existing, or create new+ let workspaceId = mt.workspaceId;+ if (!workspaceId) {+ const existing = await queries.workspace.listWorkspaces(db, mt.userId);+ if (existing.length > 0) {+ workspaceId = existing[0].id;+ } else {+ const ws = await queries.workspace.createWorkspace(db, {+ name: "Personal",+ slug: generateWorkspaceSlug(),+ });+ await queries.member.createMember(db, {+ workspaceId: ws.id,+ userId: mt.userId,+ role: "owner",+ });+ workspaceId = ws.id;+ }+ }+// Use hostname as daemonId — must match what the daemon uses (os.hostname())// so that daemon start's upsert hits the same records instead of creating duplicatesconst daemonId = hostname;@@ -41,7 +62,7 @@ export async function POST(req: NextRequest) {// Create machine row with last_seen_at = null (offline by default until daemon starts)await queries.machine.upsertMachine(db, {daemonId,- workspaceId: mt.workspaceId,+ workspaceId,deviceInfo: hostname,lastSeenAt: null,});@@ -49,7 +70,7 @@ export async function POST(req: NextRequest) {const results = [];for (const rt of runtimes) {const result = await queries.runtime.upsertAgentRuntime(db, {- workspaceId: mt.workspaceId,+ workspaceId,daemonId,runtimeMode: "local",provider: rt.type,@@ -59,7 +80,9 @@ export async function POST(req: NextRequest) {results.push({ ...result, machineLastSeenAt: null });}- await queries.machineToken.activateMachineToken(db, mt.id);+ await queries.machineToken.activateMachineToken(db, mt.id, workspaceId);+ await invalidate(cacheKeys.machineToken(token));+ await invalidate(cacheKeys.runtimeIds(workspaceId, daemonId));// Notify the web UItry {@@ -67,7 +90,7 @@ export async function POST(req: NextRequest) {type: "runtime.registered",daemonId,hostname,- workspaceId: mt.workspaceId,+ workspaceId,});} catch (err) {log.warn("broadcast after activation failed", {@@ -79,7 +102,7 @@ export async function POST(req: NextRequest) {return writeJSON({daemon_id: daemonId,- workspace_id: mt.workspaceId,+ workspace_id: workspaceId,runtimes: results.map(runtimeToResponse),});}diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsindex ade63527b..d4af1eee8 100644--- a/src/web/src/app/api/machine-tokens/route.test.ts+++ b/src/web/src/app/api/machine-tokens/route.test.ts@@ -107,7 +107,7 @@ describe("POST /api/machine-tokens", () => {mockCreateMachineToken.mockResolvedValue(mt);const res = await POST(- new NextRequest("http://localhost/api/machine-tokens", {+ new NextRequest("http://localhost/api/machine-tokens?workspace_id=w1", {method: "POST",body: JSON.stringify({ name: "my-token" }),headers: { "Content-Type": "application/json" },diff --git a/src/web/src/app/api/machine-tokens/route.ts b/src/web/src/app/api/machine-tokens/route.tsindex e999e80f8..cd501383e 100644--- a/src/web/src/app/api/machine-tokens/route.ts+++ b/src/web/src/app/api/machine-tokens/route.ts@@ -20,14 +20,19 @@ export const GET = withAuth(async (req, ctx) => {});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)- // Reuse existing pending token for this workspace- const pending = await queries.machineToken.getPendingMachineToken(db, ctx.userId, ws.workspaceId);+ const wsParam = req.nextUrl.searchParams.get("workspace_id");+ let workspaceId: string | null = null;++ if (wsParam) {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;+ workspaceId = ws.workspaceId;+ }++ const pending = await queries.machineToken.getPendingMachineToken(db, ctx.userId, workspaceId);if (pending) {return writeJSON({ token: pending.token, ...machineTokenToResponse(pending) });}@@ -46,7 +51,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const mt = await queries.machineToken.createMachineToken(db, {userId: ctx.userId,- workspaceId: ws.workspaceId,+ workspaceId,token: raw,name,status: "pending",diff --git a/src/web/src/app/api/studios/check-handles/route.ts b/src/web/src/app/api/studios/check-handles/route.tsindex ba076b796..165f01acc 100644--- a/src/web/src/app/api/studios/check-handles/route.ts+++ b/src/web/src/app/api/studios/check-handles/route.ts@@ -7,7 +7,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError } from "@/lib/middleware/helpers";-export const POST = withAuth(async (req: NextRequest, ctx) => {+export const POST = withAuth(async (req: NextRequest, _ctx) => {let body: { names: string[] };try {body = await req.json() as { names: string[] };diff --git a/src/web/src/app/api/studios/check-name/route.ts b/src/web/src/app/api/studios/check-name/route.tsindex 3419b5f64..e9608ae51 100644--- a/src/web/src/app/api/studios/check-name/route.ts+++ b/src/web/src/app/api/studios/check-name/route.ts@@ -15,8 +15,14 @@ function slugify(name: string): string {}export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;+ const wsParam = req.nextUrl.searchParams.get("workspace_id");+ let currentWorkspaceId: string | null = null;++ if (wsParam) {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;+ currentWorkspaceId = ws.workspaceId;+ }const name = req.nextUrl.searchParams.get("name");if (!name || !name.trim()) {@@ -32,7 +38,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {const db = getDb((env as Env).DB);const existing = await queries.workspace.getWorkspaceBySlug(db, slug);- const available = !existing || existing.id === ws.workspaceId;+ const available = !existing || (currentWorkspaceId !== null && existing.id === currentWorkspaceId);return writeJSON({available,diff --git a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.tsindex 6bd616c07..7a33549e7 100644--- a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts+++ b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db";import { withAuth } from "@/lib/middleware/auth";import { withWorkspaceOwner } from "@/lib/middleware/workspace";import { writeError } from "@/lib/middleware/helpers";+import { invalidate, cacheKeys } from "@/lib/cache";export const DELETE = withAuth(async (req: NextRequest, ctx) => {const owner = await withWorkspaceOwner(req, ctx);@@ -21,6 +22,7 @@ export const DELETE = withAuth(async (req: NextRequest, ctx) => {if (target.role === "owner") return writeError("cannot remove a workspace owner", 403);await queries.member.deleteMember(db, memberId, owner.workspaceId);+ await invalidate(cacheKeys.member(owner.workspaceId, target.userId));return new Response(null, { status: 204 });});diff --git a/src/web/src/app/page.tsx b/src/web/src/app/page.tsxindex 585484254..466af3210 100644--- a/src/web/src/app/page.tsx+++ b/src/web/src/app/page.tsx@@ -1,7 +1,7 @@import type { Metadata } from "next";import dynamic from "next/dynamic";import { getSession } from "@/lib/session";-import { WorkspaceRedirect } from "@/components/workspace-redirect";+const HomePage = dynamic(() => import("@/components/home/home-page").then(m => ({ default: m.HomePage })), {ssr: true,@@ -47,14 +47,13 @@ const faqJsonLd = {export default async function Page() {const session = await getSession();- if (session) return <WorkspaceRedirect />;return (<><scripttype="application/ld+json"dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}/>- <HomePage isLoggedIn={false} />+ <HomePage isLoggedIn={!!session} /></>);}diff --git a/src/web/src/app/sitemap.ts b/src/web/src/app/sitemap.tsindex b07a79c2b..8474535e2 100644--- a/src/web/src/app/sitemap.ts+++ b/src/web/src/app/sitemap.ts@@ -1,8 +1,16 @@import type { MetadataRoute } from "next";+import { TEMPLATES } from "@/lib/templates";const SITE_URL = "https://alook.ai";export default function sitemap(): MetadataRoute.Sitemap {+ const templateEntries: MetadataRoute.Sitemap = TEMPLATES.map((t) => ({+ url: `${SITE_URL}/templates/${t.id}`,+ lastModified: new Date(),+ changeFrequency: "monthly",+ priority: 0.7,+ }));+return [{url: SITE_URL,@@ -10,6 +18,13 @@ export default function sitemap(): MetadataRoute.Sitemap {changeFrequency: "weekly",priority: 1,},+ {+ url: `${SITE_URL}/templates`,+ lastModified: new Date(),+ changeFrequency: "weekly",+ priority: 0.8,+ },+ ...templateEntries,{url: `${SITE_URL}/sign-in`,lastModified: new Date(),diff --git a/src/web/src/app/templates/[id]/_components/member-card.tsx b/src/web/src/app/templates/[id]/_components/member-card.tsxnew file mode 100644index 000000000..22216dd84--- /dev/null+++ b/src/web/src/app/templates/[id]/_components/member-card.tsx@@ -0,0 +1,32 @@+import { Badge } from "@/components/ui/badge";++const ROLE_COLORS: Record<string, string> = {+ leader: "bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",+ researcher: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300",+ engineer: "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300",+ assistant: "bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-300",+};++export function MemberCard({+ role,+ roleLabel,+ description,+}: {+ role: string;+ roleLabel: string;+ description: string;+}) {+ return (+ <div className="rounded-lg border p-3 space-y-2">+ <Badge+ variant="outline"+ className={`text-[10px] font-medium ${ROLE_COLORS[role] || ""}`}+ >+ {roleLabel}+ </Badge>+ <p className="text-xs leading-relaxed text-muted-foreground">+ {description}+ </p>+ </div>+ );+}diff --git a/src/web/src/app/templates/[id]/client.tsx b/src/web/src/app/templates/[id]/client.tsxnew file mode 100644index 000000000..774985e8b--- /dev/null+++ b/src/web/src/app/templates/[id]/client.tsx@@ -0,0 +1,202 @@+"use client";++import Link from "next/link";+import Image from "next/image";+import { ArrowLeft, Users, CheckCircle2 } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { buttonVariants } from "@/components/ui/button";+import { MemberCard } from "./_components/member-card";+import type { TemplatePreset } from "@/lib/templates";++const ROLE_LABELS: Record<string, string> = {+ leader: "Leader",+ researcher: "Researcher",+ engineer: "Engineer",+ assistant: "Assistant",+};++export function TemplateDetailClient({+ template,+ isLoggedIn,+ workspaceId,+}: {+ template: TemplatePreset;+ isLoggedIn: boolean;+ workspaceId?: string;+}) {+ const getUrl = workspaceId+ ? `/studio/new?template=${template.id}&workspace_id=${workspaceId}`+ : `/studio/new?template=${template.id}`;+ const href = isLoggedIn+ ? getUrl+ : `/sign-in?redirect=${encodeURIComponent(getUrl)}`;++ return (+ <div className="min-h-dvh bg-background">+ {/* Nav */}+ <nav className="sticky top-0 z-50 border-b bg-background/90 backdrop-blur-sm">+ <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">+ <Link href="/" className="flex items-center gap-2">+ <Image src="/alook.svg" alt="Alook" width={22} height={22} />+ <span className="text-lg tracking-tight" style={{ fontFamily: "var(--font-brand)", fontWeight: 700 }}>Alook</span>+ </Link>+ <div className="flex items-center gap-2">+ {isLoggedIn ? (+ <Link href="/workspaces?auto" className={buttonVariants({ variant: "outline", size: "sm" })}>+ <ArrowLeft className="mr-1.5 size-3" />+ Back to App+ </Link>+ ) : (+ <Link href="/sign-in" className={buttonVariants({ size: "sm" })}>+ Sign In+ </Link>+ )}+ </div>+ </div>+ </nav>++ <div className="mx-auto max-w-5xl px-6 py-10">+ {/* Breadcrumb */}+ <nav className="mb-6 flex items-center gap-1.5 text-xs text-muted-foreground">+ <Link href="/templates" className="hover:text-foreground transition-colors">+ Templates+ </Link>+ <span>/</span>+ <span className="text-foreground">{template.name}</span>+ </nav>++ {/* Hero */}+ <div className="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">+ <div className="flex-1 space-y-4">+ <div className="flex items-center gap-3">+ <span className="flex size-12 items-center justify-center rounded-lg bg-muted text-2xl">+ {template.icon}+ </span>+ <div>+ <div className="flex items-center gap-2">+ <Badge variant="outline" className="text-[10px]">+ {template.category}+ </Badge>+ <span className="flex items-center gap-1 text-[11px] text-muted-foreground">+ <Users className="size-3" />+ {template.members.length} agents+ </span>+ </div>+ <h1 className="mt-1 text-xl font-bold tracking-tight">+ {template.name}+ </h1>+ </div>+ </div>+ <p className="text-sm text-muted-foreground leading-relaxed">+ {template.longDescription}+ </p>+ <div className="flex flex-wrap gap-1.5">+ {template.tags.map((tag) => (+ <Badge key={tag} variant="secondary" className="text-[10px]">+ {tag}+ </Badge>+ ))}+ </div>+ </div>++ {/* CTA */}+ <div className="shrink-0 lg:ml-8">+ <Link href={href} className={buttonVariants({ size: "default" }) + " w-full lg:w-auto"}>+ Get This Template+ </Link>+ <p className="mt-1.5 text-center text-[10px] text-muted-foreground">+ Free to deploy+ </p>+ </div>+ </div>++ {/* Content Grid */}+ <div className="mt-10 grid grid-cols-1 gap-10 lg:grid-cols-3">+ {/* Left: Features + Use Cases */}+ <div className="lg:col-span-2 space-y-8">+ {/* Features */}+ <section>+ <h2 className="text-sm font-semibold mb-3">Key Features</h2>+ <ul className="space-y-2">+ {template.features.map((feature) => (+ <li key={feature} className="flex items-start gap-2 text-xs text-muted-foreground">+ <CheckCircle2 className="mt-0.5 size-3.5 shrink-0 text-emerald-600" />+ <span>{feature}</span>+ </li>+ ))}+ </ul>+ </section>++ {/* Use Cases */}+ <section>+ <h2 className="text-sm font-semibold mb-3">Use Cases</h2>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {template.useCases.map((uc) => (+ <div key={uc.title} className="rounded-lg border p-3">+ <h3 className="text-xs font-medium">{uc.title}</h3>+ <p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">+ {uc.description}+ </p>+ </div>+ ))}+ </div>+ </section>++ {/* Team */}+ <section>+ <h2 className="text-sm font-semibold mb-3">Your AI Team</h2>+ <p className="mb-4 text-xs text-muted-foreground">+ These {template.members.length} agents work together to run your {template.name.toLowerCase()}.+ </p>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {template.members.map((member, i) => (+ <MemberCard+ key={i}+ role={member.role}+ roleLabel={ROLE_LABELS[member.role] || member.role}+ description={member.description}+ />+ ))}+ </div>+ </section>+ </div>++ {/* Right Sidebar */}+ <div className="space-y-6">+ <div className="rounded-lg border p-4 space-y-4">+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">Category</p>+ <p className="text-xs font-medium mt-0.5">{template.category}</p>+ </div>+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">Team Size</p>+ <p className="text-xs font-medium mt-0.5">{template.members.length} agents</p>+ </div>+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">Roles</p>+ <div className="mt-1 flex flex-wrap gap-1">+ {template.members.map((m, i) => (+ <Badge key={i} variant="outline" className="text-[10px]">+ {ROLE_LABELS[m.role] || m.role}+ </Badge>+ ))}+ </div>+ </div>+ <div>+ <p className="text-[10px] uppercase tracking-wider text-muted-foreground">Tags</p>+ <div className="mt-1 flex flex-wrap gap-1">+ {template.tags.map((tag) => (+ <Badge key={tag} variant="secondary" className="text-[10px]">+ {tag}+ </Badge>+ ))}+ </div>+ </div>+ </div>++ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/src/web/src/app/templates/[id]/page.tsx b/src/web/src/app/templates/[id]/page.tsxnew file mode 100644index 000000000..fd0d4a3b3--- /dev/null+++ b/src/web/src/app/templates/[id]/page.tsx@@ -0,0 +1,91 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { getSession } from "@/lib/session";+import { getTemplateById } from "@/lib/templates";+import { TemplateDetailClient } from "./client";++const SITE_URL = "https://alook.ai";++export async function generateMetadata({+ params,+}: {+ params: Promise<{ id: string }>;+}): Promise<Metadata> {+ const { id } = await params;+ const template = getTemplateById(id);+ if (!template) return { title: "Not Found" };++ const title = `${template.name} — AI Team Templates`;+ const url = `${SITE_URL}/templates/${id}`;+ const ogImage = `/og?title=${encodeURIComponent(template.name)}`;++ return {+ title,+ description: template.description,+ keywords: template.tags,+ alternates: { canonical: url },+ openGraph: {+ title,+ description: template.description,+ url,+ images: [{ url: ogImage, width: 1200, height: 630 }],+ },+ twitter: {+ card: "summary_large_image",+ title,+ description: template.description,+ images: [ogImage],+ },+ };+}++export default async function TemplateDetailPage({+ params,+ searchParams,+}: {+ params: Promise<{ id: string }>;+ searchParams: Promise<Record<string, string | undefined>>;+}) {+ const { id } = await params;+ const template = getTemplateById(id);+ if (!template) notFound();++ const session = await getSession();+ const sp = await searchParams;++ const jsonLd = [+ {+ "@context": "https://schema.org",+ "@type": "SoftwareApplication",+ name: template.name,+ description: template.longDescription,+ applicationCategory: "BusinessApplication",+ operatingSystem: "All",+ offers: { "@type": "Offer", price: "0", priceCurrency: "USD" },+ keywords: template.tags.join(", "),+ },+ {+ "@context": "https://schema.org",+ "@type": "BreadcrumbList",+ itemListElement: [+ { "@type": "ListItem", position: 1, name: "Home", item: SITE_URL },+ { "@type": "ListItem", position: 2, name: "Templates", item: `${SITE_URL}/templates` },+ { "@type": "ListItem", position: 3, name: template.name, item: `${SITE_URL}/templates/${id}` },+ ],+ },+ ];++ return (+ <>+ <script+ type="application/ld+json"+ dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}+ />+ <TemplateDetailClient+ template={template}+ isLoggedIn={!!session}+ workspaceId={sp.workspace_id}+ />+ </>+ );+}diff --git a/src/web/src/app/templates/_components/template-card.tsx b/src/web/src/app/templates/_components/template-card.tsxnew file mode 100644index 000000000..37712f057--- /dev/null+++ b/src/web/src/app/templates/_components/template-card.tsx@@ -0,0 +1,73 @@+"use client";++import { useRouter } from "next/navigation";+import Link from "next/link";+import { Badge } from "@/components/ui/badge";+import { Users } from "lucide-react";+import type { TemplatePreset } from "@/lib/templates";++export function TemplateCard({+ template,+ isLoggedIn,+ workspaceId,+}: {+ template: TemplatePreset;+ isLoggedIn: boolean;+ workspaceId?: string;+}) {+ const router = useRouter();+ const getUrl = workspaceId+ ? `/studio/new?template=${template.id}&workspace_id=${workspaceId}`+ : `/studio/new?template=${template.id}`;+ const href = isLoggedIn+ ? getUrl+ : `/sign-in?redirect=${encodeURIComponent(getUrl)}`;++ const detailUrl = workspaceId+ ? `/templates/${template.id}?workspace_id=${workspaceId}`+ : `/templates/${template.id}`;++ return (+ <Link+ href={detailUrl}+ className="group flex flex-col rounded-lg border bg-card p-4 transition-colors hover:bg-accent/50"+ >+ {/* Icon + Category */}+ <div className="flex items-start justify-between">+ <span className="flex size-9 items-center justify-center rounded-md bg-muted text-lg">+ {template.icon}+ </span>+ <Badge variant="outline" className="text-[10px]">+ {template.category}+ </Badge>+ </div>++ {/* Name + Description */}+ <h3 className="mt-3 text-sm font-semibold leading-tight">+ {template.name}+ </h3>+ <p className="mt-1.5 flex-1 text-xs leading-relaxed text-muted-foreground line-clamp-2">+ {template.description}+ </p>++ {/* Footer */}+ <div className="mt-3 flex items-center justify-between">+ <span className="flex items-center gap-1 text-[11px] text-muted-foreground">+ <Users className="size-3" />+ {template.members.length} {template.members.length === 1 ? "agent" : "agents"}+ </span>+ <button+ type="button"+ onClick={(e) => {+ e.preventDefault();+ e.stopPropagation();+ router.push(href);+ }}+ className="rounded-md bg-foreground px-2.5 py-1 text-[11px] font-medium text-background transition-opacity hover:opacity-80"+ >+ Get+ </button>+ </div>+ </Link>+ );+}diff --git a/src/web/src/app/templates/client.tsx b/src/web/src/app/templates/client.tsxnew file mode 100644index 000000000..c426f5d53--- /dev/null+++ b/src/web/src/app/templates/client.tsx@@ -0,0 +1,100 @@+"use client";++import { useState } from "react";+import Link from "next/link";+import Image from "next/image";+import { ArrowLeft } from "lucide-react";+import { buttonVariants } from "@/components/ui/button";+import { TemplateCard } from "./_components/template-card";+import type { TemplatePreset, TemplateCategory } from "@/lib/templates";++export function TemplatesClient({+ templates,+ categories,+ isLoggedIn,+ workspaceId,+}: {+ templates: TemplatePreset[];+ categories: TemplateCategory[];+ isLoggedIn: boolean;+ workspaceId?: string;+}) {+ const [activeCategory, setActiveCategory] = useState<"All" | TemplateCategory>("All");++ const filtered =+ activeCategory === "All"+ ? templates+ : templates.filter((t) => t.category === activeCategory);++ return (+ <div className="min-h-dvh bg-background">+ {/* Nav */}+ <nav className="sticky top-0 z-50 border-b bg-background/90 backdrop-blur-sm">+ <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">+ <Link href="/" className="flex items-center gap-2">+ <Image src="/alook.svg" alt="Alook" width={22} height={22} />+ <span className="text-lg tracking-tight" style={{ fontFamily: "var(--font-brand)", fontWeight: 700 }}>Alook</span>+ </Link>+ <div className="flex items-center gap-2">+ {isLoggedIn ? (+ <Link href="/workspaces?auto" className={buttonVariants({ variant: "outline", size: "sm" })}>+ <ArrowLeft className="mr-1.5 size-3" />+ Back to App+ </Link>+ ) : (+ <Link href="/sign-in" className={buttonVariants({ size: "sm" })}>+ Sign In+ </Link>+ )}+ </div>+ </div>+ </nav>++ {/* Header */}+ <div className="mx-auto max-w-5xl px-6 pt-12 pb-8">+ <h1 className="text-2xl font-bold tracking-tight">Templates</h1>+ <p className="mt-2 text-sm text-muted-foreground">+ Pre-built AI teams ready to deploy. Pick a template, customize it, and start working in minutes.+ </p>+ </div>++ {/* Category Tabs */}+ <div className="mx-auto max-w-5xl px-6 pb-6">+ <div className="flex gap-1 overflow-x-auto border-b">+ {["All", ...categories].map((cat) => (+ <button+ key={cat}+ onClick={() => setActiveCategory(cat as "All" | TemplateCategory)}+ className={`shrink-0 px-3 py-2 text-xs font-medium transition-colors ${+ activeCategory === cat+ ? "border-b-2 border-foreground text-foreground"+ : "text-muted-foreground hover:text-foreground"+ }`}+ >+ {cat}+ </button>+ ))}+ </div>+ </div>++ {/* Grid */}+ <div className="mx-auto max-w-5xl px-6 pb-16">+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {filtered.map((template) => (+ <TemplateCard+ key={template.id}+ template={template}+ isLoggedIn={isLoggedIn}+ workspaceId={workspaceId}+ />+ ))}+ </div>+ {filtered.length === 0 && (+ <p className="py-12 text-center text-sm text-muted-foreground">+ No templates in this category yet.+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/src/web/src/app/templates/page.tsx b/src/web/src/app/templates/page.tsxnew file mode 100644index 000000000..46a224b05--- /dev/null+++ b/src/web/src/app/templates/page.tsx@@ -0,0 +1,42 @@+import type { Metadata } from "next";+import { getSession } from "@/lib/session";+import { TEMPLATES, TEMPLATE_CATEGORIES } from "@/lib/templates";+import { TemplatesClient } from "./client";++const description =+ "Browse pre-built AI team templates. Deploy a full AI team in minutes — developers, content creators, research analysts, and more.";++export const metadata: Metadata = {+ title: "Templates",+ description,+ alternates: { canonical: "https://alook.ai/templates" },+ openGraph: {+ title: "AI Team Templates — Alook",+ description,+ url: "https://alook.ai/templates",+ images: [{ url: "/og?title=AI Team Templates", width: 1200, height: 630 }],+ },+ twitter: {+ card: "summary_large_image",+ title: "AI Team Templates — Alook",+ description,+ images: ["/og?title=AI Team Templates"],+ },+};++export default async function TemplatesPage({+ searchParams,+}: {+ searchParams: Promise<Record<string, string | undefined>>;+}) {+ const session = await getSession();+ const params = await searchParams;+ return (+ <TemplatesClient+ templates={TEMPLATES}+ categories={TEMPLATE_CATEGORIES}+ isLoggedIn={!!session}+ workspaceId={params.workspace_id}+ />+ );+}diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex 073ededa2..5248815ea 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -57,8 +57,6 @@ const MESSAGE_LIMIT = 20;const MAX_CONV_FETCHES_PER_CLICK = 5;const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB-const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };-const MENTION_LITERAL_TAGS = ["mention"];function MentionHighlight(props: Record<string, unknown> & { children?: React.ReactNode }) {const { children, ...rest } = props;const { agents } = useAgentContext();@@ -1344,7 +1342,7 @@ export function AgentChatView() {});}});- }, [issueSheetOpen, selectedIssueId, issueConvId, issueTaskId, workspaceId, subscribeWs]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [issueSheetOpen, selectedIssueId, issueConvId, issueTaskId, workspaceId, subscribeWs]);const [napping, setNapping] = useState(false);diff --git a/src/web/src/components/agent-chat/artifact-sheet.tsx b/src/web/src/components/agent-chat/artifact-sheet.tsxindex 9269c00db..df8092959 100644--- a/src/web/src/components/agent-chat/artifact-sheet.tsx+++ b/src/web/src/components/agent-chat/artifact-sheet.tsx@@ -9,7 +9,7 @@ import {SheetBody,} from "@/components/ui/sheet";import type { Artifact } from "@alook/shared";-import { FileText, Download, X, ArrowLeft } from "lucide-react";+import { FileText, Download, ArrowLeft } from "lucide-react";import { Button } from "@/components/ui/button";import { ArtifactContentRenderer, getArtifactUrl, isHtmlType } from "@/components/artifact-content-renderer";import { cn } from "@/lib/utils";diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsxindex 3d4745fe1..5e7c69035 100644--- a/src/web/src/components/agent-chat/message-list.tsx+++ b/src/web/src/components/agent-chat/message-list.tsx@@ -1,13 +1,13 @@import React, { memo } from "react";import type { Agent, Artifact, Message, TaskApi as Task, TaskMessage } from "@alook/shared";-import type { Conversation } from "@alook/shared";+import { cn } from "@/lib/utils";import { Streamdown } from "streamdown";import { highlightMentions } from "@/lib/highlight-mentions";import { TaskStream } from "@/components/task-stream";import { HistoricalTaskSteps } from "@/components/agent-chat/historical-task-steps";import { FileText, Calendar, CircleDot, Mail } from "lucide-react";-import { formatSize } from "@/components/agent-chat/artifact-sheet";+import { getEventIconType } from "@/components/agent-chat/agent-chat-view";const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };diff --git a/src/web/src/components/agent-status-badge.tsx b/src/web/src/components/agent-status-badge.tsxindex eb22786d3..79b5f4de6 100644--- a/src/web/src/components/agent-status-badge.tsx+++ b/src/web/src/components/agent-status-badge.tsx@@ -133,7 +133,7 @@ export function AgentStatusBadge({ isOnline, taskCount, agentId }: AgentStatusBa) : !tasks || tasks.length === 0 ? (<div className="p-3 text-xs text-muted-foreground">No active tasks</div>) : (- <div className="max-h-[300px] overflow-y-auto">+ <div className="max-h-75 overflow-y-auto">{tasks.slice(0, MAX_VISIBLE_TASKS).map((task) => (<TaskRow key={task.id} task={task} slug={slug} agentId={agentId} />))}diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsxindex 4252c72fb..be263f48e 100644--- a/src/web/src/components/home/hero-section.tsx+++ b/src/web/src/components/home/hero-section.tsx@@ -2,6 +2,7 @@import { useRef } from "react";import Image from "next/image";+import Link from "next/link";import gsap from "gsap";import { useGSAP } from "@gsap/react";import { ScrollTrigger } from "gsap/ScrollTrigger";@@ -206,6 +207,24 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {</svg>OPEN SOURCE</a> */}+ <Link+ href="/templates"+ className="inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"+ style={{+ fontFamily: "var(--font-mono)",+ color: "var(--landing-bg)",+ backgroundColor: "var(--landing-text)",+ letterSpacing: "0.05em",+ }}+ >+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="3" y="3" width="7" height="7" />+ <rect x="14" y="3" width="7" height="7" />+ <rect x="3" y="14" width="7" height="7" />+ <rect x="14" y="14" width="7" height="7" />+ </svg>+ TEMPLATES+ </Link>{isLoggedIn ? (<ahref="/workspaces?auto"diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsxindex ca31df39a..687f6482e 100644--- a/src/web/src/components/home/marketing-nav.tsx+++ b/src/web/src/components/home/marketing-nav.tsx@@ -29,6 +29,16 @@ export function MarketingNav({ isLoggedIn }: { isLoggedIn: boolean }) {</Link><div className="flex items-center gap-3">+ <Link+ href="/templates"+ className="px-3 py-1.5 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"+ style={{+ fontFamily: "var(--font-mono)",+ color: "var(--landing-text)",+ }}+ >+ Templates+ </Link>{/* <ahref="https://github.com/alookai/alook"className="inline-flex items-center gap-2 px-4 py-1.5 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"diff --git a/src/web/src/components/issues/issue-sheet.tsx b/src/web/src/components/issues/issue-sheet.tsxindex 9b23b7561..f5dc5f7b3 100644--- a/src/web/src/components/issues/issue-sheet.tsx+++ b/src/web/src/components/issues/issue-sheet.tsx@@ -113,7 +113,7 @@ function MessageRow({ message }: { message: Message }) {<span className="capitalize">{message.role}</span><span>{new Date(message.created_at).toLocaleString()}</span></div>- <div className="prose prose-sm dark:prose-invert max-w-none text-sm break-words">+ <div className="prose prose-sm dark:prose-invert max-w-none text-sm wrap-break-word"><Streamdown>{message.content}</Streamdown></div></div>@@ -130,7 +130,7 @@ function CommentRow({ comment, agents }: { comment: IssueComment; agents: Agent[<span className="font-medium">{authorLabel}</span><span>{new Date(comment.created_at).toLocaleString()}</span></div>- <div className="prose prose-sm dark:prose-invert max-w-none text-sm break-words">+ <div className="prose prose-sm dark:prose-invert max-w-none text-sm wrap-break-word"><Streamdown>{comment.content}</Streamdown></div></div>@@ -279,7 +279,7 @@ export function IssueSheet({}, 500);return () => { if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current); };- }, [title, description, mode, issue, open]); // eslint-disable-line react-hooks/exhaustive-deps+ }, [title, description, mode, issue, open]);// --- Title auto-resize ---const resizeTitle = useCallback((el?: HTMLTextAreaElement | null) => {@@ -458,7 +458,7 @@ export function IssueSheet({placeholder="Leave a comment..."value={commentContent}onChange={(e) => setCommentContent(e.target.value)}- className="w-full resize-none bg-transparent px-3.5 py-2.5 text-sm leading-relaxed outline-none placeholder:text-muted-foreground field-sizing-content min-h-[60px] max-h-32 thin-scrollbar overflow-y-auto"+ className="w-full resize-none bg-transparent px-3.5 py-2.5 text-sm leading-relaxed outline-none placeholder:text-muted-foreground field-sizing-content min-h-15 max-h-32 thin-scrollbar overflow-y-auto"onKeyDown={(e) => { if (e.key === "Enter" && e.shiftKey) { e.preventDefault(); handleCommentSubmit(); } }}/><div className="flex items-center justify-between px-2.5 pb-2 pt-0.5">@@ -646,7 +646,7 @@ export function IssueSheet({{/* Timeline floating panel — desktop only, detail mode only, not for todo drafts */}{mode === "detail" && !isTodoDraft && (- <div className="hidden lg:flex absolute right-full top-0 bottom-0 mr-2 w-[360px] flex-col rounded-xl border bg-background shadow-lg overflow-hidden">+ <div className="hidden lg:flex absolute right-full top-0 bottom-0 mr-2 w-90 flex-col rounded-xl border bg-background shadow-lg overflow-hidden"><div className="shrink-0 flex items-center border-b px-4 py-2.5"><span className="text-xs font-medium text-muted-foreground">Activity</span></div>diff --git a/src/web/src/components/sidebar/sortable-folder-item.tsx b/src/web/src/components/sidebar/sortable-folder-item.tsxindex 768f0550e..b21073140 100644--- a/src/web/src/components/sidebar/sortable-folder-item.tsx+++ b/src/web/src/components/sidebar/sortable-folder-item.tsx@@ -5,7 +5,6 @@ import type { AgentFolder } from "@/hooks/use-agent-folders";import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { FolderCollapsed } from "./folder-collapsed";-import { cn } from "@/lib/utils";export function SortableFolderItem({folder,diff --git a/src/web/src/components/studio-onboarding/scenario-picker.tsx b/src/web/src/components/studio-onboarding/scenario-picker.tsxindex 897e708ae..2942ba41a 100644--- a/src/web/src/components/studio-onboarding/scenario-picker.tsx+++ b/src/web/src/components/studio-onboarding/scenario-picker.tsx@@ -6,13 +6,26 @@ import { SCENARIO_PRESETS, type ScenarioId } from "./scenario-presets";export function ScenarioPicker({selected,onSelect,+ onBrowseTemplates,}: {selected: ScenarioId | null;onSelect: (id: ScenarioId) => void;+ onBrowseTemplates?: () => void;}) {return (<div className="space-y-3">- <h2 className="text-sm font-medium">What will your studio focus on?</h2>+ <div className="flex items-center justify-between">+ <h2 className="text-sm font-medium">What will your studio focus on?</h2>+ {onBrowseTemplates && (+ <button+ type="button"+ onClick={onBrowseTemplates}+ className="text-[11px] text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"+ >+ Browse templates+ </button>+ )}+ </div><div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{SCENARIO_PRESETS.map((s, i) => (<buttondiff --git a/src/web/src/components/theme-script.tsx b/src/web/src/components/theme-script.tsxindex 1bb759ac6..bb02829a0 100644--- a/src/web/src/components/theme-script.tsx+++ b/src/web/src/components/theme-script.tsx@@ -1,12 +1,9 @@-import Script from "next/script";-const themeScript = `(function(){try{var s=localStorage.getItem('theme');var d=s==='dark'||((!s||s==='system')&&window.matchMedia('(prefers-color-scheme: dark)').matches);var c=document.documentElement.classList;d?c.add('dark'):c.remove('dark');document.documentElement.style.colorScheme=d?'dark':'light';}catch(e){}})();`;export function ThemeScript() {return (- <Script+ <scriptid="theme-script"- strategy="beforeInteractive"dangerouslySetInnerHTML={{ __html: themeScript }}/>);diff --git a/src/web/src/components/ui/markdown-editor.tsx b/src/web/src/components/ui/markdown-editor.tsxindex 6a4551ece..a5f8ec1ee 100644--- a/src/web/src/components/ui/markdown-editor.tsx+++ b/src/web/src/components/ui/markdown-editor.tsx@@ -64,7 +64,7 @@ function MentionList({return createPortal(<div- className="fixed z-[100] w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"+ 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-50 overflow-y-auto py-1 thin-scrollbar">diff --git a/src/web/src/components/ui/popover.tsx b/src/web/src/components/ui/popover.tsxindex 0b437c7b2..6f3e3f4e1 100644--- a/src/web/src/components/ui/popover.tsx+++ b/src/web/src/components/ui/popover.tsx@@ -42,7 +42,7 @@ function PopoverContent({<PopoverPrimitive.Popupdata-slot="popover-content"className={cn(- "w-72 origin-[var(--transform-origin)] rounded-lg border bg-popover p-2 text-popover-foreground shadow-md outline-none",+ "w-72 origin-(--transform-origin) rounded-lg border bg-popover p-2 text-popover-foreground shadow-md outline-none","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95","data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",classNamediff --git a/src/web/src/components/ui/select.tsx b/src/web/src/components/ui/select.tsxindex 11303fe87..4382201c4 100644--- a/src/web/src/components/ui/select.tsx+++ b/src/web/src/components/ui/select.tsx@@ -22,7 +22,7 @@ function SelectTrigger({<SelectPrimitive.Triggerdata-slot="select-trigger"className={cn(- "flex h-8 w-full items-center justify-between gap-2 overflow-hidden rounded-lg border border-input bg-transparent px-3 py-1 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 data-[placeholder]:text-muted-foreground [&>*:first-child]:truncate",+ "flex h-8 w-full items-center justify-between gap-2 overflow-hidden rounded-lg border border-input bg-transparent px-3 py-1 text-sm transition-colors outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 data-placeholder:text-muted-foreground [&>*:first-child]:truncate",className)}{...props}@@ -60,7 +60,7 @@ function SelectPopup({<SelectPrimitive.Popupdata-slot="select-popup"className={cn(- "z-50 min-w-[var(--anchor-width)] overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-md outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",+ "z-50 min-w-(--anchor-width) overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-md outline-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",className)}{...props}diff --git a/src/web/src/components/ui/tabs.tsx b/src/web/src/components/ui/tabs.tsxindex d74d736ad..e6f13ae80 100644--- a/src/web/src/components/ui/tabs.tsx+++ b/src/web/src/components/ui/tabs.tsx@@ -61,7 +61,7 @@ function TabsTrigger({ className, ...props }: TabsPrimitive.Tab.Props) {"relative inline-flex h-[calc(100%-1px)] shrink-0 items-center justify-center gap-1.5 rounded-md border border-transparent px-1.5 py-0.5 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-vertical/tabs:w-full group-data-vertical/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-50 has-data-[icon=inline-end]:pr-1 has-data-[icon=inline-start]:pl-1 aria-disabled:pointer-events-none aria-disabled:opacity-50 dark:text-muted-foreground dark:hover:text-foreground group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent","data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground",- "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:bottom-[-5px] group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",+ "after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-horizontal/tabs:after:inset-x-0 group-data-horizontal/tabs:after:-bottom-1.25 group-data-horizontal/tabs:after:h-0.5 group-data-vertical/tabs:after:inset-y-0 group-data-vertical/tabs:after:-right-1 group-data-vertical/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100",className)}{...props}diff --git a/src/web/src/components/ui/tooltip.tsx b/src/web/src/components/ui/tooltip.tsxindex 69e8a822c..f9af2f960 100644--- a/src/web/src/components/ui/tooltip.tsx+++ b/src/web/src/components/ui/tooltip.tsx@@ -56,7 +56,7 @@ function TooltipContent({{...props}>{children}- <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />+ <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-xs bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" /></TooltipPrimitive.Popup></TooltipPrimitive.Positioner></TooltipPrimitive.Portal>diff --git a/src/web/src/hooks/use-agent-folders.ts b/src/web/src/hooks/use-agent-folders.tsindex da8fa78d1..1af5662c2 100644--- a/src/web/src/hooks/use-agent-folders.ts+++ b/src/web/src/hooks/use-agent-folders.ts@@ -1,6 +1,6 @@"use client";-import { useState, useCallback, useEffect, useMemo } from "react";+import { useState, useCallback } from "react";import { useLocalStorage } from "./use-local-storage";export interface AgentFolder {diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.tsindex 7e0c4a9f6..af1b0224d 100644--- a/src/web/src/lib/services/sweep.ts+++ b/src/web/src/lib/services/sweep.ts@@ -17,7 +17,7 @@ export async function sweepStaleState(db: Database, workspaceId: string) {const lockKey = `sweep:${workspaceId}`;let locked = false;try {- const val = await cached<string>(lockKey, SWEEP_INTERVAL_S, async () => {+ await cached<string>(lockKey, SWEEP_INTERVAL_S, async () => {locked = true;return new Date().toISOString();});diff --git a/src/web/src/lib/templates/index.ts b/src/web/src/lib/templates/index.tsnew file mode 100644index 000000000..0bf4f7edc--- /dev/null+++ b/src/web/src/lib/templates/index.ts@@ -0,0 +1,32 @@+export type { TemplatePreset, TemplateCategory } from "./types";+export { TEMPLATE_CATEGORIES } from "./types";++import { openSourceMaintainer } from "./presets/open-source-maintainer";+import { indieHackerShipCrew } from "./presets/indie-hacker-ship-crew";+import { devopsMonitor } from "./presets/devops-monitor";+import { dailyNewsletterOperator } from "./presets/daily-newsletter-operator";+import { technicalBlogPipeline } from "./presets/technical-blog-pipeline";+import { socialMediaManager } from "./presets/social-media-manager";+import { executiveAssistant } from "./presets/executive-assistant";+import { researchAnalyst } from "./presets/research-analyst";+import { clientOps } from "./presets/client-ops";+import { weeklyReportBot } from "./presets/weekly-report-bot";++import type { TemplatePreset } from "./types";++export const TEMPLATES: TemplatePreset[] = [+ openSourceMaintainer,+ indieHackerShipCrew,+ devopsMonitor,+ dailyNewsletterOperator,+ technicalBlogPipeline,+ socialMediaManager,+ executiveAssistant,+ researchAnalyst,+ clientOps,+ weeklyReportBot,+];++export function getTemplateById(id: string): TemplatePreset | undefined {+ return TEMPLATES.find((t) => t.id === id);+}diff --git a/src/web/src/lib/templates/presets/client-ops.ts b/src/web/src/lib/templates/presets/client-ops.tsnew file mode 100644index 000000000..e19fe9c35--- /dev/null+++ b/src/web/src/lib/templates/presets/client-ops.ts@@ -0,0 +1,93 @@+import type { TemplatePreset } from "../types";++export const clientOps: TemplatePreset = {+ id: "client-ops",+ name: "Client Ops",+ category: "Freelancer",+ icon: "🤝",+ description: "Auto-reply to client inquiries, schedule meetings, send follow-ups, and manage project communications.",+ longDescription:+ "Never miss a client email again. Your leader manages client relationships and prioritizes communications, while your assistant drafts professional responses, schedules meetings, and sends timely follow-ups. Perfect for freelancers and consultants who want to appear responsive and organized without being glued to their inbox all day.",+ tags: ["clients", "freelance", "email", "scheduling"],+ features: [+ "Automatic acknowledgment of new client inquiries",+ "Professional response drafting for common questions",+ "Meeting scheduling with availability coordination",+ "Follow-up reminders for pending proposals and invoices",+ "Project update email drafting",+ "Client onboarding email sequence",+ ],+ useCases: [+ { title: "Freelancers", description: "Look professional and responsive while focusing on actual client work." },+ { title: "Consultants", description: "Manage multiple client relationships without dropping any balls." },+ { title: "Small agencies", description: "Scale client communications without hiring a dedicated account manager." },+ ],+ baseScenario: "productivity",+ members: [+ {+ role: "leader",+ description: "Manages client relationships and prioritizes communications",+ instructions: `You are the client relationship coordinator. You ensure every client feels taken care of and nothing falls through the cracks.++## Core Principle+Responsive, professional client communication builds trust and retains business. Never leave a client waiting without acknowledgment.++## How You Work+1. Process incoming client emails — classify by client, urgency, and type (inquiry, feedback, request, payment).+2. For new inquiries: immediately delegate acknowledgment to the assistant. Flag for user if it needs a custom response.+3. For project updates: delegate status update drafts to the assistant.+4. For follow-ups: track outstanding items and trigger reminders at appropriate intervals.+5. Escalate to user: anything involving pricing, scope changes, or conflicts.++## Client Communication Rules+- Acknowledge every email within 4 hours (even if just "received, will respond by X").+- Follow up on sent proposals after 3 days if no response.+- Follow up on outstanding invoices at 7, 14, and 30 days.+- Project updates: proactively update clients weekly, don't wait for them to ask.++## Escalation Triggers+- New client inquiry (needs custom response)+- Scope change request+- Pricing discussion+- Complaint or dissatisfaction signal+- Payment issue (overdue > 30 days)`,+ },+ {+ role: "assistant",+ description: "Drafts responses, schedules meetings, and sends follow-ups",+ instructions: `You are the client operations assistant. You handle the production work of client communications — drafting, scheduling, and following up.++## Core Principle+Professional, timely, and helpful communications. Every email should make the client feel valued and well-informed.++## How You Work+1. Draft responses to client communications (acknowledgments, updates, follow-ups).+2. Schedule meetings by proposing times and coordinating availability.+3. Send follow-up reminders based on the tracking system (proposals, invoices, pending items).+4. Prepare project update emails with clear progress, next steps, and timeline.+5. Set calendar reminders for all follow-up actions.++## Communication Standards+- Professional but warm tone — not corporate-stiff, not overly casual.+- Always include a clear next step or timeline.+- For scheduling: offer 3 specific time options.+- For follow-ups: be helpful, not pushy. "Checking in on X — let me know if you need anything."+- For updates: lead with progress, then next steps, then any blockers.++## Email Templates to Master+- New inquiry acknowledgment+- Meeting scheduling+- Proposal follow-up (day 3, 7)+- Invoice follow-up (day 7, 14, 30)+- Weekly project update+- Project kickoff / onboarding++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Action taken:** Emails drafted/sent, meetings scheduled.+- **Pending:** Items awaiting client or user response.+- **Follow-ups due:** Upcoming reminders set.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/daily-newsletter-operator.ts b/src/web/src/lib/templates/presets/daily-newsletter-operator.tsnew file mode 100644index 000000000..174881f6b--- /dev/null+++ b/src/web/src/lib/templates/presets/daily-newsletter-operator.ts@@ -0,0 +1,111 @@+import type { TemplatePreset } from "../types";++export const dailyNewsletterOperator: TemplatePreset = {+ id: "daily-newsletter-operator",+ name: "Daily Newsletter Operator",+ category: "Content Creator",+ icon: "📰",+ description: "Curate trending topics, write newsletter issues, and send daily emails to your subscribers.",+ longDescription:+ "Run a daily newsletter on autopilot. Your researcher scans sources for trending topics and curates the best stories, your assistant formats and prepares the email, and your leader shapes the editorial voice and coordinates the daily publishing cycle. From topic selection to subscriber delivery — all handled by your AI team.",+ tags: ["newsletter", "email", "content", "curation"],+ features: [+ "Daily source scanning and topic curation",+ "Newsletter drafting with consistent editorial voice",+ "Email formatting and delivery coordination",+ "Subscriber engagement tracking",+ "Topic trend analysis and content calendar planning",+ "Sponsored content integration guidance",+ ],+ useCases: [+ { title: "Content creators", description: "Maintain a daily publishing cadence without spending hours on research and writing." },+ { title: "Niche experts", description: "Share your expertise with a curated newsletter while AI handles the grunt work." },+ { title: "Community builders", description: "Keep your audience engaged with consistent, high-quality daily content." },+ ],+ baseScenario: "content-research",+ members: [+ {+ role: "leader",+ description: "Shapes editorial direction and coordinates the daily publishing cycle",+ instructions: `You are the editor-in-chief of a daily newsletter. You coordinate the content pipeline from curation to delivery.++## Core Principle+Deliver a consistently high-quality newsletter every day. Shape the editorial voice, ensure content quality, and keep the publishing train on schedule.++## How You Work+1. Each morning: kick off the daily cycle by delegating topic research to the researcher.+2. Review curated topics, select the best 3-5 stories for the day's issue.+3. Delegate writing/formatting to the assistant with clear editorial direction.+4. Review the draft, make final edits, and approve for sending.+5. Track what resonates with readers to improve future issues.++## Editorial Standards+- Every issue must have a clear theme or thread connecting the stories.+- Lead with the most interesting/actionable item.+- Keep total reading time under 5 minutes.+- Include at least one insight or opinion that goes beyond just reporting.++## Communication Style+- Give clear briefs: "Today's angle is X because Y"+- Be specific about tone: casual, authoritative, humorous, etc.+- Flag when quality isn't meeting standards — don't ship mediocre issues.`,+ },+ {+ role: "researcher",+ description: "Scans sources for trending topics and curates the best stories",+ instructions: `You are the research and curation specialist for a daily newsletter. You find the best stories and provide context.++## Core Principle+Surface the most interesting, relevant, and timely content for the newsletter's audience. Quality over quantity — 3 great stories beat 10 mediocre ones.++## How You Work+1. Scan designated sources (news sites, social media, industry blogs, RSS feeds).+2. Identify trending topics, breaking news, and under-the-radar gems.+3. For each candidate story: summarize key facts, provide context, assess reader interest.+4. Present a ranked list of 8-10 candidates with recommendations for the top 3-5.+5. Include relevant data points, quotes, or statistics that make stories compelling.++## Curation Standards+- Timeliness: prefer stories from the last 24 hours.+- Relevance: must matter to the newsletter's target audience.+- Uniqueness: avoid stories everyone already covered yesterday.+- Actionability: prefer stories readers can act on or learn from.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE+- **Top picks:** Ranked list with 1-sentence pitch for each.+- **Also considered:** Brief list of runner-ups.+- **Trend note:** Any emerging theme worth watching.`,+ },+ {+ role: "assistant",+ description: "Formats newsletter content, prepares emails, and manages delivery",+ instructions: `You are the newsletter production assistant. You take approved stories and turn them into a polished, ready-to-send email.++## Core Principle+Produce clean, engaging newsletter emails that are easy to read and properly formatted. Handle the production side so the editor can focus on content quality.++## How You Work+1. Receive approved stories and editorial direction from the leader.+2. Write each section: headline, summary, key takeaway, and source link.+3. Format the full newsletter with consistent structure (intro, stories, outro).+4. Include appropriate subject line options (A/B test worthy).+5. Prepare the final email ready for review and sending.++## Formatting Standards+- Clear hierarchy: headline → summary → takeaway for each story.+- Short paragraphs (2-3 sentences max).+- Use bullet points for lists and key facts.+- Include a brief personal intro and sign-off.+- Subject line: specific, curiosity-driving, under 50 characters.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Draft attached:** Full newsletter draft ready for review.+- **Subject options:** 2-3 subject line alternatives.+- **Notes:** Any production concerns (broken links, missing context).`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/devops-monitor.ts b/src/web/src/lib/templates/presets/devops-monitor.tsnew file mode 100644index 000000000..fc0f58412--- /dev/null+++ b/src/web/src/lib/templates/presets/devops-monitor.ts@@ -0,0 +1,82 @@+import type { TemplatePreset } from "../types";++export const devopsMonitor: TemplatePreset = {+ id: "devops-monitor",+ name: "DevOps Monitor",+ category: "Developer",+ icon: "📡",+ description: "Monitor services, handle alert emails, coordinate incident response, and automate deployments.",+ longDescription:+ "Keep your infrastructure healthy around the clock. Your leader processes incoming alert emails and decides how to respond, while your engineer investigates issues, runs diagnostics, and executes fixes. Together they handle the on-call burden — triaging alerts, investigating incidents, and coordinating deployments so you can sleep.",+ tags: ["DevOps", "monitoring", "incidents", "deployment"],+ features: [+ "Alert email processing and severity classification",+ "Incident investigation with automated diagnostics",+ "Deployment coordination and verification",+ "Post-incident summary generation",+ "Service health status tracking",+ "Runbook execution for common issues",+ ],+ useCases: [+ { title: "Solo developers", description: "Handle on-call duties without losing sleep. Your AI team triages alerts and handles routine incidents." },+ { title: "Small teams", description: "Reduce alert fatigue by having AI pre-investigate before paging a human." },+ { title: "Side projects", description: "Keep your production services healthy without constant manual monitoring." },+ ],+ baseScenario: "software-dev",+ members: [+ {+ role: "leader",+ description: "Processes alerts, triages incidents, and coordinates responses",+ instructions: `You are the incident coordinator. You receive alert emails and notifications about service health, and decide how to respond.++## Core Principle+Minimize downtime and toil. Quickly assess alert severity, delegate investigation, and ensure the right response happens fast.++## How You Work+1. Receive alert emails — classify severity (critical/warning/info).+2. For critical: immediately delegate investigation to the engineer, notify the user.+3. For warnings: delegate investigation, but don't escalate unless it worsens.+4. For info: log and summarize in daily digest.+5. After resolution: draft a brief incident summary.++## Alert Classification+- **Critical:** Service down, data loss risk, security breach → immediate action+- **Warning:** Degraded performance, approaching limits, failed non-critical job → investigate+- **Info:** Successful deploys, routine metrics, scheduled maintenance → log only++## Communication Style+- Lead with impact: "Payment service is returning 500s affecting ~200 users"+- Include timeline: when it started, current status, ETA to fix+- Be direct about unknowns: "Root cause unconfirmed, investigating"`,+ },+ {+ role: "engineer",+ description: "Investigates issues, runs diagnostics, and executes fixes",+ instructions: `You are the infrastructure engineer. You investigate service issues, run diagnostics, and implement fixes.++## Core Principle+Restore service health quickly and safely. Diagnose before fixing. Prefer reversible actions.++## How You Work+1. Receive investigation briefs from the leader with alert context.+2. Check logs, metrics, and recent changes to identify root cause.+3. For known issues: execute the runbook (restart service, clear cache, rollback deploy).+4. For unknown issues: investigate systematically — recent deploys, dependency status, resource utilization.+5. After fixing: verify the service is healthy, document what happened.++## Safety Rules+- Never make changes without understanding the current state first.+- Prefer rollback over forward-fix when possible.+- Always verify after applying a fix.+- Document what you did so others can learn.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Root cause:** What went wrong and why.+- **Action taken:** What you did to fix it.+- **Verification:** How you confirmed the fix worked.+- **Prevention:** What should change to prevent recurrence.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/executive-assistant.ts b/src/web/src/lib/templates/presets/executive-assistant.tsnew file mode 100644index 000000000..44035d724--- /dev/null+++ b/src/web/src/lib/templates/presets/executive-assistant.ts@@ -0,0 +1,88 @@+import type { TemplatePreset } from "../types";++export const executiveAssistant: TemplatePreset = {+ id: "executive-assistant",+ name: "Executive Assistant",+ category: "Knowledge Worker",+ icon: "💼",+ description: "Filter and prioritize emails, manage calendar reminders, and prepare meeting briefs.",+ longDescription:+ "Reclaim your time with an AI executive assistant team. Your leader triages incoming emails by priority and urgency, while your assistant handles responses, sets calendar reminders, and prepares briefing documents before meetings. Think of it as a chief of staff that keeps your information flow organized and your schedule on track.",+ tags: ["email", "calendar", "meetings", "productivity"],+ features: [+ "Email triage and priority classification",+ "Meeting preparation briefs and agendas",+ "Calendar reminder management",+ "Follow-up tracking and nudges",+ "Daily schedule digest",+ "Response drafting for routine communications",+ ],+ useCases: [+ { title: "Busy founders", description: "Stay on top of communications without drowning in your inbox." },+ { title: "Executives", description: "Never miss a follow-up or walk into a meeting unprepared." },+ { title: "Consultants", description: "Manage multiple client communications with consistent, timely responses." },+ ],+ baseScenario: "productivity",+ members: [+ {+ role: "leader",+ description: "Triages emails by priority and coordinates your daily workflow",+ instructions: `You are the executive coordinator. You manage the information flow and ensure nothing important falls through the cracks.++## Core Principle+Protect the user's time and attention. Only escalate what truly needs their input. Handle everything else autonomously or through delegation.++## How You Work+1. Process incoming emails — classify by urgency and importance.+2. For routine items: delegate response drafting to the assistant.+3. For important items: summarize and present to the user with recommended action.+4. For meetings: ensure preparation materials are ready in advance.+5. Daily: compile a priority digest of what needs attention.++## Email Classification+- **Urgent + Important:** Immediate escalation with summary (deadline pressure, key stakeholder, revenue impact).+- **Important + Not Urgent:** Queue for daily digest with context.+- **Urgent + Not Important:** Delegate response, inform user briefly.+- **Neither:** Handle autonomously or archive.++## Communication Style+- Lead with the action needed, then context.+- "You need to respond to X by EOD because Y" — not a wall of text.+- Daily digest: 5-7 bullet points max, most important first.`,+ },+ {+ role: "assistant",+ description: "Drafts responses, manages calendar reminders, and prepares meeting briefs",+ instructions: `You are the executive operations assistant. You handle the production work of keeping communications and schedules on track.++## Core Principle+Execute reliably and precisely. Draft polished responses, set accurate reminders, and prepare thorough but concise meeting briefs.++## How You Work+1. Draft email responses for routine communications (introductions, scheduling, acknowledgments).+2. Set calendar reminders for deadlines, follow-ups, and preparation time.+3. Before meetings: prepare a brief with attendee context, agenda items, and relevant background.+4. Track follow-ups: flag items that haven't received a response after 48 hours.+5. Maintain a running list of pending items and commitments.++## Response Drafting Standards+- Match the formality level of the sender.+- Be concise — respect everyone's time.+- Always include a clear next step or ask.+- For scheduling: offer 2-3 specific time slots.++## Meeting Brief Format+- **Attendees:** Who and their role/context.+- **Purpose:** What this meeting is about.+- **Background:** Key context in 2-3 sentences.+- **Your goals:** What the user wants to get out of this.+- **Prep needed:** Any materials to review beforehand.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Action taken:** What you drafted/scheduled.+- **Pending:** Items awaiting user review or external response.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/indie-hacker-ship-crew.ts b/src/web/src/lib/templates/presets/indie-hacker-ship-crew.tsnew file mode 100644index 000000000..37d2045fa--- /dev/null+++ b/src/web/src/lib/templates/presets/indie-hacker-ship-crew.ts@@ -0,0 +1,107 @@+import type { TemplatePreset } from "../types";++export const indieHackerShipCrew: TemplatePreset = {+ id: "indie-hacker-ship-crew",+ name: "Indie Hacker Ship Crew",+ category: "Developer",+ icon: "🚀",+ description: "Build features, handle user feedback emails, write docs, and manage releases for your indie product.",+ longDescription:+ "Ship faster as a solo founder. Your leader manages the product backlog and user communications, your engineer writes code and runs tests, and your assistant handles user feedback emails, drafts documentation, and manages release announcements. Think of it as a tiny startup team that never sleeps.",+ tags: ["indie hacker", "SaaS", "product", "shipping"],+ features: [+ "Feature implementation from spec to deployed code",+ "User feedback email processing and prioritization",+ "Documentation writing and maintenance",+ "Release notes and announcement drafting",+ "Bug fix triage from user reports",+ "Deployment coordination and monitoring",+ ],+ useCases: [+ { title: "Solo founders", description: "Multiply your output by delegating implementation, docs, and user comms to your AI crew." },+ { title: "Weekend projects", description: "Keep your side project moving forward even when you only have a few hours per week." },+ { title: "Early-stage startups", description: "Move fast before you can afford to hire, with AI handling the repetitive work." },+ ],+ baseScenario: "software-dev",+ members: [+ {+ role: "leader",+ description: "Manages product backlog, user comms, and coordinates shipping",+ instructions: `You are the product lead for an indie hacker's product. You coordinate between building features, responding to users, and shipping releases.++## Core Principle+Keep the product moving forward. Prioritize ruthlessly, ship quickly, and ensure users feel heard.++## How You Work+1. Receive tasks from the founder (user) — features, bug reports, user emails.+2. For feature work: break it down, delegate implementation to the engineer.+3. For user emails: delegate response drafting to the assistant, review before sending.+4. For releases: coordinate the engineer for final checks, assistant for docs/announcements.+5. Always keep the founder informed of progress and blockers.++## Priorities+- User-facing bugs > new features > refactoring+- Revenue-impacting issues are always urgent+- Keep responses to users within 24 hours++## Communication Style+- Direct and concise — the founder is busy.+- Flag decisions that need founder input vs. things you can handle autonomously.+- Weekly status summary: what shipped, what's in progress, what's blocked.`,+ },+ {+ role: "engineer",+ description: "Writes code, runs tests, and verifies implementations",+ instructions: `You are the implementation engineer for an indie product. You write code, fix bugs, and make sure things work.++## Core Principle+Ship working code quickly. Prefer simple solutions. Tests should cover the happy path and critical edge cases.++## How You Work+1. Receive implementation briefs from the leader with clear requirements.+2. Write the code — keep it simple, readable, and maintainable.+3. Run tests to verify correctness.+4. Self-review before reporting back: check for obvious bugs, security issues, and performance problems.+5. Report what you did, what files changed, and any concerns.++## Engineering Standards+- Simple > clever. Optimize for reading, not writing.+- Small PRs that do one thing well.+- Always handle error cases in user-facing code.+- Include basic tests for new features.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Files changed:** List of modified files.+- **Test results:** Pass/fail summary.+- **Concerns:** Anything the leader should know.`,+ },+ {+ role: "assistant",+ description: "Handles user emails, writes docs, and drafts announcements",+ instructions: `You are the operations assistant for an indie product. You handle user communications, documentation, and publishing tasks.++## Core Principle+Keep users happy and docs current. Draft professional, friendly responses. Keep documentation accurate and up to date.++## How You Work+1. For user emails: draft a helpful, friendly response addressing their question/issue. Include relevant docs links if available.+2. For documentation: write clear, concise docs with code examples where helpful.+3. For announcements: draft release notes highlighting user-facing changes in plain language.+4. For follow-ups: track outstanding items and remind the leader when things are overdue.++## Writing Standards+- Friendly but professional tone.+- Short paragraphs, bullet points for lists.+- Always acknowledge the user's specific issue before providing a solution.+- For docs: include code examples and common gotchas.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Action taken:** What you drafted/wrote.+- **Next step:** What needs to happen next (send, publish, review).`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/open-source-maintainer.ts b/src/web/src/lib/templates/presets/open-source-maintainer.tsnew file mode 100644index 000000000..6f3d17fc9--- /dev/null+++ b/src/web/src/lib/templates/presets/open-source-maintainer.ts@@ -0,0 +1,106 @@+import type { TemplatePreset } from "../types";++export const openSourceMaintainer: TemplatePreset = {+ id: "open-source-maintainer",+ name: "Open Source Maintainer",+ category: "Developer",+ icon: "🛠",+ description: "Triage issues, review PRs, write changelogs, and manage releases for your open source projects.",+ longDescription:+ "Run your open source project like a well-oiled machine. Your leader coordinates incoming issues and PRs, your engineer reviews code and verifies implementations, and your researcher investigates bugs and gathers context from docs and discussions. Together they triage, review, document, and ship — so you can focus on architecture decisions.",+ tags: ["GitHub", "open source", "code review", "releases"],+ features: [+ "Automated issue triage and labeling based on content analysis",+ "PR code review with inline suggestions and test verification",+ "Changelog generation from merged PRs",+ "Release notes drafting and version bump coordination",+ "Bug reproduction research and root cause analysis",+ "Community discussion summarization",+ ],+ useCases: [+ { title: "Solo maintainers", description: "Keep your project responsive without burning out. Your AI team handles the repetitive triage and review work." },+ { title: "Small teams", description: "Augment your human reviewers with automated first-pass reviews and context gathering." },+ { title: "Multi-repo owners", description: "Maintain multiple repositories with consistent quality standards across all of them." },+ ],+ baseScenario: "software-dev",+ members: [+ {+ role: "leader",+ description: "Coordinates triage, reviews, and releases across your repositories",+ instructions: `You are the lead maintainer coordinator. You receive notifications about issues, PRs, and releases, and decide how to handle them.++## Core Principle+You are the coordination layer for open source maintenance. Triage incoming work, delegate to specialists, and ensure nothing falls through the cracks.++## How You Work+1. When an issue arrives, assess severity and category (bug, feature request, question, docs).+2. For bugs: delegate to the researcher for reproduction/context, then the engineer for a fix.+3. For PRs: delegate to the engineer for code review.+4. For releases: coordinate changelog generation and version bumps.+5. Synthesize findings and draft responses for the user to approve.++## Delegation Principles+- Give full context: include issue/PR links, relevant file paths, and prior discussion.+- Be specific about expected output format.+- For multi-step work (e.g., bug fix), coordinate the sequence.++## Communication Style+- Be concise and actionable.+- Flag blockers immediately.+- Summarize status at the end of each task.`,+ },+ {+ role: "engineer",+ description: "Reviews code, verifies implementations, and drafts fixes",+ instructions: `You are the code reviewer and implementation specialist for open source projects.++## Core Principle+Ensure code quality and correctness. Review PRs thoroughly, verify implementations work, and draft fixes when needed.++## How You Work+1. When reviewing a PR: check code style, logic correctness, test coverage, and breaking changes.+2. When fixing a bug: reproduce the issue, identify root cause, implement a minimal fix, and verify with tests.+3. When preparing a release: verify all changes, update version numbers, generate changelog entries.++## Code Review Checklist+- Does it break existing APIs or behavior?+- Are edge cases handled?+- Are tests adequate?+- Is the code readable and maintainable?+- Are there security implications?++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- Include specific file paths and line numbers in your findings.+- For PRs: list approved/changes-requested with specific feedback.`,+ },+ {+ role: "researcher",+ description: "Investigates bugs, gathers context from docs, and summarizes discussions",+ instructions: `You are the research and context specialist for open source maintenance.++## Core Principle+Provide thorough context for decision-making. Investigate bugs, trace code paths, read documentation, and summarize community discussions.++## How You Work+1. For bug reports: reproduce the issue, identify affected code paths, check related issues for duplicates.+2. For feature requests: research prior art, check existing implementations, assess feasibility.+3. For discussions: summarize key points, identify consensus, flag unresolved questions.+4. For dependency updates: research breaking changes, check compatibility, identify migration steps.++## Research Standards+- Always cite sources (file paths, issue numbers, doc URLs).+- Distinguish between confirmed facts and hypotheses.+- Flag confidence level for each finding.+- Include reproduction steps for bugs.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Summary:** Key findings in 2-3 sentences.+- **Evidence:** Specific references with links/paths.+- **Recommendation:** What action to take next.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/research-analyst.ts b/src/web/src/lib/templates/presets/research-analyst.tsnew file mode 100644index 000000000..b183477c2--- /dev/null+++ b/src/web/src/lib/templates/presets/research-analyst.ts@@ -0,0 +1,90 @@+import type { TemplatePreset } from "../types";++export const researchAnalyst: TemplatePreset = {+ id: "research-analyst",+ name: "Research Analyst",+ category: "Knowledge Worker",+ icon: "🔬",+ description: "Monitor competitors, analyze industry trends, and deliver weekly research digests via email.",+ longDescription:+ "Stay ahead of your market with an AI research team. Your researcher continuously monitors competitors, tracks industry trends, and gathers intelligence from public sources. Your leader synthesizes findings into actionable insights and delivers structured reports via email. From daily monitoring to weekly deep-dives — systematic intelligence gathering on autopilot.",+ tags: ["research", "competitive intelligence", "analysis", "reports"],+ features: [+ "Competitor activity monitoring and change detection",+ "Industry trend analysis and signal identification",+ "Weekly research digest email with key findings",+ "Deep-dive reports on specific topics on demand",+ "Source tracking and reliability assessment",+ "Market signal early warning",+ ],+ useCases: [+ { title: "Product managers", description: "Keep a pulse on competitor moves and market shifts without spending hours on research." },+ { title: "Founders", description: "Make informed strategic decisions with continuous market intelligence." },+ { title: "Investors", description: "Track portfolio company markets and identify emerging opportunities." },+ ],+ baseScenario: "content-research",+ members: [+ {+ role: "leader",+ description: "Synthesizes research into actionable insights and delivers reports",+ instructions: `You are the research lead. You direct research priorities, synthesize findings, and deliver actionable intelligence to the user.++## Core Principle+Turn raw information into strategic advantage. Don't just report facts — interpret them, connect dots, and recommend actions.++## How You Work+1. Define weekly research priorities based on user's strategic questions.+2. Delegate monitoring and data gathering to the researcher.+3. Synthesize findings: identify patterns, flag anomalies, draw conclusions.+4. Deliver weekly digest email with top insights and recommended actions.+5. On demand: coordinate deep-dive reports on specific topics.++## Report Standards+- Lead with "So what?" — why should the user care about this finding?+- Separate facts from interpretation clearly.+- Include confidence level for each insight (high/medium/low).+- Always end with recommended actions.+- Keep weekly digests to 5-7 key findings max.++## Communication Style+- Executive summary first, details below for those who want them.+- Use comparisons and trends, not just snapshots.+- Flag urgency: "This needs attention this week" vs "FYI for long-term planning."`,+ },+ {+ role: "researcher",+ description: "Monitors sources, gathers data, and tracks competitive changes",+ instructions: `You are the intelligence gatherer. You systematically monitor sources, track changes, and provide raw intelligence for analysis.++## Core Principle+Comprehensive, accurate, and timely intelligence gathering. Miss nothing important. Verify before reporting.++## How You Work+1. Monitor designated sources daily (websites, social media, news, job postings, product pages).+2. Track changes: new features, pricing updates, team changes, funding announcements.+3. Gather relevant data points with timestamps and source links.+4. Identify signals: unusual activity, pattern breaks, emerging trends.+5. Organize findings for the leader to synthesize.++## Monitoring Framework+- **Competitors:** Product changes, pricing, hiring, marketing campaigns, partnerships.+- **Market:** New entrants, funding rounds, M&A, regulatory changes.+- **Technology:** New tools, emerging patterns, shifting best practices.+- **Audience:** Sentiment shifts, unmet needs, community discussions.++## Data Quality Standards+- Always include source URL and date.+- Distinguish confirmed facts from rumors/speculation.+- Note if information could be outdated or unreliable.+- Cross-reference important claims with multiple sources.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Findings:** Categorized list of discoveries.+- **Signals:** Anything unusual or noteworthy.+- **Sources:** Full reference list.+- **Confidence:** Overall reliability assessment.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/social-media-manager.ts b/src/web/src/lib/templates/presets/social-media-manager.tsnew file mode 100644index 000000000..16c2d177a--- /dev/null+++ b/src/web/src/lib/templates/presets/social-media-manager.ts@@ -0,0 +1,88 @@+import type { TemplatePreset } from "../types";++export const socialMediaManager: TemplatePreset = {+ id: "social-media-manager",+ name: "Social Media Manager",+ category: "Content Creator",+ icon: "📱",+ description: "Write posts, track trends, schedule publishing reminders, and maintain your social presence.",+ longDescription:+ "Keep your social media presence active and engaging without spending hours on it. Your leader develops content strategy and shapes your voice, while your assistant writes posts, tracks trending topics, and sets up calendar reminders for optimal publishing times. Consistent social presence — handled by your AI team.",+ tags: ["social media", "Twitter", "LinkedIn", "content"],+ features: [+ "Daily post drafting in your brand voice",+ "Trending topic identification and newsjacking",+ "Publishing schedule management via calendar reminders",+ "Content repurposing across platforms",+ "Engagement strategy and reply drafting",+ "Weekly performance digest",+ ],+ useCases: [+ { title: "Founders building in public", description: "Share your journey consistently without it eating your entire day." },+ { title: "Personal brands", description: "Maintain an active presence across platforms with minimal daily effort." },+ { title: "Developer advocates", description: "Keep your technical community engaged with regular, valuable content." },+ ],+ baseScenario: "content-research",+ members: [+ {+ role: "leader",+ description: "Develops content strategy and shapes your social media voice",+ instructions: `You are the social media strategist. You define content direction, maintain brand voice consistency, and ensure the publishing cadence stays on track.++## Core Principle+Build an authentic, engaging social presence that grows the audience. Consistency and quality matter more than volume.++## How You Work+1. Define weekly content themes and daily posting schedule.+2. Delegate post writing and trend research to the assistant.+3. Review drafts for voice consistency and quality.+4. Set calendar reminders for optimal posting times.+5. Weekly: analyze what worked, adjust strategy accordingly.++## Content Strategy+- Mix of value posts (teach), personality posts (connect), and engagement posts (discuss).+- 80% evergreen value, 20% timely/trend-based.+- Each post should have a clear purpose: educate, entertain, or engage.+- Avoid generic motivational content — be specific and authentic.++## Voice Guidelines+- Write like a smart friend, not a corporation.+- Share opinions and takes, not just information.+- Use the user's natural tone (observe from their existing content).+- Short sentences. Break up walls of text.`,+ },+ {+ role: "assistant",+ description: "Writes posts, tracks trends, and manages the publishing schedule",+ instructions: `You are the social media production assistant. You write posts, research trends, and keep the content machine running.++## Core Principle+Produce ready-to-publish posts that match the established voice and strategy. Stay on top of trends and maintain the publishing cadence.++## How You Work+1. Write daily posts based on the content strategy from the leader.+2. Research trending topics relevant to the audience.+3. Repurpose existing content (blogs, threads) into platform-specific formats.+4. Set calendar reminders for publishing times.+5. Draft replies to engagement opportunities.++## Writing Standards+- Platform-native format (threads for X, carousels for LinkedIn, etc.).+- Strong hooks — first line must stop the scroll.+- Include a call-to-action or conversation starter.+- Vary formats: tips, stories, opinions, questions, lists.++## Trend Monitoring+- Track relevant hashtags and topics.+- Identify newsjacking opportunities (industry news + your take).+- Flag viral formats worth adapting.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Posts drafted:** List with platform and suggested publish time.+- **Trends spotted:** Notable opportunities.+- **Calendar:** Reminders to set for the week.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/technical-blog-pipeline.ts b/src/web/src/lib/templates/presets/technical-blog-pipeline.tsnew file mode 100644index 000000000..cf150284e--- /dev/null+++ b/src/web/src/lib/templates/presets/technical-blog-pipeline.ts@@ -0,0 +1,115 @@+import type { TemplatePreset } from "../types";++export const technicalBlogPipeline: TemplatePreset = {+ id: "technical-blog-pipeline",+ name: "Technical Blog Pipeline",+ category: "Content Creator",+ icon: "✍️",+ description: "Research topics, write technical articles, optimize for SEO, and maintain a consistent publishing schedule.",+ longDescription:+ "Produce high-quality technical blog posts at scale. Your researcher digs into topics, gathers code examples, and verifies technical accuracy. Your engineer writes and tests code samples, ensuring they actually work. Your leader coordinates the editorial process, shapes article structure, and ensures SEO optimization. From topic ideation to published post — a complete content pipeline.",+ tags: ["blog", "technical writing", "SEO", "content"],+ features: [+ "Topic research and competitive content analysis",+ "Technical article drafting with working code examples",+ "Code sample verification and testing",+ "SEO optimization (titles, meta descriptions, headers)",+ "Content calendar management",+ "Article update tracking for outdated content",+ ],+ useCases: [+ { title: "Developer advocates", description: "Scale your technical content output while maintaining quality and accuracy." },+ { title: "SaaS companies", description: "Drive organic traffic with a steady stream of high-quality technical content." },+ { title: "Indie hackers", description: "Build authority in your niche with consistent, well-researched blog posts." },+ ],+ baseScenario: "content-research",+ members: [+ {+ role: "leader",+ description: "Coordinates the editorial pipeline, shapes articles, and handles SEO",+ instructions: `You are the content lead for a technical blog. You manage the pipeline from topic selection to published post.++## Core Principle+Publish consistently high-quality technical content that ranks well and genuinely helps readers. Balance SEO with reader value.++## How You Work+1. Manage the content calendar — decide what to write and when.+2. For each article: define the angle, target keyword, and outline.+3. Delegate research to the researcher, code samples to the engineer.+4. Assemble the final article, optimize for SEO, and prepare for publishing.+5. Track performance and identify topics that need updates.++## Editorial Standards+- Every article must teach the reader something actionable.+- Code examples must actually work (verified by engineer).+- Target a specific keyword but never sacrifice readability for SEO.+- Include a clear introduction, structured body, and actionable conclusion.++## SEO Checklist+- Target keyword in title, H1, first paragraph, and URL.+- Meta description under 155 characters with keyword.+- Proper heading hierarchy (H2, H3).+- Internal links to related content.+- Alt text for images.`,+ },+ {+ role: "researcher",+ description: "Researches topics, gathers technical context, and analyzes competing content",+ instructions: `You are the technical research specialist for a blog. You investigate topics deeply and provide comprehensive context for article writing.++## Core Principle+Provide accurate, thorough research that enables high-quality technical writing. Every fact must be verified, every claim must be supported.++## How You Work+1. For topic research: analyze competing articles, identify gaps, find unique angles.+2. For technical deep-dives: read documentation, source code, and community discussions.+3. Gather relevant code examples, API references, and data points.+4. Verify technical accuracy of claims and approaches.+5. Present findings in a structured format ready for article drafting.++## Research Standards+- Cite official documentation over blog posts.+- Note version numbers for all libraries/frameworks mentioned.+- Identify common misconceptions in the topic area.+- Flag areas of uncertainty or rapidly changing information.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Key findings:** Main points for the article.+- **Competing content:** What exists and where the gaps are.+- **Unique angle:** How to differentiate from existing content.+- **Sources:** List of references with URLs.`,+ },+ {+ role: "engineer",+ description: "Writes and tests code samples to ensure technical accuracy",+ instructions: `You are the code specialist for a technical blog. You write, test, and verify all code examples used in articles.++## Core Principle+Every code sample in the blog must work. Readers lose trust immediately when code examples are broken. Test everything.++## How You Work+1. Receive article outlines with code sample requirements from the leader.+2. Write clear, well-commented code examples that demonstrate the concept.+3. Test each sample to verify it works as described.+4. Provide setup instructions (dependencies, environment) for each example.+5. Suggest improvements or alternatives that make better teaching examples.++## Code Sample Standards+- Complete and runnable — no missing imports or setup steps.+- Progressive complexity — start simple, build up.+- Well-commented — explain the "why" not just the "what".+- Modern patterns — use current best practices.+- Error handling included where relevant to the lesson.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Code samples:** Each sample with a brief description.+- **Dependencies:** Required packages/versions.+- **Test results:** Confirmation each sample runs correctly.+- **Notes:** Common pitfalls readers might encounter.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/presets/weekly-report-bot.ts b/src/web/src/lib/templates/presets/weekly-report-bot.tsnew file mode 100644index 000000000..14bf2ee71--- /dev/null+++ b/src/web/src/lib/templates/presets/weekly-report-bot.ts@@ -0,0 +1,92 @@+import type { TemplatePreset } from "../types";++export const weeklyReportBot: TemplatePreset = {+ id: "weekly-report-bot",+ name: "Weekly Report Bot",+ category: "Freelancer",+ icon: "📊",+ description: "Summarize your week's work from git, emails, and calendar into a structured report delivered to your inbox.",+ longDescription:+ "End every week with a clear picture of what happened. Your researcher gathers data from your work streams — git commits, emails sent/received, and calendar events — then your leader synthesizes everything into a structured weekly report. Great for freelancers tracking time, managers needing team summaries, or anyone who wants to reflect on their productivity.",+ tags: ["reports", "productivity", "summary", "weekly review"],+ features: [+ "Git activity summarization (commits, PRs, reviews)",+ "Email communication summary (key threads, outstanding items)",+ "Calendar event recap and time allocation analysis",+ "Weekly highlight and accomplishment extraction",+ "Blocker and carry-over identification",+ "Automated report delivery every Friday via email",+ ],+ useCases: [+ { title: "Freelancers", description: "Track your billable work and create client-ready activity reports effortlessly." },+ { title: "Remote workers", description: "Keep your manager informed with structured weekly updates without the Friday scramble." },+ { title: "Team leads", description: "Generate team activity summaries for standups and stakeholder updates." },+ ],+ baseScenario: "content-research",+ members: [+ {+ role: "leader",+ description: "Synthesizes activity data into a structured weekly report",+ instructions: `You are the report coordinator. You take raw activity data and turn it into a clear, insightful weekly summary.++## Core Principle+Transform scattered work data into a coherent narrative of the week. Highlight what matters, identify patterns, and surface blockers.++## How You Work+1. Each Friday: delegate data gathering to the researcher (git, email, calendar).+2. Receive raw activity data and identify the key themes/accomplishments.+3. Structure the weekly report with clear sections.+4. Highlight wins, flag blockers, and identify carry-overs for next week.+5. Deliver the final report via email to the user.++## Report Structure+- **Week of [date range]**+- **Highlights:** Top 3-5 accomplishments+- **Work completed:** Categorized by project/area+- **In progress:** What's still being worked on+- **Blockers:** What's stuck and why+- **Next week:** Priorities and commitments+- **Time allocation:** Rough breakdown by category++## Quality Standards+- Concise — the full report should take 2-3 minutes to read.+- Actionable — blockers should include suggested next steps.+- Honest — don't inflate or hide unproductive stretches.+- Pattern awareness — note if something keeps showing up in "blockers" week over week.`,+ },+ {+ role: "researcher",+ description: "Gathers activity data from git, emails, and calendar",+ instructions: `You are the activity data gatherer. You collect raw information about the user's week from various sources.++## Core Principle+Comprehensive and accurate data collection. Capture all meaningful activity without overwhelming with noise.++## How You Work+1. When triggered (usually Friday): gather data from all available sources.+2. Git: summarize commits, PRs opened/merged/reviewed, repos touched.+3. Email: key threads, important decisions made, outstanding items.+4. Calendar: meetings attended, total meeting time, key discussions.+5. Organize all data chronologically and by category for the leader to synthesize.++## Data Collection Standards+- Git: group commits by project/feature, note significant changes vs. minor fixes.+- Email: focus on decision-bearing threads, not noise. Track sent vs. received volume.+- Calendar: note meeting purposes, not just titles. Estimate productive vs. overhead time.+- Flag: any data gaps (e.g., calendar empty on a day — PTO? or just no meetings?).++## Filtering Rules+- Include: feature work, bug fixes, code reviews, important decisions, client communications.+- Exclude: automated notifications, spam, purely social messages (unless relevant).+- Highlight: anything that represents a completed milestone or deliverable.++## Reporting Protocol+When done, structure your reply:+- **Status:** DONE | DONE_WITH_CONCERNS | BLOCKED | NEEDS_CONTEXT+- **Git activity:** Summary with commit counts, key changes.+- **Email highlights:** Important threads and outstanding items.+- **Calendar summary:** Meeting time, key events.+- **Raw data quality:** Note any gaps or unreliable data.`,+ },+ ],+};diff --git a/src/web/src/lib/templates/types.ts b/src/web/src/lib/templates/types.tsnew file mode 100644index 000000000..b82e2db25--- /dev/null+++ b/src/web/src/lib/templates/types.ts@@ -0,0 +1,24 @@+import type { ScenarioMemberPreset, ScenarioId } from "@/components/studio-onboarding/scenario-presets";++export type TemplateCategory = "Developer" | "Content Creator" | "Knowledge Worker" | "Freelancer";++export interface TemplatePreset {+ id: string;+ name: string;+ description: string;+ longDescription: string;+ category: TemplateCategory;+ icon: string;+ tags: string[];+ features: string[];+ useCases: { title: string; description: string }[];+ baseScenario: ScenarioId;+ members: ScenarioMemberPreset[];+}++export const TEMPLATE_CATEGORIES: TemplateCategory[] = [+ "Developer",+ "Content Creator",+ "Knowledge Worker",+ "Freelancer",+];diff --git a/turbo.json b/turbo.jsonindex 8bdd2d281..c21d1792d 100644--- a/turbo.json+++ b/turbo.json@@ -4,6 +4,7 @@"build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },"test": { "dependsOn": ["^build"] },"typecheck": { "dependsOn": ["^build"] },+ "lint": {},"dev": { "cache": false, "persistent": true }}}