Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
4.9 KB
Raw Blame
"use client";

import { use, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { useRouter, usePathname } from "next/navigation";
import { WorkspaceSlugProvider, paths } from "@multica/core/paths";
import { workspaceBySlugOptions } from "@multica/core/workspace";
import { setCurrentWorkspace } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
import { NoAccessPage } from "@multica/views/workspace/no-access-page";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";
import { workspaceSlugFromPathname } from "@/lib/workspace-slug-from-pathname";

export default function WorkspaceLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ workspaceSlug: string }>;
}) {
  const { workspaceSlug } = use(params);
  const user = useAuthStore((s) => s.user);
  const isAuthLoading = useAuthStore((s) => s.isLoading);
  const router = useRouter();
  const pathname = usePathname();

  // Workspace routes require auth. If user is unauthenticated (initial visit
  // without a session, token expired, another tab logged out, etc.), bounce
  // to /login. Without this, the layout renders null and the user sees a
  // blank page stuck on /{slug}/...
  useEffect(() => {
    if (!isAuthLoading && !user) router.replace(paths.login());
  }, [isAuthLoading, user, router]);

  // Hard onboarding gate. Authenticated user but onboarded_at NULL means
  // they bypassed /onboarding (typed the URL, deeplink, etc.). Redirect
  // back so the questionnaire + Step 3 finish. The reverse gate lives in
  // `apps/web/app/(auth)/onboarding/page.tsx` — onboarded users hitting
  // /onboarding bounce out to their workspace. Together those two effects
  // make `onboarded_at` the single source of truth for "may access /<slug>/*".
  useEffect(() => {
    if (user && user.onboarded_at == null) {
      router.replace(paths.onboarding());
    }
  }, [user, router]);

  // Resolve workspace by slug through the shared workspace-list query. A
  // warm auth bootstrap reuses its cache; a cold route fetches it directly.
  // Keep it disabled until identity has been verified.
  const { data: workspace } = useQuery({
    ...workspaceBySlugOptions(workspaceSlug),
    enabled: !!user,
  });

  // Sync routed workspace identity during render so the first child request has
  // the correct workspace header. Gate this global write on the live pathname:
  // App Router can retain old layouts whose rerenders would otherwise switch the
  // singleton and realtime connection back to a stale workspace.
  if (workspace && workspaceSlug === workspaceSlugFromPathname(pathname)) {
    setCurrentWorkspace(workspaceSlug, workspace.id);
  }

  // Cookie write (last_workspace_slug) — proxy reads it on next page load
  // to redirect unauthenticated-URL hits to the user's last workspace.
  useEffect(() => {
    if (!workspace || typeof document === "undefined") return;
    const oneYear = 60 * 60 * 24 * 365;
    const secure = location.protocol === "https:" ? "; Secure" : "";
    document.cookie = `last_workspace_slug=${encodeURIComponent(workspaceSlug)}; path=/; max-age=${oneYear}; SameSite=Lax${secure}`;
  }, [workspace, workspaceSlug]);

  // Remember whether this slug has resolved before. Used below to avoid
  // flashing NoAccessPage during active workspace removal (delete, leave,
  // or realtime eviction) — in those cases the caller is navigating away
  // and we just need to hold null briefly.
  const hasBeenSeen = useWorkspaceSeen(workspaceSlug, !!workspace);

  const loadingIndicator = (
    <div className="flex h-svh items-center justify-center">
      <MulticaIcon mode="think" size={40} />
    </div>
  );

  if (isAuthLoading) return loadingIndicator;
  // Don't render children until workspace is resolved. useWorkspaceId()
  // throws when the list hasn't populated or the slug is unknown — gating
  // here makes that invariant hold for every descendant.
  // The selector returns undefined until the list has resolved, including
  // after an initial request failure. It returns null only when an
  // authoritative list does not contain this slug.
  if (workspace === undefined) return loadingIndicator;
  if (workspace === null) {
    // If we've resolved this slug before in this session, it was just
    // removed from our list (deleted/left/evicted). A navigate is almost
    // certainly in flight — render null to avoid a NoAccessPage flash.
    if (hasBeenSeen) return null;
    // Otherwise: the URL points at a workspace the user never had access
    // to. Show explicit feedback instead of silently redirecting. Doesn't
    // distinguish 404 vs 403 to avoid letting attackers enumerate slugs.
    return <NoAccessPage />;
  }

  return (
    <WorkspaceSlugProvider slug={workspaceSlug}>
      {children}
    </WorkspaceSlugProvider>
  );
}