Open-source SEO, GEO, and marketing skills for AI agents.
feat: per-agent + per-project mgmt — clone/create, rename, delete, cron UX
Yuting Zhong200d95463a0d
diff --git a/package.json b/package.jsonindex 05a6dc2b..f915c805 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"react-dom": "^19.0.0","sonner": "^2.0.7","tailwind-merge": "^2.5.0",+ "ws": "^8.20.1","zod": "^3.23.0"},"devDependencies": {@@ -50,6 +51,7 @@"@types/node": "^22.0.0","@types/react": "^19.0.0","@types/react-dom": "^19.0.0",+ "@types/ws": "^8.18.1","eslint": "^9.0.0","eslint-config-next": "^16.2.6","postcss": "^8.4.0",@@ -66,7 +68,8 @@"keytar","esbuild","sharp",- "unrs-resolver"+ "unrs-resolver",+ "node-pty"]}}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a9b73de0..9f2b4e7c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -71,6 +71,9 @@ importers:tailwind-merge:specifier: ^2.5.0version: 2.6.1+ ws:+ specifier: ^8.20.1+ version: 8.20.1zod:specifier: ^3.23.0version: 3.25.76@@ -90,6 +93,9 @@ importers:'@types/react-dom':specifier: ^19.0.0version: 19.2.3(@types/[email protected])+ '@types/ws':+ specifier: ^8.18.1+ version: 8.18.1eslint:specifier: ^9.0.0version: 9.39.4([email protected])@@ -1534,6 +1540,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==}+ '@types/[email protected]':+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}+'@typescript-eslint/[email protected]':resolution: {integrity: sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -3258,6 +3267,18 @@ packages:resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}+ resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==}+ engines: {node: '>=10.0.0'}+ peerDependencies:+ bufferutil: ^4.0.1+ utf-8-validate: '>=5.0.2'+ peerDependenciesMeta:+ bufferutil:+ optional: true+ utf-8-validate:+ optional: true+resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}engines: {node: '>=18'}@@ -4627,6 +4648,10 @@ snapshots:dependencies:csstype: 3.2.3+ '@types/[email protected]':+ dependencies:+ '@types/node': 22.19.19+'@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@eslint-community/regexpp': 4.12.2@@ -6681,6 +6706,8 @@ snapshots:+ [email protected]: {}+dependencies:is-wsl: 3.1.1diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsxnew file mode 100644index 00000000..395f595a--- /dev/null+++ b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx@@ -0,0 +1,100 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import {+ buildPendingSessionKey,+ findSessionBySessionId,+ listSessionsForAgent,+ loadSessionHistory,+} from "@/server/openclaw/sessions";+import { AgentChat } from "@/components/agent-chat";+import { ThreadSelector } from "@/components/thread-selector";++type Params = { agent: string; thread: string };++export default async function AgentChatThreadPage({+ params,+}: {+ params: Promise<Params>;+}) {+ const { agent: agentSlug, thread: threadId } = await params;++ const project = await getActiveProject();+ if (!project) {+ return (+ <div className="mx-auto max-w-md p-6 pt-12">+ <Card>+ <CardHeader>+ <CardTitle>No active project</CardTitle>+ <CardDescription>+ Create a project before chatting with this agent.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Link href="/projects/new" className="text-sm underline">+ Create one+ </Link>+ </CardContent>+ </Card>+ </div>+ );+ }++ const resolved = await resolveAgentBySlug(project.slug, agentSlug);+ if (!resolved) notFound();+ const agentFullId = resolved.agent_id;+ const allSessions = listSessionsForAgent(agentFullId);+ const existing = findSessionBySessionId(agentFullId, threadId);++ // Either we have a known session (use its registered sessionKey) or this is+ // a brand-new thread the user just navigated into; use a self-named key so+ // OpenClaw can create the entry on the first turn.+ const sessionKey = existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);+ const history = existing ? loadSessionHistory(agentFullId, threadId) : [];++ // For the dropdown: surface the pending thread at the top so the user sees+ // it's "selected" even before sending the first message.+ const sessionsForDropdown = existing+ ? allSessions+ : [+ {+ sessionId: threadId,+ label: threadId.slice(0, 8),+ sessionKey,+ lastInteractionAt: 0,+ pending: true,+ },+ ...allSessions,+ ];++ return (+ <div className="flex h-full flex-col">+ <div className="flex items-center justify-between border-b bg-background/80 px-6 py-2 backdrop-blur">+ <div className="text-xs text-muted-foreground">+ {sessionsForDropdown.length === 0+ ? "No threads yet"+ : `${sessionsForDropdown.length} thread${sessionsForDropdown.length === 1 ? "" : "s"}`}+ </div>+ <ThreadSelector+ agentSlug={agentSlug}+ sessions={sessionsForDropdown}+ activeSessionId={threadId}+ />+ </div>++ <div className="min-h-0 flex-1">+ <AgentChat+ key={threadId}+ projectSlug={project.slug}+ agentSlug={agentSlug}+ agentDisplayName={resolved.display_name}+ sessionId={threadId}+ sessionKey={sessionKey}+ initialMessages={history.map((m) => ({ id: m.id, role: m.role, body: m.body }))}+ />+ </div>+ </div>+ );+}diff --git a/src/app/(app)/agents/[agent]/chat/page.tsx b/src/app/(app)/agents/[agent]/chat/page.tsxnew file mode 100644index 00000000..0278e045--- /dev/null+++ b/src/app/(app)/agents/[agent]/chat/page.tsx@@ -0,0 +1,31 @@+import { redirect, notFound } from "next/navigation";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import {+ listSessionsForAgent,+ newSessionId,+} from "@/server/openclaw/sessions";++/**+ * Default landing for /agents/[agent]/chat — pick a thread and redirect into+ * the per-thread URL so refresh/share/back-button all keep the thread context.+ */+export default async function ChatIndexPage({+ params,+}: {+ params: Promise<{ agent: string }>;+}) {+ const { agent: agentSlug } = await params;+ const project = await getActiveProject();+ if (!project) {+ // No project means no agent workspace; let the threaded page render the+ // friendly empty state instead of bouncing through redirects.+ redirect(`/agents/${agentSlug}/chat/_pending`);+ }+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);+ if (!resolved) notFound();++ const existing = listSessionsForAgent(resolved.agent_id);+ const target = existing[0]?.sessionId ?? newSessionId();+ redirect(`/agents/${agentSlug}/chat/${target}`);+}diff --git a/src/app/(app)/agents/[agent]/cron/page.tsx b/src/app/(app)/agents/[agent]/cron/page.tsxnew file mode 100644index 00000000..ab7a9fc5--- /dev/null+++ b/src/app/(app)/agents/[agent]/cron/page.tsx@@ -0,0 +1,198 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { Card, CardContent } from "@/components/ui/card";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { listCronsForProject } from "@/server/openclaw/crons";+import {+ annotateOccurrencesWithRunStatus,+ expandSchedule,+} from "@/server/openclaw/cron-schedule";+import {+ CronCalendar,+ type CalendarCron,+ type CalendarOccurrence,+} from "@/components/cron-calendar";+import { ScheduleCronDialog } from "@/components/schedule-cron-dialog";+import type { ScheduleInput } from "@/server/actions/cron-runs";++const NUM_DAYS = 14;++/**+ * Narrow the loose `CronSchedule` shape from OpenClaw to the discriminated+ * union our run-matching server action accepts. Drops schedules whose `kind`+ * we don't recognise so the action can fall back to time-window matching.+ */+function scheduleForCalendar(s: unknown): ScheduleInput | null {+ if (!s || typeof s !== "object") return null;+ const obj = s as { kind?: string; expr?: unknown; tz?: unknown; everyMs?: unknown; anchorMs?: unknown };+ if (obj.kind === "cron" && typeof obj.expr === "string") {+ return { kind: "cron", expr: obj.expr, ...(typeof obj.tz === "string" ? { tz: obj.tz } : {}) };+ }+ if (obj.kind === "every" && typeof obj.everyMs === "number") {+ return {+ kind: "every",+ everyMs: obj.everyMs,+ ...(typeof obj.anchorMs === "number" ? { anchorMs: obj.anchorMs } : {}),+ };+ }+ return null;+}++type Params = { agent: string };++export default async function AgentCronPage({+ params,+}: {+ params: Promise<Params>;+}) {+ const { agent: agentSlug } = await params;+ const project = await getActiveProject();+ const resolved = project ? await resolveAgentBySlug(project.slug, agentSlug) : null;+ if (project && !resolved) notFound();+ if (!project || !resolved) {+ return (+ <div className="h-full overflow-y-auto p-6">+ <Card className="mx-auto max-w-md">+ <CardContent className="space-y-2 p-6">+ <h2 className="text-base font-medium">No active project</h2>+ <p className="text-sm text-muted-foreground">+ Create a project to schedule recurring work for this agent.+ </p>+ <Link href="/projects/new" className="text-sm underline">+ Create one+ </Link>+ </CardContent>+ </Card>+ </div>+ );+ }++ const templateSlug = resolved.slug;++ let error: string | null = null;+ let view: Awaited<ReturnType<typeof listCronsForProject>>;+ try {+ view = await listCronsForProject(project.slug);+ } catch (err) {+ view = { project_slug: project.slug, groups: [] };+ error = err instanceof Error ? err.message : String(err);+ }++ // Scope to this agent only.+ const myGroup = view.groups.find((g) => g.agent === templateSlug);+ const allCrons = myGroup?.crons ?? [];++ // Expand to occurrences over the window.+ const today = new Date();+ today.setHours(0, 0, 0, 0);+ const startOfFirstDay = today.getTime();+ const dayMs = 24 * 60 * 60 * 1000;+ const until = startOfFirstDay + NUM_DAYS * dayMs;++ const occurrences: CalendarOccurrence[] = [];+ const schedulesByCronId = new Map<string, ReturnType<typeof scheduleForCalendar>>();+ for (const cron of allCrons) {+ const occs = expandSchedule(+ cron.id,+ cron.schedule_raw,+ { from: startOfFirstDay, until },+ {+ name: cron.name,+ short_name: cron.short_name,+ agent_id: cron.agent_id,+ agent_slug: cron.agent_slug,+ schedule_text: cron.schedule_text,+ },+ );+ for (const o of occs) occurrences.push({ ...o, cron_disabled: cron.disabled });+ schedulesByCronId.set(cron.id, scheduleForCalendar(cron.schedule_raw));+ }+ // Stamp each past occurrence with its run's status so the calendar chip+ // can render the green-check / red-X indicator without a per-chip fetch.+ annotateOccurrencesWithRunStatus(+ occurrences,+ new Map(+ [...schedulesByCronId.entries()].map(([k, v]) => [k, v ?? undefined]),+ ),+ );++ const cronsById: Record<string, CalendarCron> = {};+ for (const cron of allCrons) {+ cronsById[cron.id] = {+ id: cron.id,+ short_name: cron.short_name,+ full_name: cron.name,+ agent_id: cron.agent_id,+ agent_slug: cron.agent_slug,+ schedule_text: cron.schedule_text,+ disabled: cron.disabled,+ status_text: cron.status_text,+ message: cron.message,+ description: cron.description,+ last_run_at_ms: cron.last_run_at_ms,+ last_status: cron.last_status,+ last_error: cron.last_error,+ schedule_raw: scheduleForCalendar(cron.schedule_raw),+ };+ }++ const totalActive = allCrons.filter((c) => !c.disabled).length;+ const totalDisabled = allCrons.length - totalActive;++ return (+ <div className="h-full overflow-y-auto p-6">+ <div className="mx-auto max-w-6xl space-y-4">+ <header className="flex flex-row items-center justify-between gap-4">+ <div>+ <h2 className="text-lg font-semibold tracking-tight">+ {resolved.display_name}’s scheduled work+ </h2>+ <p className="text-sm text-muted-foreground">+ {totalActive} active+ {totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""}+ {" · backed by OpenClaw"}+ </p>+ </div>+ <ScheduleCronDialog projectSlug={project.slug} />+ </header>++ {error && (+ <Card>+ <CardContent className="py-6 text-sm">+ <p className="font-medium text-destructive">Could not reach OpenClaw.</p>+ <p className="mt-1 text-xs text-muted-foreground">{error}</p>+ </CardContent>+ </Card>+ )}++ {!error && allCrons.length === 0 && (+ <Card>+ <CardContent className="space-y-2 py-10 text-center">+ <p className="text-sm font-medium">+ No scheduled work for {resolved.display_name} yet.+ </p>+ <p className="text-xs text-muted-foreground">+ Ask the agent in chat (“run a daily bid review at 9am”) or+ schedule one directly.+ </p>+ <div className="flex justify-center pt-2">+ <ScheduleCronDialog projectSlug={project.slug} />+ </div>+ </CardContent>+ </Card>+ )}++ {!error && allCrons.length > 0 && (+ <CronCalendar+ startOfFirstDay={startOfFirstDay}+ numDays={NUM_DAYS}+ occurrences={occurrences}+ cronsById={cronsById}+ agentSlugs={[templateSlug]}+ />+ )}+ </div>+ </div>+ );+}diff --git a/src/app/(app)/agents/[agent]/files/page.tsx b/src/app/(app)/agents/[agent]/files/page.tsxnew file mode 100644index 00000000..cbc436d6--- /dev/null+++ b/src/app/(app)/agents/[agent]/files/page.tsx@@ -0,0 +1,195 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { FileText, FileX } from "lucide-react";+import { Card, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { listAgentFiles, getAgentFile } from "@/server/openclaw/gateway-rpc";+import { cn } from "@/lib/utils";++type Params = { agent: string };+type Search = { file?: string };++export default async function AgentFilesPage({+ params,+ searchParams,+}: {+ params: Promise<Params>;+ searchParams: Promise<Search>;+}) {+ const { agent: agentSlug } = await params;+ const { file: requestedFile } = await searchParams;++ const project = await getActiveProject();+ if (!project) {+ return (+ <div className="h-full overflow-y-auto p-6">+ <NoProject />+ </div>+ );+ }++ const resolved = await resolveAgentBySlug(project.slug, agentSlug);+ if (!resolved) notFound();+ const agentFullId = resolved.agent_id;++ let error: string | null = null;+ let files: Awaited<ReturnType<typeof listAgentFiles>>["files"] = [];+ let workspace = "";+ try {+ const list = await listAgentFiles(agentFullId);+ files = list.files;+ workspace = list.workspace;+ } catch (err) {+ error = err instanceof Error ? err.message : String(err);+ }++ // Pick which file to show: explicit search param wins, else first present+ // file, else first overall (which may be missing).+ const selectedName =+ (requestedFile && files.find((f) => f.name === requestedFile)?.name) ||+ files.find((f) => !f.missing)?.name ||+ files[0]?.name;++ let selectedContent: string | null = null;+ let selectedSize: number | undefined;+ let selectedUpdatedAtMs: number | undefined;+ let selectedMissing = false;+ let selectedError: string | null = null;+ if (selectedName) {+ const entry = files.find((f) => f.name === selectedName);+ selectedMissing = entry?.missing ?? true;+ if (!selectedMissing) {+ try {+ const got = await getAgentFile(agentFullId, selectedName);+ selectedContent = got.file.content;+ selectedSize = got.file.size;+ selectedUpdatedAtMs = got.file.updatedAtMs;+ } catch (err) {+ selectedError = err instanceof Error ? err.message : String(err);+ }+ }+ }++ return (+ <div className="grid h-full grid-cols-[260px_minmax(0,1fr)] divide-x">+ {/* Left rail — file list */}+ <aside className="flex min-h-0 flex-col">+ <div className="border-b px-4 py-2">+ <div className="text-[11px] uppercase tracking-wide text-muted-foreground">+ Workspace files+ </div>+ {workspace && (+ <div className="mt-1 truncate font-mono text-[10px] text-muted-foreground">+ {workspace}+ </div>+ )}+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto py-1">+ {error && (+ <div className="px-4 py-3 text-xs text-destructive">{error}</div>+ )}+ {!error && files.length === 0 && (+ <div className="px-4 py-3 text-xs text-muted-foreground">+ No files yet.+ </div>+ )}+ {files.map((f) => {+ const isActive = f.name === selectedName;+ return (+ <Link+ key={f.name}+ href={`/agents/${agentSlug}/files?file=${encodeURIComponent(f.name)}`}+ className={cn(+ "flex items-center gap-2 px-4 py-1.5 text-sm transition-colors",+ isActive+ ? "bg-accent text-accent-foreground"+ : "hover:bg-accent/50",+ f.missing && "text-muted-foreground/70",+ )}+ >+ {f.missing ? (+ <FileX className="size-3.5 shrink-0 opacity-60" />+ ) : (+ <FileText className="size-3.5 shrink-0" />+ )}+ <span className="truncate font-mono text-[13px]">{f.name}</span>+ {f.missing && (+ <Badge+ variant="outline"+ className="ml-auto h-4 px-1 text-[9px] uppercase tracking-wide"+ >+ empty+ </Badge>+ )}+ </Link>+ );+ })}+ </div>+ </aside>++ {/* Right pane — file viewer */}+ <section className="flex min-h-0 flex-col">+ {!selectedName ? (+ <div className="flex h-full items-center justify-center p-6 text-sm text-muted-foreground">+ Select a file to view its contents.+ </div>+ ) : selectedMissing ? (+ <div className="flex h-full flex-col items-center justify-center gap-2 p-6 text-center">+ <FileX className="size-6 text-muted-foreground/60" />+ <div className="text-sm text-muted-foreground">+ <span className="font-mono">{selectedName}</span> does not exist yet for this agent.+ </div>+ <div className="text-xs text-muted-foreground/80">+ The agent may create it during onboarding or when first invoked.+ </div>+ </div>+ ) : selectedError ? (+ <div className="p-6 text-sm text-destructive">{selectedError}</div>+ ) : (+ <>+ <header className="flex items-center justify-between border-b px-6 py-3">+ <div className="min-w-0">+ <div className="truncate font-mono text-sm">{selectedName}</div>+ <div className="mt-0.5 text-[11px] text-muted-foreground">+ {selectedSize !== undefined && `${formatBytes(selectedSize)}`}+ {selectedSize !== undefined && selectedUpdatedAtMs && " · "}+ {selectedUpdatedAtMs &&+ `updated ${new Date(selectedUpdatedAtMs).toLocaleString()}`}+ </div>+ </div>+ </header>+ <div className="min-h-0 flex-1 overflow-y-auto">+ <pre className="whitespace-pre-wrap break-words p-6 font-mono text-[13px] leading-relaxed">+ {selectedContent}+ </pre>+ </div>+ </>+ )}+ </section>+ </div>+ );+}++function NoProject() {+ return (+ <Card className="mx-auto max-w-md">+ <CardContent className="space-y-2 p-6">+ <h2 className="text-base font-medium">No active project</h2>+ <p className="text-sm text-muted-foreground">+ Create a project to inspect agent files.+ </p>+ <Link href="/projects/new" className="text-sm underline">+ Create one+ </Link>+ </CardContent>+ </Card>+ );+}++function formatBytes(n: number): string {+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;+}diff --git a/src/app/(app)/agents/[agent]/layout.tsx b/src/app/(app)/agents/[agent]/layout.tsxnew file mode 100644index 00000000..052c0e64--- /dev/null+++ b/src/app/(app)/agents/[agent]/layout.tsx@@ -0,0 +1,28 @@+import { notFound } from "next/navigation";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { AgentTabs } from "@/components/agent-tabs";++type Params = { agent: string };++export default async function AgentLayout({+ children,+ params,+}: {+ children: React.ReactNode;+ params: Promise<Params>;+}) {+ const { agent: agentSlug } = await params;+ const project = await getActiveProject();+ const resolved = project ? await resolveAgentBySlug(project.slug, agentSlug) : null;+ if (!resolved) notFound();++ return (+ // Escape parent main's p-6 so the tab strip + content area can own the+ // full viewport region. Children pick their own scroll/padding strategy.+ <div className="absolute inset-0 flex flex-col">+ <AgentTabs agentSlug={agentSlug} />+ <div className="min-h-0 flex-1">{children}</div>+ </div>+ );+}diff --git a/src/app/(app)/agents/[agent]/page.tsx b/src/app/(app)/agents/[agent]/page.tsxnew file mode 100644index 00000000..bca1d7ca--- /dev/null+++ b/src/app/(app)/agents/[agent]/page.tsx@@ -0,0 +1,10 @@+import { redirect } from "next/navigation";++export default async function AgentIndexPage({+ params,+}: {+ params: Promise<{ agent: string }>;+}) {+ const { agent } = await params;+ redirect(`/agents/${agent}/chat`);+}diff --git a/src/app/(app)/agents/[agent]/settings/page.tsx b/src/app/(app)/agents/[agent]/settings/page.tsxnew file mode 100644index 00000000..1cfc0fc5--- /dev/null+++ b/src/app/(app)/agents/[agent]/settings/page.tsx@@ -0,0 +1,109 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { Card, CardContent } from "@/components/ui/card";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug, readAgentMeta } from "@/server/agent-meta";+import { AgentDangerZone } from "@/components/agent-danger-zone";+import { AgentRenameCard } from "@/components/agent-rename-card";++type Params = { agent: string };++export default async function AgentSettingsPage({+ params,+}: {+ params: Promise<Params>;+}) {+ const { agent: agentSlug } = await params;+ const project = await getActiveProject();+ const resolved = project ? await resolveAgentBySlug(project.slug, agentSlug) : null;+ if (project && !resolved) notFound();++ if (!project || !resolved) {+ return (+ <div className="h-full overflow-y-auto p-6">+ <Card className="mx-auto max-w-md">+ <CardContent className="space-y-2 p-6">+ <h2 className="text-base font-medium">No active project</h2>+ <p className="text-sm text-muted-foreground">+ Create a project to edit agent settings.+ </p>+ <Link href="/projects/new" className="text-sm underline">+ Create one+ </Link>+ </CardContent>+ </Card>+ </div>+ );+ }++ const meta = readAgentMeta(resolved.agent_id);++ return (+ <div className="h-full overflow-y-auto p-6">+ <div className="mx-auto max-w-2xl space-y-6">+ <header>+ <h2 className="text-lg font-semibold tracking-tight">Settings</h2>+ <p className="text-sm text-muted-foreground">+ {resolved.display_name}{" "}+ <span className="font-mono text-xs">· {resolved.agent_id}</span>+ </p>+ </header>++ <Card>+ <CardContent className="p-4">+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-sm">+ <dt className="text-muted-foreground">Agent id</dt>+ <dd className="font-mono text-xs">{resolved.agent_id}</dd>++ <dt className="text-muted-foreground">URL slug</dt>+ <dd className="font-mono text-xs">{resolved.slug}</dd>++ <dt className="text-muted-foreground">Display name</dt>+ <dd>{resolved.display_name}</dd>++ {resolved.template_key && (+ <>+ <dt className="text-muted-foreground">Template</dt>+ <dd className="font-mono text-xs">{resolved.template_key}</dd>+ </>+ )}++ {meta?.source_agent_id && (+ <>+ <dt className="text-muted-foreground">Cloned from</dt>+ <dd className="font-mono text-xs">{meta.source_agent_id}</dd>+ </>+ )}++ {meta?.created_at && (+ <>+ <dt className="text-muted-foreground">Created</dt>+ <dd className="tabular-nums">+ {new Date(meta.created_at).toLocaleString()}+ </dd>+ </>+ )}+ </dl>+ </CardContent>+ </Card>++ <AgentRenameCard+ agentId={resolved.agent_id}+ projectSlug={project.slug}+ currentDisplayName={resolved.display_name}+ currentSlug={resolved.slug}+ />++ <section className="space-y-2 pt-2">+ <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ Danger zone+ </h3>+ <AgentDangerZone+ agentId={resolved.agent_id}+ agentDisplayName={resolved.display_name}+ />+ </section>+ </div>+ </div>+ );+}diff --git a/src/app/(app)/agents/[agent]/skills/page.tsx b/src/app/(app)/agents/[agent]/skills/page.tsxnew file mode 100644index 00000000..4cd25ab0--- /dev/null+++ b/src/app/(app)/agents/[agent]/skills/page.tsx@@ -0,0 +1,85 @@+import Link from "next/link";+import { notFound } from "next/navigation";+import { Card, CardContent } from "@/components/ui/card";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { getSkillStatus } from "@/server/openclaw/gateway-rpc";+import { SkillsList } from "@/components/skills-list";++type Params = { agent: string };++export default async function AgentSkillsPage({+ params,+}: {+ params: Promise<Params>;+}) {+ const { agent: agentSlug } = await params;+ const project = await getActiveProject();+ const resolved = project ? await resolveAgentBySlug(project.slug, agentSlug) : null;+ if (project && !resolved) notFound();+ if (!project) {+ return (+ <div className="h-full overflow-y-auto p-6">+ <Card className="mx-auto max-w-md">+ <CardContent className="space-y-2 p-6">+ <h2 className="text-base font-medium">No active project</h2>+ <p className="text-sm text-muted-foreground">+ Create a project to see this agent's skills.+ </p>+ <Link href="/projects/new" className="text-sm underline">+ Create one+ </Link>+ </CardContent>+ </Card>+ </div>+ );+ }++ const agentFullId = resolved!.agent_id;+ let report: Awaited<ReturnType<typeof getSkillStatus>> | null = null;+ let error: string | null = null;+ try {+ report = await getSkillStatus(agentFullId);+ } catch (err) {+ error = err instanceof Error ? err.message : String(err);+ }++ const skills = report?.skills ?? [];++ return (+ <div className="h-full overflow-y-auto p-6">+ <div className="mx-auto max-w-4xl space-y-4">+ <header>+ <h2 className="text-lg font-semibold tracking-tight">Skills</h2>+ <p className="text-sm text-muted-foreground">+ Capabilities OpenClaw exposes to {resolved!.display_name}.+ {report?.agentSkillFilter?.length+ ? ` Filtered to this agent's allowlist (${report.agentSkillFilter.length}).`+ : " Workspace-wide; no per-agent filter."}+ </p>+ </header>++ {error && (+ <Card>+ <CardContent className="space-y-1 py-4 text-sm">+ <p className="font-medium text-destructive">Could not reach OpenClaw.</p>+ <p className="text-xs text-muted-foreground">{error}</p>+ </CardContent>+ </Card>+ )}++ {!error && skills.length === 0 && (+ <Card>+ <CardContent className="py-12 text-center text-sm text-muted-foreground">+ No skills installed in this workspace yet.+ </CardContent>+ </Card>+ )}++ {!error && skills.length > 0 && (+ <SkillsList skills={skills} agentSlug={agentSlug} />+ )}+ </div>+ </div>+ );+}diff --git a/src/app/(app)/agents/page.tsx b/src/app/(app)/agents/page.tsxindex c61baece..33fdeddf 100644--- a/src/app/(app)/agents/page.tsx+++ b/src/app/(app)/agents/page.tsx@@ -80,7 +80,7 @@ export default async function AgentsPage() {</Link>)}<Button asChild size="sm">- <Link href={`/chat/${slug}`}>+ <Link href={`/agents/${slug}/chat`}><MessageSquare className="mr-1.5 size-4" />Chat</Link>diff --git a/src/app/(app)/chat/[agent]/page.tsx b/src/app/(app)/chat/[agent]/page.tsxdeleted file mode 100644index 9b490687..00000000--- a/src/app/(app)/chat/[agent]/page.tsx+++ /dev/null@@ -1,81 +0,0 @@-import { notFound } from "next/navigation";-import Link from "next/link";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";-import { getActiveProject } from "@/server/active-project";-import {- templateForUrlSlug,- agentNameFor,-} from "@/server/agent-templates";-import { getSessionsView, loadSessionHistory } from "@/server/openclaw/sessions";-import { AgentChat } from "@/components/agent-chat";-import { ThreadSelector } from "@/components/thread-selector";--type Params = { agent: string };--export default async function AgentChatPage({ params }: { params: Promise<Params> }) {- const { agent: agentSlug } = await params;- const template = templateForUrlSlug(agentSlug);- if (!template) notFound();-- const project = await getActiveProject();- if (!project) {- return (- <div className="mx-auto max-w-md p-6 pt-12">- <Card>- <CardHeader>- <CardTitle>No active project</CardTitle>- <CardDescription>- Create a project before chatting with the {template.display_name} agent.- </CardDescription>- </CardHeader>- <CardContent>- <Link href="/projects/new" className="text-sm underline">- Create one- </Link>- </CardContent>- </Card>- </div>- );- }-- const agentFullId = agentNameFor(project.slug, template.key);- const sessionsView = await getSessionsView(project.slug, template.key);- const history = sessionsView.active.pending- ? []- : loadSessionHistory(agentFullId, sessionsView.active.sessionId);-- return (- <>- {/* Top bar — agent identity + thread selector. Does not scroll. */}- <header className="flex items-center gap-3 border-b bg-background/80 px-6 py-3 backdrop-blur">- <div className="min-w-0 flex-1">- <div className="flex items-baseline gap-2">- <h1 className="text-base font-semibold tracking-tight">- {template.display_name}- </h1>- <span className="hidden truncate font-mono text-[11px] text-muted-foreground sm:inline">- {agentFullId}- </span>- </div>- </div>- <ThreadSelector- agentSlug={agentSlug}- sessions={sessionsView.all}- activeSessionId={sessionsView.active.sessionId}- />- </header>-- {/* Chat fills the remaining height. min-h-0 so the inner scroll works. */}- <div className="min-h-0 flex-1">- <AgentChat- key={sessionsView.active.sessionId}- projectSlug={project.slug}- agentSlug={agentSlug}- agentDisplayName={template.display_name}- sessionId={sessionsView.active.sessionId}- initialMessages={history.map((m) => ({ id: m.id, role: m.role, body: m.body }))}- />- </div>- </>- );-}diff --git a/src/app/(app)/chat/layout.tsx b/src/app/(app)/chat/layout.tsxdeleted file mode 100644index 3d246f59..00000000--- a/src/app/(app)/chat/layout.tsx+++ /dev/null@@ -1,11 +0,0 @@-/**- * Chat layout: escape the parent main's p-6 padding so the conversation can- * fill the entire content area edge-to-edge. Sticky composer + scrollable- * thread need a single flex column that owns the viewport region.- *- * Parent main has `relative p-6`; this absolute child fills the padding box- * (i.e., the main element's full inner area, ignoring the padding inset).- */-export default function ChatLayout({ children }: { children: React.ReactNode }) {- return <div className="absolute inset-0 flex flex-col">{children}</div>;-}diff --git a/src/app/(app)/chat/page.tsx b/src/app/(app)/chat/page.tsxdeleted file mode 100644index 3e8c8d9a..00000000--- a/src/app/(app)/chat/page.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { redirect } from "next/navigation";--export default function ChatIndex() {- redirect("/chat/cmo");-}diff --git a/src/app/(app)/crons/page.tsx b/src/app/(app)/crons/page.tsxindex 26b16aee..6f7d61ff 100644--- a/src/app/(app)/crons/page.tsx+++ b/src/app/(app)/crons/page.tsx@@ -1,13 +1,33 @@import { Card, CardContent } from "@/components/ui/card";import { getActiveProject } from "@/server/active-project";import { listCronsForProject } from "@/server/openclaw/crons";-import { expandSchedule } from "@/server/openclaw/cron-schedule";+import {+ annotateOccurrencesWithRunStatus,+ expandSchedule,+} from "@/server/openclaw/cron-schedule";import { ScheduleCronDialog } from "@/components/schedule-cron-dialog";import {CronCalendar,type CalendarCron,type CalendarOccurrence,} from "@/components/cron-calendar";+import type { ScheduleInput } from "@/server/actions/cron-runs";++function scheduleForCalendar(s: unknown): ScheduleInput | null {+ if (!s || typeof s !== "object") return null;+ const obj = s as { kind?: string; expr?: unknown; tz?: unknown; everyMs?: unknown; anchorMs?: unknown };+ if (obj.kind === "cron" && typeof obj.expr === "string") {+ return { kind: "cron", expr: obj.expr, ...(typeof obj.tz === "string" ? { tz: obj.tz } : {}) };+ }+ if (obj.kind === "every" && typeof obj.everyMs === "number") {+ return {+ kind: "every",+ everyMs: obj.everyMs,+ ...(typeof obj.anchorMs === "number" ? { anchorMs: obj.anchorMs } : {}),+ };+ }+ return null;+}const NUM_DAYS = 14; // 2-week window; UI shows 7 at a time with prev/next.@@ -43,12 +63,12 @@ export default async function CronsPage() {// Expand every cron into occurrences within the window.const occurrences: CalendarOccurrence[] = [];+ const schedulesByCronId = new Map<string, ReturnType<typeof scheduleForCalendar>>();for (const cron of allCrons) {- if (cron.disabled) continue;const occs = expandSchedule(cron.id,cron.schedule_raw,- { from: Date.now(), until },+ { from: startOfFirstDay, until },{name: cron.name,short_name: cron.short_name,@@ -57,8 +77,13 @@ export default async function CronsPage() {schedule_text: cron.schedule_text,},);- for (const o of occs) occurrences.push(o);+ for (const o of occs) occurrences.push({ ...o, cron_disabled: cron.disabled });+ schedulesByCronId.set(cron.id, scheduleForCalendar(cron.schedule_raw));}+ annotateOccurrencesWithRunStatus(+ occurrences,+ new Map([...schedulesByCronId.entries()].map(([k, v]) => [k, v ?? undefined])),+ );const cronsById: Record<string, CalendarCron> = {};for (const cron of allCrons) {@@ -71,6 +96,12 @@ export default async function CronsPage() {schedule_text: cron.schedule_text,disabled: cron.disabled,status_text: cron.status_text,+ message: cron.message,+ description: cron.description,+ last_run_at_ms: cron.last_run_at_ms,+ last_status: cron.last_status,+ last_error: cron.last_error,+ schedule_raw: scheduleForCalendar(cron.schedule_raw),};}@@ -84,7 +115,7 @@ export default async function CronsPage() {<h1 className="text-2xl font-semibold tracking-tight">Crons</h1><p className="text-sm text-muted-foreground">Project <span className="font-mono">{project.slug}</span> ·{" "}- {totalActive} active{totalDisabled > 0 ? ` · ${totalDisabled} paused` : ""} ·{" "}+ {totalActive} active{totalDisabled > 0 ? ` · ${totalDisabled} disabled` : ""} ·{" "}backed by OpenClaw</p></div>diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsxindex 7b830eb3..e612ec70 100644--- a/src/app/(app)/layout.tsx+++ b/src/app/(app)/layout.tsx@@ -1,10 +1,5 @@-import {- SidebarInset,- SidebarProvider,- SidebarTrigger,-} from "@/components/ui/sidebar";+import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";import { AppSidebar } from "@/components/app-sidebar";-import { Separator } from "@/components/ui/separator";import { ClientMountGate } from "@/components/client-mount-gate";export default function AppLayout({ children }: { children: React.ReactNode }) {@@ -19,13 +14,9 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {<SidebarProvider><AppSidebar /><SidebarInset>- <header className="sticky top-0 z-10 flex h-12 items-center gap-2 border-b bg-background/95 px-3 backdrop-blur supports-[backdrop-filter]:bg-background/60">- <SidebarTrigger />- <Separator orientation="vertical" className="h-5" />- <a href="#main-content" className="sr-only focus:not-sr-only">- Skip to content- </a>- </header>+ <a href="#main-content" className="sr-only focus:not-sr-only">+ Skip to content+ </a><main id="main-content" className="relative flex-1 p-6">{children}</main>diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsxindex 32e8035a..09fa9d36 100644--- a/src/app/(app)/page.tsx+++ b/src/app/(app)/page.tsx@@ -62,7 +62,7 @@ export default async function ProjectHomePage() {</p></div><Button asChild>- <Link href="/chat/cmo">+ <Link href="/agents/cmo/chat"><MessageSquare className="mr-1.5 size-4" />Chat with CMO</Link>@@ -190,7 +190,7 @@ export default async function ProjectHomePage() {if you want agents to do real work (optional, chat works without it)</li><li>- 2. <Link href="/chat/cmo" className="underline">Chat with the CMO</Link> to plan+ 2. <Link href="/agents/cmo/chat" className="underline">Chat with the CMO</Link> to planwhat to do</li><li>diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsxindex 0caab829..a4d8df17 100644--- a/src/app/(app)/settings/page.tsx+++ b/src/app/(app)/settings/page.tsx@@ -5,6 +5,8 @@ import { Button } from "@/components/ui/button";import { getActiveProject } from "@/server/active-project";import { getGuardrails } from "@/server/db/guardrails";import { updateGuardrailsAction } from "@/server/actions/guardrails";+import { DangerZone } from "@/components/danger-zone";+import { ProjectRenameCard } from "@/components/project-rename-card";export default async function SettingsPage() {const project = await getActiveProject();@@ -88,6 +90,18 @@ export default async function SettingsPage() {</form></CardContent></Card>++ <ProjectRenameCard+ currentSlug={project.slug}+ currentDisplayName={project.display_name}+ />++ <section className="space-y-2 pt-4">+ <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ Danger zone+ </h2>+ <DangerZone projectSlug={project.slug} projectName={project.display_name} />+ </section></div>);}diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.tsindex 70d30a4a..f5ce1987 100644--- a/src/app/api/chat/route.ts+++ b/src/app/api/chat/route.ts@@ -1,12 +1,11 @@import { NextResponse } from "next/server";import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { streamChatViaGateway } from "@/server/openclaw/gateway-client";import {- agentNameFor,- templateForUrlSlug,- type AgentTemplateKey,-} from "@/server/agent-templates";-import { streamAgentTurn } from "@/server/openclaw/agent-turn";-import { getSessionsView, setActiveSession } from "@/server/openclaw/sessions";+ buildPendingSessionKey,+ findSessionBySessionId,+} from "@/server/openclaw/sessions";export const dynamic = "force-dynamic";export const runtime = "nodejs";@@ -14,8 +13,15 @@ export const runtime = "nodejs";type ChatPostBody = {message: string;agent?: string;- /** Optional explicit OpenClaw session id (UUID). Defaults to the active one. */+ /** OpenClaw session UUID — used for trajectory file naming. */sessionId?: string;+ /**+ * OpenClaw's canonical `agent:<agent>:<label>` key for this thread. When the+ * client knows the right key (e.g., `agent:foo:main` for an existing thread+ * whose label is not the sessionId), pass it here. Falls back to a+ * sessionId-derived key for brand-new threads.+ */+ sessionKey?: string;};export async function POST(request: Request) {@@ -38,27 +44,32 @@ export async function POST(request: Request) {}const requestedSlug = (body.agent ?? "cmo").trim();- const template = templateForUrlSlug(requestedSlug);- if (!template) {+ const resolved = await resolveAgentBySlug(project.slug, requestedSlug);+ if (!resolved) {return NextResponse.json({ error: `Unknown agent: '${requestedSlug}'` },{ status: 404 },);}- // Resolve session: explicit body wins, otherwise the active session for- // (project, agent). If none, getSessionsView mints a fresh UUID and uses it.- let sessionId = body.sessionId?.trim();+ const agentName = resolved.agent_id;++ // Resolve session: explicit body wins. New pages always pass both sessionId+ // and sessionKey; sessionKey-only callers (legacy or external) get the+ // canonical key looked up below.+ const sessionId = body.sessionId?.trim();if (!sessionId) {- const view = await getSessionsView(project.slug, template.key as AgentTemplateKey);- sessionId = view.active.sessionId;+ return NextResponse.json(+ { error: "sessionId is required (call from a threaded chat URL)." },+ { status: 400 },+ );+ }+ let sessionKey = body.sessionKey?.trim();+ if (!sessionKey) {+ const known = findSessionBySessionId(agentName, sessionId);+ sessionKey = known?.sessionKey ?? buildPendingSessionKey(agentName, sessionId);}- // Persist the active session in the cookie so reloads land back in the same- // thread without us tracking anything ourselves.- await setActiveSession(project.slug, template.key as AgentTemplateKey, sessionId);-- const agentName = agentNameFor(project.slug, template.key as AgentTemplateKey);const encoder = new TextEncoder();const stream = new ReadableStream({@@ -69,18 +80,28 @@ export async function POST(request: Request) {);};+ const abortCtl = new AbortController();+ request.signal?.addEventListener("abort", () => abortCtl.abort(), { once: true });+try {send("meta", {project_slug: project.slug,agent: agentName,session_id: sessionId,+ session_key: sessionKey,});- for await (const chunk of streamAgentTurn({- agent: agentName,- message: body.message,+ for await (const evt of streamChatViaGateway({+ sessionKey,sessionId,+ message: body.message,+ signal: abortCtl.signal,})) {- send("text", { chunk });+ if (evt.kind === "delta") {+ send("text", { chunk: evt.text });+ } else if (evt.kind === "error") {+ send("error", { message: evt.message });+ }+ // "final" implicitly ends the loop after; no separate signal needed.}send("done", {});} catch (err) {diff --git a/src/components/agent-chat.tsx b/src/components/agent-chat.tsxindex 645bb8fe..7cdc1cac 100644--- a/src/components/agent-chat.tsx+++ b/src/components/agent-chat.tsx@@ -13,7 +13,6 @@ import {type SlashCommand,} from "@/lib/slash-commands";import { SlashCommandPopover } from "./slash-command-popover";-import { newSessionAction } from "@/server/actions/sessions";type Message = {id: string;@@ -32,6 +31,12 @@ type Props = {agentSlug: string;agentDisplayName: string;sessionId: string;+ /**+ * OpenClaw's canonical `agent:<agent>:<label>` key for this thread. For+ * existing threads, label might be `main` (not the sessionId UUID), so we+ * thread the resolved key through instead of reconstructing it server-side.+ */+ sessionKey: string;initialMessages?: InitialMessage[];};@@ -40,6 +45,7 @@ export function AgentChat({agentSlug,agentDisplayName,sessionId,+ sessionKey,initialMessages = [],}: Props) {const [messages, setMessages] = useState<Message[]>(initialMessages);@@ -115,15 +121,15 @@ export function AgentChat({case "clear":setMessages([]);return;- case "new-session":- // Create a fresh OpenClaw session id via server action, then refresh- // the route so the page re-loads with empty history.- startTransition(async () => {- const r = await newSessionAction(agentSlug);- if (!r.ok) toast.error(r.error);- else router.refresh();+ case "new-session": {+ // Mint a fresh UUID and navigate — the new threaded URL becomes+ // the source of truth, no cookie roundtrip needed.+ const newId = crypto.randomUUID();+ startTransition(() => {+ router.push(`/agents/${agentSlug}/chat/${newId}`);});return;+ }case "stop":if (abortRef.current) abortRef.current.abort();return;@@ -156,7 +162,7 @@ export function AgentChat({const res = await fetch("/api/chat", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ message: text, agent: agentSlug, sessionId }),+ body: JSON.stringify({ message: text, agent: agentSlug, sessionId, sessionKey }),signal: ctrl.signal,});if (!res.ok || !res.body) {diff --git a/src/components/agent-danger-zone.tsx b/src/components/agent-danger-zone.tsxnew file mode 100644index 00000000..6eed6d1a--- /dev/null+++ b/src/components/agent-danger-zone.tsx@@ -0,0 +1,257 @@+"use client";++import { useEffect, useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { AlertTriangle, Loader2, Trash2 } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ getAgentDeletionSummaryAction,+ deleteAgentCascadeAction,+ type AgentDeletionSummary,+} from "@/server/actions/agents";++type Props = {+ agentId: string;+ agentDisplayName: string;+};++export function AgentDangerZone({ agentId, agentDisplayName }: Props) {+ const router = useRouter();+ const [open, setOpen] = useState(false);+ const [summary, setSummary] = useState<AgentDeletionSummary | null>(null);+ const [summaryError, setSummaryError] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);+ const [pending, startTransition] = useTransition();++ useEffect(() => {+ if (!open) {+ setSummary(null);+ setSummaryError(null);+ return;+ }+ setLoading(true);+ (async () => {+ const r = await getAgentDeletionSummaryAction(agentId);+ if (r.ok) setSummary(r.data);+ else setSummaryError(r.error);+ setLoading(false);+ })();+ }, [open, agentId]);++ function onConfirm() {+ startTransition(async () => {+ const r = await deleteAgentCascadeAction(agentId);+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ const d = r.data;+ if (d.crons_failed > 0) {+ toast.warning(+ `Deleted ${agentDisplayName}. ${d.crons_removed} crons removed, ${d.crons_failed} failed.`,+ );+ } else {+ toast.success(+ `Deleted ${agentDisplayName}. ${d.crons_removed} cron${d.crons_removed === 1 ? "" : "s"} removed.`,+ );+ }+ setOpen(false);+ router.push("/");+ router.refresh();+ });+ }++ function shortLabel(s: string): string {+ if (s === "main") return "Main thread";+ return s.length > 28 ? `${s.slice(0, 28)}…` : s;+ }++ function timeAgo(ms: number): string {+ if (!ms) return "new";+ const sec = Math.max(0, (Date.now() - ms) / 1000);+ if (sec < 60) return `${Math.floor(sec)}s ago`;+ if (sec < 3600) return `${Math.floor(sec / 60)}m ago`;+ if (sec < 86400) return `${Math.floor(sec / 3600)}h ago`;+ return `${Math.floor(sec / 86400)}d ago`;+ }++ const canDelete = !pending && !loading;++ return (+ <>+ <div className="space-y-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4">+ <div className="flex items-start gap-3">+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-destructive" />+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold text-destructive">Delete this agent</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">+ Removes the agent from OpenClaw along with every thread of chat history and+ every scheduled cron job that targets it. This cannot be undone.+ </p>+ </div>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => setOpen(true)}+ className="shrink-0"+ >+ <Trash2 className="mr-1.5 size-3.5" />+ Delete agent+ </Button>+ </div>+ </div>++ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-base">+ <AlertTriangle className="size-4 text-destructive" />+ Delete “{agentDisplayName}”?+ </DialogTitle>+ <DialogDescription>+ This permanently removes the items below from OpenClaw and notfair-cmo's+ local store.+ </DialogDescription>+ </DialogHeader>++ {loading ? (+ <div className="flex items-center gap-2 py-4 text-sm text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" />+ Counting what will be removed…+ </div>+ ) : summaryError ? (+ <div className="rounded border border-destructive/40 bg-destructive/5 p-3 text-xs text-destructive">+ {summaryError}+ </div>+ ) : summary ? (+ <div className="space-y-4">+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs">+ <dt className="text-muted-foreground">Agent id</dt>+ <dd className="truncate font-mono">{summary.agent_id}</dd>++ {summary.template_key && (+ <>+ <dt className="text-muted-foreground">Template</dt>+ <dd className="font-mono">{summary.template_key}</dd>+ </>+ )}++ {summary.source_agent_id && (+ <>+ <dt className="text-muted-foreground">Cloned from</dt>+ <dd className="font-mono">{summary.source_agent_id}</dd>+ </>+ )}++ {!summary.exists_in_openclaw && (+ <>+ <dt className="text-muted-foreground">OpenClaw</dt>+ <dd className="text-amber-600 dark:text-amber-400">+ already removed+ </dd>+ </>+ )}+ </dl>++ <ItemList+ title={`Cron jobs (${summary.crons.length})`}+ emptyHint="No scheduled jobs target this agent."+ >+ {summary.crons.map((c) => (+ <li key={c.id} className="flex items-center justify-between gap-2 px-3 py-1.5">+ <span className="truncate font-mono text-[11px]">{c.name}</span>+ {c.disabled && (+ <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">+ disabled+ </span>+ )}+ </li>+ ))}+ </ItemList>++ <ItemList+ title={`Threads (${summary.threads.length})`}+ emptyHint="No chat threads yet."+ >+ {summary.threads.map((t) => (+ <li key={t.session_id} className="flex items-center justify-between gap-2 px-3 py-1.5">+ <span className="truncate text-[11px]">{shortLabel(t.label)}</span>+ <span className="shrink-0 text-[10px] text-muted-foreground tabular-nums">+ {timeAgo(t.last_interaction_at)}+ </span>+ </li>+ ))}+ </ItemList>+ </div>+ ) : null}++ <DialogFooter className="gap-2 sm:gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ disabled={pending}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={onConfirm}+ disabled={!canDelete}+ >+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ Deleting…+ </>+ ) : (+ <>+ <Trash2 className="mr-1.5 size-3.5" />+ Delete forever+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}++function ItemList({+ title,+ emptyHint,+ children,+}: {+ title: string;+ emptyHint: string;+ children: React.ReactNode;+}) {+ const items = Array.isArray(children) ? children : [children];+ const empty = items.filter(Boolean).length === 0;+ return (+ <div className="space-y-1.5">+ <div className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {title}+ </div>+ <ul className="max-h-40 divide-y overflow-y-auto rounded-md border bg-card text-xs">+ {empty ? (+ <li className="px-3 py-2 text-muted-foreground">{emptyHint}</li>+ ) : (+ children+ )}+ </ul>+ </div>+ );+}diff --git a/src/components/agent-nav.tsx b/src/components/agent-nav.tsxindex 6d6ff863..c51e7688 100644--- a/src/components/agent-nav.tsx+++ b/src/components/agent-nav.tsx@@ -2,26 +2,29 @@import Link from "next/link";import { usePathname } from "next/navigation";-import { Briefcase, Megaphone, Search, type LucideIcon } from "lucide-react";+import { Bot, Briefcase, Megaphone, Search, type LucideIcon } from "lucide-react";import {SidebarMenu,SidebarMenuButton,SidebarMenuItem,} from "@/components/ui/sidebar";-import type { AgentTemplate, AgentTemplateKey } from "@/server/agent-templates";+import type { AgentTemplateKey } from "@/server/agent-templates";type AgentNavEntry = {- key: AgentTemplate["key"];+ /** Stable key for React, e.g. the agent_id. */+ key: string;slug: string;display_name: string;- description: string;+ description?: string;+ /** Filled for template agents; undefined for cloned/custom ones. */+ template_key?: AgentTemplateKey;};type Props = {agents: AgentNavEntry[];};-const ICONS: Record<AgentTemplateKey, LucideIcon> = {+const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {cmo: Briefcase,google_ads: Megaphone,seo: Search,@@ -33,9 +36,11 @@ export function AgentNav({ agents }: Props) {return (<SidebarMenu>{agents.map((a) => {- const href = `/chat/${a.slug}`;- const isActive = pathname === href;- const Icon = ICONS[a.key] ?? Briefcase;+ const href = `/agents/${a.slug}/chat`;+ const agentBase = `/agents/${a.slug}`;+ const isActive =+ pathname === agentBase || pathname?.startsWith(`${agentBase}/`);+ const Icon = a.template_key ? TEMPLATE_ICONS[a.template_key] ?? Bot : Bot;return (<SidebarMenuItem key={a.key}><SidebarMenuButton asChild isActive={isActive}>diff --git a/src/components/agent-rename-card.tsx b/src/components/agent-rename-card.tsxnew file mode 100644index 00000000..4c1a59f9--- /dev/null+++ b/src/components/agent-rename-card.tsx@@ -0,0 +1,150 @@+"use client";++import { useEffect, useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { Loader2, Pencil } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { cn } from "@/lib/utils";+import { slugify } from "@/lib/slug";+import { renameAgentAction } from "@/server/actions/agents";++type Props = {+ agentId: string;+ projectSlug: string;+ currentDisplayName: string;+ currentSlug: string;+};++export function AgentRenameCard({+ agentId,+ projectSlug,+ currentDisplayName,+ currentSlug,+}: Props) {+ const router = useRouter();+ const [name, setName] = useState(currentDisplayName);+ const [pending, startTransition] = useTransition();++ useEffect(() => {+ setName(currentDisplayName);+ }, [currentDisplayName]);++ const trimmed = name.trim();+ const slugAttempt = trimmed ? slugify(trimmed) : null;+ const derivedSlug = slugAttempt?.ok ? slugAttempt.slug : null;+ const slugError = slugAttempt && !slugAttempt.ok ? slugAttempt.reason : null;+ const slugChanged = !!derivedSlug && derivedSlug !== currentSlug;+ const nameChanged = trimmed !== currentDisplayName;++ function save() {+ if (!nameChanged && !slugChanged) return;+ startTransition(async () => {+ const r = await renameAgentAction({+ agent_id: agentId,+ new_display_name: trimmed,+ });+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ const d = r.data;+ toast.success(+ d.full_rename+ ? `Renamed to "${d.display_name}" (new URL: /agents/${d.slug})`+ : `Renamed to "${d.display_name}"`,+ );+ if (d.full_rename) {+ // agent_id and URL slug changed — route to the new chat page.+ router.push(`/agents/${d.slug}/settings`);+ router.refresh();+ } else {+ router.refresh();+ }+ });+ }++ const canSave =+ !pending && !slugError && trimmed.length > 0 && (nameChanged || slugChanged);++ return (+ <div className="space-y-3 rounded-lg border bg-card p-4">+ <div className="flex items-start gap-3">+ <Pencil className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold">Rename this agent</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">+ Changing the slug rewrites the URL, workspace path, sessions+ location, and every cron name. Chat history and prompts come along.+ </p>+ </div>+ </div>++ <div className="space-y-2">+ <Label htmlFor="rename-display-name" className="text-xs">+ Display name+ </Label>+ <div+ className={cn(+ "flex h-9 items-stretch overflow-hidden rounded-md border bg-background text-sm shadow-sm focus-within:ring-1 focus-within:ring-ring",+ slugError && "border-destructive focus-within:ring-destructive",+ pending && "opacity-50",+ )}+ >+ <span+ className="flex select-none items-center border-r bg-muted/50 px-2.5 font-mono text-[12px] text-muted-foreground"+ aria-hidden+ >+ {projectSlug}-+ </span>+ <input+ id="rename-display-name"+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ disabled={pending}+ className="flex-1 bg-transparent px-2 font-mono text-[13px] placeholder:text-muted-foreground/60 focus-visible:outline-none disabled:cursor-not-allowed"+ placeholder={currentSlug}+ aria-invalid={!!slugError}+ />+ </div>+ {slugError ? (+ <p className="text-[11px] text-destructive">Invalid name: {slugError}</p>+ ) : slugChanged ? (+ <p className="text-[11px] text-muted-foreground">+ Slug changes from{" "}+ <code className="rounded bg-muted px-1 font-mono">{currentSlug}</code>{" "}+ to{" "}+ <code className="rounded bg-muted px-1 font-mono">{derivedSlug}</code>+ . Full rename: clones into the new id, then deletes the old.+ </p>+ ) : (+ <p className="text-[11px] text-muted-foreground">+ Same slug — only the display name changes.+ </p>+ )}+ </div>++ <div className="flex justify-end">+ <Button+ type="button"+ size="sm"+ onClick={save}+ disabled={!canSave}+ >+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ {slugChanged ? "Renaming…" : "Saving…"}+ </>+ ) : slugChanged ? (+ "Rename agent"+ ) : (+ "Save name"+ )}+ </Button>+ </div>+ </div>+ );+}diff --git a/src/components/agent-tabs.tsx b/src/components/agent-tabs.tsxnew file mode 100644index 00000000..8da8da94--- /dev/null+++ b/src/components/agent-tabs.tsx@@ -0,0 +1,59 @@+"use client";++import Link from "next/link";+import { usePathname } from "next/navigation";+import { MessageSquare, FileText, Sparkles, Clock, Settings } from "lucide-react";+import { cn } from "@/lib/utils";++type Tab = {+ key: string;+ label: string;+ icon: React.ComponentType<{ className?: string }>;+};++const TABS: Tab[] = [+ { key: "chat", label: "Chat", icon: MessageSquare },+ { key: "files", label: "Files", icon: FileText },+ { key: "skills", label: "Skills", icon: Sparkles },+ { key: "cron", label: "Cron", icon: Clock },+ { key: "settings", label: "Settings", icon: Settings },+];++export function AgentTabs({ agentSlug }: { agentSlug: string }) {+ const pathname = usePathname();+ const base = `/agents/${agentSlug}`;++ return (+ <nav+ className="flex items-center gap-1 border-b bg-background/60 px-4 backdrop-blur"+ aria-label="Agent sections"+ >+ {TABS.map(({ key, label, icon: Icon }) => {+ const href = `${base}/${key}`;+ const isActive =+ pathname === href || pathname?.startsWith(`${href}/`);+ return (+ <Link+ key={key}+ href={href}+ className={cn(+ "relative flex items-center gap-1.5 px-3 py-2 text-sm transition-colors",+ isActive+ ? "text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ <Icon className="size-3.5" />+ {label}+ {isActive && (+ <span+ aria-hidden+ className="absolute inset-x-2 -bottom-px h-0.5 rounded-full bg-foreground"+ />+ )}+ </Link>+ );+ })}+ </nav>+ );+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 844e76e3..99b08679 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -11,6 +11,7 @@ import {SidebarMenuButton,SidebarMenuItem,SidebarSeparator,+ SidebarTrigger,} from "@/components/ui/sidebar";import {Home,@@ -25,10 +26,11 @@ import {import { listProjects } from "@/server/db/projects";import { getActiveProject } from "@/server/active-project";import { pendingApprovalCount } from "@/server/db/approvals";-import { TEMPLATES, urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templates";+import { listProjectAgents } from "@/server/agent-meta";import { ProjectSwitcher } from "./project-switcher";import { CostMeter } from "./cost-meter";import { AgentNav } from "./agent-nav";+import { CreateAgentButton } from "./create-agent-button";import { Badge } from "@/components/ui/badge";type NavItem = {@@ -52,31 +54,43 @@ export async function AppSidebar() {const projects = listProjects();const active = await getActiveProject();const approvalsBadge = active ? pendingApprovalCount(active.slug) : 0;+ const agentEntries = active ? await listProjectAgents(active.slug) : [];return (<Sidebar collapsible="icon"><SidebarHeader>- <SidebarMenu>- <SidebarMenuItem>- <ProjectSwitcher- projects={projects}- activeSlug={active?.slug ?? null}- />- </SidebarMenuItem>- </SidebarMenu>+ {/* Project switcher + collapse toggle. Toggle stays visible in+ icon-collapsed mode so the user can always re-expand the rail. */}+ <div className="flex items-center gap-1">+ <div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">+ <SidebarMenu>+ <SidebarMenuItem>+ <ProjectSwitcher+ projects={projects}+ activeSlug={active?.slug ?? null}+ />+ </SidebarMenuItem>+ </SidebarMenu>+ </div>+ <SidebarTrigger className="shrink-0" />+ </div></SidebarHeader><SidebarContent>{active && (<SidebarGroup>- <SidebarGroupLabel>Agents</SidebarGroupLabel>+ <SidebarGroupLabel className="flex items-center justify-between">+ <span>Agents</span>+ <CreateAgentButton projectSlug={active.slug} />+ </SidebarGroupLabel><SidebarGroupContent><AgentNav- agents={TEMPLATES.map((t) => ({- key: t.key,- slug: urlSlugForTemplate(t.key as AgentTemplateKey),- display_name: t.display_name,- description: t.description,+ agents={agentEntries.map((a) => ({+ key: a.agent_id,+ slug: a.slug,+ display_name: a.display_name,+ description: a.description,+ template_key: a.template_key,}))}/></SidebarGroupContent>diff --git a/src/components/create-agent-button.tsx b/src/components/create-agent-button.tsxnew file mode 100644index 00000000..472dc68a--- /dev/null+++ b/src/components/create-agent-button.tsx@@ -0,0 +1,32 @@+"use client";++import { useState } from "react";+import { Plus } from "lucide-react";+import { CreateAgentDialog } from "./create-agent-dialog";++type Props = {+ /** Active project slug — used as the agent_id prefix in the name input. */+ projectSlug: string;+};++export function CreateAgentButton({ projectSlug }: Props) {+ const [open, setOpen] = useState(false);+ return (+ <>+ <button+ type="button"+ onClick={() => setOpen(true)}+ className="flex size-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ title="Create or clone agent"+ aria-label="Create or clone agent"+ >+ <Plus className="size-3.5" />+ </button>+ <CreateAgentDialog+ open={open}+ onOpenChange={setOpen}+ projectSlug={projectSlug}+ />+ </>+ );+}diff --git a/src/components/create-agent-dialog.tsx b/src/components/create-agent-dialog.tsxnew file mode 100644index 00000000..efb83fa4--- /dev/null+++ b/src/components/create-agent-dialog.tsx@@ -0,0 +1,399 @@+"use client";++import { useEffect, useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { Loader2, Sparkles, Copy } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Label } from "@/components/ui/label";+import { cn } from "@/lib/utils";+import {+ listOpenClawAgentsAction,+ listProjectAgentsAction,+ createAgentAction,+ cloneAgentAction,+ type AgentChoice,+} from "@/server/actions/agents";+import { slugify } from "@/lib/slug";+import type { CloneAgentResult } from "@/server/openclaw/clone-agent";+import { DisableSourceCronsDialog } from "./disable-source-crons-dialog";++type Mode = "create" | "clone";++type Props = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** Active project slug; rendered as the prefix on the new-agent name input. */+ projectSlug: string;+};++export function CreateAgentDialog({ open, onOpenChange, projectSlug }: Props) {+ const router = useRouter();+ const [mode, setMode] = useState<Mode>("create");+ const [name, setName] = useState("");+ const [sourceId, setSourceId] = useState("");+ const [choices, setChoices] = useState<AgentChoice[]>([]);+ const [loadingChoices, setLoadingChoices] = useState(false);+ const [choicesError, setChoicesError] = useState<string | null>(null);+ const [projectSlugs, setProjectSlugs] = useState<Set<string>>(new Set());+ const [pending, startTransition] = useTransition();++ const [postClone, setPostClone] = useState<{+ result: CloneAgentResult;+ sourceLabel: string;+ } | null>(null);++ useEffect(() => {+ if (!open) {+ setMode("create");+ setName("");+ setSourceId("");+ return;+ }+ setLoadingChoices(true);+ (async () => {+ // Load both: full agent catalog (for the clone dropdown) and the+ // current project's agents (for name-uniqueness validation).+ const [allRes, projectRes] = await Promise.all([+ listOpenClawAgentsAction(),+ listProjectAgentsAction(),+ ]);+ if (allRes.ok) setChoices(allRes.data);+ else setChoicesError(allRes.error);+ if (projectRes.ok) {+ setProjectSlugs(new Set(projectRes.data.map((a) => a.slug)));+ }+ setLoadingChoices(false);+ })();+ }, [open]);++ const selectedSource = choices.find((c) => c.agent_id === sourceId);++ // Compute the slug the typed name would produce so we can validate against+ // existing project agents inline (instead of bouncing through the server).+ const trimmedName = name.trim();+ const slugAttempt = trimmedName ? slugify(trimmedName) : null;+ const derivedSlug = slugAttempt && slugAttempt.ok ? slugAttempt.slug : null;+ const slugInvalidReason =+ slugAttempt && !slugAttempt.ok ? slugAttempt.reason : null;+ const nameCollision = !!derivedSlug && projectSlugs.has(derivedSlug);++ function onSubmit() {+ if (mode === "create") {+ if (!name.trim()) {+ toast.error("Please enter an agent name.");+ return;+ }+ startTransition(async () => {+ const r = await createAgentAction({ display_name: name.trim() });+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ toast.success(`Created ${name.trim()}`);+ onOpenChange(false);+ router.push(`/agents/${r.data.slug}/chat`);+ router.refresh();+ });+ return;+ }+ // Clone mode+ if (!sourceId) {+ toast.error("Please pick a source agent.");+ return;+ }+ const displayName = name.trim();+ if (!displayName) {+ toast.error("Please give the cloned agent a name.");+ return;+ }+ startTransition(async () => {+ const r = await cloneAgentAction({+ source_agent_id: sourceId,+ new_display_name: displayName,+ });+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ toast.success(+ `Cloned ${selectedSource?.display_name ?? sourceId} → ${displayName}`,+ );+ onOpenChange(false);+ // Surface the disable-source-crons follow-up if there were any.+ if (r.data.source_crons.length > 0) {+ setPostClone({ result: r.data, sourceLabel: selectedSource?.display_name ?? sourceId });+ } else {+ // Send the user straight into the new agent.+ router.push(`/agents/${r.data.new_slug}/chat`);+ }+ router.refresh();+ });+ }++ return (+ <>+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle>New agent</DialogTitle>+ <DialogDescription>+ Add a fresh agent to this project, or clone one of your existing OpenClaw agents.+ </DialogDescription>+ </DialogHeader>++ <div+ className="inline-flex items-center gap-1 rounded-lg border bg-muted/40 p-1"+ role="tablist"+ >+ <ModeButton+ active={mode === "create"}+ onClick={() => setMode("create")}+ icon={<Sparkles className="size-3.5" />}+ label="Create new"+ />+ <ModeButton+ active={mode === "clone"}+ onClick={() => setMode("clone")}+ icon={<Copy className="size-3.5" />}+ label="Clone existing"+ />+ </div>++ {mode === "create" ? (+ <div className="space-y-2">+ <Label htmlFor="new-agent-name">Agent name</Label>+ <PrefixedInput+ id="new-agent-name"+ prefix={`${projectSlug}-`}+ placeholder="content-writer"+ value={name}+ onChange={setName}+ disabled={pending}+ autoFocus+ invalid={nameCollision || !!slugInvalidReason}+ />+ <NameHint+ derivedSlug={derivedSlug}+ collision={nameCollision}+ invalidReason={slugInvalidReason}+ defaultHint="Becomes the URL slug too (lowercased, hyphenated)."+ />+ </div>+ ) : (+ <div className="space-y-3">+ <div className="space-y-2">+ <Label htmlFor="clone-source">Source agent</Label>+ {loadingChoices ? (+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="size-3 animate-spin" /> Loading agents…+ </div>+ ) : choicesError ? (+ <div className="text-xs text-destructive">{choicesError}</div>+ ) : (+ <select+ id="clone-source"+ value={sourceId}+ onChange={(e) => setSourceId(e.target.value)}+ disabled={pending}+ className="h-9 w-full rounded-md border bg-background px-3 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ <option value="">Pick one…</option>+ {choices.map((c) => (+ <option key={c.agent_id} value={c.agent_id}>+ {c.display_name}+ {c.display_name !== c.agent_id ? ` · ${c.agent_id}` : ""}+ {c.in_current_project ? " (in this project)" : ""}+ </option>+ ))}+ </select>+ )}+ {selectedSource && (+ <p className="text-[11px] text-muted-foreground">+ Copies workspace files, chat threads, and cron jobs. Cron jobs will be+ renamed to match this project.+ </p>+ )}+ </div>+ <div className="space-y-2">+ <Label htmlFor="clone-name">+ New agent name <span className="text-destructive">*</span>+ </Label>+ <PrefixedInput+ id="clone-name"+ prefix={`${projectSlug}-`}+ placeholder="supa-backup"+ value={name}+ onChange={setName}+ disabled={pending}+ invalid={nameCollision || !!slugInvalidReason}+ />+ <NameHint+ derivedSlug={derivedSlug}+ collision={nameCollision}+ invalidReason={slugInvalidReason}+ defaultHint="Must be unique within this project."+ />+ </div>+ </div>+ )}++ <DialogFooter className="gap-2 sm:gap-2">+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={pending}>+ Cancel+ </Button>+ <Button+ type="button"+ onClick={onSubmit}+ disabled={+ pending ||+ nameCollision ||+ !!slugInvalidReason ||+ (mode === "create" && !name.trim()) ||+ (mode === "clone" && (!sourceId || !name.trim()))+ }+ >+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ {mode === "clone" ? "Cloning…" : "Creating…"}+ </>+ ) : mode === "clone" ? (+ "Clone agent"+ ) : (+ "Create agent"+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ {postClone && (+ <DisableSourceCronsDialog+ open+ onOpenChange={(o) => !o && setPostClone(null)}+ sourceLabel={postClone.sourceLabel}+ newAgentId={postClone.result.new_agent_id}+ sourceCrons={postClone.result.source_crons}+ onDone={() => {+ router.push(`/agents/${postClone.result.new_slug}/chat`);+ router.refresh();+ }}+ />+ )}+ </>+ );+}++function PrefixedInput({+ id,+ prefix,+ value,+ onChange,+ placeholder,+ disabled,+ autoFocus,+ invalid,+}: {+ id: string;+ prefix: string;+ value: string;+ onChange: (next: string) => void;+ placeholder?: string;+ disabled?: boolean;+ autoFocus?: boolean;+ invalid?: boolean;+}) {+ return (+ <div+ className={cn(+ "flex h-9 items-stretch overflow-hidden rounded-md border bg-background text-sm shadow-sm focus-within:ring-1 focus-within:ring-ring",+ invalid && "border-destructive focus-within:ring-destructive",+ disabled && "opacity-50",+ )}+ >+ <span+ className="select-none border-r bg-muted/50 px-2.5 font-mono text-[12px] text-muted-foreground flex items-center"+ aria-hidden+ >+ {prefix}+ </span>+ <input+ id={id}+ type="text"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ disabled={disabled}+ autoFocus={autoFocus}+ aria-invalid={invalid || undefined}+ className="flex-1 bg-transparent px-2 font-mono text-[13px] placeholder:text-muted-foreground/60 focus-visible:outline-none disabled:cursor-not-allowed"+ />+ </div>+ );+}++function NameHint({+ derivedSlug,+ collision,+ invalidReason,+ defaultHint,+}: {+ derivedSlug: string | null;+ collision: boolean;+ invalidReason: string | null;+ defaultHint: string;+}) {+ if (invalidReason) {+ return (+ <p className="text-[11px] text-destructive">+ Invalid name: {invalidReason}+ </p>+ );+ }+ if (collision && derivedSlug) {+ return (+ <p className="text-[11px] text-destructive">+ An agent named “{derivedSlug}” already exists in this project.+ Pick a different name.+ </p>+ );+ }+ return <p className="text-[11px] text-muted-foreground">{defaultHint}</p>;+}++function ModeButton({+ active,+ onClick,+ icon,+ label,+}: {+ active: boolean;+ onClick: () => void;+ icon: React.ReactNode;+ label: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ "flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium transition-colors",+ active+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {icon}+ {label}+ </button>+ );+}diff --git a/src/components/cron-calendar.tsx b/src/components/cron-calendar.tsxindex 54119e6c..34aa8244 100644--- a/src/components/cron-calendar.tsx+++ b/src/components/cron-calendar.tsx@@ -1,7 +1,21 @@"use client";-import { useMemo, useState } from "react";-import { ChevronLeft, ChevronRight, Pause, Play, Trash2, ExternalLink } from "lucide-react";+import { useEffect, useMemo, useState, useTransition } from "react";+import {+ AlertCircle,+ Check,+ ChevronLeft,+ ChevronRight,+ ChevronRight as ChevronRightSmall,+ Loader2,+ Pause,+ Pencil,+ Play,+ Save,+ Trash2,+ X,+} from "lucide-react";+/* note: ExternalLink import removed with the OpenClaw docs button */import { Button } from "@/components/ui/button";import {Dialog,@@ -19,7 +33,9 @@ import {pauseCronAction,resumeCronAction,deleteCronAction,+ updateCronPromptAction,} from "@/server/actions/crons";+import { getCronRunsAction, type CronRunWithTick, type ScheduleInput } from "@/server/actions/cron-runs";/*** Pre-computed cron occurrence used by the calendar. Server computes these@@ -33,6 +49,10 @@ export type CalendarOccurrence = {agent_id: string;agent_slug: string;schedule_text: string;+ /** Raw OpenClaw status when this occurrence has fired (e.g. "ok", "error"). */+ run_status?: string;+ /** True when the underlying cron is currently paused/disabled. */+ cron_disabled?: boolean;};export type CalendarCron = {@@ -44,6 +64,16 @@ export type CalendarCron = {schedule_text: string;disabled: boolean;status_text: string;+ /** Prompt sent to the agent on every tick. */+ message?: string;+ description?: string;+ /** Last execution time (ms epoch). */+ last_run_at_ms?: number;+ /** Raw OpenClaw status string for the most recent run (e.g. "ok", "error"). */+ last_status?: string;+ last_error?: string;+ /** Schedule shape — used to attribute runs to occurrences via nominal ticks. */+ schedule_raw?: ScheduleInput | null;};type Props = {@@ -58,6 +88,8 @@ type Props = {const DAY_MS = 24 * 60 * 60 * 1000;+type CronFilter = "all" | "enabled" | "disabled";+export function CronCalendar({startOfFirstDay,numDays,@@ -67,21 +99,37 @@ export function CronCalendar({}: Props) {const [focusDayOffset, setFocusDayOffset] = useState(0);const [selected, setSelected] = useState<CalendarOccurrence | null>(null);+ const [filter, setFilter] = useState<CronFilter>("enabled");++ const visibleOccurrences = useMemo(() => {+ if (filter === "all") return occurrences;+ return occurrences.filter((o) => {+ const d = cronsById[o.cron_id]?.disabled;+ return filter === "disabled" ? !!d : !d;+ });+ }, [occurrences, filter, cronsById]);- // Group occurrences into days. Memoize because we slice the same data on- // every state change.+ // Agent slugs visible right now drive the legend.+ const visibleAgentSlugs = useMemo(() => {+ if (filter === "all") return agentSlugs;+ const set = new Set<string>();+ for (const o of visibleOccurrences) set.add(o.agent_slug);+ return Array.from(set).sort();+ }, [agentSlugs, visibleOccurrences, filter]);++ // Group filtered occurrences into days.const days = useMemo(() => {const buckets: CalendarOccurrence[][] = Array.from({ length: numDays },() => [],);- for (const o of occurrences) {+ for (const o of visibleOccurrences) {const idx = Math.floor((o.at - startOfFirstDay) / DAY_MS);if (idx >= 0 && idx < numDays) buckets[idx]!.push(o);}for (const day of buckets) day.sort((a, b) => a.at - b.at);return buckets;- }, [occurrences, numDays, startOfFirstDay]);+ }, [visibleOccurrences, numDays, startOfFirstDay]);// 7-day window navigation (we keep numDays at 14 to allow scrolling).const visibleDays = Math.min(7, numDays);@@ -93,10 +141,12 @@ export function CronCalendar({return (<><div className="space-y-3">- {/* Legend + window navigator */}+ {/* Legend + filter chips + window navigator */}<div className="flex flex-wrap items-center justify-between gap-2"><div className="flex flex-wrap items-center gap-3">- {agentSlugs.map((slug) => {+ <FilterChips filter={filter} onChange={setFilter} />+ <span className="h-4 w-px bg-border" aria-hidden />+ {visibleAgentSlugs.map((slug) => {const color = colorForAgentSlug(slug);return (<div key={slug} className="flex items-center gap-1.5 text-xs">@@ -105,9 +155,9 @@ export function CronCalendar({</div>);})}- {agentSlugs.length === 0 && (+ {visibleAgentSlugs.length === 0 && (<span className="text-xs text-muted-foreground">- No agents have scheduled work in this window.+ Nothing to show with this filter.</span>)}</div>@@ -178,6 +228,48 @@ export function CronCalendar({// --- Day column ---+function FilterChips({+ filter,+ onChange,+}: {+ filter: CronFilter;+ onChange: (f: CronFilter) => void;+}) {+ const items: Array<{ key: CronFilter; label: string }> = [+ { key: "enabled", label: "Enabled" },+ { key: "disabled", label: "Disabled" },+ { key: "all", label: "All" },+ ];+ return (+ <div+ className="inline-flex items-center gap-0.5 rounded-md border bg-muted/40 p-0.5"+ role="tablist"+ aria-label="Filter crons"+ >+ {items.map(({ key, label }) => {+ const isActive = filter === key;+ return (+ <button+ key={key}+ type="button"+ role="tab"+ aria-selected={isActive}+ onClick={() => onChange(key)}+ className={cn(+ "rounded px-2 py-0.5 text-[11px] font-medium transition-colors",+ isActive+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {label}+ </button>+ );+ })}+ </div>+ );+}+function DayColumn({dayStart,occurrences,@@ -259,15 +351,60 @@ function OccurrenceChip({className={cn("block w-full rounded-md border px-2 py-1 text-left text-[11px] leading-tight transition-colors hover:brightness-95",color.chip,+ occurrence.cron_disabled && "opacity-50 border-dashed",)}- title={`${occurrence.cron_name} · ${occurrence.schedule_text}`}+ title={`${occurrence.cron_name} · ${occurrence.schedule_text}${+ occurrence.cron_disabled ? " · disabled" : ""+ }${occurrence.run_status ? ` · ${occurrence.run_status}` : ""}`}>- <div className="tabular-nums font-medium">{time}</div>+ <div className="flex items-center justify-between gap-1 tabular-nums font-medium">+ <span className={cn(occurrence.cron_disabled && "line-through")}>+ {time}+ </span>+ {occurrence.cron_disabled ? (+ <Pause className="size-3 shrink-0 text-muted-foreground" />+ ) : (+ <RunStatusGlyph status={occurrence.run_status} />+ )}+ </div><div className="truncate opacity-80">{occurrence.short_name}</div></button>);}+function RunStatusGlyph({ status }: { status: string | undefined }) {+ if (!status) return null;+ const lower = status.toLowerCase();+ if (lower === "ok") {+ return (+ <span+ className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full bg-emerald-500 text-white"+ aria-label="success"+ >+ <Check className="size-2.5" strokeWidth={3} />+ </span>+ );+ }+ if (lower === "error") {+ return (+ <span+ className="inline-flex size-3.5 shrink-0 items-center justify-center rounded-full bg-destructive text-white"+ aria-label="error"+ >+ <AlertCircle className="size-2.5" strokeWidth={3} />+ </span>+ );+ }+ // Other statuses (e.g. "skipped"): show a neutral dot to flag "ran but+ // neither ok nor error". Keeps the chip honest without picking a color.+ return (+ <span+ className="inline-flex size-2 shrink-0 rounded-full bg-zinc-400"+ aria-label={status}+ />+ );+}+// --- Detail dialog with pause/resume/delete ---function CronDetailDialog({@@ -279,38 +416,248 @@ function CronDetailDialog({cron: CalendarCron | null;onClose: () => void;}) {+ const [runs, setRuns] = useState<CronRunWithTick[] | null>(null);+ const [runsLoading, setRunsLoading] = useState(false);+ const [runsError, setRunsError] = useState<string | null>(null);++ // Fetch this cron's run history when the dialog opens. Stays mounted across+ // occurrence clicks for the same cron, so cache by id.+ useEffect(() => {+ if (!cron) {+ setRuns(null);+ setRunsError(null);+ return;+ }+ let cancelled = false;+ setRunsLoading(true);+ setRunsError(null);+ (async () => {+ const r = await getCronRunsAction(cron.id, cron.schedule_raw ?? null, 200);+ if (cancelled) return;+ if (r.ok) setRuns(r.runs);+ else setRunsError(r.error);+ setRunsLoading(false);+ })();+ return () => {+ cancelled = true;+ };+ }, [cron]);++ // Prompt-edit state lives here (not in EditablePrompt) so the section+ // header can host the Edit / Save / Cancel buttons next to the title.+ const [promptEditing, setPromptEditing] = useState(false);+ const [promptDraft, setPromptDraft] = useState(cron?.message ?? "");+ const [promptPending, startPromptTransition] = useTransition();+ useEffect(() => {+ setPromptEditing(false);+ setPromptDraft(cron?.message ?? "");+ }, [cron?.id, cron?.message]);+if (!occurrence || !cron) return null;+ const matchedRun = findRunForOccurrence(runs, occurrence.at);+ const occStatus = computeOccurrenceStatus(occurrence, matchedRun);++ function savePrompt() {+ const trimmed = promptDraft.trim();+ if (!trimmed) {+ toast.error("Prompt cannot be empty.");+ return;+ }+ if (trimmed === cron!.message) {+ setPromptEditing(false);+ return;+ }+ startPromptTransition(async () => {+ const r = await updateCronPromptAction(cron!.id, trimmed);+ if (!r.ok) {+ toast.error(r.error ?? "Could not update prompt");+ return;+ }+ setPromptEditing(false);+ toast.success("Prompt updated");+ });+ }++ function cancelPromptEdit() {+ setPromptDraft(cron!.message ?? "");+ setPromptEditing(false);+ }+return (<Dialog open={!!occurrence} onOpenChange={(o) => !o && onClose()}>- <DialogContent className="max-w-md">- <DialogHeader>- <DialogTitle className="text-base">{cron.short_name}</DialogTitle>- <DialogDescription className="font-mono text-xs">- {cron.full_name}- </DialogDescription>+ <DialogContent className="flex max-h-[80vh] max-w-xl flex-col gap-0 p-0">+ {/* Header — single row: title + status pill, tight padding. */}+ <DialogHeader className="shrink-0 space-y-0 border-b px-4 py-2.5">+ <div className="flex items-center gap-2">+ <DialogTitle className="truncate text-sm font-semibold leading-tight">+ {cron.short_name}+ </DialogTitle>+ <OccurrenceStatusBadge status={occStatus} />+ </div>+ {cron.description && (+ <DialogDescription className="mt-0.5 truncate text-[11px] text-muted-foreground">+ {cron.description}+ </DialogDescription>+ )}</DialogHeader>- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-sm">- <dt className="text-muted-foreground">Agent</dt>- <dd className="font-mono text-xs">{cron.agent_id}</dd>+ {/* Body — scrolls. Sections are flat (no card chrome) to keep the+ modal short when collapsed. */}+ <div className="min-h-0 flex-1 divide-y overflow-y-auto">+ <CollapsibleSection title="Details" defaultOpen>+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-[11px]">+ <dt className="text-muted-foreground">Full name</dt>+ <dd className="truncate font-mono">{cron.full_name}</dd>++ <dt className="text-muted-foreground">Agent</dt>+ <dd className="font-mono">{cron.agent_id}</dd>- <dt className="text-muted-foreground">Schedule</dt>- <dd className="font-mono text-xs">{cron.schedule_text}</dd>+ <dt className="text-muted-foreground">Schedule</dt>+ <dd className="font-mono">{cron.schedule_text}</dd>++ <dt className="text-muted-foreground">Occurrence</dt>+ <dd className="tabular-nums">{new Date(occurrence.at).toLocaleString()}</dd>++ {matchedRun && (+ <>+ <dt className="text-muted-foreground">Finished</dt>+ <dd className="tabular-nums">+ {new Date(matchedRun.finished_at_ms).toLocaleString()}+ {matchedRun.duration_ms != null && (+ <span className="ml-1 text-muted-foreground">+ ({formatDuration(matchedRun.duration_ms)})+ </span>+ )}+ </dd>+ {matchedRun.model && (+ <>+ <dt className="text-muted-foreground">Model</dt>+ <dd className="font-mono">+ {matchedRun.model}+ {matchedRun.provider && (+ <span className="ml-1 text-muted-foreground">+ · {matchedRun.provider}+ </span>+ )}+ </dd>+ </>+ )}+ {matchedRun.usage?.total_tokens != null && (+ <>+ <dt className="text-muted-foreground">Tokens</dt>+ <dd className="tabular-nums">+ {matchedRun.usage.total_tokens.toLocaleString()}+ </dd>+ </>+ )}+ </>+ )}+ </dl>+ </CollapsibleSection>++ {cron.message != null && (+ <CollapsibleSection+ title="Prompt"+ defaultOpen+ actions={+ promptEditing ? (+ <>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={cancelPromptEdit}+ disabled={promptPending}+ className="h-6 px-2 text-[11px]"+ >+ <X className="mr-1 size-3" />+ Cancel+ </Button>+ <Button+ type="button"+ size="sm"+ onClick={savePrompt}+ disabled={promptPending}+ className="h-6 px-2 text-[11px]"+ >+ {promptPending ? (+ <Loader2 className="mr-1 size-3 animate-spin" />+ ) : (+ <Save className="mr-1 size-3" />+ )}+ Save+ </Button>+ </>+ ) : (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => setPromptEditing(true)}+ className="h-6 px-2 text-[11px]"+ >+ <Pencil className="mr-1 size-3" />+ Edit+ </Button>+ )+ }+ >+ {promptEditing ? (+ <textarea+ value={promptDraft}+ onChange={(e) => setPromptDraft(e.target.value)}+ disabled={promptPending}+ className="max-h-64 min-h-[80px] w-full resize-y overflow-y-auto rounded border bg-background p-2 font-mono text-[11px] leading-relaxed focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"+ rows={6}+ autoFocus+ />+ ) : (+ <pre className="max-h-56 overflow-y-auto whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed">+ {cron.message}+ </pre>+ )}+ </CollapsibleSection>+ )}- <dt className="text-muted-foreground">This occurrence</dt>- <dd className="tabular-nums">- {new Date(occurrence.at).toLocaleString()}- </dd>+ {matchedRun?.error && (+ <CollapsibleSection title="Error" tone="destructive" defaultOpen>+ <div className="whitespace-pre-wrap break-words font-mono text-[11px] text-muted-foreground">+ {matchedRun.error}+ </div>+ </CollapsibleSection>+ )}- <dt className="text-muted-foreground">Status</dt>- <dd>- <Badge variant={cron.disabled ? "outline" : "secondary"} className="text-[10px]">- {cron.disabled ? "paused" : cron.status_text}- </Badge>- </dd>- </dl>+ <CollapsibleSection title="Result" defaultOpen>+ {matchedRun ? (+ matchedRun.summary ? (+ <div className="max-h-64 overflow-y-auto whitespace-pre-wrap break-words text-[12px] leading-relaxed">+ {matchedRun.summary}+ </div>+ ) : (+ <div className="text-[11px] text-muted-foreground">+ Run finished with no summary.+ </div>+ )+ ) : runsLoading ? (+ <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Loader2 className="size-3 animate-spin" /> Loading…+ </div>+ ) : runsError ? (+ <div className="text-[11px] text-destructive">{runsError}</div>+ ) : occurrence.at <= Date.now() ? (+ <div className="text-[11px] text-muted-foreground">+ No run log for this occurrence.+ </div>+ ) : (+ <div className="text-[11px] text-muted-foreground">+ Not fired yet.+ </div>+ )}+ </CollapsibleSection>+ </div>- <DialogFooter className="gap-2 sm:gap-2">+ {/* Footer — sticky, tight. */}+ <DialogFooter className="shrink-0 gap-2 border-t bg-background/95 px-4 py-2 sm:gap-2"><CronActions cronId={cron.id} cronName={cron.short_name} disabled={cron.disabled} onAfter={onClose} /></DialogFooter></DialogContent>@@ -318,6 +665,143 @@ function CronDetailDialog({);}+function CollapsibleSection({+ title,+ tone = "default",+ defaultOpen,+ actions,+ children,+}: {+ title: string;+ tone?: "default" | "destructive";+ defaultOpen?: boolean;+ /** Right-aligned controls in the section header (don't toggle the section). */+ actions?: React.ReactNode;+ children: React.ReactNode;+}) {+ const [open, setOpen] = useState(!!defaultOpen);+ useEffect(() => {+ setOpen(!!defaultOpen);+ }, [defaultOpen]);++ return (+ <section className={cn(tone === "destructive" && "bg-destructive/5")}>+ <div className="flex items-center gap-2 pr-2">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ className={cn(+ "flex flex-1 items-center gap-1.5 px-4 py-1.5 text-left text-[10px] font-semibold uppercase tracking-wide",+ tone === "destructive" ? "text-destructive" : "text-muted-foreground hover:text-foreground",+ )}+ aria-expanded={open}+ >+ <ChevronRightSmall+ className={cn("size-3 transition-transform", open && "rotate-90")}+ />+ {title}+ </button>+ {actions && (+ <div className="flex shrink-0 items-center gap-1">{actions}</div>+ )}+ </div>+ {open && <div className="px-4 pb-3">{children}</div>}+ </section>+ );+}+++function findRunForOccurrence(+ runs: CronRunWithTick[] | null,+ occAt: number,+): CronRunWithTick | null {+ if (!runs?.length) return null;+ // Preferred path: server tagged each run with its owning nominal tick via+ // the cron schedule. Exact match handles late-fires (e.g., a 11:00 tick+ // whose run actually ran at 11:06:20) without time-window guesswork.+ const exact = runs.find((r) => r.owning_occurrence_at_ms === occAt);+ if (exact) return exact;+ // Fallback for older schedules we couldn't parse: pick the closest run+ // within ±15 minutes — wide enough to cover scheduler drift but tight+ // enough to keep adjacent hourly ticks from cross-matching.+ let best: CronRunWithTick | null = null;+ let bestDelta = Number.POSITIVE_INFINITY;+ for (const r of runs) {+ const delta = Math.abs(r.run_at_ms - occAt);+ if (delta < bestDelta && delta < 15 * 60_000) {+ best = r;+ bestDelta = delta;+ }+ }+ return best;+}++function formatDuration(ms: number): string {+ if (ms < 1000) return `${ms} ms`;+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;+ return `${Math.round(ms / 60_000)}m`;+}++type OccurrenceStatus =+ /** Future tick the scheduler hasn't fired yet. */+ | { kind: "scheduled"; at: number }+ /** Past tick we have a status string for from OpenClaw (verbatim). */+ | { kind: "ran"; at: number; raw: string }+ /** Past tick but no status from OpenClaw (the cron has never run here, or we+ * don't have a recent enough run to align). */+ | { kind: "past"; at: number };++/**+ * Decide how to label this occurrence using OpenClaw's own status vocabulary:+ * - future → "scheduled"+ * - past tick with a matching entry in the run log → show that run's raw+ * status string (e.g. "ok", "error", "skipped")+ * - past tick with no matching run → "past"+ */+function computeOccurrenceStatus(+ occ: CalendarOccurrence,+ run: CronRunWithTick | null,+): OccurrenceStatus {+ if (occ.at > Date.now()) return { kind: "scheduled", at: occ.at };+ if (run) return { kind: "ran", at: occ.at, raw: run.status };+ return { kind: "past", at: occ.at };+}++function OccurrenceStatusBadge({ status }: { status: OccurrenceStatus }) {+ if (status.kind === "scheduled") {+ return <Pill cls="bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/30">scheduled</Pill>;+ }+ if (status.kind === "past") {+ return <Pill cls="bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/30">past</Pill>;+ }+ // Past run with a known status — show OpenClaw's raw string, color by it.+ return <Pill cls={colorForRawStatus(status.raw)}>{status.raw}</Pill>;+}++function colorForRawStatus(raw: string): string {+ const lower = raw.toLowerCase();+ if (lower === "ok") {+ return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/30";+ }+ if (lower === "error") {+ return "bg-destructive/10 text-destructive border-destructive/40";+ }+ return "bg-zinc-500/10 text-zinc-700 dark:text-zinc-300 border-zinc-500/30";+}++function Pill({ cls, children }: { cls: string; children: React.ReactNode }) {+ return (+ <span+ className={cn(+ "inline-flex w-fit items-center gap-1 rounded-md border px-2 py-0.5 font-mono text-[11px] font-medium",+ cls,+ )}+ >+ {children}+ </span>+ );+}+function CronActions({cronId,cronName,@@ -347,19 +831,19 @@ function CronActions({<Buttonvariant="outline"size="sm"- onClick={() => run("Resumed", () => resumeCronAction(cronId))}+ onClick={() => run("Enabled", () => resumeCronAction(cronId))}><Play className="mr-1.5 size-3.5" />- Resume+ Enable</Button>) : (<Buttonvariant="outline"size="sm"- onClick={() => run("Paused", () => pauseCronAction(cronId))}+ onClick={() => run("Disabled", () => pauseCronAction(cronId))}><Pause className="mr-1.5 size-3.5" />- Pause+ Disable</Button>)}<Button@@ -374,17 +858,6 @@ function CronActions({<Trash2 className="mr-1.5 size-3.5" />Delete</Button>- <Button asChild variant="ghost" size="sm">- <a- href={`https://docs.openclaw.ai/cli/cron`}- target="_blank"- rel="noreferrer"- className="text-xs"- >- <ExternalLink className="mr-1 size-3" />- OpenClaw docs- </a>- </Button></>);}diff --git a/src/components/danger-zone.tsx b/src/components/danger-zone.tsxnew file mode 100644index 00000000..55ad9478--- /dev/null+++ b/src/components/danger-zone.tsx@@ -0,0 +1,192 @@+"use client";++import { useEffect, useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { AlertTriangle, Trash2, Loader2 } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ getProjectDeletionSummaryAction,+ deleteProjectAction,+} from "@/server/actions/projects";+import type { ProjectDeletionSummary } from "@/server/openclaw/project-delete";++type Props = {+ projectSlug: string;+ projectName: string;+};++export function DangerZone({ projectSlug, projectName }: Props) {+ const router = useRouter();+ const [open, setOpen] = useState(false);+ const [summary, setSummary] = useState<ProjectDeletionSummary | null>(null);+ const [summaryError, setSummaryError] = useState<string | null>(null);+ const [loadingSummary, setLoadingSummary] = useState(false);+ const [pending, startTransition] = useTransition();++ useEffect(() => {+ if (!open) {+ setSummary(null);+ setSummaryError(null);+ return;+ }+ setLoadingSummary(true);+ (async () => {+ const r = await getProjectDeletionSummaryAction(projectSlug);+ if (r.ok) setSummary(r.data);+ else setSummaryError(r.error);+ setLoadingSummary(false);+ })();+ }, [open, projectSlug]);++ const canDelete = !pending && !loadingSummary;++ function onConfirm() {+ startTransition(async () => {+ const r = await deleteProjectAction(projectSlug, projectSlug);+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ const d = r.data;+ const partial = d.agentsFailed.length + d.cronsFailed;+ if (partial > 0) {+ toast.warning(+ `Deleted with ${partial} issue${partial === 1 ? "" : "s"}. ` ++ `${d.agents.length} agents, ${d.crons} crons removed.`,+ );+ } else {+ toast.success(`Deleted ${projectName}. ${d.agents.length} agents, ${d.crons} crons removed.`);+ }+ setOpen(false);+ router.push("/");+ router.refresh();+ });+ }++ return (+ <>+ <div className="space-y-3 rounded-lg border border-destructive/40 bg-destructive/5 p-4">+ <div className="flex items-start gap-3">+ <AlertTriangle className="mt-0.5 size-4 shrink-0 text-destructive" />+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold text-destructive">Delete this project</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">+ Removes all agents created for this project, every scheduled cron job, and+ every thread of chat history. This cannot be undone.+ </p>+ </div>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => setOpen(true)}+ className="shrink-0"+ >+ <Trash2 className="mr-1.5 size-3.5" />+ Delete project+ </Button>+ </div>+ </div>++ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle className="flex items-center gap-2 text-base">+ <AlertTriangle className="size-4 text-destructive" />+ Delete “{projectName}”?+ </DialogTitle>+ <DialogDescription>+ This will permanently delete the items below from OpenClaw and notfair-cmo's+ local store. There is no recovery.+ </DialogDescription>+ </DialogHeader>++ {loadingSummary ? (+ <div className="flex items-center gap-2 py-4 text-sm text-muted-foreground">+ <Loader2 className="size-3.5 animate-spin" />+ Counting what will be removed…+ </div>+ ) : summaryError ? (+ <div className="rounded border border-destructive/40 bg-destructive/5 p-3 text-xs text-destructive">+ Could not load deletion summary: {summaryError}+ </div>+ ) : summary ? (+ <div className="space-y-3">+ <div className="grid grid-cols-3 divide-x rounded-lg border bg-card">+ <Stat label="Agents" value={summary.totals.agents} />+ <Stat label="Threads" value={summary.totals.threads} />+ <Stat label="Crons" value={summary.totals.crons} />+ </div>+ {summary.agents.some((a) => a.exists) && (+ <ul className="space-y-1 text-xs">+ {summary.agents+ .filter((a) => a.exists)+ .map((a) => (+ <li key={a.agentId} className="flex items-center justify-between gap-2">+ <span>+ {a.display_name}{" "}+ <span className="font-mono text-[10px] text-muted-foreground">+ {a.agentId}+ </span>+ </span>+ <span className="tabular-nums text-muted-foreground">+ {a.threadCount} thread{a.threadCount === 1 ? "" : "s"}+ </span>+ </li>+ ))}+ </ul>+ )}+ </div>+ ) : null}++ <DialogFooter className="gap-2 sm:gap-2">+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ disabled={pending}+ >+ Cancel+ </Button>+ <Button+ type="button"+ variant="destructive"+ onClick={onConfirm}+ disabled={!canDelete}+ >+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ Deleting…+ </>+ ) : (+ <>+ <Trash2 className="mr-1.5 size-3.5" />+ Delete forever+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}++function Stat({ label, value }: { label: string; value: number }) {+ return (+ <div className="px-3 py-2 text-center">+ <div className="text-lg font-semibold tabular-nums">{value}</div>+ <div className="text-[10px] uppercase tracking-wide text-muted-foreground">{label}</div>+ </div>+ );+}diff --git a/src/components/disable-source-crons-dialog.tsx b/src/components/disable-source-crons-dialog.tsxnew file mode 100644index 00000000..e8ab8212--- /dev/null+++ b/src/components/disable-source-crons-dialog.tsx@@ -0,0 +1,119 @@+"use client";++import { useState, useTransition } from "react";+import { Loader2, Pause } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { disableCronsAction } from "@/server/actions/agents";+import type { CloneSourceCron } from "@/server/openclaw/clone-agent";++type Props = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ sourceLabel: string;+ newAgentId: string;+ sourceCrons: CloneSourceCron[];+ onDone: () => void;+};++export function DisableSourceCronsDialog({+ open,+ onOpenChange,+ sourceLabel,+ newAgentId,+ sourceCrons,+ onDone,+}: Props) {+ const [pending, startTransition] = useTransition();+ const [completed, setCompleted] = useState(false);++ const enabledSource = sourceCrons.filter((c) => !c.disabled);++ function disableAll() {+ if (enabledSource.length === 0) {+ finish();+ return;+ }+ startTransition(async () => {+ const r = await disableCronsAction(enabledSource.map((c) => c.id));+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ if (r.data.failed > 0) {+ toast.warning(`Disabled ${r.data.disabled} crons (${r.data.failed} failed)`);+ } else {+ toast.success(`Disabled ${r.data.disabled} cron${r.data.disabled === 1 ? "" : "s"} on ${sourceLabel}`);+ }+ setCompleted(true);+ finish();+ });+ }++ function keepRunning() {+ finish();+ }++ function finish() {+ onOpenChange(false);+ onDone();+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-md">+ <DialogHeader>+ <DialogTitle className="text-base">Disable {sourceLabel}’s cron jobs?</DialogTitle>+ <DialogDescription>+ We just copied {sourceCrons.length} cron job+ {sourceCrons.length === 1 ? "" : "s"} from <span className="font-mono text-xs">{sourceLabel}</span>{" "}+ onto your new agent <span className="font-mono text-xs">{newAgentId}</span>. Leaving the originals+ running will fire both copies on schedule.+ </DialogDescription>+ </DialogHeader>++ {sourceCrons.length > 0 && (+ <ul className="max-h-44 space-y-1 overflow-y-auto rounded-lg border bg-card p-2 text-xs">+ {sourceCrons.map((c) => (+ <li key={c.id} className="flex items-center justify-between gap-2 px-2 py-1">+ <span className="truncate">{c.name}</span>+ {c.disabled && (+ <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">+ already off+ </span>+ )}+ </li>+ ))}+ </ul>+ )}++ <DialogFooter className="gap-2 sm:gap-2">+ <Button type="button" variant="outline" onClick={keepRunning} disabled={pending}>+ Keep them running+ </Button>+ <Button type="button" onClick={disableAll} disabled={pending || completed}>+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ Disabling…+ </>+ ) : (+ <>+ <Pause className="mr-1.5 size-3.5" />+ Disable on source (recommended)+ </>+ )}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/components/project-rename-card.tsx b/src/components/project-rename-card.tsxnew file mode 100644index 00000000..a00399b4--- /dev/null+++ b/src/components/project-rename-card.tsx@@ -0,0 +1,131 @@+"use client";++import { useEffect, useState, useTransition } from "react";+import { useRouter } from "next/navigation";+import { Loader2, Pencil } from "lucide-react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Label } from "@/components/ui/label";+import { cn } from "@/lib/utils";+import { slugify } from "@/lib/slug";+import { renameProjectFullAction } from "@/server/actions/projects";++type Props = {+ currentSlug: string;+ currentDisplayName: string;+};++export function ProjectRenameCard({+ currentSlug,+ currentDisplayName,+}: Props) {+ const router = useRouter();+ const [name, setName] = useState(currentDisplayName);+ const [pending, startTransition] = useTransition();++ useEffect(() => {+ setName(currentDisplayName);+ }, [currentDisplayName]);++ const trimmed = name.trim();+ const slugAttempt = trimmed ? slugify(trimmed) : null;+ const derivedSlug = slugAttempt?.ok ? slugAttempt.slug : null;+ const slugError = slugAttempt && !slugAttempt.ok ? slugAttempt.reason : null;+ const slugChanged = !!derivedSlug && derivedSlug !== currentSlug;+ const nameChanged = trimmed !== currentDisplayName;++ function save() {+ if (!nameChanged && !slugChanged) return;+ startTransition(async () => {+ const r = await renameProjectFullAction({+ current_slug: currentSlug,+ new_display_name: trimmed,+ });+ if (!r.ok) {+ toast.error(r.error);+ return;+ }+ const d = r.data;+ if (d.full_rename) {+ const failed = d.agents_failed.length;+ toast.success(+ failed > 0+ ? `Renamed to "${d.display_name}" (${d.agents_relocated.length} agents moved, ${failed} failed)`+ : `Renamed to "${d.display_name}" (${d.agents_relocated.length} agents moved)`,+ );+ } else {+ toast.success(`Renamed to "${d.display_name}"`);+ }+ router.refresh();+ });+ }++ const canSave =+ !pending && !slugError && trimmed.length > 0 && (nameChanged || slugChanged);++ return (+ <div className="space-y-3 rounded-lg border bg-card p-4">+ <div className="flex items-start gap-3">+ <Pencil className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold">Rename this project</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">+ Changing the slug renames every agent in the project, rewrites all+ cron names, moves workspace dirs, relocates session JSONL files,+ and repoints DB rows.+ </p>+ </div>+ </div>++ <div className="space-y-2">+ <Label htmlFor="project-rename-name" className="text-xs">+ Display name+ </Label>+ <input+ id="project-rename-name"+ type="text"+ value={name}+ onChange={(e) => setName(e.target.value)}+ disabled={pending}+ className={cn(+ "h-9 w-full rounded-md border bg-background px-3 font-mono text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",+ slugError && "border-destructive focus-visible:ring-destructive",+ pending && "opacity-50",+ )}+ aria-invalid={!!slugError}+ />+ {slugError ? (+ <p className="text-[11px] text-destructive">Invalid name: {slugError}</p>+ ) : slugChanged ? (+ <p className="text-[11px] text-muted-foreground">+ Slug changes from{" "}+ <code className="rounded bg-muted px-1 font-mono">{currentSlug}</code>{" "}+ to{" "}+ <code className="rounded bg-muted px-1 font-mono">{derivedSlug}</code>+ . Every agent will be cloned into the new project and the old one+ removed.+ </p>+ ) : (+ <p className="text-[11px] text-muted-foreground">+ Same slug — only the display name changes.+ </p>+ )}+ </div>++ <div className="flex justify-end">+ <Button type="button" size="sm" onClick={save} disabled={!canSave}>+ {pending ? (+ <>+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />+ {slugChanged ? "Renaming…" : "Saving…"}+ </>+ ) : slugChanged ? (+ "Rename project"+ ) : (+ "Save name"+ )}+ </Button>+ </div>+ </div>+ );+}diff --git a/src/components/skills-list.tsx b/src/components/skills-list.tsxnew file mode 100644index 00000000..26554e65--- /dev/null+++ b/src/components/skills-list.tsx@@ -0,0 +1,183 @@+"use client";++import { useMemo, useState, useTransition } from "react";+import { Loader2 } from "lucide-react";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { toast } from "sonner";+import type { SkillEntry } from "@/server/openclaw/gateway-rpc";+import { setSkillEnabledAction } from "@/server/actions/skills";++type FilterKey = "all" | "enabled" | "disabled";++const FILTER_LABELS: Record<FilterKey, string> = {+ all: "All",+ enabled: "Enabled",+ disabled: "Disabled",+};++type Props = {+ skills: SkillEntry[];+ agentSlug: string;+};++/**+ * Definition used by both the filter and the toggle:+ * enabled = !skill.disabled+ * `eligible` is computed by OpenClaw from `enabled` + requirement checks (binary+ * present, allowlist passes, etc.). The user can flip `enabled`; they can't flip+ * `eligible`. So our toggle binds to `!disabled`, and we surface ineligibility+ * with a side badge instead of locking the switch.+ */+export function SkillsList({ skills, agentSlug }: Props) {+ const [filter, setFilter] = useState<FilterKey>("all");++ const counts = useMemo(() => {+ let enabled = 0;+ let disabled = 0;+ for (const s of skills) {+ if (s.disabled) disabled++;+ else enabled++;+ }+ return { all: skills.length, enabled, disabled };+ }, [skills]);++ const filtered = useMemo(() => {+ if (filter === "all") return skills;+ if (filter === "enabled") return skills.filter((s) => !s.disabled);+ return skills.filter((s) => s.disabled);+ }, [skills, filter]);++ return (+ <div className="space-y-4">+ <div+ className="inline-flex items-center gap-1 rounded-lg border bg-muted/40 p-1"+ role="tablist"+ aria-label="Filter skills"+ >+ {(Object.keys(FILTER_LABELS) as FilterKey[]).map((key) => {+ const isActive = filter === key;+ return (+ <button+ key={key}+ type="button"+ role="tab"+ aria-selected={isActive}+ onClick={() => setFilter(key)}+ className={cn(+ "rounded-md px-3 py-1 text-xs font-medium transition-colors",+ isActive+ ? "bg-background text-foreground shadow-sm"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {FILTER_LABELS[key]}+ <span className="ml-1.5 text-[10px] tabular-nums text-muted-foreground">+ {counts[key]}+ </span>+ </button>+ );+ })}+ </div>++ {filtered.length === 0 ? (+ <div className="rounded-lg border bg-card py-10 text-center text-sm text-muted-foreground">+ No skills match this filter.+ </div>+ ) : (+ <ul className="divide-y rounded-lg border bg-card">+ {filtered.map((s) => (+ <SkillRow key={s.skillKey} skill={s} agentSlug={agentSlug} />+ ))}+ </ul>+ )}+ </div>+ );+}++function SkillRow({ skill, agentSlug }: { skill: SkillEntry; agentSlug: string }) {+ const [pending, startTransition] = useTransition();+ // Optimistic flag so the row reflects the toggle instantly while the server+ // round-trip + revalidation finishes.+ const [optimistic, setOptimistic] = useState<boolean | null>(null);+ const isEnabled = optimistic ?? !skill.disabled;++ function onToggle() {+ const next = !isEnabled;+ setOptimistic(next);+ startTransition(async () => {+ const r = await setSkillEnabledAction(skill.skillKey, next, agentSlug);+ if (!r.ok) {+ setOptimistic(!next); // revert+ toast.error(r.error ?? `Could not ${next ? "enable" : "disable"} ${skill.name}`);+ } else {+ toast.success(`${next ? "Enabled" : "Disabled"} ${skill.name}`);+ // Server revalidation will fold optimistic state back in on next render.+ }+ });+ }++ return (+ <li+ className={cn(+ "flex items-start gap-3 px-4 py-3 transition-opacity",+ !isEnabled && "opacity-70",+ )}+ >+ <div className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-base">+ {skill.emoji ?? "·"}+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2">+ <span className="font-mono text-sm">{skill.name}</span>+ {skill.bundled && (+ <Badge variant="outline" className="h-4 px-1 text-[9px] uppercase tracking-wide">+ bundled+ </Badge>+ )}+ {skill.always && (+ <Badge variant="secondary" className="h-4 px-1 text-[9px] uppercase tracking-wide">+ always-on+ </Badge>+ )}+ {isEnabled && !skill.eligible && (+ <Badge+ variant="outline"+ className="h-4 px-1 text-[9px] uppercase tracking-wide text-amber-600 dark:text-amber-400"+ title="Enabled in config, but a requirement is missing (binary, allowlist, agent filter)."+ >+ needs setup+ </Badge>+ )}+ </div>+ {skill.description && (+ <p className="mt-0.5 text-xs text-muted-foreground">{skill.description}</p>+ )}+ <p className="mt-1 truncate font-mono text-[10px] text-muted-foreground/70">+ {skill.source}+ </p>+ </div>++ <div className="shrink-0 self-center">+ <Button+ type="button"+ variant={isEnabled ? "outline" : "default"}+ size="sm"+ onClick={onToggle}+ disabled={pending || skill.always}+ title={skill.always ? "Always-on skill; cannot be disabled." : undefined}+ className="h-7 w-20 text-xs"+ >+ {pending ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : isEnabled ? (+ "Enabled"+ ) : (+ "Enable"+ )}+ </Button>+ </div>+ </li>+ );+}diff --git a/src/components/thread-selector.tsx b/src/components/thread-selector.tsxindex 45d11eda..55600ba0 100644--- a/src/components/thread-selector.tsx+++ b/src/components/thread-selector.tsx@@ -12,12 +12,11 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import { toast } from "sonner";-import { newSessionAction, switchSessionAction } from "@/server/actions/sessions";export type SessionLite = {sessionId: string;label: string;+ sessionKey: string;lastInteractionAt: number;pending: boolean;};@@ -48,27 +47,14 @@ export function ThreadSelector({ agentSlug, sessions, activeSessionId }: Props)const [pending, start] = useTransition();const active = sessions.find((s) => s.sessionId === activeSessionId);- function newThread() {- start(async () => {- const r = await newSessionAction(agentSlug);- if (!r.ok) {- toast.error(r.error);- return;- }- router.refresh();- });+ function go(sessionId: string) {+ if (sessionId === activeSessionId) return;+ start(() => router.push(`/agents/${agentSlug}/chat/${sessionId}`));}- function switchTo(sessionId: string) {- if (sessionId === activeSessionId) return;- start(async () => {- const r = await switchSessionAction(agentSlug, sessionId);- if (!r.ok) {- toast.error(r.error);- return;- }- router.refresh();- });+ function newThread() {+ const id = crypto.randomUUID();+ start(() => router.push(`/agents/${agentSlug}/chat/${id}`));}return (@@ -101,7 +87,7 @@ export function ThreadSelector({ agentSlug, sessions, activeSessionId }: Props)key={s.sessionId}onSelect={(e) => {e.preventDefault();- switchTo(s.sessionId);+ go(s.sessionId);}}className="flex items-center gap-2">diff --git a/src/lib/agent-colors.ts b/src/lib/agent-colors.tsindex 8a9db6da..87588b78 100644--- a/src/lib/agent-colors.ts+++ b/src/lib/agent-colors.ts@@ -32,17 +32,73 @@ const PALETTE: Record<AgentTemplateKey, AgentColor> = {},};-const FALLBACK: AgentColor = {- chip: "bg-zinc-100 text-zinc-900 dark:bg-zinc-900 dark:text-zinc-100 border-zinc-200/60 dark:border-zinc-800",- dot: "bg-zinc-500",- label: "text-zinc-700 dark:text-zinc-300",-};+/**+ * Extra palette used for custom or cloned agents (anything not in TEMPLATES).+ * Each entry is intentionally vivid — zinc/neutral would read as "disabled"+ * against the rest of the UI. Hue-hashing the slug below keeps the mapping+ * stable across renders without needing a DB.+ */+const EXTRA_PALETTE: AgentColor[] = [+ {+ chip: "bg-violet-100 text-violet-900 dark:bg-violet-950 dark:text-violet-100 border-violet-200/60 dark:border-violet-900",+ dot: "bg-violet-500",+ label: "text-violet-700 dark:text-violet-300",+ },+ {+ chip: "bg-rose-100 text-rose-900 dark:bg-rose-950 dark:text-rose-100 border-rose-200/60 dark:border-rose-900",+ dot: "bg-rose-500",+ label: "text-rose-700 dark:text-rose-300",+ },+ {+ chip: "bg-cyan-100 text-cyan-900 dark:bg-cyan-950 dark:text-cyan-100 border-cyan-200/60 dark:border-cyan-900",+ dot: "bg-cyan-500",+ label: "text-cyan-700 dark:text-cyan-300",+ },+ {+ chip: "bg-fuchsia-100 text-fuchsia-900 dark:bg-fuchsia-950 dark:text-fuchsia-100 border-fuchsia-200/60 dark:border-fuchsia-900",+ dot: "bg-fuchsia-500",+ label: "text-fuchsia-700 dark:text-fuchsia-300",+ },+ {+ chip: "bg-teal-100 text-teal-900 dark:bg-teal-950 dark:text-teal-100 border-teal-200/60 dark:border-teal-900",+ dot: "bg-teal-500",+ label: "text-teal-700 dark:text-teal-300",+ },+ {+ chip: "bg-orange-100 text-orange-900 dark:bg-orange-950 dark:text-orange-100 border-orange-200/60 dark:border-orange-900",+ dot: "bg-orange-500",+ label: "text-orange-700 dark:text-orange-300",+ },+ {+ chip: "bg-indigo-100 text-indigo-900 dark:bg-indigo-950 dark:text-indigo-100 border-indigo-200/60 dark:border-indigo-900",+ dot: "bg-indigo-500",+ label: "text-indigo-700 dark:text-indigo-300",+ },+ {+ chip: "bg-lime-100 text-lime-900 dark:bg-lime-950 dark:text-lime-100 border-lime-200/60 dark:border-lime-900",+ dot: "bg-lime-500",+ label: "text-lime-700 dark:text-lime-300",+ },+];++/** Fast deterministic hash (djb2) so a slug always maps to the same color. */+function hashSlug(slug: string): number {+ let h = 5381;+ for (let i = 0; i < slug.length; i++) {+ h = ((h << 5) + h + slug.charCodeAt(i)) | 0;+ }+ return Math.abs(h);+}/*** Resolve a color for an agent slug as it appears in our cron view.- * Accepts both URL slugs ("google-ads") and template keys ("google_ads").+ * Templates (cmo / google-ads / seo) get their reserved hue. Anything else+ * gets a stable color from the extras palette via slug hash — never the+ * zinc fallback, which reads as "disabled".*/export function colorForAgentSlug(slug: string): AgentColor {const normalized = slug.replace(/-/g, "_") as AgentTemplateKey;- return PALETTE[normalized] ?? FALLBACK;+ const fromTemplate = PALETTE[normalized];+ if (fromTemplate) return fromTemplate;+ return EXTRA_PALETTE[hashSlug(slug) % EXTRA_PALETTE.length]!;}diff --git a/src/server/actions/agents.ts b/src/server/actions/agents.tsnew file mode 100644index 00000000..2b32489a--- /dev/null+++ b/src/server/actions/agents.ts@@ -0,0 +1,563 @@+"use server";++import { existsSync } from "node:fs";+import { rm } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";+import { revalidatePath } from "next/cache";+import { getActiveProject } from "@/server/active-project";+import { disableCron, listCronsForProject, removeCron } from "@/server/openclaw/crons";+import {+ createAgentViaRpc,+ deleteAgent,+ listAllAgents,+} from "@/server/openclaw/gateway-rpc";+import {+ agentExistsInProject,+ cloneAgent,+ type CloneAgentResult,+} from "@/server/openclaw/clone-agent";+import {+ readAgentMeta,+ writeAgentMeta,+ workspaceDirFor,+ listProjectAgents,+ type AgentMeta,+ type ProjectAgentEntry,+} from "@/server/agent-meta";+import { listSessionsForAgent } from "@/server/openclaw/sessions";+import { slugify } from "@/lib/slug";+import type { AgentTemplate } from "@/server/agent-templates";++const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");++export type ActionResult<T = void> =+ | { ok: true; data: T }+ | { ok: false; error: string };++export type AgentChoice = {+ agent_id: string;+ display_name: string;+ in_current_project: boolean;+};++export async function listOpenClawAgentsAction(): Promise<ActionResult<AgentChoice[]>> {+ try {+ const project = await getActiveProject();+ const projectAgentIds = new Set<string>(+ project+ ? (await listProjectAgents(project.slug)).map((a) => a.agent_id)+ : [],+ );+ const list = await listAllAgents();+ const out: AgentChoice[] = list.agents.map((a) => ({+ agent_id: a.id,+ display_name: a.identity?.name?.trim() || a.name?.trim() || a.id,+ in_current_project: projectAgentIds.has(a.id),+ }));+ out.sort((a, b) => a.display_name.localeCompare(b.display_name));+ return { ok: true, data: out };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}++export async function listProjectAgentsAction(): Promise<ActionResult<ProjectAgentEntry[]>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };+ try {+ return { ok: true, data: await listProjectAgents(project.slug) };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}++export type CreateAgentInput = {+ display_name: string;+};++export async function createAgentAction(+ input: CreateAgentInput,+): Promise<ActionResult<{ agent_id: string; slug: string }>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };+ const slug = slugify(input.display_name);+ if (!slug.ok) return { ok: false, error: `Invalid name: ${slug.reason}` };++ if (agentExistsInProject(project.slug, slug.slug)) {+ return {+ ok: false,+ error: `An agent named "${slug.slug}" already exists in this project.`,+ };+ }++ const agentId = `${project.slug}-${slug.slug}`;+ const workspace = workspaceDirFor(agentId);+ try {+ await createAgentViaRpc({ name: agentId, workspace });+ await writeAgentMeta({+ agent_id: agentId,+ project_slug: project.slug,+ slug: slug.slug,+ display_name: input.display_name.trim(),+ created_at: new Date().toISOString(),+ });+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+ revalidatePath("/", "layout");+ return { ok: true, data: { agent_id: agentId, slug: slug.slug } };+}++export type CloneAgentActionInput = {+ source_agent_id: string;+ new_display_name: string;+ /** Optional override for the URL slug; defaults to slugified display name. */+ new_slug?: string;+};++export async function cloneAgentAction(+ input: CloneAgentActionInput,+): Promise<ActionResult<CloneAgentResult>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };++ const slugSource = (input.new_slug ?? input.new_display_name).trim();+ if (!slugSource) {+ return { ok: false, error: "Please provide a name for the cloned agent." };+ }+ try {+ const result = await cloneAgent({+ source_agent_id: input.source_agent_id,+ project_slug: project.slug,+ new_slug: slugSource,+ display_name: input.new_display_name,+ });+ revalidatePath("/", "layout");+ return { ok: true, data: result };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}++export async function disableCronsAction(+ cronIds: string[],+): Promise<ActionResult<{ disabled: number; failed: number }>> {+ let disabled = 0;+ let failed = 0;+ for (const id of cronIds) {+ try {+ await disableCron(id);+ disabled++;+ } catch {+ failed++;+ }+ }+ revalidatePath("/", "layout");+ return { ok: true, data: { disabled, failed } };+}++// --- Relocate (used by per-agent rename AND project rename) ---++export type RelocateAgentInput = {+ /** Current full agent_id (e.g. `acme-supa`). */+ old_agent_id: string;+ /** Source project slug — used for cron-cleanup lookup. */+ source_project_slug: string;+ /** Destination project slug — same as source for a rename within a project. */+ new_project_slug: string;+ /** Destination agent slug — same as source when only the project changes. */+ new_slug: string;+ /** Display name to write into the new agent's meta sidecar. */+ new_display_name: string;+ /**+ * Optional template_key to preserve on the new agent's meta sidecar (kept+ * during renames so the sidebar icon stays consistent for template-derived+ * agents).+ */+ preserve_template_key?: AgentTemplate["key"];+ /** Optional source_agent_id to preserve on the new meta (clone provenance). */+ preserve_source_agent_id?: string;+ /** Optional original created_at to keep the agent's age stable. */+ preserve_created_at?: string;+};++export type RelocateAgentResult = {+ new_agent_id: string;+ new_slug: string;+};++/**+ * Move an agent from one (project, slug) to another. Underneath: full clone+ * into the destination identifiers, overwrite meta with the preserved fields,+ * then cascade-delete the source. Shared by per-agent rename (same project,+ * new slug) and project rename (new project, same slug per agent).+ *+ * Throws on clone failure (source stays intact). If clone succeeds but the+ * source delete partially fails, the destination is still live and the caller+ * can surface a warning.+ */+export async function relocateAgent(+ input: RelocateAgentInput,+): Promise<RelocateAgentResult> {+ const cloneResult = await cloneAgent({+ source_agent_id: input.old_agent_id,+ project_slug: input.new_project_slug,+ new_slug: input.new_slug,+ display_name: input.new_display_name,+ // We're handing cloneAgent an already-canonical slug from existing meta,+ // not user input — skip the reserved-slug check so template slugs like+ // `cmo` survive a relocate.+ slug_is_canonical: true,+ });++ // Overwrite meta to drop the clone-provenance fields that cloneAgent set,+ // and preserve the caller-supplied identity (template_key, source, created).+ await writeAgentMeta({+ agent_id: cloneResult.new_agent_id,+ project_slug: input.new_project_slug,+ slug: cloneResult.new_slug,+ display_name: input.new_display_name,+ ...(input.preserve_template_key ? { template_key: input.preserve_template_key } : {}),+ ...(input.preserve_source_agent_id+ ? { source_agent_id: input.preserve_source_agent_id }+ : {}),+ created_at: input.preserve_created_at ?? new Date().toISOString(),+ });++ // Delete the source (its crons are looked up under its source project).+ // Best-effort — if it fails the new agent is still usable.+ await cascadeDeleteAgent({+ agent_id: input.old_agent_id,+ projectSlug: input.source_project_slug,+ }).catch(() => {});++ return {+ new_agent_id: cloneResult.new_agent_id,+ new_slug: cloneResult.new_slug,+ };+}++// --- Rename ---++export type RenameAgentInput = {+ /** Current agent_id (e.g. `e2e-test-brand-supa`). */+ agent_id: string;+ /** New display name; slugified to derive the new URL slug. */+ new_display_name: string;+};++export type RenameAgentData = {+ agent_id: string;+ slug: string;+ display_name: string;+ /** True when the slug actually changed (i.e. a full clone+delete ran). */+ full_rename: boolean;+};++/**+ * Rename an agent. OpenClaw treats the agent_id as immutable, so a "real"+ * rename — where the URL slug, cron names, workspace dir, and sessions dir all+ * pick up the new name — has to be done by self-cloning into a new agent_id+ * and deleting the old one.+ *+ * When the new display name slugifies to the same value as the current slug,+ * we short-circuit and just update our meta sidecar. Cheap, no data motion.+ */+export async function renameAgentAction(+ input: RenameAgentInput,+): Promise<ActionResult<RenameAgentData>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };++ const newName = input.new_display_name.trim();+ if (!newName) return { ok: false, error: "Name cannot be empty." };++ const newSlugResult = slugify(newName);+ if (!newSlugResult.ok) {+ return { ok: false, error: `Invalid name: ${newSlugResult.reason}` };+ }+ const newSlug = newSlugResult.slug;++ const existingMeta = readAgentMeta(input.agent_id);+ if (!existingMeta) {+ return { ok: false, error: `Agent '${input.agent_id}' has no meta on disk.` };+ }+ if (existingMeta.project_slug !== project.slug) {+ return { ok: false, error: "Agent belongs to a different project." };+ }++ // Display-name-only change → just rewrite the meta sidecar.+ if (newSlug === existingMeta.slug) {+ if (newName === existingMeta.display_name) {+ return {+ ok: true,+ data: {+ agent_id: input.agent_id,+ slug: existingMeta.slug,+ display_name: existingMeta.display_name,+ full_rename: false,+ },+ };+ }+ await writeAgentMeta({ ...existingMeta, display_name: newName });+ revalidatePath("/", "layout");+ return {+ ok: true,+ data: {+ agent_id: input.agent_id,+ slug: existingMeta.slug,+ display_name: newName,+ full_rename: false,+ },+ };+ }++ // Real rename — different slug. Refuse if the new slug is taken.+ if (agentExistsInProject(project.slug, newSlug)) {+ return {+ ok: false,+ error: `An agent named "${newSlug}" already exists in this project.`,+ };+ }++ let relocated: RelocateAgentResult;+ try {+ relocated = await relocateAgent({+ old_agent_id: input.agent_id,+ source_project_slug: project.slug,+ new_project_slug: project.slug,+ new_slug: newSlug,+ new_display_name: newName,+ preserve_template_key: existingMeta.template_key,+ preserve_created_at: existingMeta.created_at,+ // Renames intentionally drop the clone provenance — the new agent is+ // not a clone of the old one, it IS the old one with a new identity.+ });+ } catch (err) {+ return {+ ok: false,+ error: `Rename failed: ${err instanceof Error ? err.message : String(err)}`,+ };+ }++ revalidatePath("/", "layout");+ return {+ ok: true,+ data: {+ agent_id: relocated.new_agent_id,+ slug: relocated.new_slug,+ display_name: newName,+ full_rename: true,+ },+ };+}++// --- Per-agent deletion ---++export type AgentDeletionSummary = {+ agent_id: string;+ display_name: string;+ exists_in_openclaw: boolean;+ threads: Array<{ session_id: string; label: string; last_interaction_at: number }>;+ crons: Array<{ id: string; name: string; disabled: boolean }>;+ source_agent_id?: string;+ template_key?: string;+};++export async function getAgentDeletionSummaryAction(+ agent_id: string,+): Promise<ActionResult<AgentDeletionSummary>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };++ const meta: AgentMeta | null = readAgentMeta(agent_id);+ const agentDir = join(OPENCLAW_HOME, "agents", agent_id);+ const existsInOpenclaw = existsSync(agentDir);+ const sessions = existsInOpenclaw ? listSessionsForAgent(agent_id) : [];+ const threads = sessions.map((s) => ({+ session_id: s.sessionId,+ label: s.label,+ last_interaction_at: s.lastInteractionAt,+ }));++ const crons: Array<{ id: string; name: string; disabled: boolean }> = [];+ try {+ const view = await listCronsForProject(project.slug);+ for (const g of view.groups) {+ for (const c of g.crons) {+ if (c.agent_id !== agent_id) continue;+ crons.push({ id: c.id, name: c.short_name || c.name, disabled: c.disabled });+ }+ }+ } catch {+ // Best-effort; cron service unreachable means we just show an empty list.+ }++ return {+ ok: true,+ data: {+ agent_id,+ display_name: meta?.display_name ?? agent_id,+ exists_in_openclaw: existsInOpenclaw,+ threads,+ crons,+ source_agent_id: meta?.source_agent_id,+ template_key: meta?.template_key,+ },+ };+}++export type DeleteAgentData = {+ agent_id: string;+ crons_removed: number;+ crons_failed: number;+ openclaw_deleted: boolean;+ meta_removed: boolean;+};++/**+ * Cascading agent deletion: removes the agent's crons, calls OpenClaw's+ * `agents.delete` RPC (with deleteFiles:true so workspace + sessions go too),+ * and cleans up the empty parent dirs OpenClaw and our meta sidecar leave+ * behind. Shared by per-agent delete (settings danger zone) and project-wide+ * delete so the cleanup logic stays in one place.+ *+ * Pure helper — does NOT revalidate, redirect, or touch cookies. Callers add+ * their own surrounding concerns (per-agent action revalidates the layout,+ * project delete clears the active-project cookie + db rows).+ *+ * Pass `cronsByAgentId` to skip the cron lookup when the caller already has+ * it (project-wide delete grabs every project cron once up front).+ */+export type CascadeAgentDeleteOutcome = {+ agent_id: string;+ crons_removed: number;+ crons_failed: number;+ openclaw_deleted: boolean;+ meta_removed: boolean;+};++export async function cascadeDeleteAgent(opts: {+ agent_id: string;+ /**+ * Optional: caller-supplied list of cron IDs to remove for this agent.+ * When omitted, we look them up via the project's cron list.+ */+ projectSlug?: string;+ cronIds?: string[];+}): Promise<CascadeAgentDeleteOutcome> {+ const { agent_id } = opts;++ // 1) Remove agent's crons first — once the agent is gone OpenClaw may reject+ // removeCron for orphans.+ let cronsRemoved = 0;+ let cronsFailed = 0;+ let cronIds = opts.cronIds;+ if (!cronIds && opts.projectSlug) {+ try {+ const view = await listCronsForProject(opts.projectSlug);+ cronIds = view.groups+ .flatMap((g) => g.crons)+ .filter((c) => c.agent_id === agent_id)+ .map((c) => c.id);+ } catch {+ cronIds = [];+ }+ }+ for (const id of cronIds ?? []) {+ try {+ await removeCron(id);+ cronsRemoved++;+ } catch {+ cronsFailed++;+ }+ }++ // 2) Delete the OpenClaw agent.+ let openclawDeleted = false;+ try {+ await deleteAgent(agent_id);+ openclawDeleted = true;+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ if (msg.includes("unknown agent") || msg.includes("not found")) {+ openclawDeleted = true; // already gone — treat as success+ } else {+ // Rethrow so callers can decide whether to abort.+ throw err;+ }+ }++ // 3) Remove our meta sidecar + workspace dir.+ let metaRemoved = false;+ try {+ const wsDir = workspaceDirFor(agent_id);+ if (existsSync(wsDir)) {+ await rm(wsDir, { recursive: true, force: true });+ metaRemoved = true;+ }+ } catch {+ // Non-fatal; agent stays shadow-visible until the sidecar disappears.+ }++ // 4) OpenClaw's deleteFiles:true trashes the dir contents but leaves the+ // now-empty `~/.openclaw/agents/<id>/` parent behind. Remove it so the+ // slug becomes free to reuse immediately (otherwise next rename/clone+ // rejects with "already exists").+ try {+ const openclawAgentDir = join(OPENCLAW_HOME, "agents", agent_id);+ if (existsSync(openclawAgentDir)) {+ await rm(openclawAgentDir, { recursive: true, force: true });+ }+ } catch {+ // Best-effort — trashed contents already represent a successful delete.+ }++ return {+ agent_id,+ crons_removed: cronsRemoved,+ crons_failed: cronsFailed,+ openclaw_deleted: openclawDeleted,+ meta_removed: metaRemoved,+ };+}++export async function deleteAgentCascadeAction(+ agent_id: string,+): Promise<ActionResult<DeleteAgentData>> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };++ let outcome: CascadeAgentDeleteOutcome;+ try {+ outcome = await cascadeDeleteAgent({+ agent_id,+ projectSlug: project.slug,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ return { ok: false, error: `OpenClaw refused to delete agent: ${msg}` };+ }++ revalidatePath("/", "layout");+ return { ok: true, data: outcome };+}++/** Used by the clone-result confirmation if the user opts to delete instead. */+export async function removeCronsAction(+ cronIds: string[],+): Promise<ActionResult<{ removed: number; failed: number }>> {+ let removed = 0;+ let failed = 0;+ for (const id of cronIds) {+ try {+ await removeCron(id);+ removed++;+ } catch {+ failed++;+ }+ }+ revalidatePath("/", "layout");+ return { ok: true, data: { removed, failed } };+}diff --git a/src/server/actions/cron-runs.ts b/src/server/actions/cron-runs.tsnew file mode 100644index 00000000..7c1c4b21--- /dev/null+++ b/src/server/actions/cron-runs.ts@@ -0,0 +1,41 @@+"use server";++import { loadCronRuns, type CronRun } from "@/server/openclaw/crons";+import { tickAtOrBefore } from "@/server/openclaw/cron-schedule";++export type CronRunWithTick = CronRun & {+ /**+ * The scheduled tick (ms epoch) this run belongs to. Computed by walking the+ * cron schedule backwards from `runAtMs` and taking the most recent tick at+ * or before it. Lets the UI match a run to the calendar occurrence the user+ * clicked, regardless of how late the scheduler fired.+ */+ owning_occurrence_at_ms?: number;+};++export type ScheduleInput =+ | { kind: "cron"; expr: string; tz?: string }+ | { kind: "every"; everyMs: number; anchorMs?: number };++export type GetCronRunsResult =+ | { ok: true; runs: CronRunWithTick[] }+ | { ok: false; error: string };++export async function getCronRunsAction(+ cron_id: string,+ schedule: ScheduleInput | null,+ limit = 100,+): Promise<GetCronRunsResult> {+ try {+ const raw = loadCronRuns(cron_id, limit);+ const enriched: CronRunWithTick[] = raw.map((r) => ({+ ...r,+ owning_occurrence_at_ms: schedule+ ? tickAtOrBefore(schedule, r.run_at_ms)+ : undefined,+ }));+ return { ok: true, runs: enriched };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}diff --git a/src/server/actions/crons.ts b/src/server/actions/crons.tsindex 144e1b15..789e562f 100644--- a/src/server/actions/crons.ts+++ b/src/server/actions/crons.ts@@ -1,7 +1,14 @@"use server";import { revalidatePath } from "next/cache";-import { createCron, disableCron, enableCron, removeCron } from "@/server/openclaw/crons";+import {+ createCron,+ disableCron,+ enableCron,+ invalidateCronCache,+ removeCron,+} from "@/server/openclaw/crons";+import { updateCronMessage } from "@/server/openclaw/gateway-rpc";import { agentNameFor, type AgentTemplate } from "@/server/agent-templates";import { slugify } from "@/lib/slug";import { logAgentAction } from "@/server/db/agent-actions";@@ -89,3 +96,19 @@ export async function deleteCronAction(id: string): Promise<{ ok: boolean; errorreturn { ok: false, error: err instanceof Error ? err.message : String(err) };}}++export async function updateCronPromptAction(+ id: string,+ message: string,+): Promise<{ ok: boolean; error?: string }> {+ const trimmed = message.trim();+ if (!trimmed) return { ok: false, error: "Prompt cannot be empty." };+ try {+ await updateCronMessage(id, trimmed);+ invalidateCronCache();+ revalidatePath("/", "layout");+ return { ok: true };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}diff --git a/src/server/actions/projects.ts b/src/server/actions/projects.tsindex 72c0a603..50a219b2 100644--- a/src/server/actions/projects.ts+++ b/src/server/actions/projects.ts@@ -2,11 +2,29 @@import { revalidatePath } from "next/cache";import { redirect } from "next/navigation";-import { archiveProject, createProject, renameProject } from "@/server/db/projects";-import { setActiveProject } from "@/server/active-project";+import { cookies } from "next/headers";+import {+ archiveProject,+ changeProjectSlug,+ createProject,+ deleteProjectRow,+ getProject,+ renameProject,+} from "@/server/db/projects";+import { slugify } from "@/lib/slug";+import {+ clearActiveProject,+ setActiveProject,+} from "@/server/active-project";import { ensureProjectAgents } from "@/server/agent-templates";+import { listProjectAgents, readAgentMeta } from "@/server/agent-meta";+import { cascadeDeleteAgent, relocateAgent } from "@/server/actions/agents";import { listCronsForProject, disableCron } from "@/server/openclaw/crons";import { logAgentAction } from "@/server/db/agent-actions";+import {+ getProjectDeletionSummary,+ type ProjectDeletionSummary,+} from "@/server/openclaw/project-delete";export type ActionResult<T = void> =| { ok: true; data: T }@@ -102,3 +120,236 @@ export async function renameProjectAction(slug: string, display_name: string): PrevalidatePath("/", "layout");return { ok: true, data: undefined };}++export type RenameProjectFullInput = {+ current_slug: string;+ new_display_name: string;+};++export type RenameProjectFullData = {+ slug: string;+ display_name: string;+ /** True when the slug actually changed (a full cascade ran). */+ full_rename: boolean;+ /** Per-agent outcomes for the rename pass. */+ agents_relocated: string[];+ agents_failed: Array<{ agent_id: string; error: string }>;+};++/**+ * Rename a project — display name and (when the slugified name differs) URL+ * slug too. Display-name-only changes hit just the DB. Slug changes cascade:+ * relocate every agent in the project to the new slug (re-uses+ * `relocateAgent`, which itself is the shared helper that powers per-agent+ * rename), then migrate every DB row keyed off project_slug.+ *+ * After a full rename: agent_ids change from `<old>-<slug>` to `<new>-<slug>`,+ * cron names rewrite via clone, workspace dirs move, session JSONL files+ * relocate, and the active-project cookie repoints at the new slug.+ */+export async function renameProjectFullAction(+ input: RenameProjectFullInput,+): Promise<ActionResult<RenameProjectFullData>> {+ const current = getProject(input.current_slug);+ if (!current) return { ok: false, error: `Project '${input.current_slug}' not found.` };++ const newName = input.new_display_name.trim();+ if (!newName) return { ok: false, error: "Name cannot be empty." };++ const newSlugResult = slugify(newName);+ if (!newSlugResult.ok) {+ return { ok: false, error: `Invalid name: ${newSlugResult.reason}` };+ }+ const newSlug = newSlugResult.slug;+ const sameSlug = newSlug === current.slug;++ // Display-name-only change — cheap path.+ if (sameSlug) {+ if (newName === current.display_name) {+ return {+ ok: true,+ data: {+ slug: current.slug,+ display_name: current.display_name,+ full_rename: false,+ agents_relocated: [],+ agents_failed: [],+ },+ };+ }+ renameProject(current.slug, newName);+ revalidatePath("/", "layout");+ return {+ ok: true,+ data: {+ slug: current.slug,+ display_name: newName,+ full_rename: false,+ agents_relocated: [],+ agents_failed: [],+ },+ };+ }++ if (getProject(newSlug)) {+ return { ok: false, error: `A project with slug '${newSlug}' already exists.` };+ }++ // 1) Relocate every agent into the new project slug (keeping each agent's+ // own slug + display name + clone provenance intact).+ const agents = await listProjectAgents(current.slug);+ const agentsRelocated: string[] = [];+ const agentsFailed: Array<{ agent_id: string; error: string }> = [];+ for (const a of agents) {+ try {+ const meta = readAgentMeta(a.agent_id);+ await relocateAgent({+ old_agent_id: a.agent_id,+ source_project_slug: current.slug,+ new_project_slug: newSlug,+ new_slug: a.slug,+ new_display_name: a.display_name,+ preserve_template_key: a.template_key,+ preserve_source_agent_id: meta?.source_agent_id,+ preserve_created_at: meta?.created_at,+ });+ agentsRelocated.push(a.agent_id);+ } catch (err) {+ agentsFailed.push({+ agent_id: a.agent_id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ // 2) Migrate DB rows. If a child-table update fails the rename is partial;+ // surface a clear error but leave the moved agents in place (they're+ // addressable under the new slug already).+ try {+ changeProjectSlug(current.slug, newSlug, newName);+ } catch (err) {+ return {+ ok: false,+ error: `DB migration failed after agent move: ${+ err instanceof Error ? err.message : String(err)+ }. Agents already moved; cleanup needed.`,+ };+ }++ // 3) Repoint the active-project cookie if it was this one.+ const c = await cookies();+ if (c.get("notfair_active_project")?.value === current.slug) {+ await setActiveProject(newSlug);+ }++ revalidatePath("/", "layout");++ return {+ ok: true,+ data: {+ slug: newSlug,+ display_name: newName,+ full_rename: true,+ agents_relocated: agentsRelocated,+ agents_failed: agentsFailed,+ },+ };+}++export async function getProjectDeletionSummaryAction(+ slug: string,+): Promise<ActionResult<ProjectDeletionSummary>> {+ const project = getProject(slug);+ if (!project) return { ok: false, error: `Project '${slug}' not found.` };+ try {+ const summary = await getProjectDeletionSummary(slug);+ return { ok: true, data: summary };+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+}++export type DeleteProjectData = {+ agents: string[];+ agentsFailed: Array<{ agentId: string; error: string }>;+ crons: number;+ cronsFailed: number;+};++export async function deleteProjectAction(+ slug: string,+ confirmedSlug: string,+): Promise<ActionResult<DeleteProjectData>> {+ if (slug !== confirmedSlug) {+ return { ok: false, error: "Confirmation slug does not match." };+ }+ const project = getProject(slug);+ if (!project) return { ok: false, error: `Project '${slug}' not found.` };++ const deletedAgents: string[] = [];+ const agentsFailed: Array<{ agentId: string; error: string }> = [];++ // 1) Look up project crons once so we can hand each agent its own slice+ // (avoids N redundant lookups inside the shared helper).+ let cronsByAgent = new Map<string, string[]>();+ try {+ const cronView = await listCronsForProject(slug);+ for (const group of cronView.groups) {+ for (const cron of group.crons) {+ const arr = cronsByAgent.get(cron.agent_id) ?? [];+ arr.push(cron.id);+ cronsByAgent.set(cron.agent_id, arr);+ }+ }+ } catch {+ // Cron service unavailable; continue — cascadeDeleteAgent will skip cron+ // cleanup when given an empty list.+ }++ // 2) Agents — single source of truth lives in cascadeDeleteAgent. Iterates+ // every agent the project actually has (templates + cloned/custom).+ const projectAgentEntries = await listProjectAgents(slug);+ let cronsDeleted = 0;+ let cronsFailed = 0;+ for (const entry of projectAgentEntries) {+ try {+ const outcome = await cascadeDeleteAgent({+ agent_id: entry.agent_id,+ cronIds: cronsByAgent.get(entry.agent_id) ?? [],+ });+ deletedAgents.push(entry.agent_id);+ cronsDeleted += outcome.crons_removed;+ cronsFailed += outcome.crons_failed;+ } catch (err) {+ agentsFailed.push({+ agentId: entry.agent_id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }++ // 3) Local DB rows.+ deleteProjectRow(slug);++ // 4) Clear active-project cookie if it pointed at this one.+ const c = await cookies();+ if (c.get("notfair_active_project")?.value === slug) {+ await clearActiveProject();+ }++ // No logAgentAction here — agent_actions has a FK to projects.slug, and+ // deleteProjectRow already purges rows for this slug, so any log entry+ // would either FK-fail or be wiped on the spot.++ revalidatePath("/", "layout");++ return {+ ok: true,+ data: {+ agents: deletedAgents,+ agentsFailed,+ crons: cronsDeleted,+ cronsFailed,+ },+ };+}diff --git a/src/server/actions/sessions.ts b/src/server/actions/sessions.tsdeleted file mode 100644index 6be66109..00000000--- a/src/server/actions/sessions.ts+++ /dev/null@@ -1,38 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import { getActiveProject } from "@/server/active-project";-import { templateForUrlSlug } from "@/server/agent-templates";-import { newSessionId, setActiveSession } from "@/server/openclaw/sessions";--type Result<T> = { ok: true; data: T } | { ok: false; error: string };--/**- * "New thread" = mint a UUID, set it as active. OpenClaw creates the actual- * session entry on the first agent turn under that UUID. We do not persist- * anything ourselves.- */-export async function newSessionAction(agentSlug: string): Promise<Result<{ sessionId: string }>> {- const project = await getActiveProject();- if (!project) return { ok: false, error: "No active project." };- const template = templateForUrlSlug(agentSlug);- if (!template) return { ok: false, error: `Unknown agent: ${agentSlug}` };-- const sessionId = newSessionId();- await setActiveSession(project.slug, template.key, sessionId);- revalidatePath(`/chat/${agentSlug}`);- return { ok: true, data: { sessionId } };-}--export async function switchSessionAction(- agentSlug: string,- sessionId: string,-): Promise<Result<{ sessionId: string }>> {- const project = await getActiveProject();- if (!project) return { ok: false, error: "No active project." };- const template = templateForUrlSlug(agentSlug);- if (!template) return { ok: false, error: `Unknown agent: ${agentSlug}` };- await setActiveSession(project.slug, template.key, sessionId);- revalidatePath(`/chat/${agentSlug}`);- return { ok: true, data: { sessionId } };-}diff --git a/src/server/actions/skills.ts b/src/server/actions/skills.tsnew file mode 100644index 00000000..81139c4b--- /dev/null+++ b/src/server/actions/skills.ts@@ -0,0 +1,24 @@+"use server";++import { revalidatePath } from "next/cache";+import { setSkillEnabled } from "@/server/openclaw/gateway-rpc";++export type SetSkillEnabledResult = { ok: true } | { ok: false; error: string };++export async function setSkillEnabledAction(+ skillKey: string,+ enabled: boolean,+ agentSlug: string,+): Promise<SetSkillEnabledResult> {+ if (!skillKey) return { ok: false, error: "skillKey is required" };+ try {+ await setSkillEnabled(skillKey, enabled);+ } catch (err) {+ return { ok: false, error: err instanceof Error ? err.message : String(err) };+ }+ // Skills config is workspace-wide, so any agent's skills tab needs to refresh.+ // Cheapest correct invalidation: revalidate the caller's page; user can refresh+ // other tabs themselves on the rare cross-agent reconfig.+ revalidatePath(`/agents/${agentSlug}/skills`);+ return { ok: true };+}diff --git a/src/server/agent-meta.ts b/src/server/agent-meta.tsnew file mode 100644index 00000000..1c575c03--- /dev/null+++ b/src/server/agent-meta.ts@@ -0,0 +1,157 @@+import { existsSync, readFileSync } from "node:fs";+import { mkdir, writeFile, readdir } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";+import {+ TEMPLATES,+ agentNameFor,+ urlSlugForTemplate,+ type AgentTemplateKey,+} from "./agent-templates";++/**+ * Per-agent meta we own (notfair-cmo) and store next to the agent's workspace+ * directory. OpenClaw doesn't have a place for our UI-facing display name ++ * project linkage, so this sidecar fills the gap without requiring a DB+ * migration. Authored at agent creation/clone time, read by the sidebar.+ */++export type AgentMeta = {+ /** Full OpenClaw agentId, e.g. `acme-cmo` or `acme-supa-clone`. */+ agent_id: string;+ /** Project slug this agent belongs to. */+ project_slug: string;+ /** URL-friendly slug (post-project prefix), e.g. `cmo`, `supa-clone`. */+ slug: string;+ /** Display name shown in sidebar / chat headers. */+ display_name: string;+ /** If from one of our bootstrap templates, which one. */+ template_key?: AgentTemplateKey;+ /** When cloned, the source agentId. */+ source_agent_id?: string;+ created_at: string;+};++function notfairDataDir(): string {+ return process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");+}++function metaPath(agentId: string): string {+ return join(notfairDataDir(), "agents", agentId, "notfair-meta.json");+}++export async function writeAgentMeta(meta: AgentMeta): Promise<void> {+ const path = metaPath(meta.agent_id);+ await mkdir(join(path, ".."), { recursive: true });+ await writeFile(path, JSON.stringify(meta, null, 2), "utf8");+}++export function readAgentMeta(agentId: string): AgentMeta | null {+ const path = metaPath(agentId);+ if (!existsSync(path)) return null;+ try {+ return JSON.parse(readFileSync(path, "utf8")) as AgentMeta;+ } catch {+ return null;+ }+}++export type ProjectAgentEntry = {+ agent_id: string;+ slug: string;+ display_name: string;+ description?: string;+ template_key?: AgentTemplateKey;+ source_agent_id?: string;+ is_template_default: boolean;+};++/**+ * List agents for a project. Source of truth:+ * - notfair-meta.json sidecars under `<DATA_DIR>/agents/<projectSlug>-*`.+ * - For each TEMPLATE not yet present on disk, fall back to a synthesized+ * default entry so the user sees the bootstrap agents immediately even+ * before `ensureProjectAgents` runs.+ */+export async function listProjectAgents(project_slug: string): Promise<ProjectAgentEntry[]> {+ const result = new Map<string, ProjectAgentEntry>();++ // 1) Seed with templates (they may or may not exist on disk yet).+ for (const t of TEMPLATES) {+ const agentId = agentNameFor(project_slug, t.key);+ result.set(agentId, {+ agent_id: agentId,+ slug: urlSlugForTemplate(t.key),+ display_name: t.display_name,+ description: t.description,+ template_key: t.key,+ is_template_default: true,+ });+ }++ // 2) Overlay anything we have meta for (template agents written by+ // ensureProjectAgents, plus cloned/custom agents).+ const agentsRoot = join(notfairDataDir(), "agents");+ let entries: string[] = [];+ try {+ entries = await readdir(agentsRoot);+ } catch {+ // No agents dir yet — keep templates-only view.+ return Array.from(result.values());+ }+ const prefix = `${project_slug}-`;+ for (const entry of entries) {+ if (!entry.startsWith(prefix)) continue;+ const meta = readAgentMeta(entry);+ if (!meta) continue;+ result.set(meta.agent_id, {+ agent_id: meta.agent_id,+ slug: meta.slug,+ display_name: meta.display_name,+ template_key: meta.template_key,+ source_agent_id: meta.source_agent_id,+ is_template_default: false,+ });+ }++ // Stable order: templates first (in declared order), then custom by slug.+ const templateOrder = new Map(TEMPLATES.map((t, i) => [t.key, i]));+ return Array.from(result.values()).sort((a, b) => {+ const ai = a.template_key ? templateOrder.get(a.template_key) ?? 99 : 99;+ const bi = b.template_key ? templateOrder.get(b.template_key) ?? 99 : 99;+ if (ai !== bi) return ai - bi;+ return a.slug.localeCompare(b.slug);+ });+}++/** Workspace dir we hand to OpenClaw at creation time. */+export function workspaceDirFor(agentId: string): string {+ return join(notfairDataDir(), "agents", agentId);+}++export type ResolvedAgent = {+ agent_id: string;+ display_name: string;+ slug: string;+ template_key?: AgentTemplateKey;+};++/**+ * Resolve a URL slug to its full agent_id within the current project. Looks+ * up templates first, then any cloned/custom agents via the meta sidecar.+ * Returns null when no project agent matches the slug.+ */+export async function resolveAgentBySlug(+ project_slug: string,+ url_slug: string,+): Promise<ResolvedAgent | null> {+ const all = await listProjectAgents(project_slug);+ const hit = all.find((a) => a.slug === url_slug);+ if (!hit) return null;+ return {+ agent_id: hit.agent_id,+ display_name: hit.display_name,+ slug: hit.slug,+ template_key: hit.template_key,+ };+}diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.tsindex 63835097..51f3265f 100644--- a/src/server/agent-templates.ts+++ b/src/server/agent-templates.ts@@ -2,6 +2,7 @@ import { mkdir, writeFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";import { openclaw } from "@/server/openclaw/cli";+import { writeAgentMeta } from "@/server/agent-meta";/*** Embedded in every agent's system prompt so the agent knows how to create@@ -195,6 +196,16 @@ export async function ensureProjectAgents(project_slug: string): Promise<{// Idempotently refresh the IDENTITY.md so prompt edits propagate to// existing agents without forcing the user to delete + recreate.await writeIdentityFile(workspaceAbs, template);+ // Backfill the notfair meta sidecar in case this agent was created+ // before we started writing it (so the sidebar still finds them).+ await writeAgentMeta({+ agent_id: name,+ project_slug,+ slug: urlSlugForTemplate(template.key),+ display_name: template.display_name,+ template_key: template.key,+ created_at: new Date().toISOString(),+ });existed.push(name);continue;}@@ -215,6 +226,14 @@ export async function ensureProjectAgents(project_slug: string): Promise<{workspaceAbs,]);await writeIdentityFile(workspaceAbs, template);+ await writeAgentMeta({+ agent_id: name,+ project_slug,+ slug: urlSlugForTemplate(template.key),+ display_name: template.display_name,+ template_key: template.key,+ created_at: new Date().toISOString(),+ });created.push(name);} catch (err) {// Surface but don't crash the loop; partial provisioning recoverable on retry.diff --git a/src/server/db/projects.ts b/src/server/db/projects.tsindex bc0de9e0..a1d10d2a 100644--- a/src/server/db/projects.ts+++ b/src/server/db/projects.ts@@ -58,6 +58,85 @@ export function renameProject(slug: string, display_name: string): Project | nulreturn getProject(slug);}+/**+ * Migrate every DB row keyed off `project_slug` from `old` to `new`. Wraps+ * the updates in a transaction with `defer_foreign_keys=ON` so the+ * referential checks happen at COMMIT instead of per-row — required because+ * our FKs reference `projects(slug)` without `ON UPDATE CASCADE`.+ *+ * Returns the renamed project, or null when the old slug doesn't exist.+ */+export function changeProjectSlug(+ old_slug: string,+ new_slug: string,+ new_display_name?: string,+): Project | null {+ const db = getDb();+ if (old_slug === new_slug) {+ if (new_display_name) {+ db.prepare("UPDATE projects SET display_name = ? WHERE slug = ?").run(+ new_display_name.trim(),+ old_slug,+ );+ }+ return getProject(old_slug);+ }+ // Bail if the source doesn't exist or the destination already exists.+ if (!db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(old_slug)) {+ return null;+ }+ if (db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(new_slug)) {+ throw new Error(`Project slug '${new_slug}' already exists`);+ }++ const childTables = [+ "tasks",+ "approvals",+ "cost_events",+ "oauth_tokens",+ "guardrails",+ "agent_actions",+ "sequence_runs",+ ];++ // Disable FK enforcement for the duration of the rename. Our FKs reference+ // `projects(slug)` without ON UPDATE CASCADE, so updating the PK while+ // child rows still point at the old value would violate. `defer_foreign_keys`+ // inside a wrapped transaction doesn't take effect reliably across SQLite+ // releases; toggling `foreign_keys` is universally supported and works the+ // same way every popular SQLite migration tool uses.+ const fkWasOn = db.pragma("foreign_keys = OFF", { simple: true });+ try {+ const tx = db.transaction(() => {+ for (const table of childTables) {+ try {+ db.prepare(`UPDATE ${table} SET project_slug = ? WHERE project_slug = ?`).run(+ new_slug,+ old_slug,+ );+ } catch {+ // table missing on this install; skip.+ }+ }+ if (new_display_name) {+ db.prepare("UPDATE projects SET slug = ?, display_name = ? WHERE slug = ?").run(+ new_slug,+ new_display_name.trim(),+ old_slug,+ );+ } else {+ db.prepare("UPDATE projects SET slug = ? WHERE slug = ?").run(new_slug, old_slug);+ }+ });+ tx();+ } finally {+ // Restore prior FK state (1 if it was on, 0 if it was already off).+ db.pragma(`foreign_keys = ${fkWasOn === 0 ? "OFF" : "ON"}`);+ }++ return getProject(new_slug);+}+export function archiveProject(slug: string): Project | null {const db = getDb();const now = new Date().toISOString();@@ -70,3 +149,27 @@ export function unarchiveProject(slug: string): Project | null {db.prepare("UPDATE projects SET archived_at = NULL WHERE slug = ?").run(slug);return getProject(slug);}++/**+ * Hard-delete a project row plus any rows in tables that key off project_slug+ * (guardrails, approvals, agent_actions, etc.). OpenClaw-side state — agents,+ * sessions, crons — is cleaned up by the deleteProject orchestrator, not here.+ */+export function deleteProjectRow(slug: string): void {+ const db = getDb();+ const childTables = [+ "guardrails",+ "approvals",+ "agent_actions",+ "cost_snapshots",+ "connections",+ ];+ for (const table of childTables) {+ try {+ db.prepare(`DELETE FROM ${table} WHERE project_slug = ?`).run(slug);+ } catch {+ // table missing on this install; skip.+ }+ }+ db.prepare("DELETE FROM projects WHERE slug = ?").run(slug);+}diff --git a/src/server/openclaw/clone-agent.ts b/src/server/openclaw/clone-agent.tsnew file mode 100644index 00000000..63626f5d--- /dev/null+++ b/src/server/openclaw/clone-agent.ts@@ -0,0 +1,306 @@+import { cp, mkdir, readFile, writeFile } from "node:fs/promises";+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { slugify } from "@/lib/slug";+import { workspaceDirFor, writeAgentMeta } from "@/server/agent-meta";++const NOTFAIR_DATA_DIR =+ process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");+import { openclaw } from "@/server/openclaw/cli";+import {+ createAgentViaRpc,+ getAgentFile,+ listAgentFiles,+} from "@/server/openclaw/gateway-rpc";++const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");+const NAME_SEPARATOR = "/";++export type CloneAgentInput = {+ source_agent_id: string;+ project_slug: string;+ /** URL-safe slug for the new agent (post-project prefix). Required. */+ new_slug: string;+ /** Display name shown in sidebar etc. Defaults to source agent id if unset. */+ display_name?: string;+ /**+ * When true, treat `new_slug` as already-canonical: skip the user-input+ * reserved-slug check (so internal callers can reuse template slugs like+ * `cmo` during a relocate without slugify rejecting them).+ */+ slug_is_canonical?: boolean;+};++export type CloneSourceCron = {+ id: string;+ /** The cron's original name, kept so the UI can show the user what they're disabling. */+ name: string;+ disabled: boolean;+};++export type CloneAgentResult = {+ new_agent_id: string;+ new_slug: string;+ files_copied: number;+ sessions_copied: number;+ source_crons: CloneSourceCron[];+ new_cron_ids: string[];+};++/**+ * Clone an existing OpenClaw agent into the active project.+ *+ * Steps (in order; each is idempotent enough to retry after a partial failure):+ * 1. Validate inputs + compute target ids.+ * 2. Create the destination agent via `agents.create` RPC.+ * 3. Copy workspace files (read via agents.files.get, write via agents.files.set).+ * 4. Filesystem-copy ~/.openclaw/agents/<src>/sessions → ~/.openclaw/agents/<dst>/sessions+ * and rewrite sessions.json keys to point at the new agent name.+ * 5. List source crons, recreate each targeting the new agent with our+ * `<project> / <slug> / <cron>` naming convention.+ * 6. Write our notfair-meta sidecar so the sidebar finds it.+ */+export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResult> {+ let newSlug: string;+ if (input.slug_is_canonical) {+ // Internal caller (e.g. relocateAgent) has a slug that already passed+ // user-facing validation at creation time. Re-running slugify would+ // reject reserved slugs like `cmo` that are valid template slugs.+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.new_slug)) {+ throw new Error(`Invalid canonical slug: ${input.new_slug}`);+ }+ newSlug = input.new_slug;+ } else {+ const slugResult = slugify(input.new_slug);+ if (!slugResult.ok) {+ throw new Error(`Invalid agent slug: ${slugResult.reason}`);+ }+ newSlug = slugResult.slug;+ }+ const newAgentId = `${input.project_slug}-${newSlug}`;+ if (agentExistsInProject(input.project_slug, newSlug)) {+ throw new Error(+ `An agent named "${newSlug}" already exists in this project. Pick a different name.`,+ );+ }+ const dstWorkspace = workspaceDirFor(newAgentId);+ const displayName = (input.display_name ?? input.source_agent_id).trim() || input.source_agent_id;++ // 2) Create the destination agent.+ await createAgentViaRpc({ name: newAgentId, workspace: dstWorkspace });++ // 3) Copy workspace files.+ let filesCopied = 0;+ try {+ const list = await listAgentFiles(input.source_agent_id);+ for (const f of list.files) {+ if (f.missing) continue;+ try {+ const got = await getAgentFile(input.source_agent_id, f.name);+ // Use the gateway's setter so OpenClaw's safety/symlink checks run.+ await callAgentsFilesSet(newAgentId, f.name, got.file.content);+ filesCopied++;+ } catch (err) {+ console.error(`clone: skipping file ${f.name}:`, err);+ }+ }+ } catch (err) {+ console.error("clone: could not list source workspace files:", err);+ }++ // 4) Copy sessions (filesystem) + rewrite sessions.json keys.+ const srcSessionsDir = join(OPENCLAW_HOME, "agents", input.source_agent_id, "sessions");+ const dstSessionsDir = join(OPENCLAW_HOME, "agents", newAgentId, "sessions");+ let sessionsCopied = 0;+ if (existsSync(srcSessionsDir)) {+ await mkdir(dstSessionsDir, { recursive: true });+ // Copy everything (jsonl, .trajectory*, sessions.json, .bak files). `force:true`+ // overwrites anything OpenClaw auto-created at agents.create time.+ await cp(srcSessionsDir, dstSessionsDir, { recursive: true, force: true });++ // Rewrite sessions.json so key prefix matches the new agent. Without this,+ // OpenClaw won't recognize the imported entries as belonging to the dest.+ const dstSessionsJson = join(dstSessionsDir, "sessions.json");+ if (existsSync(dstSessionsJson)) {+ try {+ const raw = await readFile(dstSessionsJson, "utf8");+ const parsed = JSON.parse(raw) as Record<string, unknown>;+ const oldPrefix = `agent:${input.source_agent_id}:`;+ const newPrefix = `agent:${newAgentId}:`;+ const rewritten: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(parsed)) {+ const newKey = k.startsWith(oldPrefix) ? newPrefix + k.slice(oldPrefix.length) : k;+ rewritten[newKey] = v;+ sessionsCopied++;+ }+ await writeFile(dstSessionsJson, JSON.stringify(rewritten, null, 2), "utf8");+ } catch (err) {+ console.error("clone: could not rewrite sessions.json:", err);+ }+ }+ }++ // 5) Crons.+ const sourceCrons: CloneSourceCron[] = [];+ const newCronIds: string[] = [];+ try {+ const allCrons = await loadAllCrons();+ const mine = allCrons.filter((c) => c.agentId === input.source_agent_id);+ for (const c of mine) {+ sourceCrons.push({ id: c.id, name: c.name, disabled: c.enabled === false || !!c.disabled });+ try {+ const newId = await createClonedCron(c, input.project_slug, newSlug, newAgentId);+ newCronIds.push(newId);+ } catch (err) {+ console.error(`clone: could not recreate cron '${c.name}':`, err);+ }+ }+ } catch (err) {+ console.error("clone: could not list crons:", err);+ }++ // 6) Meta sidecar so the sidebar shows the new agent.+ await writeAgentMeta({+ agent_id: newAgentId,+ project_slug: input.project_slug,+ slug: newSlug,+ display_name: displayName,+ source_agent_id: input.source_agent_id,+ created_at: new Date().toISOString(),+ });++ return {+ new_agent_id: newAgentId,+ new_slug: newSlug,+ files_copied: filesCopied,+ sessions_copied: sessionsCopied,+ source_crons: sourceCrons,+ new_cron_ids: newCronIds,+ };+}++// --- helpers ---++/**+ * True if a project already has an agent at this slug. Considers both our+ * notfair meta sidecar and OpenClaw's agent dir, but only counts directories+ * that contain something — OpenClaw's `agents.delete` leaves an empty parent+ * dir behind after moving the contents to trash, and we don't want that+ * remnant to block reusing the slug.+ */+export function agentExistsInProject(project_slug: string, slug: string): boolean {+ const agentId = `${project_slug}-${slug}`;+ return (+ hasNonEmptyDir(join(NOTFAIR_DATA_DIR, "agents", agentId)) ||+ hasNonEmptyDir(join(OPENCLAW_HOME, "agents", agentId))+ );+}++function hasNonEmptyDir(path: string): boolean {+ if (!existsSync(path)) return false;+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const { readdirSync } = require("node:fs") as typeof import("node:fs");+ return readdirSync(path).length > 0;+ } catch {+ return true; // be conservative if we can't read it+ }+}++async function callAgentsFilesSet(agentId: string, name: string, content: string): Promise<void> {+ // setAgentFile in gateway-rpc.ts already wraps this; import lazily to keep+ // the top of this file readable.+ const { setAgentFile } = await import("./gateway-rpc");+ await setAgentFile(agentId, name, content);+}++type RawCron = {+ id: string;+ agentId?: string;+ name: string;+ enabled?: boolean;+ disabled?: boolean;+ description?: string;+ schedule?:+ | { kind: "cron"; expr: string; tz?: string }+ | { kind: "every"; everyMs: number; anchorMs?: number }+ | { kind: string; [k: string]: unknown };+ payload?: { kind?: string; message?: string; timeoutSeconds?: number };+};++async function loadAllCrons(): Promise<RawCron[]> {+ // Read jobs.json directly — same data the CLI prints, but avoids spawning+ // a subprocess (which can be 5–15s on cold paths).+ const jobsPath = join(OPENCLAW_HOME, "cron", "jobs.json");+ if (!existsSync(jobsPath)) return [];+ try {+ const raw = readFileSync(jobsPath, "utf8");+ const parsed = JSON.parse(raw) as unknown;+ if (Array.isArray(parsed)) return parsed as RawCron[];+ if (parsed && typeof parsed === "object") {+ const cands = parsed as { jobs?: unknown; crons?: unknown };+ if (Array.isArray(cands.jobs)) return cands.jobs as RawCron[];+ if (Array.isArray(cands.crons)) return cands.crons as RawCron[];+ }+ } catch {+ // Fall through to empty list.+ }+ return [];+}++async function createClonedCron(+ source: RawCron,+ projectSlug: string,+ newAgentSlug: string,+ newAgentId: string,+): Promise<string> {+ // Convention: `<project>/<agent-slug>/<cron-slug>` (no surrounding spaces).+ // When cloning, the source's name may already follow `<proj>/<agent>/<cron>`+ // (e.g. a clone of a clone). Only take the trailing segment so we don't+ // end up with redundant project/agent prefixes baked into the cron slug.+ const lastSegment = source.name.split(/\s*\/\s*/).pop()?.trim() ?? source.name;+ const slugAttempt = slugify(lastSegment);+ const cronSlug = slugAttempt.ok && slugAttempt.slug ? slugAttempt.slug : "cloned-job";+ const fullName = `${projectSlug}${NAME_SEPARATOR}${newAgentSlug}${NAME_SEPARATOR}${cronSlug}`;++ const args = [+ "cron",+ "add",+ "--name",+ fullName,+ "--agent",+ newAgentId,+ "--no-deliver",+ ];+ if (source.description) {+ args.push("--description", source.description);+ }+ const message = source.payload?.message ?? "";+ if (message) {+ args.push("--message", message);+ }+ const schedule = source.schedule;+ if (schedule?.kind === "cron" && typeof (schedule as { expr?: string }).expr === "string") {+ args.push("--cron", (schedule as { expr: string }).expr);+ const tz = (schedule as { tz?: string }).tz;+ if (tz) args.push("--tz", tz);+ } else if (schedule?.kind === "every" && typeof (schedule as { everyMs?: number }).everyMs === "number") {+ args.push("--every", msToDuration((schedule as { everyMs: number }).everyMs));+ } else {+ // Unknown schedule shape — fall back to disabled hourly so we don't lose+ // the job. User will see it in the crons tab and can fix.+ args.push("--every", "1h");+ }++ const result = (await openclaw(args)) as { id?: string };+ if (!result?.id) throw new Error(`openclaw cron add returned no id for '${fullName}'`);+ return String(result.id);+}++function msToDuration(ms: number): string {+ if (ms < 60_000) return `${Math.max(1, Math.round(ms / 1000))}s`;+ if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m`;+ if (ms < 86_400_000) return `${Math.round(ms / 3_600_000)}h`;+ return `${Math.round(ms / 86_400_000)}d`;+}diff --git a/src/server/openclaw/cron-schedule.ts b/src/server/openclaw/cron-schedule.tsindex 9a139a96..efe6df7a 100644--- a/src/server/openclaw/cron-schedule.ts+++ b/src/server/openclaw/cron-schedule.ts@@ -1,5 +1,6 @@import { CronExpressionParser } from "cron-parser";import type { DisplayCron } from "./crons";+import { loadCronRuns } from "./crons";export type CronOccurrence = {/** ms epoch */@@ -10,6 +11,8 @@ export type CronOccurrence = {agent_id: string;agent_slug: string;schedule_text: string;+ /** Raw status string from OpenClaw when a matching run is found. */+ run_status?: string;};type ScheduleInput =@@ -85,6 +88,99 @@ export function expandSchedule(return [];}+/**+ * Find the most recent scheduled tick at or before `at` for a given schedule.+ * Used to attribute a cron run (whose `runAtMs` is when the scheduler actually+ * fired, often 5-10 minutes after the nominal tick) back to the calendar+ * occurrence it belongs to.+ *+ * Returns the tick's ms epoch, or `undefined` if no tick before `at` is in the+ * lookback window (defaults to 14 days, enough to catch the previous tick of+ * any reasonable daily/weekly schedule).+ */+export function tickAtOrBefore(+ schedule: ScheduleInput | undefined,+ at: number,+ lookbackMs = 14 * 24 * 60 * 60 * 1000,+): number | undefined {+ if (!schedule) return undefined;+ const from = at - lookbackMs;++ if (schedule.kind === "cron" && typeof (schedule as { expr?: unknown }).expr === "string") {+ const s = schedule as { expr: string; tz?: string };+ try {+ const it = CronExpressionParser.parse(s.expr, {+ currentDate: new Date(from),+ endDate: new Date(at + 1),+ tz: s.tz,+ });+ let last: number | undefined;+ for (let i = 0; i < 10_000; i++) {+ try {+ const t = it.next().toDate().getTime();+ if (t > at) break;+ last = t;+ } catch {+ break;+ }+ }+ return last;+ } catch {+ return undefined;+ }+ }++ if (schedule.kind === "every" && typeof (schedule as { everyMs?: unknown }).everyMs === "number") {+ const s = schedule as { everyMs: number; anchorMs?: number };+ if (s.everyMs <= 0) return undefined;+ const anchor = typeof s.anchorMs === "number" ? s.anchorMs : at;+ if (anchor > at) return undefined;+ const k = Math.floor((at - anchor) / s.everyMs);+ return anchor + k * s.everyMs;+ }++ return undefined;+}++/**+ * Annotate occurrences with their owning run's status (when one exists in the+ * cron run log). Mutates and returns the list for caller convenience.+ *+ * Reads `~/.openclaw/cron/runs/<cronId>.jsonl` per unique cron in the input.+ * Each run's owning nominal tick is computed via `tickAtOrBefore` so late-fired+ * runs still match their intended occurrence.+ */+export function annotateOccurrencesWithRunStatus(+ occurrences: CronOccurrence[],+ schedulesByCronId: Map<string, ScheduleInput | undefined>,+): CronOccurrence[] {+ // Group occurrences by cron so we hit the run log at most once per cron.+ const byCron = new Map<string, CronOccurrence[]>();+ for (const occ of occurrences) {+ const arr = byCron.get(occ.cron_id) ?? [];+ arr.push(occ);+ byCron.set(occ.cron_id, arr);+ }+ for (const [cronId, occs] of byCron) {+ const schedule = schedulesByCronId.get(cronId);+ if (!schedule) continue;+ const runs = loadCronRuns(cronId, 200);+ // Index runs by owning tick for O(1) lookup.+ const statusByTick = new Map<number, string>();+ for (const run of runs) {+ const tick = tickAtOrBefore(schedule, run.run_at_ms);+ if (tick != null && !statusByTick.has(tick)) {+ statusByTick.set(tick, run.status);+ }+ }+ for (const o of occs) {+ const s = statusByTick.get(o.at);+ if (s) o.run_status = s;+ }+ }+ return occurrences;+}+/*** Expand a list of crons into a flat occurrence list grouped by day-of-week.* Days are in user local time (matches what the user sees in the calendar).diff --git a/src/server/openclaw/crons.ts b/src/server/openclaw/crons.tsindex f93019ab..b6a60280 100644--- a/src/server/openclaw/crons.ts+++ b/src/server/openclaw/crons.ts@@ -1,6 +1,11 @@+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";import { cache } from "react";import { openclaw } from "./cli";+const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");+/*** Module-level in-memory cache for the `openclaw cron list` subprocess.* Single-user local app, so a tiny TTL across requests is safe and avoids@@ -20,7 +25,9 @@ async function rawListAllCrons(): Promise<unknown> {return cachedCronsPromise;}cachedCronsAt = now;- cachedCronsPromise = openclaw(["cron", "list"]).catch((err) => {+ // `--all` because the CLI defaults to enabled-only and we want disabled+ // crons in the calendar too (so the Disabled filter has something to show).+ cachedCronsPromise = openclaw(["cron", "list", "--all"]).catch((err) => {// Invalidate on failure so the next caller retries instead of getting a cached reject.cachedCronsAt = 0;cachedCronsPromise = null;@@ -43,6 +50,9 @@ type CronState = {nextRunAtMs?: number;lastRunAtMs?: number;lastStatus?: string;+ lastRunStatus?: string;+ lastError?: string;+ lastErrorReason?: string;runs?: number;};@@ -54,6 +64,8 @@ export type OpenClawCron = {schedule?: CronSchedule;state?: CronState;disabled?: boolean;+ enabled?: boolean;+ payload?: { kind?: string; message?: string; timeoutSeconds?: number };// Catch any other fields without losing them.[k: string]: unknown;};@@ -71,6 +83,15 @@ export type DisplayCron = {last_run_text: string;status_text: string;disabled: boolean;+ /** The prompt/message the cron sends to the agent on each tick. */+ message?: string;+ description?: string;+ /** Last execution time (ms epoch); used to align "ran" vs "scheduled" per occurrence. */+ last_run_at_ms?: number;+ /** Raw status string from OpenClaw (e.g. "ok", "error", "skipped"). */+ last_status?: string;+ last_error?: string;+ next_run_at_ms?: number;};export type CronGroup = {@@ -128,9 +149,9 @@ export const listCronsForProject = cache(async (project_slug: string): Promise<Pfunction toDisplay(cron: OpenClawCron, shortAgent: string, _project_slug: string): DisplayCron {const agent_id = cron.agentId ?? "unknown";- const status = cron.disabled- ? "disabled"- : (cron.state?.lastStatus as string | undefined) ?? "idle";+ const disabled = !!cron.disabled || cron.enabled === false;+ const rawStatus = cron.state?.lastStatus ?? cron.state?.lastRunStatus;+ const status_text = disabled ? "disabled" : rawStatus ?? "idle";return {id: cron.id,name: cron.name,@@ -141,8 +162,14 @@ function toDisplay(cron: OpenClawCron, shortAgent: string, _project_slug: stringschedule_text: formatSchedule(cron.schedule),next_run_text: formatRelativeMs(cron.state?.nextRunAtMs),last_run_text: formatRelativeMs(cron.state?.lastRunAtMs),- status_text: status,- disabled: !!cron.disabled,+ status_text,+ disabled,+ message: cron.payload?.message,+ description: cron.description,+ last_run_at_ms: cron.state?.lastRunAtMs,+ last_status: rawStatus,+ last_error: cron.state?.lastError ?? cron.state?.lastErrorReason,+ next_run_at_ms: cron.state?.nextRunAtMs,};}@@ -253,8 +280,74 @@ export type CreateCronResult = {* Create a cron in OpenClaw using our naming convention.* Called by the `schedule_recurring_work` MCP tool from specialist agents.*/+// --- Per-run history ---++export type CronRun = {+ /** When the run was scheduled to fire (matches calendar occurrence.at within ~seconds). */+ run_at_ms: number;+ /** When the run finished (ts in the JSONL). */+ finished_at_ms: number;+ /** Raw OpenClaw status: "ok" | "error" | "skipped" | etc. */+ status: string;+ /** Agent's final reply / report. Empty when missing (e.g. crashed runs). */+ summary: string;+ /** Failure detail string, when status="error". */+ error?: string;+ duration_ms?: number;+ session_id?: string;+ model?: string;+ provider?: string;+ usage?: { input_tokens?: number; output_tokens?: number; total_tokens?: number };+};++/**+ * Read the per-job cron run log. Returns the most recent runs (newest first).+ * The file is JSONL with one entry per finished run, persisted by OpenClaw's+ * cron service under `~/.openclaw/cron/runs/<jobId>.jsonl`.+ */+export function loadCronRuns(cron_id: string, limit = 100): CronRun[] {+ const path = join(OPENCLAW_HOME, "cron", "runs", `${cron_id}.jsonl`);+ if (!existsSync(path)) return [];+ let raw: string;+ try {+ raw = readFileSync(path, "utf8");+ } catch {+ return [];+ }+ const lines = raw.split("\n").filter((l) => l.trim().length > 0);+ // Iterate newest-last → flip + cap.+ const out: CronRun[] = [];+ for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {+ let entry: Record<string, unknown>;+ try {+ entry = JSON.parse(lines[i]!) as Record<string, unknown>;+ } catch {+ continue;+ }+ if (entry.action !== "finished") continue;+ const run_at_ms = typeof entry.runAtMs === "number" ? entry.runAtMs : 0;+ if (!run_at_ms) continue;+ out.push({+ run_at_ms,+ finished_at_ms: typeof entry.ts === "number" ? entry.ts : run_at_ms,+ status: typeof entry.status === "string" ? entry.status : "unknown",+ summary: typeof entry.summary === "string" ? entry.summary : "",+ error: typeof entry.error === "string" ? entry.error : undefined,+ duration_ms: typeof entry.durationMs === "number" ? entry.durationMs : undefined,+ session_id: typeof entry.sessionId === "string" ? entry.sessionId : undefined,+ model: typeof entry.model === "string" ? entry.model : undefined,+ provider: typeof entry.provider === "string" ? entry.provider : undefined,+ usage:+ entry.usage && typeof entry.usage === "object"+ ? (entry.usage as CronRun["usage"])+ : undefined,+ });+ }+ return out;+}+export async function createCron(input: CreateCronInput): Promise<CreateCronResult> {- const fullName = `${input.project_slug} ${NAME_SEPARATOR} ${input.agent_slug} ${NAME_SEPARATOR} ${input.cron_name}`;+ const fullName = `${input.project_slug}${NAME_SEPARATOR}${input.agent_slug}${NAME_SEPARATOR}${input.cron_name}`;const args = ["cron","add",diff --git a/src/server/openclaw/gateway-client.ts b/src/server/openclaw/gateway-client.tsnew file mode 100644index 00000000..3fd90826--- /dev/null+++ b/src/server/openclaw/gateway-client.ts@@ -0,0 +1,406 @@+import { existsSync, readFileSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { randomUUID } from "node:crypto";+import WebSocket from "ws";++/**+ * Minimal OpenClaw Gateway WebSocket client for streaming chat.+ *+ * Wire protocol (lifted from openclaw/openclaw `ui/src/ui/gateway.ts`):+ * - Open WS to ws://<host>:<port>+ * - Server may emit `event: connect.challenge` with a nonce; we ignore for+ * token-only auth on loopback.+ * - Client sends `{ type: "req", id, method: "connect", params: {...} }`+ * with auth.token; server replies `{ type: "res", ok: true, payload: helloOk }`.+ * - All requests use `{ type: "req", id, method, params }` and receive+ * `{ type: "res", id, ok, payload?, error? }`.+ * - Streaming chat tokens arrive as `{ type: "event", event: "chat", payload }`+ * events; payload includes { runId, sessionKey, state, deltaText, message }.+ *+ * URL + token discovery: read OpenClaw's own config file. We never hard-code+ * port or host — the user's `~/.openclaw/openclaw.json` (or+ * `OPENCLAW_STATE_DIR`/profile path) is the source of truth.+ */++// --- Discovery ---++export type GatewayConfig = {+ url: string; // ws://host:port+ token?: string;+ password?: string;+ configFile: string;+};++function resolveConfigFile(): string {+ const dir =+ process.env.OPENCLAW_STATE_DIR?.trim() ||+ process.env.OPENCLAW_HOME?.trim() ||+ join(homedir(), ".openclaw");+ return join(dir, "openclaw.json");+}++export function discoverGateway(): GatewayConfig {+ const configFile = resolveConfigFile();+ if (!existsSync(configFile)) {+ throw new Error(+ `OpenClaw config not found at ${configFile}. Is OpenClaw installed and configured?`,+ );+ }+ let parsed: Record<string, unknown>;+ try {+ parsed = JSON.parse(readFileSync(configFile, "utf8")) as Record<string, unknown>;+ } catch (err) {+ throw new Error(+ `Could not parse ${configFile}: ${err instanceof Error ? err.message : String(err)}`,+ );+ }++ const gateway = (parsed.gateway ?? {}) as Record<string, unknown>;++ // Prefer remote URL if user configured one; otherwise build from port + bind.+ const remote = (gateway.remote ?? {}) as Record<string, unknown>;+ const remoteUrl = typeof remote.url === "string" ? remote.url.trim() : "";+ let url = remoteUrl;++ if (!url) {+ const port = Number(gateway.port);+ if (!Number.isFinite(port) || port <= 0) {+ throw new Error(`Could not read gateway.port from ${configFile}`);+ }+ const bind = typeof gateway.bind === "string" ? gateway.bind : "loopback";+ // For loopback/auto, connect to 127.0.0.1. For lan/tailnet, the user+ // typically also sets gateway.remote.url; if not, loopback is the safest+ // local default.+ const host = bind === "lan" || bind === "tailnet" ? "127.0.0.1" : "127.0.0.1";+ url = `ws://${host}:${port}`;+ }++ const auth = (gateway.auth ?? {}) as Record<string, unknown>;+ const token = typeof auth.token === "string" && auth.token.length > 0 ? auth.token : undefined;+ const password =+ typeof auth.password === "string" && auth.password.length > 0 ? auth.password : undefined;++ return { url, token, password, configFile };+}++// --- Frame types ---++type ReqFrame = { type: "req"; id: string; method: string; params?: unknown };+type ResFrame = {+ type: "res";+ id: string;+ ok: boolean;+ payload?: unknown;+ error?: { code: string; message: string; details?: unknown };+};+type EventFrame = { type: "event"; event: string; payload?: unknown; seq?: number };+type AnyFrame = ResFrame | EventFrame | { type: string; [k: string]: unknown };++// Wide protocol range so the gateway picks whatever it supports. Older+// installs speak protocol 3; newer ones speak 4+. The server returns the+// chosen version in hello-ok.+const CLIENT_MIN_PROTOCOL = 2 as const;+const CLIENT_MAX_PROTOCOL = 10 as const;++export type GatewayConnectOptions = {+ /** override discovery. */+ url?: string;+ token?: string;+ password?: string;+ /** scopes to request; default operator.read + write (enough for chat.send). */+ scopes?: string[];+};++export class GatewayClient {+ private ws: WebSocket | null = null;+ private pending = new Map<+ string,+ { resolve: (v: unknown) => void; reject: (err: Error) => void }+ >();+ private eventListeners = new Set<(evt: EventFrame) => void>();+ private connected = false;+ private connectPromise: Promise<void> | null = null;+ private readonly cfg: GatewayConfig;+ private readonly scopes: string[];++ constructor(opts: GatewayConnectOptions = {}) {+ const discovered = discoverGateway();+ this.cfg = {+ url: opts.url ?? discovered.url,+ token: opts.token ?? discovered.token,+ password: opts.password ?? discovered.password,+ configFile: discovered.configFile,+ };+ // Local single-user app; default to admin so config mutations (skills.update,+ // crons CRUD) work without per-call scope juggling.+ this.scopes = opts.scopes ?? [+ "operator.read",+ "operator.write",+ "operator.admin",+ ];+ }++ /** Open + connect, idempotent. */+ async open(): Promise<void> {+ if (this.connected) return;+ if (this.connectPromise) return this.connectPromise;+ this.connectPromise = this.openInternal().finally(() => {+ this.connectPromise = null;+ });+ return this.connectPromise;+ }++ private async openInternal(): Promise<void> {+ const ws = new WebSocket(this.cfg.url, {+ perMessageDeflate: false,+ handshakeTimeout: 5_000,+ });+ this.ws = ws;++ await new Promise<void>((resolve, reject) => {+ const onErr = (err: Error) => reject(err);+ ws.once("error", onErr);+ ws.once("open", () => {+ ws.removeListener("error", onErr);+ resolve();+ });+ });++ ws.on("message", (raw) => this.handleMessage(String(raw)));+ ws.on("close", () => {+ this.connected = false;+ for (const p of this.pending.values()) {+ p.reject(new Error("gateway connection closed"));+ }+ this.pending.clear();+ });+ ws.on("error", () => {+ // Errors after open propagate via close.+ });++ // Send connect frame and wait for hello-ok payload.+ await this.request("connect", {+ minProtocol: CLIENT_MIN_PROTOCOL,+ maxProtocol: CLIENT_MAX_PROTOCOL,+ client: {+ id: "gateway-client",+ version: "0.1.0",+ platform: process.platform,+ mode: "backend",+ instanceId: process.pid.toString(),+ },+ role: "operator",+ scopes: this.scopes,+ caps: [],+ ...(this.cfg.token || this.cfg.password+ ? { auth: { token: this.cfg.token, password: this.cfg.password } }+ : {}),+ userAgent: `notfair-cmo/0.1.0 node/${process.versions.node}`,+ locale: "en-US",+ });+ this.connected = true;+ }++ close(): void {+ this.connected = false;+ try {+ this.ws?.close();+ } catch {}+ this.ws = null;+ this.pending.clear();+ this.eventListeners.clear();+ }++ request<T = unknown>(method: string, params?: unknown): Promise<T> {+ const ws = this.ws;+ if (!ws || ws.readyState !== WebSocket.OPEN) {+ return Promise.reject(new Error("gateway not connected"));+ }+ const id = randomUUID();+ const frame: ReqFrame = { type: "req", id, method, params };+ return new Promise<T>((resolve, reject) => {+ this.pending.set(id, {+ resolve: (v) => resolve(v as T),+ reject,+ });+ ws.send(JSON.stringify(frame));+ });+ }++ addEventListener(listener: (evt: EventFrame) => void): () => void {+ this.eventListeners.add(listener);+ return () => this.eventListeners.delete(listener);+ }++ private handleMessage(raw: string): void {+ let parsed: AnyFrame;+ try {+ parsed = JSON.parse(raw) as AnyFrame;+ } catch {+ return;+ }+ if (parsed.type === "res") {+ const res = parsed as ResFrame;+ const p = this.pending.get(res.id);+ if (!p) return;+ this.pending.delete(res.id);+ if (res.ok) p.resolve(res.payload);+ else {+ const detailsStr = res.error?.details+ ? ` details=${JSON.stringify(res.error.details).slice(0, 300)}`+ : "";+ p.reject(+ new Error(+ `gateway error (${res.error?.code ?? "UNKNOWN"}): ${res.error?.message ?? "request failed"}${detailsStr}`,+ ),+ );+ }+ return;+ }+ if (parsed.type === "event") {+ const evt = parsed as EventFrame;+ // connect.challenge is for device auth; we don't use it on loopback ++ // shared-token. Safe to ignore.+ if (evt.event === "connect.challenge") return;+ for (const listener of this.eventListeners) {+ try {+ listener(evt);+ } catch (err) {+ console.error("[gateway-client] event listener error:", err);+ }+ }+ }+ }+}++// --- High-level streaming chat helper ---++export type StreamChatInput = {+ sessionKey: string;+ sessionId?: string;+ message: string;+ /** Cancellation signal. When aborted, we issue chat.abort and stop. */+ signal?: AbortSignal;+};++export type ChatStreamEvent =+ | { kind: "delta"; text: string }+ | { kind: "final"; text: string }+ | { kind: "error"; message: string };++/**+ * Stream a chat turn from OpenClaw. Yields incremental delta text events as+ * the agent produces tokens, then a final event with the full text once done.+ *+ * Strategy: subscribe to `event: "chat"` frames filtered to our runId. Each+ * payload carries the merged text in message.content[0].text; we compute the+ * delta against what we've already yielded so the consumer sees pure new+ * characters per event (cleaner than relying on the gateway's optional+ * `deltaText` field which can have buffering quirks).+ */+export async function* streamChatViaGateway(+ input: StreamChatInput,+): AsyncGenerator<ChatStreamEvent, void, void> {+ const client = new GatewayClient();+ await client.open();++ const runId = randomUUID();+ const events: ChatStreamEvent[] = [];+ let done = false;+ let lastEmittedLen = 0;+ let resolveWait: (() => void) | null = null;++ const wake = () => {+ if (resolveWait) {+ const r = resolveWait;+ resolveWait = null;+ r();+ }+ };++ const unsubscribe = client.addEventListener((evt) => {+ if (evt.event !== "chat") return;+ const payload = evt.payload as+ | {+ runId?: string;+ state?: string;+ deltaText?: string;+ replace?: boolean;+ message?: { content?: Array<{ type?: string; text?: string }> };+ }+ | undefined;+ if (!payload || payload.runId !== runId) return;++ const merged = extractText(payload.message?.content);+ if (merged.length > lastEmittedLen) {+ const delta = merged.slice(lastEmittedLen);+ lastEmittedLen = merged.length;+ events.push({ kind: "delta", text: delta });+ wake();+ }+ if (payload.state === "final" || payload.state === "complete") {+ events.push({ kind: "final", text: merged });+ done = true;+ wake();+ }+ });++ // Wire abort: best-effort chat.abort + bail out.+ const onAbort = () => {+ void client.request("chat.abort", { sessionKey: input.sessionKey, runId }).catch(() => {});+ done = true;+ wake();+ };+ if (input.signal) {+ if (input.signal.aborted) onAbort();+ else input.signal.addEventListener("abort", onAbort, { once: true });+ }++ try {+ // Fire the request. The promise resolves quickly with the runId-or-ack+ // payload; streaming text arrives as events.+ void client+ .request("chat.send", {+ sessionKey: input.sessionKey,+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),+ message: input.message,+ deliver: false,+ idempotencyKey: runId,+ })+ .catch((err: Error) => {+ events.push({ kind: "error", message: err.message });+ done = true;+ wake();+ });++ while (!done || events.length > 0) {+ while (events.length > 0) {+ yield events.shift()!;+ }+ if (done) break;+ await new Promise<void>((resolve) => {+ resolveWait = resolve;+ // Safety: time-bounded wait so we never hang forever if events stop.+ setTimeout(() => {+ if (resolveWait === resolve) {+ resolveWait = null;+ resolve();+ }+ }, 30_000);+ });+ }+ } finally {+ unsubscribe();+ if (input.signal) input.signal.removeEventListener("abort", onAbort);+ client.close();+ }+}++function extractText(content: Array<{ type?: string; text?: string }> | undefined): string {+ if (!Array.isArray(content)) return "";+ return content+ .filter((c) => c?.type === "text" && typeof c.text === "string")+ .map((c) => c.text as string)+ .join("");+}diff --git a/src/server/openclaw/gateway-rpc.ts b/src/server/openclaw/gateway-rpc.tsnew file mode 100644index 00000000..6d6c0f11--- /dev/null+++ b/src/server/openclaw/gateway-rpc.ts@@ -0,0 +1,176 @@+import { GatewayClient } from "./gateway-client";++/**+ * Thin wrappers around the OpenClaw gateway RPC methods we use from server+ * components. Each call opens a fresh GatewayClient, does one request, and+ * closes it. Per-request overhead is a single WS handshake to loopback (sub+ * 50ms on local), which is fine for SSR page loads where the alternative is+ * a multi-second `openclaw …` subprocess spawn.+ *+ * If we need higher-throughput access later, swap to a long-lived shared+ * client at process scope.+ */++async function withClient<T>(fn: (c: GatewayClient) => Promise<T>): Promise<T> {+ const client = new GatewayClient();+ await client.open();+ try {+ return await fn(client);+ } finally {+ client.close();+ }+}++// --- agents.files ---++export type AgentFileEntry = {+ name: string;+ path: string;+ missing: boolean;+ size?: number;+ updatedAtMs?: number;+};++export type AgentFilesList = {+ agentId: string;+ workspace: string;+ files: AgentFileEntry[];+};++export async function listAgentFiles(agentId: string): Promise<AgentFilesList> {+ return withClient((c) => c.request<AgentFilesList>("agents.files.list", { agentId }));+}++export type AgentFileGet = {+ agentId: string;+ workspace: string;+ file: AgentFileEntry & { content: string };+};++export async function getAgentFile(agentId: string, name: string): Promise<AgentFileGet> {+ return withClient((c) => c.request<AgentFileGet>("agents.files.get", { agentId, name }));+}++export async function setAgentFile(+ agentId: string,+ name: string,+ content: string,+): Promise<void> {+ await withClient((c) => c.request("agents.files.set", { agentId, name, content }));+}++// --- skills.status ---++export type SkillEntry = {+ name: string;+ description: string;+ source: string;+ bundled: boolean;+ filePath: string;+ baseDir: string;+ skillKey: string;+ emoji?: string;+ always: boolean;+ disabled: boolean;+ eligible: boolean;+ blockedByAllowlist: boolean;+ blockedByAgentFilter: boolean;+ userInvocable: boolean;+ commandVisible: boolean;+ // Other fields exist (requirements, install) — leave as unknown until we+ // surface them in the UI.+};++export type SkillStatusReport = {+ workspaceDir: string;+ managedSkillsDir: string;+ agentId?: string;+ agentSkillFilter?: string[];+ skills: SkillEntry[];+};++export async function getSkillStatus(agentId: string): Promise<SkillStatusReport> {+ return withClient((c) =>+ c.request<SkillStatusReport>("skills.status", { agentId }),+ );+}++/**+ * Toggle a skill on/off in the workspace config. Requires operator.admin scope.+ * Affects all agents in the workspace (skills.config is workspace-wide).+ */+export async function setSkillEnabled(+ skillKey: string,+ enabled: boolean,+): Promise<void> {+ await withClient((c) =>+ c.request("skills.update", { skillKey, enabled }),+ );+}++// --- agents.delete ---++/**+ * Delete an agent from OpenClaw. With deleteFiles:true (default), removes the+ * workspace dir + sessions store so all thread history goes with it.+ * Requires operator.admin scope.+ */+export async function deleteAgent(agentId: string): Promise<void> {+ await withClient((c) =>+ c.request("agents.delete", { agentId, deleteFiles: true }),+ );+}++// --- agents.list / agents.create ---++export type GatewayAgentRow = {+ id: string;+ name?: string;+ identity?: {+ name?: string;+ emoji?: string;+ avatar?: string;+ };+ model?: string;+};++export type AgentsListResult = {+ defaultId: string;+ mainKey: string;+ agents: GatewayAgentRow[];+};++export async function listAllAgents(): Promise<AgentsListResult> {+ return withClient((c) => c.request<AgentsListResult>("agents.list", {}));+}++export type AgentCreateInput = {+ /** Full agentId, e.g. `<project>-<slug>`. */+ name: string;+ /** Absolute workspace directory. */+ workspace: string;+ model?: string;+ emoji?: string;+};++export async function createAgentViaRpc(input: AgentCreateInput): Promise<void> {+ await withClient((c) => c.request("agents.create", input));+}++// --- cron.update ---++/**+ * Replace a cron's agent-turn prompt. Other fields (schedule, agent target,+ * delivery) are left as-is. Requires operator.admin scope.+ */+export async function updateCronMessage(cron_id: string, message: string): Promise<void> {+ await withClient((c) =>+ c.request("cron.update", {+ id: cron_id,+ patch: {+ payload: { kind: "agentTurn", message },+ },+ }),+ );+}+diff --git a/src/server/openclaw/project-delete.ts b/src/server/openclaw/project-delete.tsnew file mode 100644index 00000000..9857c344--- /dev/null+++ b/src/server/openclaw/project-delete.ts@@ -0,0 +1,72 @@+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import type { AgentTemplate } from "@/server/agent-templates";+import { listProjectAgents } from "@/server/agent-meta";+import { listSessionsForAgent } from "@/server/openclaw/sessions";+import { listCronsForProject } from "@/server/openclaw/crons";++const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");++export type ProjectDeletionAgentSummary = {+ /** Template key when this agent came from a bootstrap template, else undefined. */+ template?: AgentTemplate["key"];+ display_name: string;+ agentId: string;+ exists: boolean;+ threadCount: number;+};++export type ProjectDeletionSummary = {+ project_slug: string;+ agents: ProjectDeletionAgentSummary[];+ totals: {+ agents: number;+ threads: number;+ crons: number;+ };+};++/**+ * Inventory everything tied to a project so the confirmation dialog can show+ * the user exactly what will be deleted. Reads-only; no mutations.+ *+ * Source of truth: `listProjectAgents()` — covers bootstrap templates AND any+ * cloned/custom agents created via the `+` button. Iterating TEMPLATES alone+ * would silently skip user-created agents and leak them after project delete.+ */+export async function getProjectDeletionSummary(+ project_slug: string,+): Promise<ProjectDeletionSummary> {+ const entries = await listProjectAgents(project_slug);+ const agents: ProjectDeletionAgentSummary[] = entries.map((e) => {+ const agentDir = join(OPENCLAW_HOME, "agents", e.agent_id);+ const exists = existsSync(agentDir);+ const threadCount = exists ? listSessionsForAgent(e.agent_id).length : 0;+ return {+ template: e.template_key,+ display_name: e.display_name,+ agentId: e.agent_id,+ exists,+ threadCount,+ };+ });++ let cronCount = 0;+ try {+ const cronView = await listCronsForProject(project_slug);+ cronCount = cronView.groups.reduce((acc, g) => acc + g.crons.length, 0);+ } catch {+ // OpenClaw cron service unreachable — show 0 and let the user decide.+ }++ return {+ project_slug,+ agents,+ totals: {+ agents: agents.filter((a) => a.exists).length,+ threads: agents.reduce((acc, a) => acc + a.threadCount, 0),+ crons: cronCount,+ },+ };+}diff --git a/src/server/openclaw/sessions.ts b/src/server/openclaw/sessions.tsindex 0d8bd816..688ce22f 100644--- a/src/server/openclaw/sessions.ts+++ b/src/server/openclaw/sessions.ts@@ -24,6 +24,13 @@ export type OpenClawSession = {sessionId: string;/** Optional short label parsed from the full session-key, if present. */label: string;+ /**+ * Full sessionKey OpenClaw uses internally (`agent:<agent>:<label>`). The+ * label half is the canonical identifier for an existing thread — OpenClaw+ * may register `<main>` for its bootstrap thread instead of the sessionId.+ * For brand-new threads we create, the label IS the sessionId UUID.+ */+ sessionKey: string;/** Last interaction (ms epoch). 0 if unknown / freshly minted. */lastInteractionAt: number;/** True if this session exists only in our cookie (user clicked New, hasn't sent a message yet). */@@ -57,6 +64,7 @@ export function listSessionsForAgent(agentFullId: string): OpenClawSession[] {out.push({sessionId: entry.sessionId,label,+ sessionKey: key,lastInteractionAt: entry.lastInteractionAt ?? entry.updatedAt ?? 0,pending: false,});@@ -65,6 +73,27 @@ export function listSessionsForAgent(agentFullId: string): OpenClawSession[] {return out;}+/**+ * Build the canonical sessionKey for a brand-new thread we're about to send+ * the first message to. Label = the same UUID we're using as sessionId, so+ * the thread becomes self-identifying in OpenClaw's store.+ */+export function buildPendingSessionKey(agentFullId: string, sessionId: string): string {+ return `agent:${agentFullId}:${sessionId}`;+}++/**+ * Look up an existing session by its sessionId (UUID), returning the entry+ * with its OpenClaw-registered sessionKey. Returns null when the sessionId is+ * not yet known to OpenClaw — caller should treat it as a pending new thread.+ */+export function findSessionBySessionId(+ agentFullId: string,+ sessionId: string,+): OpenClawSession | null {+ return listSessionsForAgent(agentFullId).find((s) => s.sessionId === sessionId) ?? null;+}+/** Generate a brand-new session id. OpenClaw creates the entry on first turn. */export function newSessionId(): string {return randomUUID();@@ -99,6 +128,7 @@ export async function getSessionsView(active = {sessionId: cookieSessionId,label: cookieSessionId.slice(0, 8),+ sessionKey: buildPendingSessionKey(agentFullId, cookieSessionId),lastInteractionAt: 0,pending: true,};@@ -111,9 +141,11 @@ export async function getSessionsView(} else {// No history yet — synthesize a default session id. Cookie will be set// when the user sends their first message.+ const newId = newSessionId();active = {- sessionId: newSessionId(),+ sessionId: newId,label: "main",+ sessionKey: buildPendingSessionKey(agentFullId, newId),lastInteractionAt: 0,pending: true,};