ubiquitous-invention/apps/web/app/(app)/[workspaceSlug]/docs/[docId]/page.tsx
Randall Stillwell c582d621ce multi-tenancy: promote workspaces to top-level table
Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`,
which made it impossible to put a real RLS-friendly tenant boundary on the schema
or to give each workspace a stable URL slug. This commit:

- Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook).
- Migrates the 8 anchor tables (objects, workspace_members, object_type_defs,
  property_definitions, templates, forms, markdown_backlog_items,
  cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`,
  with a hand-augmented data-copy migration that preserves IDs and slug-collision-
  proofs on backfill.
- Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper
  that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All
  tenant-scoped routers (objects, types, properties, templates, forms, search,
  ai, relations, favorites) now flow through it.
- Updates the web app to pass `workspace` slugs from the URL (or store) instead
  of the old `workspaceId`, including a workspace-sync layer that rewrites
  /<UUID>/... links to /<slug>/...
- Updates the MCP tools (list_objects, create_object, search_objects) and the
  workspace://{handle}/tree resource to accept either a slug or UUID so existing
  agents keep working.
- Adds a Create Workspace dialog and a Workspace Settings page (rename + slug
  rename with redirect, owner-only archive).

Verified locally against a fresh Postgres: migration applies cleanly, slug
uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution
works in both directions, and ON DELETE CASCADE cleans up child rows in the
correct workspace only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 23:02:55 -05:00

160 lines
4.8 KiB
TypeScript

"use client";
import * as React from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useSession } from "next-auth/react";
import { ChevronRight } from "lucide-react";
import { CollaborativeBlockEditor } from "@/components/editor";
import { api } from "@/lib/trpc";
import { Input } from "@/components/ui/input";
function contentToHtml(content: unknown): string {
if (content == null) return "<p></p>";
if (typeof content === "string") return content || "<p></p>";
if (
typeof content === "object" &&
content !== null &&
"html" in content &&
typeof (content as { html: unknown }).html === "string"
) {
return (content as { html: string }).html || "<p></p>";
}
return "<p></p>";
}
export default function DocEditorPage() {
const params = useParams();
const { data: session } = useSession();
const utils = api.useUtils();
const workspaceSlug =
typeof params?.workspaceSlug === "string" ? params.workspaceSlug : undefined;
const docId = typeof params?.docId === "string" ? params.docId : undefined;
const docQuery = api.objects.getById.useQuery(
{ id: docId!, workspace: workspaceSlug! },
{ enabled: Boolean(docId) && Boolean(workspaceSlug) },
);
const doc = docQuery.data as
| { id: string; title: string; content: unknown; type: string }
| undefined;
const [titleDraft, setTitleDraft] = React.useState("");
React.useEffect(() => {
if (doc?.title != null) setTitleDraft(doc.title);
}, [doc?.title]);
const saveContentTimeoutRef = React.useRef<ReturnType<typeof setTimeout> | null>(
null,
);
React.useEffect(
() => () => {
if (saveContentTimeoutRef.current) {
clearTimeout(saveContentTimeoutRef.current);
}
},
[],
);
const updateMutation = api.objects.update.useMutation({
onSuccess: async (_row, variables) => {
if (!workspaceSlug) return;
await utils.objects.getById.invalidate({ id: variables.id, workspace: workspaceSlug });
void utils.objects.list.invalidate({ workspace: workspaceSlug });
},
});
const scheduleContentSave = React.useCallback(
(html: string) => {
if (!docId || !workspaceSlug) return;
if (saveContentTimeoutRef.current) {
clearTimeout(saveContentTimeoutRef.current);
}
saveContentTimeoutRef.current = setTimeout(() => {
saveContentTimeoutRef.current = null;
updateMutation.mutate({ workspace: workspaceSlug, id: docId, content: html });
}, 500);
},
[docId, workspaceSlug, updateMutation],
);
const handleTitleBlur = () => {
if (!docId || !doc || !workspaceSlug) return;
const next = titleDraft.trim();
if (next.length === 0) {
setTitleDraft(doc.title);
return;
}
if (next === doc.title) return;
updateMutation.mutate({ workspace: workspaceSlug, id: docId, title: next });
};
if (!docId || !workspaceSlug) {
return (
<div className="mx-auto max-w-4xl px-8 py-10 text-sm text-muted-foreground">
Invalid document link.
</div>
);
}
if (docQuery.isPending) {
return (
<div className="mx-auto max-w-4xl px-8 py-10">
<div className="animate-pulse space-y-4">
<div className="h-4 w-48 rounded bg-muted" />
<div className="h-10 w-full max-w-xl rounded-md bg-muted" />
<div className="h-[320px] w-full rounded-xl bg-muted" />
</div>
</div>
);
}
if (docQuery.isError || !doc) {
return (
<div className="mx-auto max-w-4xl px-8 py-10 text-sm text-muted-foreground">
Could not load this document.
</div>
);
}
return (
<div className="mx-auto max-w-4xl px-8 py-10">
<nav
className="mb-6 flex flex-wrap items-center gap-1 text-sm text-muted-foreground"
aria-label="Breadcrumb"
>
<Link
href={`/${workspaceSlug}/docs`}
className="hover:text-foreground"
>
Documents
</Link>
<ChevronRight className="size-4 shrink-0 opacity-60" />
<span className="min-w-0 truncate text-foreground">{doc.title}</span>
</nav>
<Input
value={titleDraft}
onChange={(e) => setTitleDraft(e.target.value)}
onBlur={handleTitleBlur}
className="mb-6 border-0 border-b border-transparent bg-transparent px-0 text-3xl font-bold tracking-tight shadow-none focus-visible:border-border focus-visible:ring-0"
placeholder="Untitled"
aria-label="Document title"
/>
<CollaborativeBlockEditor
key={doc.id}
documentId={doc.id}
userName={session?.user?.name ?? undefined}
content={contentToHtml(doc.content)}
onChange={scheduleContentSave}
placeholder="Start typing, or use '/' for commands..."
/>
</div>
);
}