Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(routing): scope project routes under /<slug>/...

Yuting Zhong20c07c5b4141
diff --git a/src/app/(app)/activity/page.tsx b/src/app/(app)/[project]/activity/page.tsx
similarity index 89%
rename from src/app/(app)/activity/page.tsx
rename to src/app/(app)/[project]/activity/page.tsx
index 1031e880..2778cf13 100644
--- a/src/app/(app)/activity/page.tsx
+++ b/src/app/(app)/[project]/activity/page.tsx
@@ -1,6 +1,7 @@
+import { notFound } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { listAgentActions } from "@/server/db/agent-actions";
function timeAgo(iso: string) {
@@ -11,15 +12,14 @@ function timeAgo(iso: string) {
return `${Math.floor(seconds / 86400)}d ago`;
}
-export default async function ActivityPage() {
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to see its activity.
- </div>
- );
- }
+export default async function ActivityPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
const actions = listAgentActions(project.slug, 200);
return (
diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
similarity index 81%
rename from src/app/(app)/agents/[agent]/chat/[thread]/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
index b5380e0e..bc8b19ff 100644
--- a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/chat/[thread]/page.tsx
@@ -1,7 +1,5 @@
-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 { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import {
buildPendingSessionKey,
@@ -16,7 +14,7 @@ import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";
import { McpFlashBanner } from "@/components/mcp-flash-banner";
import { ThreadSelector } from "@/components/thread-selector";
-type Params = { agent: string; thread: string };
+type Params = { agent: string; thread: string; project: string };
type Search = { mcp_connected?: string; mcp_error?: string };
export default async function AgentChatThreadPage({
@@ -26,29 +24,11 @@ export default async function AgentChatThreadPage({
params: Promise<Params>;
searchParams: Promise<Search>;
}) {
- const { agent: agentSlug, thread: threadId } = await params;
+ const { agent: agentSlug, thread: threadId, project: projectSlug } = await params;
const { mcp_connected, mcp_error } = await searchParams;
- 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="/onboarding" className="text-sm underline">
- Create one
- </Link>
- </CardContent>
- </Card>
- </div>
- );
- }
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
@@ -100,7 +80,7 @@ export default async function AgentChatThreadPage({
<McpFlashBanner connected={mcp_connected} error={mcp_error} />
{googleAdsMcpStatus && googleAdsMcpStatus.state !== "connected" && (
- <GoogleAdsMcpBanner status={googleAdsMcpStatus} />
+ <GoogleAdsMcpBanner status={googleAdsMcpStatus} projectSlug={projectSlug} />
)}
<div className="flex items-center justify-between border-b bg-background/80 px-6 py-2 backdrop-blur">
@@ -110,6 +90,7 @@ export default async function AgentChatThreadPage({
: `${sessionsForDropdown.length} thread${sessionsForDropdown.length === 1 ? "" : "s"}`}
</div>
<ThreadSelector
+ projectSlug={projectSlug}
agentSlug={agentSlug}
sessions={sessionsForDropdown}
activeSessionId={threadId}
@@ -119,6 +100,7 @@ export default async function AgentChatThreadPage({
<div className="min-h-0 flex-1">
<LiveTranscript
key={threadId}
+ projectSlug={projectSlug}
agentSlug={agentSlug}
agentDisplayName={resolved.display_name}
threadId={threadId}
diff --git a/src/app/(app)/[project]/agents/[agent]/chat/page.tsx b/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
new file mode 100644
index 00000000..a14f2d3c
--- /dev/null
+++ b/src/app/(app)/[project]/agents/[agent]/chat/page.tsx
@@ -0,0 +1,29 @@
+import { redirect, notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import {
+ listSessionsForAgent,
+ newSessionId,
+} from "@/server/openclaw/sessions";
+import { projectHref } from "@/lib/project-href";
+
+/**
+ * Default landing for /<project>/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; project: string }>;
+}) {
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
+
+ const existing = listSessionsForAgent(resolved.agent_id);
+ const target = existing[0]?.sessionId ?? newSessionId();
+ redirect(projectHref(projectSlug, `/agents/${agentSlug}/chat/${target}`));
+}
diff --git a/src/app/(app)/agents/[agent]/cron/page.tsx b/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
similarity index 86%
rename from src/app/(app)/agents/[agent]/cron/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/cron/page.tsx
index 7cf718f4..43ec4962 100644
--- a/src/app/(app)/agents/[agent]/cron/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/cron/page.tsx
@@ -1,7 +1,6 @@
-import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { listCronsForProject } from "@/server/openclaw/crons";
import {
@@ -39,34 +38,18 @@ function scheduleForCalendar(s: unknown): ScheduleInput | null {
return null;
}
-type Params = { agent: string };
+type Params = { agent: string; project: 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="/onboarding" className="text-sm underline">
- Create one
- </Link>
- </CardContent>
- </Card>
- </div>
- );
- }
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
const templateSlug = resolved.slug;
diff --git a/src/app/(app)/agents/[agent]/files/page.tsx b/src/app/(app)/[project]/agents/[agent]/files/page.tsx
similarity index 87%
rename from src/app/(app)/agents/[agent]/files/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/files/page.tsx
index 6153270d..f01346b5 100644
--- a/src/app/(app)/agents/[agent]/files/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/files/page.tsx
@@ -1,14 +1,14 @@
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 { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { listAgentFiles, getAgentFile } from "@/server/openclaw/gateway-rpc";
import { cn } from "@/lib/utils";
+import { projectHref } from "@/lib/project-href";
-type Params = { agent: string };
+type Params = { agent: string; project: string };
type Search = { file?: string };
export default async function AgentFilesPage({
@@ -18,17 +18,11 @@ export default async function AgentFilesPage({
params: Promise<Params>;
searchParams: Promise<Search>;
}) {
- const { agent: agentSlug } = await params;
+ const { agent: agentSlug, project: projectSlug } = 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 project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
@@ -100,7 +94,10 @@ export default async function AgentFilesPage({
return (
<Link
key={f.name}
- href={`/agents/${agentSlug}/files?file=${encodeURIComponent(f.name)}`}
+ href={projectHref(
+ projectSlug,
+ `/agents/${agentSlug}/files?file=${encodeURIComponent(f.name)}`,
+ )}
className={cn(
"flex items-center gap-2 px-4 py-1.5 text-sm transition-colors",
isActive
@@ -172,22 +169,6 @@ export default async function AgentFilesPage({
);
}
-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="/onboarding" 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`;
diff --git a/src/app/(app)/agents/[agent]/layout.tsx b/src/app/(app)/[project]/agents/[agent]/layout.tsx
similarity index 60%
rename from src/app/(app)/agents/[agent]/layout.tsx
rename to src/app/(app)/[project]/agents/[agent]/layout.tsx
index 052c0e64..ea259904 100644
--- a/src/app/(app)/agents/[agent]/layout.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/layout.tsx
@@ -1,9 +1,9 @@
import { notFound } from "next/navigation";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { AgentTabs } from "@/components/agent-tabs";
-type Params = { agent: string };
+type Params = { agent: string; project: string };
export default async function AgentLayout({
children,
@@ -12,16 +12,17 @@ export default async function AgentLayout({
children: React.ReactNode;
params: Promise<Params>;
}) {
- const { agent: agentSlug } = await params;
- const project = await getActiveProject();
- const resolved = project ? await resolveAgentBySlug(project.slug, agentSlug) : null;
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
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} />
+ <AgentTabs projectSlug={projectSlug} agentSlug={agentSlug} />
<div className="min-h-0 flex-1">{children}</div>
</div>
);
diff --git a/src/app/(app)/[project]/agents/[agent]/page.tsx b/src/app/(app)/[project]/agents/[agent]/page.tsx
new file mode 100644
index 00000000..db507500
--- /dev/null
+++ b/src/app/(app)/[project]/agents/[agent]/page.tsx
@@ -0,0 +1,11 @@
+import { redirect } from "next/navigation";
+import { projectHref } from "@/lib/project-href";
+
+export default async function AgentIndexPage({
+ params,
+}: {
+ params: Promise<{ agent: string; project: string }>;
+}) {
+ const { agent, project } = await params;
+ redirect(projectHref(project, `/agents/${agent}/tasks`));
+}
diff --git a/src/app/(app)/agents/[agent]/settings/page.tsx b/src/app/(app)/[project]/agents/[agent]/settings/page.tsx
similarity index 75%
rename from src/app/(app)/agents/[agent]/settings/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/settings/page.tsx
index f7b81e48..cdad208d 100644
--- a/src/app/(app)/agents/[agent]/settings/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/settings/page.tsx
@@ -1,40 +1,22 @@
-import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
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 };
+type Params = { agent: string; project: 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="/onboarding" className="text-sm underline">
- Create one
- </Link>
- </CardContent>
- </Card>
- </div>
- );
- }
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
const meta = readAgentMeta(resolved.agent_id);
diff --git a/src/app/(app)/agents/[agent]/skills/page.tsx b/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
similarity index 64%
rename from src/app/(app)/agents/[agent]/skills/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/skills/page.tsx
index 4bcff700..c45dde54 100644
--- a/src/app/(app)/agents/[agent]/skills/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/skills/page.tsx
@@ -1,41 +1,24 @@
-import Link from "next/link";
import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { getSkillStatus } from "@/server/openclaw/gateway-rpc";
import { SkillsList } from "@/components/skills-list";
-type Params = { agent: string };
+type Params = { agent: string; project: 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&apos;s skills.
- </p>
- <Link href="/onboarding" className="text-sm underline">
- Create one
- </Link>
- </CardContent>
- </Card>
- </div>
- );
- }
+ const { agent: agentSlug, project: projectSlug } = await params;
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
- const agentFullId = resolved!.agent_id;
+ const agentFullId = resolved.agent_id;
let report: Awaited<ReturnType<typeof getSkillStatus>> | null = null;
let error: string | null = null;
try {
@@ -52,7 +35,7 @@ export default async function AgentSkillsPage({
<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}.
+ 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."}
diff --git a/src/app/(app)/agents/[agent]/tasks/page.tsx b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
similarity index 87%
rename from src/app/(app)/agents/[agent]/tasks/page.tsx
rename to src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
index ccf19be6..82398e57 100644
--- a/src/app/(app)/agents/[agent]/tasks/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -1,7 +1,7 @@
import { notFound } from "next/navigation";
import { AgentTaskWorkspace } from "@/components/agent-task-workspace";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { resolveAgentBySlug } from "@/server/agent-meta";
import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";
import { buildPendingSessionKey, findSessionBySessionId } from "@/server/openclaw/sessions";
@@ -14,7 +14,7 @@ import { startTaskIfProposed } from "@/server/orchestration/run-task";
import type { Task } from "@/types";
type Props = {
- params: Promise<{ agent: string }>;
+ params: Promise<{ agent: string; project: string }>;
searchParams: Promise<{ task?: string }>;
};
@@ -27,19 +27,11 @@ type SelectedBundle = {
};
export default async function AgentTasksPage({ params, searchParams }: Props) {
- const [{ agent: agentSlug }, { task: selectedTaskId }] = await Promise.all([
- params,
- searchParams,
- ]);
-
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md p-6 pt-12 text-sm text-muted-foreground">
- Select a project to view this agent&rsquo;s tasks.
- </div>
- );
- }
+ const [{ agent: agentSlug, project: projectSlug }, { task: selectedTaskId }] =
+ await Promise.all([params, searchParams]);
+
+ const project = getProject(projectSlug);
+ if (!project || project.archived_at) notFound();
const resolved = await resolveAgentBySlug(project.slug, agentSlug);
if (!resolved) notFound();
@@ -62,6 +54,7 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {
return (
<AgentTaskWorkspace
+ projectSlug={projectSlug}
agentSlug={agentSlug}
agentFullId={agentFullId}
agentDisplayName={resolved.display_name}
diff --git a/src/app/(app)/agents/page.tsx b/src/app/(app)/[project]/agents/page.tsx
similarity index 85%
rename from src/app/(app)/agents/page.tsx
rename to src/app/(app)/[project]/agents/page.tsx
index 33fdeddf..f662896d 100644
--- a/src/app/(app)/agents/page.tsx
+++ b/src/app/(app)/[project]/agents/page.tsx
@@ -3,7 +3,8 @@ import { Bot, Check, MessageSquare, Clock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
-import { getActiveProject } from "@/server/active-project";
+import { notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
import {
TEMPLATES,
urlSlugForTemplate,
@@ -13,16 +14,16 @@ import {
import { listCronsForProject } from "@/server/openclaw/crons";
import { reprovisionAgentsAction } from "@/server/actions/projects";
import { ReprovisionButton } from "@/components/reprovision-button";
+import { projectHref } from "@/lib/project-href";
-export default async function AgentsPage() {
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to see its agents.
- </div>
- );
- }
+export default async function AgentsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
// Best-effort cron count per agent.
const cronByAgent = new Map<string, number>();
@@ -49,9 +50,9 @@ export default async function AgentsPage() {
<div className="grid gap-4">
{TEMPLATES.map((t) => {
- const slug = urlSlugForTemplate(t.key as AgentTemplateKey);
+ const agentSlug = urlSlugForTemplate(t.key as AgentTemplateKey);
const fullId = agentNameFor(project.slug, t.key as AgentTemplateKey);
- const crons = cronByAgent.get(slug) ?? 0;
+ const crons = cronByAgent.get(agentSlug) ?? 0;
return (
<Card key={t.key}>
<CardHeader className="flex flex-row items-start justify-between space-y-0">
@@ -72,7 +73,7 @@ export default async function AgentsPage() {
<div className="flex shrink-0 items-center gap-2">
{crons > 0 && (
<Link
- href="/crons"
+ href={projectHref(slug, "/crons")}
className="flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
>
<Clock className="size-3" />
@@ -80,7 +81,7 @@ export default async function AgentsPage() {
</Link>
)}
<Button asChild size="sm">
- <Link href={`/agents/${slug}/chat`}>
+ <Link href={projectHref(slug, `/agents/${agentSlug}/chat`)}>
<MessageSquare className="mr-1.5 size-4" />
Chat
</Link>
diff --git a/src/app/(app)/approvals/page.tsx b/src/app/(app)/[project]/approvals/page.tsx
similarity index 73%
rename from src/app/(app)/approvals/page.tsx
rename to src/app/(app)/[project]/approvals/page.tsx
index ee40074c..425ac8de 100644
--- a/src/app/(app)/approvals/page.tsx
+++ b/src/app/(app)/[project]/approvals/page.tsx
@@ -1,18 +1,18 @@
+import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { listPendingApprovals } from "@/server/db/approvals";
import { ApprovalCard } from "@/components/approval-card";
+import { projectHref } from "@/lib/project-href";
-export default async function ApprovalsPage() {
- const project = await getActiveProject();
-
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to see its pending approvals.
- </div>
- );
- }
+export default async function ApprovalsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
const pending = listPendingApprovals(project.slug);
@@ -32,7 +32,7 @@ export default async function ApprovalsPage() {
<p className="mt-2 text-sm text-muted-foreground">
CMO will surface decisions here. Items above your thresholds appear
here for approval. Adjust thresholds in{" "}
- <a href="/settings" className="underline">
+ <a href={projectHref(slug, "/settings")} className="underline">
Settings
</a>
.
diff --git a/src/app/(app)/connections/page.tsx b/src/app/(app)/[project]/connections/page.tsx
similarity index 86%
rename from src/app/(app)/connections/page.tsx
rename to src/app/(app)/[project]/connections/page.tsx
index efbb4084..9a300a53 100644
--- a/src/app/(app)/connections/page.tsx
+++ b/src/app/(app)/[project]/connections/page.tsx
@@ -1,5 +1,6 @@
+import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { MCP_CATALOG, storedMcpKey } from "@/server/mcp-catalog";
import { getMcpStatus } from "@/server/mcp-state";
import { McpCard } from "@/components/mcp-card";
@@ -9,19 +10,15 @@ type Search = { mcp_connected?: string; mcp_error?: string };
export default async function ConnectionsPage({
searchParams,
+ params,
}: {
searchParams: Promise<Search>;
+ params: Promise<{ project: string }>;
}) {
- const project = await getActiveProject();
+ const { project: slug } = await params;
+ const project = getProject(slug);
const { mcp_connected, mcp_error } = await searchParams;
-
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to manage its connections.
- </div>
- );
- }
+ if (!project || project.archived_at) notFound();
// Status probes happen in parallel — each has its own 2s timeout so a
// flaky upstream doesn't gate the whole page.
diff --git a/src/app/(app)/crons/page.tsx b/src/app/(app)/[project]/crons/page.tsx
similarity index 94%
rename from src/app/(app)/crons/page.tsx
rename to src/app/(app)/[project]/crons/page.tsx
index 6f7d61ff..8b3d66bb 100644
--- a/src/app/(app)/crons/page.tsx
+++ b/src/app/(app)/[project]/crons/page.tsx
@@ -1,5 +1,6 @@
+import { notFound } from "next/navigation";
import { Card, CardContent } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { listCronsForProject } from "@/server/openclaw/crons";
import {
annotateOccurrencesWithRunStatus,
@@ -31,15 +32,14 @@ function scheduleForCalendar(s: unknown): ScheduleInput | null {
const NUM_DAYS = 14; // 2-week window; UI shows 7 at a time with prev/next.
-export default async function CronsPage() {
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to see its scheduled work.
- </div>
- );
- }
+export default async function CronsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
let error: string | null = null;
let view: Awaited<ReturnType<typeof listCronsForProject>>;
diff --git a/src/app/(app)/[project]/layout.tsx b/src/app/(app)/[project]/layout.tsx
new file mode 100644
index 00000000..9244f47c
--- /dev/null
+++ b/src/app/(app)/[project]/layout.tsx
@@ -0,0 +1,29 @@
+import { notFound } from "next/navigation";
+import { getProject } from "@/server/db/projects";
+import { ProjectCookieSync } from "@/components/project-cookie-sync";
+
+/**
+ * Validates that the URL's project slug actually exists. Live-syncing the
+ * cookie used by `getActiveProject()` (which the sidebar + API routes still
+ * read) is handled by a thin client component so we can stay inside server
+ * render. The actual sidebar / chrome is mounted by the parent `(app)/layout`.
+ */
+export default async function ProjectScopedLayout({
+ children,
+ params,
+}: {
+ children: React.ReactNode;
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) {
+ notFound();
+ }
+ return (
+ <>
+ <ProjectCookieSync slug={slug} />
+ {children}
+ </>
+ );
+}
diff --git a/src/app/(app)/[project]/page.tsx b/src/app/(app)/[project]/page.tsx
new file mode 100644
index 00000000..e6520761
--- /dev/null
+++ b/src/app/(app)/[project]/page.tsx
@@ -0,0 +1,250 @@
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { MessageSquare, Clock, Bot, ListChecks, CheckCircle2 } from "lucide-react";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { getProject } from "@/server/db/projects";
+import { costToday } from "@/server/db/cost";
+import { listPendingApprovals } from "@/server/db/approvals";
+import { listTasks } from "@/server/db/tasks";
+import { listAgentActions } from "@/server/db/agent-actions";
+import {
+ TEMPLATES,
+ urlSlugForTemplate,
+ type AgentTemplateKey,
+} from "@/server/agent-templates";
+import { projectHref } from "@/lib/project-href";
+
+function formatUsd(n: number) {
+ return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
+}
+
+function timeAgo(iso: string) {
+ const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
+ if (seconds < 60) return `${Math.floor(seconds)}s ago`;
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
+ return `${Math.floor(seconds / 86400)}d ago`;
+}
+
+export default async function ProjectHomePage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
+
+ const cost = costToday(project.slug);
+ const pending = listPendingApprovals(project.slug);
+ const tasks = listTasks(project.slug);
+ const recent = listAgentActions(project.slug, 8);
+
+ // Intentionally NOT calling openclaw here. The cron tab is the source of
+ // truth for scheduled jobs; calling `openclaw cron list` from the home page
+ // would block render for 5-15s on some machines. Show a link instead.
+ const running = tasks.filter((t) => t.status === "running").length;
+
+ return (
+ <div className="mx-auto max-w-6xl space-y-6">
+ <div className="flex items-baseline justify-between">
+ <div>
+ <h1 className="text-2xl font-semibold tracking-tight">{project.display_name}</h1>
+ <p className="text-sm text-muted-foreground">
+ Project home · slug <span className="font-mono">{project.slug}</span>
+ </p>
+ </div>
+ <Button asChild>
+ <Link href={projectHref(slug, "/agents/cmo/chat")}>
+ <MessageSquare className="mr-1.5 size-4" />
+ Chat with CMO
+ </Link>
+ </Button>
+ </div>
+
+ {/* KPI row */}
+ <div className="grid gap-4 md:grid-cols-4">
+ <KpiCard
+ label="Spend today"
+ value={formatUsd(cost.total_usd)}
+ hint={`LLM ${formatUsd(cost.by_source.llm)} · Ads ${formatUsd(
+ cost.by_source.google_ads + cost.by_source.gsc,
+ )}`}
+ />
+ <KpiCard
+ label="Scheduled crons"
+ value="→"
+ hint="open cron tab"
+ href={projectHref(slug, "/crons")}
+ />
+ <KpiCard
+ label="Active tasks"
+ value={String(running)}
+ hint={`${tasks.length} total`}
+ href={projectHref(slug, "/tasks")}
+ />
+ <KpiCard
+ label="Pending approvals"
+ value={String(pending.length)}
+ hint={pending.length === 0 ? "all caught up" : "review →"}
+ href={projectHref(slug, "/approvals")}
+ />
+ </div>
+
+ <div className="grid gap-4 lg:grid-cols-3">
+ {/* Agents column */}
+ <Card className="lg:col-span-2">
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <div>
+ <CardTitle className="text-base">Your agents</CardTitle>
+ <CardDescription>
+ Each agent runs in its own OpenClaw workspace. Click to chat.
+ </CardDescription>
+ </div>
+ <Button asChild variant="outline" size="sm">
+ <Link href={projectHref(slug, "/agents")}>View all</Link>
+ </Button>
+ </div>
+ </CardHeader>
+ <CardContent className="space-y-2">
+ {TEMPLATES.map((t) => {
+ const agentSlug = urlSlugForTemplate(t.key as AgentTemplateKey);
+ return (
+ <Link
+ key={t.key}
+ href={projectHref(slug, `/agents/${agentSlug}/chat`)}
+ className="flex items-center gap-3 rounded-md border bg-card p-3 transition-colors hover:bg-accent/50"
+ >
+ <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted">
+ <Bot className="size-4" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="font-medium">{t.display_name}</div>
+ <p className="line-clamp-1 text-xs text-muted-foreground">{t.description}</p>
+ </div>
+ <MessageSquare className="size-4 shrink-0 text-muted-foreground" />
+ </Link>
+ );
+ })}
+ </CardContent>
+ </Card>
+
+ {/* Activity column */}
+ <Card>
+ <CardHeader>
+ <div className="flex items-center justify-between">
+ <div>
+ <CardTitle className="text-base">Recent activity</CardTitle>
+ <CardDescription>Last 8 agent actions</CardDescription>
+ </div>
+ <Button asChild variant="outline" size="sm">
+ <Link href={projectHref(slug, "/activity")}>All</Link>
+ </Button>
+ </div>
+ </CardHeader>
+ <CardContent>
+ {recent.length === 0 ? (
+ <div className="space-y-2 text-sm">
+ <p className="text-muted-foreground">No activity yet.</p>
+ <p className="text-xs text-muted-foreground">
+ Activity logs autonomous decisions, scheduled work, and tool calls.
+ </p>
+ </div>
+ ) : (
+ <ul className="space-y-2.5 text-xs">
+ {recent.map((a) => (
+ <li key={a.id} className="space-y-0.5">
+ <div className="flex items-center gap-2">
+ <Badge variant="outline" className="font-mono text-[9px]">
+ {a.action_type}
+ </Badge>
+ <span className="ml-auto text-[10px] text-muted-foreground tabular-nums">
+ {timeAgo(a.occurred_at)}
+ </span>
+ </div>
+ <p className="line-clamp-2 leading-snug">{a.summary}</p>
+ </li>
+ ))}
+ </ul>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+
+ {/* Onboarding nudge if nothing has happened yet */}
+ {tasks.length === 0 && recent.length === 0 && (
+ <Card>
+ <CardContent className="space-y-3 py-6 text-sm">
+ <h3 className="font-medium">Getting started</h3>
+ <ol className="space-y-1.5 text-muted-foreground">
+ <li>
+ 1.{" "}
+ <Link href={projectHref(slug, "/connections")} className="underline">
+ Connect Google Ads or GSC
+ </Link>{" "}
+ if you want agents to do real work (optional, chat works without it)
+ </li>
+ <li>
+ 2.{" "}
+ <Link href={projectHref(slug, "/agents/cmo/chat")} className="underline">
+ Chat with the CMO
+ </Link>{" "}
+ to plan what to do
+ </li>
+ <li>
+ 3.{" "}
+ <Link href={projectHref(slug, "/crons")} className="underline">
+ Schedule recurring jobs
+ </Link>{" "}
+ for specialist agents
+ </li>
+ </ol>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+}
+
+function KpiCard({
+ label,
+ value,
+ hint,
+ href,
+}: {
+ label: string;
+ value: string;
+ hint: string;
+ href?: string;
+}) {
+ const content = (
+ <Card className={href ? "transition-colors hover:bg-accent/30" : undefined}>
+ <CardHeader className="pb-2">
+ <CardDescription>{label}</CardDescription>
+ <CardTitle className="text-2xl tabular-nums">{value}</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-0 text-xs text-muted-foreground">{hint}</CardContent>
+ </Card>
+ );
+ if (href)
+ return (
+ <Link href={href} className="block">
+ {content}
+ </Link>
+ );
+ return content;
+}
+
+// Silence unused lint for icons reserved for future activity-feed expansion.
+void ListChecks;
+void CheckCircle2;
+void Clock;
diff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/[project]/settings/page.tsx
similarity index 93%
rename from src/app/(app)/settings/page.tsx
rename to src/app/(app)/[project]/settings/page.tsx
index a4d8df17..e76101b4 100644
--- a/src/app/(app)/settings/page.tsx
+++ b/src/app/(app)/[project]/settings/page.tsx
@@ -1,22 +1,22 @@
+import { notFound } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
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();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to edit its settings.
- </div>
- );
- }
+export default async function SettingsPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
const g = getGuardrails(project.slug);
const submit = updateGuardrailsAction.bind(null, project.slug);
diff --git a/src/app/(app)/tasks/[id]/page.tsx b/src/app/(app)/[project]/tasks/[id]/page.tsx
similarity index 75%
rename from src/app/(app)/tasks/[id]/page.tsx
rename to src/app/(app)/[project]/tasks/[id]/page.tsx
index 05213a8b..83595816 100644
--- a/src/app/(app)/tasks/[id]/page.tsx
+++ b/src/app/(app)/[project]/tasks/[id]/page.tsx
@@ -1,9 +1,10 @@
import { notFound, redirect } from "next/navigation";
import { readAgentMeta } from "@/server/agent-meta";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { getTask } from "@/server/db/tasks";
import { urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templates";
+import { projectHref } from "@/lib/project-href";
/**
* Deep-link destination for task IDs. The canonical view lives in the agent
@@ -14,17 +15,11 @@ import { urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templa
export default async function TaskDetailPage({
params,
}: {
- params: Promise<{ id: string }>;
+ params: Promise<{ id: string; project: string }>;
}) {
- const { id } = await params;
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to view this task.
- </div>
- );
- }
+ const { id, project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
const task = getTask(id);
if (!task || task.project_slug !== project.slug) notFound();
@@ -38,5 +33,7 @@ export default async function TaskDetailPage({
// Use the human-readable display_id in the canonical URL so the path
// someone bookmarks reads "?task=demo7-3" not a UUID. getTask in the
// workspace accepts either form, so legacy UUID deep-links still resolve.
- redirect(`/agents/${agentSlug}/tasks?task=${task.display_id}`);
+ redirect(
+ projectHref(slug, `/agents/${agentSlug}/tasks?task=${task.display_id}`),
+ );
}
diff --git a/src/app/(app)/tasks/page.tsx b/src/app/(app)/[project]/tasks/page.tsx
similarity index 89%
rename from src/app/(app)/tasks/page.tsx
rename to src/app/(app)/[project]/tasks/page.tsx
index 8459bc73..dfe2a162 100644
--- a/src/app/(app)/tasks/page.tsx
+++ b/src/app/(app)/[project]/tasks/page.tsx
@@ -1,9 +1,12 @@
import Link from "next/link";
+import { notFound } from "next/navigation";
+
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
import { listTasks } from "@/server/db/tasks";
+import { projectHref } from "@/lib/project-href";
import type { TaskStatus } from "@/types";
const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [
@@ -24,15 +27,14 @@ const STATUS_VARIANT: Record<TaskStatus, "default" | "secondary" | "outline" | "
cancelled: "outline",
};
-export default async function TasksPage() {
- const project = await getActiveProject();
- if (!project) {
- return (
- <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">
- Select a project to see its tasks.
- </div>
- );
- }
+export default async function TasksPage({
+ params,
+}: {
+ params: Promise<{ project: string }>;
+}) {
+ const { project: slug } = await params;
+ const project = getProject(slug);
+ if (!project || project.archived_at) notFound();
const tasks = listTasks(project.slug);
const byStatus = new Map<TaskStatus, typeof tasks>();
@@ -77,7 +79,7 @@ export default async function TasksPage() {
{items.map((t) => (
<Link
key={t.id}
- href={`/tasks/${t.id}`}
+ href={projectHref(slug, `/tasks/${t.id}`)}
className="block rounded-md border bg-card p-3 text-xs space-y-1 transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30"
>
<div className="flex items-center gap-2">
diff --git a/src/app/(app)/agents/[agent]/chat/page.tsx b/src/app/(app)/agents/[agent]/chat/page.tsx
deleted file mode 100644
index 0278e045..00000000
--- a/src/app/(app)/agents/[agent]/chat/page.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-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]/page.tsx b/src/app/(app)/agents/[agent]/page.tsx
deleted file mode 100644
index 7843847b..00000000
--- a/src/app/(app)/agents/[agent]/page.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import { redirect } from "next/navigation";
-
-export default async function AgentIndexPage({
- params,
-}: {
- params: Promise<{ agent: string }>;
-}) {
- const { agent } = await params;
- redirect(`/agents/${agent}/tasks`);
-}
diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx
index a246b872..8cd2d406 100644
--- a/src/app/(app)/page.tsx
+++ b/src/app/(app)/page.tsx
@@ -1,239 +1,16 @@
-import Link from "next/link";
-import { MessageSquare, Clock, Bot, ListChecks, CheckCircle2 } from "lucide-react";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
-import { Button } from "@/components/ui/button";
-import { Badge } from "@/components/ui/badge";
+import { redirect } from "next/navigation";
import { getActiveProject } from "@/server/active-project";
-import { costToday } from "@/server/db/cost";
-import { listPendingApprovals } from "@/server/db/approvals";
-import { listTasks } from "@/server/db/tasks";
-import { listAgentActions } from "@/server/db/agent-actions";
-import { TEMPLATES, urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templates";
-
-function formatUsd(n: number) {
- return n.toLocaleString("en-US", { style: "currency", currency: "USD" });
-}
-
-function timeAgo(iso: string) {
- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
- if (seconds < 60) return `${Math.floor(seconds)}s ago`;
- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
- return `${Math.floor(seconds / 86400)}d ago`;
-}
-
-export default async function ProjectHomePage() {
+import { projectHref } from "@/lib/project-href";
+
+/**
+ * Root entry. Project-scoped routes now live under `/<slug>/...`, so the
+ * bare root just resolves the user's active (or first) project and bounces
+ * them to that home. With no projects at all, kick into onboarding.
+ */
+export default async function RootRedirect() {
const project = await getActiveProject();
-
- if (!project) {
- return (
- <div className="mx-auto flex max-w-lg flex-col items-start gap-4 pt-16">
- <h1 className="text-2xl font-semibold tracking-tight">
- Hire a CMO.
- </h1>
- <p className="text-sm text-muted-foreground">
- Connect your Google Ads account and watch a real audit in under 60
- seconds. Skip the connect if you just want to chat.
- </p>
- <Button asChild size="lg">
- <Link href="/onboarding">Set up your CMO</Link>
- </Button>
- </div>
- );
+ if (project) {
+ redirect(projectHref(project.slug));
}
-
- const cost = costToday(project.slug);
- const pending = listPendingApprovals(project.slug);
- const tasks = listTasks(project.slug);
- const recent = listAgentActions(project.slug, 8);
-
- // Intentionally NOT calling openclaw here. The cron tab is the source of
- // truth for scheduled jobs; calling `openclaw cron list` from the home page
- // would block render for 5-15s on some machines. Show a link instead.
- const running = tasks.filter((t) => t.status === "running").length;
-
- return (
- <div className="mx-auto max-w-6xl space-y-6">
- <div className="flex items-baseline justify-between">
- <div>
- <h1 className="text-2xl font-semibold tracking-tight">{project.display_name}</h1>
- <p className="text-sm text-muted-foreground">
- Project home · slug <span className="font-mono">{project.slug}</span>
- </p>
- </div>
- <Button asChild>
- <Link href="/agents/cmo/chat">
- <MessageSquare className="mr-1.5 size-4" />
- Chat with CMO
- </Link>
- </Button>
- </div>
-
- {/* KPI row */}
- <div className="grid gap-4 md:grid-cols-4">
- <KpiCard
- label="Spend today"
- value={formatUsd(cost.total_usd)}
- hint={`LLM ${formatUsd(cost.by_source.llm)} · Ads ${formatUsd(
- cost.by_source.google_ads + cost.by_source.gsc,
- )}`}
- />
- <KpiCard
- label="Scheduled crons"
- value="→"
- hint="open cron tab"
- href="/crons"
- />
- <KpiCard
- label="Active tasks"
- value={String(running)}
- hint={`${tasks.length} total`}
- href="/tasks"
- />
- <KpiCard
- label="Pending approvals"
- value={String(pending.length)}
- hint={pending.length === 0 ? "all caught up" : "review →"}
- href="/approvals"
- />
- </div>
-
- <div className="grid gap-4 lg:grid-cols-3">
- {/* Agents column */}
- <Card className="lg:col-span-2">
- <CardHeader>
- <div className="flex items-center justify-between">
- <div>
- <CardTitle className="text-base">Your agents</CardTitle>
- <CardDescription>
- Each agent runs in its own OpenClaw workspace. Click to chat.
- </CardDescription>
- </div>
- <Button asChild variant="outline" size="sm">
- <Link href="/agents">View all</Link>
- </Button>
- </div>
- </CardHeader>
- <CardContent className="space-y-2">
- {TEMPLATES.map((t) => {
- const slug = urlSlugForTemplate(t.key as AgentTemplateKey);
- return (
- <Link
- key={t.key}
- href={`/chat/${slug}`}
- className="flex items-center gap-3 rounded-md border bg-card p-3 transition-colors hover:bg-accent/50"
- >
- <div className="flex size-8 shrink-0 items-center justify-center rounded-md bg-muted">
- <Bot className="size-4" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="font-medium">{t.display_name}</div>
- <p className="line-clamp-1 text-xs text-muted-foreground">{t.description}</p>
- </div>
- <MessageSquare className="size-4 shrink-0 text-muted-foreground" />
- </Link>
- );
- })}
- </CardContent>
- </Card>
-
- {/* Activity column */}
- <Card>
- <CardHeader>
- <div className="flex items-center justify-between">
- <div>
- <CardTitle className="text-base">Recent activity</CardTitle>
- <CardDescription>Last 8 agent actions</CardDescription>
- </div>
- <Button asChild variant="outline" size="sm">
- <Link href="/activity">All</Link>
- </Button>
- </div>
- </CardHeader>
- <CardContent>
- {recent.length === 0 ? (
- <div className="space-y-2 text-sm">
- <p className="text-muted-foreground">No activity yet.</p>
- <p className="text-xs text-muted-foreground">
- Activity logs autonomous decisions, scheduled work, and tool calls.
- </p>
- </div>
- ) : (
- <ul className="space-y-2.5 text-xs">
- {recent.map((a) => (
- <li key={a.id} className="space-y-0.5">
- <div className="flex items-center gap-2">
- <Badge variant="outline" className="font-mono text-[9px]">
- {a.action_type}
- </Badge>
- <span className="ml-auto text-[10px] text-muted-foreground tabular-nums">
- {timeAgo(a.occurred_at)}
- </span>
- </div>
- <p className="line-clamp-2 leading-snug">{a.summary}</p>
- </li>
- ))}
- </ul>
- )}
- </CardContent>
- </Card>
- </div>
-
- {/* Onboarding nudge if nothing has happened yet */}
- {tasks.length === 0 && recent.length === 0 && (
- <Card>
- <CardContent className="space-y-3 py-6 text-sm">
- <h3 className="font-medium">Getting started</h3>
- <ol className="space-y-1.5 text-muted-foreground">
- <li>
- 1. <Link href="/connections" className="underline">Connect Google Ads or GSC</Link>{" "}
- if you want agents to do real work (optional, chat works without it)
- </li>
- <li>
- 2. <Link href="/agents/cmo/chat" className="underline">Chat with the CMO</Link> to plan
- what to do
- </li>
- <li>
- 3. <Link href="/crons" className="underline">Schedule recurring jobs</Link> for
- specialist agents
- </li>
- </ol>
- </CardContent>
- </Card>
- )}
- </div>
- );
-}
-
-function KpiCard({
- label,
- value,
- hint,
- href,
-}: {
- label: string;
- value: string;
- hint: string;
- href?: string;
-}) {
- const content = (
- <Card className={href ? "transition-colors hover:bg-accent/30" : undefined}>
- <CardHeader className="pb-2">
- <CardDescription>{label}</CardDescription>
- <CardTitle className="text-2xl tabular-nums">{value}</CardTitle>
- </CardHeader>
- <CardContent className="pt-0 text-xs text-muted-foreground">{hint}</CardContent>
- </Card>
- );
- if (href)
- return (
- <Link href={href} className="block">
- {content}
- </Link>
- );
- return content;
+ redirect("/onboarding");
}
-
-// Silence unused lint for icons reserved for future activity-feed expansion.
-void ListChecks;
-void CheckCircle2;
diff --git a/src/app/api/mcp-oauth/callback/route.ts b/src/app/api/mcp-oauth/callback/route.ts
index ab4d994b..61c01f77 100644
--- a/src/app/api/mcp-oauth/callback/route.ts
+++ b/src/app/api/mcp-oauth/callback/route.ts
@@ -32,11 +32,11 @@ export async function GET(request: Request) {
}
// The pending state may carry a `return_to` (e.g. the chat URL the user
- // started from). Default to /connections — that's where the MCP cards
- // live, so it's a sensible landing if no caller asked for somewhere else.
+ // started from). Default to / so the root redirect bounces them to their
+ // active project's home if no caller asked for a specific destination.
// `return_to` is already sanitized in startMcpConnect to be a same-origin
// path; URL() with a base will additionally reject anything malformed.
- const back = new URL(pending.return_to ?? "/connections", request.url);
+ const back = new URL(pending.return_to ?? "/", request.url);
if (upstreamError) {
back.searchParams.set(
diff --git a/src/app/api/oauth/[provider]/callback/route.ts b/src/app/api/oauth/[provider]/callback/route.ts
index af49e0ed..e6451736 100644
--- a/src/app/api/oauth/[provider]/callback/route.ts
+++ b/src/app/api/oauth/[provider]/callback/route.ts
@@ -22,7 +22,7 @@ export async function GET(
if (errorParam) {
return htmlResponse(
- `<h1>OAuth denied</h1><p>The provider returned: <code>${escapeHtml(errorParam)}</code></p><p><a href="/connections">Back to Connections</a></p>`,
+ `<h1>OAuth denied</h1><p>The provider returned: <code>${escapeHtml(errorParam)}</code></p><p><a href="/">Back to app</a></p>`,
400,
);
}
@@ -79,7 +79,7 @@ export async function GET(
if (!tokenData.refresh_token) {
return htmlResponse(
- `<h1>No refresh token</h1><p>Re-authorize and ensure the consent screen prompts for offline access.</p><p><a href="/connections">Back</a></p>`,
+ `<h1>No refresh token</h1><p>Re-authorize and ensure the consent screen prompts for offline access.</p><p><a href="/${encodeURIComponent(project)}/connections">Back</a></p>`,
400,
);
}
@@ -101,7 +101,9 @@ export async function GET(
);
}
- return NextResponse.redirect(`${callbackBase}/connections?connected=${provider}`);
+ return NextResponse.redirect(
+ `${callbackBase}/${encodeURIComponent(project)}/connections?connected=${provider}`,
+ );
}
type TokenConfig = {
diff --git a/src/components/agent-nav.tsx b/src/components/agent-nav.tsx
index 2cb02275..158a40e2 100644
--- a/src/components/agent-nav.tsx
+++ b/src/components/agent-nav.tsx
@@ -10,6 +10,7 @@ import {
} from "@/components/ui/sidebar";
import { RunningDot } from "@/components/running-dot";
import type { AgentTemplateKey } from "@/server/agent-templates";
+import { projectHref } from "@/lib/project-href";
type AgentNavEntry = {
/** Stable key for React, e.g. the agent_id. */
@@ -22,6 +23,7 @@ type AgentNavEntry = {
};
type Props = {
+ projectSlug: string;
agents: AgentNavEntry[];
/**
* agent_id → in-flight task count. Drives the live-dot + count badge on
@@ -37,7 +39,7 @@ const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {
seo: Search,
};
-export function AgentNav({ agents, inFlightCounts = {} }: Props) {
+export function AgentNav({ projectSlug, agents, inFlightCounts = {} }: Props) {
const pathname = usePathname();
return (
@@ -47,8 +49,8 @@ export function AgentNav({ agents, inFlightCounts = {} }: Props) {
// its own first-turn work (onboarding audit, user-assigned planning
// jobs); the work it delegates to specialists shows up in those
// specialists' tabs. Chat tab is still one click away for free-form.
- const href = `/agents/${a.slug}/tasks`;
- const agentBase = `/agents/${a.slug}`;
+ const href = projectHref(projectSlug, `/agents/${a.slug}/tasks`);
+ const agentBase = `/${projectSlug}/agents/${a.slug}`;
const isActive =
pathname === agentBase || pathname?.startsWith(`${agentBase}/`);
const Icon = a.template_key ? TEMPLATE_ICONS[a.template_key] ?? Bot : Bot;
diff --git a/src/components/agent-rename-card.tsx b/src/components/agent-rename-card.tsx
index 4c1a59f9..2bf71cdc 100644
--- a/src/components/agent-rename-card.tsx
+++ b/src/components/agent-rename-card.tsx
@@ -8,6 +8,7 @@ import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
import { slugify } from "@/lib/slug";
+import { projectHref } from "@/lib/project-href";
import { renameAgentAction } from "@/server/actions/agents";
type Props = {
@@ -52,12 +53,12 @@ export function AgentRenameCard({
const d = r.data;
toast.success(
d.full_rename
- ? `Renamed to "${d.display_name}" (new URL: /agents/${d.slug})`
+ ? `Renamed to "${d.display_name}" (new URL: ${projectHref(projectSlug, `/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`);
+ // agent_id and URL slug changed — route to the new settings page.
+ router.push(projectHref(projectSlug, `/agents/${d.slug}/settings`));
router.refresh();
} else {
router.refresh();
diff --git a/src/components/agent-tabs.tsx b/src/components/agent-tabs.tsx
index 25bf820d..eaeebf86 100644
--- a/src/components/agent-tabs.tsx
+++ b/src/components/agent-tabs.tsx
@@ -23,9 +23,15 @@ const TABS: Tab[] = [
{ key: "settings", label: "Settings", icon: Settings },
];
-export function AgentTabs({ agentSlug }: { agentSlug: string }) {
+export function AgentTabs({
+ projectSlug,
+ agentSlug,
+}: {
+ projectSlug: string;
+ agentSlug: string;
+}) {
const pathname = usePathname();
- const base = `/agents/${agentSlug}`;
+ const base = `/${projectSlug}/agents/${agentSlug}`;
return (
<nav
diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsx
index fafab4e1..63593ed9 100644
--- a/src/components/agent-task-workspace.tsx
+++ b/src/components/agent-task-workspace.tsx
@@ -20,6 +20,7 @@ import { RunningDot } from "@/components/running-dot";
import { StartAllTasksButton } from "@/components/start-all-tasks-button";
import { cancelTaskAction } from "@/server/actions/tasks";
import { cn } from "@/lib/utils";
+import { projectHref } from "@/lib/project-href";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
import type { Task, TaskStatus } from "@/types";
@@ -55,6 +56,7 @@ type SelectedTaskBundle = {
};
type Props = {
+ projectSlug: string;
agentSlug: string;
agentFullId: string;
agentDisplayName: string;
@@ -64,6 +66,7 @@ type Props = {
};
export function AgentTaskWorkspace({
+ projectSlug,
agentSlug,
agentFullId,
agentDisplayName,
@@ -184,7 +187,10 @@ export function AgentTaskWorkspace({
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
- <Link href="/tasks" className="hover:text-foreground">
+ <Link
+ href={projectHref(projectSlug, "/tasks")}
+ className="hover:text-foreground"
+ >
Tasks
</Link>
<span>/</span>
@@ -234,7 +240,12 @@ export function AgentTaskWorkspace({
</header>
<div className="min-h-0 flex-1">
- <SelectedTaskPanel selected={selected} agentSlug={agentSlug} agentDisplayName={agentDisplayName} />
+ <SelectedTaskPanel
+ selected={selected}
+ projectSlug={projectSlug}
+ agentSlug={agentSlug}
+ agentDisplayName={agentDisplayName}
+ />
</div>
</>
) : (
@@ -250,10 +261,12 @@ export function AgentTaskWorkspace({
function SelectedTaskPanel({
selected,
+ projectSlug,
agentSlug,
agentDisplayName,
}: {
selected: SelectedTaskBundle;
+ projectSlug: string;
agentSlug: string;
agentDisplayName: string;
}) {
@@ -285,6 +298,7 @@ function SelectedTaskPanel({
return (
<LiveTranscript
key={selected.task.id}
+ projectSlug={projectSlug}
agentSlug={agentSlug}
agentDisplayName={agentDisplayName}
threadId={selected.threadId}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index aeb2470e..adaf617c 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -28,6 +28,7 @@ import { getActiveProject } from "@/server/active-project";
import { pendingApprovalCount } from "@/server/db/approvals";
import { listProjectAgents } from "@/server/agent-meta";
import { inFlightCountsByAgent } from "@/server/db/tasks";
+import { projectHref } from "@/lib/project-href";
import { ProjectSwitcher } from "./project-switcher";
import { PairedOpenclawPill } from "./paired-openclaw-pill";
import { AgentNav } from "./agent-nav";
@@ -43,7 +44,7 @@ type NavItem = {
};
const NAV: NavItem[] = [
- { href: "/", label: "Home", icon: Home },
+ { href: "", label: "Home", icon: Home },
{ href: "/approvals", label: "Approvals", icon: CheckCircle2, badge: true },
{ href: "/tasks", label: "Tasks", icon: ListChecks },
{ href: "/crons", label: "Crons", icon: Clock },
@@ -99,6 +100,7 @@ export async function AppSidebar() {
</SidebarGroupLabel>
<SidebarGroupContent>
<AgentNav
+ projectSlug={active.slug}
agents={agentEntries.map((a) => ({
key: a.agent_id,
slug: a.slug,
@@ -112,28 +114,30 @@ export async function AppSidebar() {
</SidebarGroup>
)}
- <SidebarGroup>
- <SidebarGroupLabel>Project</SidebarGroupLabel>
- <SidebarGroupContent>
- <SidebarMenu>
- {NAV.map((item) => (
- <SidebarMenuItem key={item.href}>
- <SidebarMenuButton asChild>
- <Link href={item.href}>
- <item.icon />
- <span>{item.label}</span>
- {item.badge && approvalsBadge > 0 && (
- <Badge variant="secondary" className="ml-auto h-5 px-1.5 text-[10px]">
- {approvalsBadge}
- </Badge>
- )}
- </Link>
- </SidebarMenuButton>
- </SidebarMenuItem>
- ))}
- </SidebarMenu>
- </SidebarGroupContent>
- </SidebarGroup>
+ {active && (
+ <SidebarGroup>
+ <SidebarGroupLabel>Project</SidebarGroupLabel>
+ <SidebarGroupContent>
+ <SidebarMenu>
+ {NAV.map((item) => (
+ <SidebarMenuItem key={item.href || "home"}>
+ <SidebarMenuButton asChild>
+ <Link href={projectHref(active.slug, item.href)}>
+ <item.icon />
+ <span>{item.label}</span>
+ {item.badge && approvalsBadge > 0 && (
+ <Badge variant="secondary" className="ml-auto h-5 px-1.5 text-[10px]">
+ {approvalsBadge}
+ </Badge>
+ )}
+ </Link>
+ </SidebarMenuButton>
+ </SidebarMenuItem>
+ ))}
+ </SidebarMenu>
+ </SidebarGroupContent>
+ </SidebarGroup>
+ )}
</SidebarContent>
<SidebarFooter>
diff --git a/src/components/create-agent-dialog.tsx b/src/components/create-agent-dialog.tsx
index efb83fa4..f46275f4 100644
--- a/src/components/create-agent-dialog.tsx
+++ b/src/components/create-agent-dialog.tsx
@@ -23,6 +23,7 @@ import {
type AgentChoice,
} from "@/server/actions/agents";
import { slugify } from "@/lib/slug";
+import { projectHref } from "@/lib/project-href";
import type { CloneAgentResult } from "@/server/openclaw/clone-agent";
import { DisableSourceCronsDialog } from "./disable-source-crons-dialog";
@@ -100,7 +101,7 @@ export function CreateAgentDialog({ open, onOpenChange, projectSlug }: Props) {
}
toast.success(`Created ${name.trim()}`);
onOpenChange(false);
- router.push(`/agents/${r.data.slug}/chat`);
+ router.push(projectHref(projectSlug, `/agents/${r.data.slug}/chat`));
router.refresh();
});
return;
@@ -133,7 +134,7 @@ export function CreateAgentDialog({ open, onOpenChange, projectSlug }: Props) {
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.push(projectHref(projectSlug, `/agents/${r.data.new_slug}/chat`));
}
router.refresh();
});
@@ -284,7 +285,9 @@ export function CreateAgentDialog({ open, onOpenChange, projectSlug }: Props) {
newAgentId={postClone.result.new_agent_id}
sourceCrons={postClone.result.source_crons}
onDone={() => {
- router.push(`/agents/${postClone.result.new_slug}/chat`);
+ router.push(
+ projectHref(projectSlug, `/agents/${postClone.result.new_slug}/chat`),
+ );
router.refresh();
}}
/>
diff --git a/src/components/google-ads-mcp-banner.tsx b/src/components/google-ads-mcp-banner.tsx
index 9b62e1fb..f6e363b2 100644
--- a/src/components/google-ads-mcp-banner.tsx
+++ b/src/components/google-ads-mcp-banner.tsx
@@ -7,9 +7,11 @@ import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { startMcpConnect } from "@/server/actions/mcp";
import type { McpRuntimeStatus } from "@/server/mcp-state";
+import { projectHref } from "@/lib/project-href";
type Props = {
status: McpRuntimeStatus;
+ projectSlug: string;
};
/**
@@ -18,7 +20,7 @@ type Props = {
* the Connections page, but threads the current chat URL through as
* `return_to` so the user lands back here on success.
*/
-export function GoogleAdsMcpBanner({ status }: Props) {
+export function GoogleAdsMcpBanner({ status, projectSlug }: Props) {
const [busy, setBusy] = useState(false);
if (status.state === "connected") return null;
@@ -71,7 +73,7 @@ export function GoogleAdsMcpBanner({ status }: Props) {
<p className="mt-0.5 text-xs text-amber-900/80 dark:text-amber-100/80">
{detail}{" "}
<Link
- href="/connections"
+ href={projectHref(projectSlug, "/connections")}
className="underline underline-offset-2 hover:text-amber-900 dark:hover:text-amber-50"
>
Manage connections
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index f6246768..9e23103f 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -38,10 +38,12 @@ import {
} from "@/lib/slash-commands";
import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";
import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";
+import { projectHref } from "@/lib/project-href";
const POLL_INTERVAL_MS = 2_000;
type Props = {
+ projectSlug: string;
agentSlug: string;
agentDisplayName: string;
/** OpenClaw thread (the URL label half of `agent:<agent>:<label>`). */
@@ -78,6 +80,7 @@ type Props = {
const KICKOFF_FIRED = new Set<string>();
export function LiveTranscript({
+ projectSlug,
agentSlug,
agentDisplayName,
threadId,
@@ -235,7 +238,9 @@ export function LiveTranscript({
return;
case "new-session": {
const newId = crypto.randomUUID();
- router.push(`/agents/${agentSlug}/chat/${newId}`);
+ router.push(
+ projectHref(projectSlug, `/agents/${agentSlug}/chat/${newId}`),
+ );
return;
}
case "stop":
@@ -320,7 +325,7 @@ export function LiveTranscript({
abortRef.current = null;
}
},
- [agentSlug, input, pollOnce, router, sendingChat, sessionKey, threadId],
+ [agentSlug, input, pollOnce, projectSlug, router, sendingChat, sessionKey, threadId],
);
// ── Auto-kickoff for FIRST_TURN-style flows. ────────────────────────
diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsx
index 5280174e..20a83ee7 100644
--- a/src/components/onboarding-flow.tsx
+++ b/src/components/onboarding-flow.tsx
@@ -11,6 +11,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { cn } from "@/lib/utils";
+import { projectHref } from "@/lib/project-href";
import { startMcpConnect } from "@/server/actions/mcp";
import { createProjectForOnboardingAction } from "@/server/actions/projects";
import {
@@ -123,6 +124,8 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {
function ConnectStep({ slug }: { slug: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
+ const connectionsHref = projectHref(slug, "/connections");
+ const cmoTasksHref = projectHref(slug, "/agents/cmo/tasks");
async function onConnect() {
setBusy(true);
@@ -148,7 +151,7 @@ function ConnectStep({ slug }: { slug: string }) {
// Without Google Ads connected, there's nothing for the CMO to audit
// yet — drop the user on the CMO's task tab so they can see "no tasks
// assigned, connect Google Ads to start".
- router.push("/agents/cmo/tasks");
+ router.push(cmoTasksHref);
}
return (
@@ -185,7 +188,7 @@ function ConnectStep({ slug }: { slug: string }) {
</div>
<p className="text-xs text-muted-foreground">
You can disconnect anytime in{" "}
- <Link href="/connections" className="underline underline-offset-2">
+ <Link href={connectionsHref} className="underline underline-offset-2">
Connections
</Link>
.
@@ -253,7 +256,10 @@ function AccountStep({ slug }: { slug: string }) {
// task pre-selected — startTaskIfProposed kicks it off, the user
// watches it run live in the standard task UX.
router.replace(
- `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,
+ projectHref(
+ slug,
+ `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,
+ ),
);
})();
}, [state, slug, router]);
@@ -268,7 +274,10 @@ function AccountStep({ slug }: { slug: string }) {
return;
}
router.replace(
- `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,
+ projectHref(
+ slug,
+ `/agents/cmo/tasks?task=${encodeURIComponent(result.task_display_id)}`,
+ ),
);
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
@@ -305,7 +314,7 @@ function AccountStep({ slug }: { slug: string }) {
<Link href="/onboarding">Retry from start</Link>
</Button>
<Button variant="outline" asChild>
- <Link href="/agents/cmo/chat">Skip to chat</Link>
+ <Link href={projectHref(slug, "/agents/cmo/chat")}>Skip to chat</Link>
</Button>
</div>
</CardContent>
@@ -334,7 +343,7 @@ function AccountStep({ slug }: { slug: string }) {
</Link>
</Button>
<Button variant="outline" asChild>
- <Link href="/agents/cmo/chat">Skip to chat</Link>
+ <Link href={projectHref(slug, "/agents/cmo/chat")}>Skip to chat</Link>
</Button>
</div>
</CardContent>
diff --git a/src/components/project-cookie-sync.tsx b/src/components/project-cookie-sync.tsx
new file mode 100644
index 00000000..5e92a9cf
--- /dev/null
+++ b/src/components/project-cookie-sync.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { switchProjectAction } from "@/server/actions/projects";
+
+/**
+ * Keeps the legacy `notfair_active_project` cookie in lockstep with the URL
+ * project slug. The cookie is still consulted by the sidebar (mounted higher
+ * up in the tree than the `[project]` dynamic segment) and the API routes,
+ * so when a user deep-links into `/<other-slug>/...` we need the cookie to
+ * flip over to that slug. Fires at most once per slug change per mount.
+ */
+export function ProjectCookieSync({ slug }: { slug: string }) {
+ const lastSlug = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (lastSlug.current === slug) return;
+ lastSlug.current = slug;
+ // Server action — sets the cookie and revalidates layout cache so the
+ // sidebar's `activeSlug` matches the URL on next render.
+ void switchProjectAction(slug);
+ }, [slug]);
+
+ return null;
+}
diff --git a/src/components/project-switcher.tsx b/src/components/project-switcher.tsx
index 6b6baa74..9c99df2a 100644
--- a/src/components/project-switcher.tsx
+++ b/src/components/project-switcher.tsx
@@ -1,7 +1,7 @@
"use client";
import { useTransition } from "react";
-import { useRouter } from "next/navigation";
+import { useRouter, usePathname } from "next/navigation";
import { ChevronsUpDown, Plus, Check } from "lucide-react";
import {
DropdownMenu,
@@ -14,6 +14,7 @@ import {
import { SidebarMenuButton } from "@/components/ui/sidebar";
import type { Project } from "@/types";
import { switchProjectAction } from "@/server/actions/projects";
+import { projectHref, subPathFromPathname } from "@/lib/project-href";
import { toast } from "sonner";
type Props = {
@@ -23,18 +24,20 @@ type Props = {
export function ProjectSwitcher({ projects, activeSlug }: Props) {
const router = useRouter();
+ const pathname = usePathname();
const [pending, start] = useTransition();
const active = projects.find((p) => p.slug === activeSlug) ?? null;
function pick(slug: string) {
if (slug === activeSlug) return;
+ const subPath = subPathFromPathname(pathname, activeSlug);
start(async () => {
const result = await switchProjectAction(slug);
if (!result.ok) {
toast.error(result.error);
return;
}
- router.refresh();
+ router.push(projectHref(slug, subPath));
});
}
diff --git a/src/components/thread-selector.tsx b/src/components/thread-selector.tsx
index 55600ba0..f147a289 100644
--- a/src/components/thread-selector.tsx
+++ b/src/components/thread-selector.tsx
@@ -4,6 +4,7 @@ import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { ChevronsUpDown, Plus, Check } from "lucide-react";
import { Button } from "@/components/ui/button";
+import { projectHref } from "@/lib/project-href";
import {
DropdownMenu,
DropdownMenuContent,
@@ -22,6 +23,7 @@ export type SessionLite = {
};
type Props = {
+ projectSlug: string;
agentSlug: string;
sessions: SessionLite[];
activeSessionId: string;
@@ -42,19 +44,28 @@ function displayTitle(s: SessionLite): string {
return s.label.length > 32 ? `${s.label.slice(0, 32)}...` : s.label;
}
-export function ThreadSelector({ agentSlug, sessions, activeSessionId }: Props) {
+export function ThreadSelector({
+ projectSlug,
+ agentSlug,
+ sessions,
+ activeSessionId,
+}: Props) {
const router = useRouter();
const [pending, start] = useTransition();
const active = sessions.find((s) => s.sessionId === activeSessionId);
function go(sessionId: string) {
if (sessionId === activeSessionId) return;
- start(() => router.push(`/agents/${agentSlug}/chat/${sessionId}`));
+ start(() =>
+ router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${sessionId}`)),
+ );
}
function newThread() {
const id = crypto.randomUUID();
- start(() => router.push(`/agents/${agentSlug}/chat/${id}`));
+ start(() =>
+ router.push(projectHref(projectSlug, `/agents/${agentSlug}/chat/${id}`)),
+ );
}
return (
diff --git a/src/lib/project-href.test.ts b/src/lib/project-href.test.ts
new file mode 100644
index 00000000..0d38458e
--- /dev/null
+++ b/src/lib/project-href.test.ts
@@ -0,0 +1,79 @@
+import { describe, it, expect } from "vitest";
+import { projectHref, subPathFromPathname } from "./project-href";
+
+describe("projectHref", () => {
+ it("returns /:slug for empty path", () => {
+ expect(projectHref("acme")).toBe("/acme");
+ expect(projectHref("acme", "")).toBe("/acme");
+ expect(projectHref("acme", "/")).toBe("/acme");
+ });
+
+ it("prefixes paths missing a leading slash", () => {
+ expect(projectHref("acme", "agents/cmo")).toBe("/acme/agents/cmo");
+ });
+
+ it("prefixes paths with a leading slash", () => {
+ expect(projectHref("acme", "/agents/cmo")).toBe("/acme/agents/cmo");
+ });
+
+ it("preserves nested segments and query strings verbatim", () => {
+ expect(projectHref("acme", "/agents/cmo/chat/abc-123")).toBe(
+ "/acme/agents/cmo/chat/abc-123",
+ );
+ expect(projectHref("acme", "/tasks?status=running")).toBe(
+ "/acme/tasks?status=running",
+ );
+ });
+
+ it("rejects an empty slug", () => {
+ expect(() => projectHref("", "/agents")).toThrow();
+ });
+
+ it("works with hyphenated slugs", () => {
+ expect(projectHref("my-cool-co", "/connections")).toBe(
+ "/my-cool-co/connections",
+ );
+ });
+});
+
+describe("subPathFromPathname", () => {
+ it("returns empty for the project home", () => {
+ expect(subPathFromPathname("/acme", "acme")).toBe("");
+ });
+
+ it("strips the project slug from a nested path", () => {
+ expect(subPathFromPathname("/acme/agents/cmo/tasks", "acme")).toBe(
+ "/agents/cmo/tasks",
+ );
+ expect(subPathFromPathname("/acme/crons", "acme")).toBe("/crons");
+ });
+
+ it("returns empty when pathname is missing or doesn't match", () => {
+ expect(subPathFromPathname(null, "acme")).toBe("");
+ expect(subPathFromPathname(undefined, "acme")).toBe("");
+ expect(subPathFromPathname("/onboarding", "acme")).toBe("");
+ expect(subPathFromPathname("/other/agents", "acme")).toBe("");
+ });
+
+ it("returns empty when slug is missing", () => {
+ expect(subPathFromPathname("/acme/agents", null)).toBe("");
+ expect(subPathFromPathname("/acme/agents", "")).toBe("");
+ });
+
+ it("handles hyphenated slugs", () => {
+ expect(
+ subPathFromPathname("/my-cool-co/agents/cmo", "my-cool-co"),
+ ).toBe("/agents/cmo");
+ });
+
+ it("does not strip when the slug is a partial prefix", () => {
+ // "/acmeful/agents" shouldn't match slug "acme"
+ expect(subPathFromPathname("/acmeful/agents", "acme")).toBe("");
+ });
+
+ it("supports round-tripping through projectHref", () => {
+ const original = "/acme/agents/cmo/tasks";
+ const sub = subPathFromPathname(original, "acme");
+ expect(projectHref("zeta", sub)).toBe("/zeta/agents/cmo/tasks");
+ });
+});
diff --git a/src/lib/project-href.ts b/src/lib/project-href.ts
new file mode 100644
index 00000000..daacc13b
--- /dev/null
+++ b/src/lib/project-href.ts
@@ -0,0 +1,42 @@
+/**
+ * Build a project-scoped URL like `/<slug>/agents/cmo/chat`.
+ *
+ * The router treats every URL under `(app)/[project]/...` as project-scoped,
+ * so every internal link inside the app shell needs the slug prefix. This
+ * helper keeps that prefixing consistent and centralizes the leading-slash
+ * normalisation so callers can pass either `agents/cmo` or `/agents/cmo`.
+ *
+ * Passing an empty `path` returns the project root: `/<slug>`.
+ */
+export function projectHref(slug: string, path = ""): string {
+ if (!slug) {
+ throw new Error("projectHref: slug is required");
+ }
+ if (!path || path === "/" || path === "") {
+ return `/${slug}`;
+ }
+ const trimmed = path.startsWith("/") ? path.slice(1) : path;
+ return `/${slug}/${trimmed}`;
+}
+
+/**
+ * Strip the leading `/<currentSlug>` segment from a pathname and return the
+ * rest (always with a leading slash, or empty when the pathname is the
+ * project home). Used by the ProjectSwitcher so picking a different project
+ * preserves the user's current view (`/foo/agents/cmo/tasks` → `/agents/cmo/tasks`).
+ *
+ * Returns `""` when the pathname doesn't actually start with `/<currentSlug>` —
+ * the caller should treat that as "send the user to the new project's home."
+ */
+export function subPathFromPathname(
+ pathname: string | null | undefined,
+ currentSlug: string | null | undefined,
+): string {
+ if (!pathname || !currentSlug) return "";
+ if (pathname === `/${currentSlug}`) return "";
+ const prefix = `/${currentSlug}/`;
+ if (pathname.startsWith(prefix)) {
+ return `/${pathname.slice(prefix.length)}`;
+ }
+ return "";
+}
diff --git a/src/server/actions/approvals.ts b/src/server/actions/approvals.ts
index b5465e9d..06d35a86 100644
--- a/src/server/actions/approvals.ts
+++ b/src/server/actions/approvals.ts
@@ -6,7 +6,6 @@ import { resolveApproval } from "@/server/db/approvals";
export async function approveAction(id: string): Promise<{ ok: boolean; error?: string }> {
const result = resolveApproval(id, "approved");
if (!result) return { ok: false, error: "Approval not found or already resolved." };
- revalidatePath("/approvals");
revalidatePath("/", "layout");
return { ok: true };
}
@@ -14,7 +13,6 @@ export async function approveAction(id: string): Promise<{ ok: boolean; error?:
export async function rejectAction(id: string): Promise<{ ok: boolean; error?: string }> {
const result = resolveApproval(id, "rejected");
if (!result) return { ok: false, error: "Approval not found or already resolved." };
- revalidatePath("/approvals");
revalidatePath("/", "layout");
return { ok: true };
}
diff --git a/src/server/actions/crons.ts b/src/server/actions/crons.ts
index 789e562f..e6684148 100644
--- a/src/server/actions/crons.ts
+++ b/src/server/actions/crons.ts
@@ -59,7 +59,7 @@ export async function scheduleCronAction(input: ScheduleCronInput): Promise<Sche
summary: `Scheduled '${nameSlug.slug}' (${input.schedule_kind} ${scheduleValueTrimmed})`,
payload: { cron_id: result.id, cron_name: result.name, brief: briefTrimmed },
});
- revalidatePath("/crons");
+ revalidatePath("/", "layout");
revalidatePath("/", "layout");
return { ok: true, cron_id: result.id, cron_name: result.name };
} catch (err) {
@@ -70,7 +70,7 @@ export async function scheduleCronAction(input: ScheduleCronInput): Promise<Sche
export async function pauseCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
try {
await disableCron(id);
- revalidatePath("/crons");
+ revalidatePath("/", "layout");
return { ok: true };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -80,7 +80,7 @@ export async function pauseCronAction(id: string): Promise<{ ok: boolean; error?
export async function resumeCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
try {
await enableCron(id);
- revalidatePath("/crons");
+ revalidatePath("/", "layout");
return { ok: true };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
@@ -90,7 +90,7 @@ export async function resumeCronAction(id: string): Promise<{ ok: boolean; error
export async function deleteCronAction(id: string): Promise<{ ok: boolean; error?: string }> {
try {
await removeCron(id);
- revalidatePath("/crons");
+ revalidatePath("/", "layout");
return { ok: true };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
diff --git a/src/server/actions/guardrails.ts b/src/server/actions/guardrails.ts
index 967d4820..0a4b3c00 100644
--- a/src/server/actions/guardrails.ts
+++ b/src/server/actions/guardrails.ts
@@ -35,7 +35,6 @@ export async function updateGuardrailsAction(
},
});
- revalidatePath("/settings");
revalidatePath("/", "layout");
}
diff --git a/src/server/actions/mcp.ts b/src/server/actions/mcp.ts
index c85e39b5..3f209f65 100644
--- a/src/server/actions/mcp.ts
+++ b/src/server/actions/mcp.ts
@@ -102,7 +102,7 @@ export async function disconnectMcpAction(input: {
} catch (err) {
return { ok: false, error: humanError(err) };
}
- revalidatePath("/connections");
+ revalidatePath("/", "layout");
return { ok: true };
}
diff --git a/src/server/actions/skills.ts b/src/server/actions/skills.ts
index 81139c4b..41f06b24 100644
--- a/src/server/actions/skills.ts
+++ b/src/server/actions/skills.ts
@@ -19,6 +19,9 @@ export async function setSkillEnabledAction(
// 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`);
+ // Path is project-scoped now; invalidating the layout tree is the safest
+ // cheap option since we don't have the project slug at this call site.
+ void agentSlug;
+ revalidatePath("/", "layout");
return { ok: true };
}