Skip to content

AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).

19.0 KB
Raw Blame
"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useSession } from "next-auth/react";
import BriefDeliveryNotice, { useBriefDeliveryNotice } from "@/components/BriefDeliveryNotice";
import Briefing from "@/components/Briefing";
import Chat from "@/components/Chat";
import DebugPanel from "@/components/DebugPanel";
import Icon from "@/components/Icon";
import { PROFILE_COPY } from "@/components/company-profile/profileCopy";
import { useSessions } from "@/components/sessions/SessionsContext";
import { MobileBottomNav } from "@/components/shell/AppShell";
import AppSidebar from "@/components/shell/AppSidebar";
import { profileWording } from "@/components/shell/navConfig";
import { useWorkspace } from "@/components/workspace/WorkspaceContext";
import { useExecutiveStatus } from "@/components/executive/ExecutiveStatusContext";
import { GettingStartedCard, useGettingStarted } from "@/components/onboard/GettingStarted";
import { useFirstRunRedirect } from "@/components/onboard/useFirstRunRedirect";
import PausedBanner from "@/components/executive/PausedBanner";
import OverflowMenu from "@/components/ui/OverflowMenu";
import { ChatMessage, DebugEvent, getSessionMessages, updateSession } from "@/lib/api";
import { downloadChat } from "@/lib/downloadChat";
import { ASK_SUGGESTION, recall, remember, STORAGE_KEYS } from "@/lib/firstRun";
import { sessionTitle } from "@/lib/sessionChannel";
import Link from "next/link";
import { useRouter } from "next/navigation";

interface HealthData {
  company_profile_loaded: boolean;
  company_name?: string;
  status: string;
}

// Upper bound on a `?draft=` seed — a deep link pre-fills a prompt, not a document.
const MAX_DRAFT_PARAM_CHARS = 2000;

export default function HomePage() {
  const { data: session } = useSession();
  const firstName = session?.user?.name?.trim().split(/\s+/)[0];
  // What the profile is called here (a team's company; in solo, an owner's
  // business or anyone else's work), for the no-profile banner.
  const { mode: workspaceMode, role } = useWorkspace();

  const [health, setHealth] = useState<HealthData | null>(null);
  const [debugOpen, setDebugOpen] = useState(false);
  const [debugEvents, setDebugEvents] = useState<DebugEvent[]>([]);
  const activeTurnIdRef = useRef<string | null>(null);
  const [isTurnInFlight, setIsTurnInFlight] = useState(false);
  const { sessions, loaded: sessionsLoaded, refresh: refreshSessions } = useSessions();
  const [activeSessionId, setActiveSessionId] = useState<string | undefined>();
  const [activeMessages, setActiveMessages] = useState<ChatMessage[]>([]);
  // Words to find in the chat opened from a Chats-page search (`?find=`).
  const [activeFind, setActiveFind] = useState<string | undefined>();
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  // Briefing-first landing: default to "briefing" so opening the app shows
  // what's been happening, not an empty chat. Switches to "chat" when the
  // user picks a session, clicks "New chat", or clicks a briefing item to
  // continue the thread in conversation.
  const [mode, setMode] = useState<"briefing" | "chat">("briefing");
  // Seeded into Chat's input when the user enters chat mode from a briefing
  // item. Cleared on every mode transition so it doesn't leak between turns.
  const [pendingPrompt, setPendingPrompt] = useState<string | undefined>(undefined);
  // Companion to pendingPrompt: what peer memory records for the handoff turn.
  const [pendingMemoryText, setPendingMemoryText] = useState<string | undefined>(undefined);
  // Briefing handoffs auto-send pendingPrompt; a `?draft=` deep link only
  // pre-fills it, since the text comes from a URL the user didn't type.
  const [autoSubmitPending, setAutoSubmitPending] = useState(true);

  useEffect(() => {
    fetch("/api/backend/health")
      .then((r) => r.json())
      .then(setHealth)
      .catch(() => setHealth({ status: "error", company_profile_loaded: false }));
  }, []);

  // Bumped by every navigation handler below. A session load that resolves
  // after the user has already moved on (new chat, briefing, a hand-off, or
  // another session) sees a stale generation and is dropped instead of
  // yanking them into the old chat mid-turn.
  const selectGenRef = useRef(0);

  const handleSelectSession = useCallback(async (sessionId: string, find?: string) => {
    const gen = ++selectGenRef.current;
    try {
      const msgs = await getSessionMessages(sessionId);
      if (gen !== selectGenRef.current) return;
      setActiveFind(find);
      setActiveSessionId(sessionId);
      setActiveMessages(msgs);
      setDebugEvents([]);
      setMobileNavOpen(false);
      setMode("chat");
      setPendingPrompt(undefined);
      setPendingMemoryText(undefined);
    } catch {
      // ignore — session may not exist yet
    }
  }, []);

  const handleNewChat = useCallback(() => {
    selectGenRef.current++;
    setActiveSessionId(undefined);
    setActiveMessages([]);
    setDebugEvents([]);
    activeTurnIdRef.current = null;
    setIsTurnInFlight(false);
    setMobileNavOpen(false);
    setMode("chat");
    setPendingPrompt(undefined);
    setPendingMemoryText(undefined);
  }, []);

  // The getting-started checklist's Ask: a new chat with its suggested
  // question typed in, to edit or send.
  const handleAskFromChecklist = useCallback(() => {
    handleNewChat();
    setPendingPrompt(ASK_SUGGESTION);
    setAutoSubmitPending(false);
  }, [handleNewChat]);

  // Continue a briefing thread in chat — invoked when the user clicks a
  // Department card, proposal, or activity row. Switches mode to "chat"
  // and seeds the input with the briefing context. The user can edit
  // before sending, or just hit send.
  const handleContinueFromBriefing = useCallback((prompt: string, memoryText?: string) => {
    selectGenRef.current++;
    setActiveSessionId(undefined);
    setActiveMessages([]);
    setDebugEvents([]);
    setMode("chat");
    setPendingPrompt(prompt);
    setPendingMemoryText(memoryText);
    setAutoSubmitPending(true);
  }, []);

  // Reset to the briefing view from anywhere. Used by the sidebar
  // brandmark/header — clicking it returns home from a chat session.
  const handleBackToBriefing = useCallback(() => {
    selectGenRef.current++;
    setActiveSessionId(undefined);
    setActiveMessages([]);
    setDebugEvents([]);
    setMode("briefing");
    setPendingPrompt(undefined);
    setPendingMemoryText(undefined);
    setMobileNavOpen(false);
  }, []);

  const handleTurnComplete = useCallback((sessionId: string) => {
    // Only adopt a real id. A turn that ends without ever learning one (an
    // aborted stream) would otherwise set this to "", which <Chat> reads as
    // "the parent selected a different session" and clears the transcript
    // with — losing the very reply the stop was meant to keep. The in-flight
    // flag is cleared either way, so the Agent Activity panel never sticks.
    if (sessionId) setActiveSessionId(sessionId);
    setIsTurnInFlight(false);
    refreshSessions();
  }, [refreshSessions]);

  // Cross-route entries: from every inner route the sidebar and mobile
  // bottom nav link to `/?new=1` (New chat) and `/?session=<id>` (a
  // Recent chat, or a row on /chats). `/?new=1&draft=<text>` also seeds
  // the new chat's input without sending it (the Workflows page's "Talk it through in chat"). When either param is present on
  // mount, apply it and strip the query so a refresh doesn't reapply it.
  // A `session` id is held until the caller's own (owner-scoped) session
  // list has loaded, and opened only if that list contains it: the id comes
  // from the URL, and the per-session backend routes don't check ownership,
  // so a crafted link must not open — or send turns into — someone else's
  // conversation. It is also dropped if the user navigates first.
  //
  // Read directly from `window.location` rather than `useSearchParams`:
  // that hook opts the page out of static rendering in Next 15 unless
  // wrapped in <Suspense>, and the chat home is a heavy static page we
  // want to keep prerendered. The effect runs client-only anyway.
  const router = useRouter();
  const deepLinkRef = useRef<{ sessionId: string; gen: number; find?: string } | null>(null);
  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    const sessionParam = params.get("session");
    const draftParam = params.get("draft");
    // The last setup screen's first question: asked once, as if typed here.
    // It comes from session storage the setup screen wrote, never from the
    // URL, so it is the person's own and may send without a second tap.
    const firstQuestion = recall(STORAGE_KEYS.firstQuestion);
    if (firstQuestion) {
      remember(STORAGE_KEYS.firstQuestion, null);
      handleContinueFromBriefing(firstQuestion.slice(0, MAX_DRAFT_PARAM_CHARS));
      if (params.toString()) router.replace("/");
      return;
    }
    if (params.get("new") === "1") {
      handleNewChat();
      if (draftParam) {
        setPendingPrompt(draftParam.slice(0, MAX_DRAFT_PARAM_CHARS));
        setAutoSubmitPending(false);
      }
      router.replace("/");
    } else if (sessionParam) {
      deepLinkRef.current = {
        sessionId: sessionParam,
        gen: selectGenRef.current,
        find: params.get("find")?.slice(0, 200) || undefined,
      };
      router.replace("/");
    }
  }, [handleNewChat, handleContinueFromBriefing, router]);

  useEffect(() => {
    const pending = deepLinkRef.current;
    if (!pending || !sessionsLoaded) return;
    deepLinkRef.current = null;
    if (pending.gen !== selectGenRef.current) return;
    if (sessions.some((s) => s.session_id === pending.sessionId)) {
      void handleSelectSession(pending.sessionId, pending.find);
    }
  }, [sessions, sessionsLoaded, handleSelectSession]);

  // Group debug events by turn_id. When we see a new turn_id, reset the
  // panel. Track the current turn_id in a ref — state updater functions
  // must be pure, but React Strict Mode double-invokes them in dev, so
  // doing the "is this a new turn?" check inside `setDebugEvents`'s
  // updater would append the event twice.
  const handleDebugEvent = useCallback((event: DebugEvent) => {
    const incoming = event.turn_id ?? null;
    if (incoming && incoming !== activeTurnIdRef.current) {
      activeTurnIdRef.current = incoming;
      setDebugEvents([event]);
      setIsTurnInFlight(true);
    } else {
      setDebugEvents((prev) => [...prev, event]);
    }
    if (event.kind === "turn_complete" || event.kind === "turn_error") {
      setIsTurnInFlight(false);
    }
  }, []);

  const isOnboarded = health?.company_profile_loaded === true;
  const companyName = health?.company_name;
  const profileCopy = PROFILE_COPY[profileWording(workspaceMode, role.role_kind)];

  // First run: the owner lands on setup until a profile exists (unless they
  // chose to do it later), and the first days show a getting-started
  // checklist in the banner slot.
  const redirecting = useFirstRunRedirect(health?.company_profile_loaded);
  const gettingStarted = useGettingStarted(health?.company_profile_loaded, companyName);

  // The briefing's one banner slot shows the most important notice: paused,
  // then the getting-started checklist, then no profile, then a brief that
  // wasn't sent. With none, the briefing shows its quiet-day note there
  // instead.
  const { status: execStatus, unknown: execStatusUnknown } = useExecutiveStatus();
  const deliveryNotice = useBriefDeliveryNotice();
  const homeBanner = execStatus?.paused && !execStatusUnknown ? (
    <div className="overflow-hidden rounded-2xl border border-amber-500/30 [&>div]:border-b-0">
      <PausedBanner />
    </div>
  ) : gettingStarted.visible ? (
    <GettingStartedCard {...gettingStarted} onAsk={handleAskFromChecklist} />
  ) : !isOnboarded && health ? (
    <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-accent/25 bg-accent/5 px-4 py-3">
      <p className="text-[15px] text-fg-muted">{profileCopy.missingBanner}</p>
      <Link href="/onboard" className="text-sm font-semibold text-accent hover:underline whitespace-nowrap">
        Set up profile →
      </Link>
    </div>
  ) : deliveryNotice ? (
    <BriefDeliveryNotice notice={deliveryNotice} />
  ) : undefined;

  // The open chat, when it is one of the caller's own saved chats: its
  // Pin, Rename and Download sit in the header's ⋯ menu.
  const openChat =
    mode === "chat" && activeSessionId
      ? sessions.find((s) => s.session_id === activeSessionId)
      : undefined;
  // Bumped by the ⋯ menu's Share; Chat opens its Share panel on each bump.
  const [shareRequest, setShareRequest] = useState(0);
  const chatItems = openChat
    ? [
        {
          label: openChat.pinned_at ? "Unpin" : "Pin",
          onSelect: () => {
            updateSession(openChat.session_id, { pinned: !openChat.pinned_at })
              .then(refreshSessions)
              .catch(() => window.alert("Couldn't pin this chat."));
          },
        },
        {
          label: "Rename",
          onSelect: () => {
            const title = window.prompt("Name this chat", sessionTitle(openChat))?.trim();
            if (!title) return;
            updateSession(openChat.session_id, { title: title.slice(0, 120) })
              .then(refreshSessions)
              .catch(() => window.alert("Couldn't rename this chat."));
          },
        },
        {
          label: "Share",
          // Chat opens its Share panel, above the conversation.
          onSelect: () => setShareRequest((n) => n + 1),
        },
        {
          label: "Download",
          onSelect: () => {
            downloadChat(openChat.session_id).catch(() => window.alert("Couldn't download this chat."));
          },
        },
      ]
    : [];

  // Hold the page while the browser moves to setup.
  if (redirecting) return <div className="h-full bg-surface" />;

  return (
    <div className="flex h-full relative">
      {/* Mobile backdrop */}
      {mobileNavOpen && (
        <div
          className="fixed top-8 bottom-0 left-0 right-0 bg-black/50 z-30 md:hidden"
          onClick={() => setMobileNavOpen(false)}
          aria-hidden="true"
        />
      )}

      {/* Sidebar — the same one every route renders (AppShell uses it
          too); slides in on mobile, static on md+. On the home page its
          entries drive this page's in-memory state instead of navigating. */}
      <AppSidebar
        pathname="/"
        open={mobileNavOpen}
        onClose={() => setMobileNavOpen(false)}
        breakpoint="md"
        isOnboarded={health ? isOnboarded : undefined}
        companyName={companyName}
        home={{
          mode,
          activeSessionId,
          onBriefing: handleBackToBriefing,
          onNewChat: handleNewChat,
        }}
      />

      {/* Main */}
      <main className="flex-1 flex flex-col min-w-0">
        {/* Top bar */}
        <div className="h-14 border-b border-line flex items-center px-4 sm:px-6 flex-shrink-0 justify-between gap-2">
          <div className="flex items-center gap-2 min-w-0">
            {/* Hamburger — mobile only */}
            <button
              type="button"
              aria-label="Open menu"
              aria-expanded={mobileNavOpen}
              onClick={() => setMobileNavOpen(true)}
              className="md:hidden min-h-touch min-w-touch flex items-center justify-center text-fg-muted hover:text-fg cursor-pointer rounded-lg hover:bg-surface-overlay transition-colors"
            >
              <Icon name="menu" size="w-5 h-5" />
            </button>
            <span className="text-sm text-fg-muted font-medium truncate">
              {isOnboarded && companyName ? `${companyName} · Executive` : "Executive"}
            </span>
          </div>
          {/* Agent activity (the live trace of the Executive's turn) lives in
              this ⋯ menu; the panel itself opens on the right as before. Only
              in a chat: on the briefing there is no turn to trace and no chat
              to pin or rename, so the menu would hold nothing useful. */}
          {mode === "chat" && <OverflowMenu
            label="Home options"
            items={[
              ...chatItems,
              {
                label: debugOpen ? "Hide agent activity" : "Show agent activity",
                onSelect: () => setDebugOpen((o) => !o),
              },
            ]}
          />}
        </div>

        {/* In chat the notices stay as strips above the conversation; on
            the briefing they share one banner slot (see homeBanner). */}
        {mode === "chat" && <PausedBanner />}
        {mode === "chat" && !isOnboarded && health && (
          <div className="border-b border-line bg-accent/5 px-4 sm:px-6 py-2.5 flex items-center justify-between gap-3">
            <p className="text-sm text-fg-muted">{profileCopy.missingBanner}</p>
            <Link href="/onboard" className="text-sm text-accent hover:underline font-medium whitespace-nowrap cursor-pointer">
              Set up profile →
            </Link>
          </div>
        )}

        <div className="flex-1 min-h-0">
          {mode === "briefing" ? (
            <Briefing
              onContinue={handleContinueFromBriefing}
              showHeader
              firstName={firstName ?? undefined}
              banner={homeBanner}
            />
          ) : (
            // No `key` here — Chat handles undefined→sid session adoption
            // via its internal `adoptedSessionIdRef` so a just-streamed
            // reply isn't wiped when the parent echoes back the new
            // session id. Mode toggle (briefing ↔ chat) naturally
            // mounts/unmounts via the conditional render above, so
            // `initialInput` is consumed fresh on each chat entry.
            <Chat
              onDebugEvent={handleDebugEvent}
              initialMessages={activeMessages}
              initialSessionId={activeSessionId}
              initialFind={activeFind}
              initialInput={pendingPrompt}
              // Briefing handoffs (Discuss / Approve / Dismiss / Edit&Approve)
              // are commitments, not drafts, so they auto-fire the first
              // turn. A `?draft=` deep link also sets pendingPrompt but
              // clears autoSubmitPending, so it only pre-fills.
              autoSubmitInitialInput={Boolean(pendingPrompt) && autoSubmitPending}
              initialMemoryText={pendingMemoryText}
              onTurnComplete={handleTurnComplete}
              onTurnStart={() => setIsTurnInFlight(true)}
              shareRequest={shareRequest}
            />
          )}
        </div>

        {/* Mobile bottom nav — the chat home owns its own layout (it's
            exempt from AppShell), so it renders the shared bar itself to
            match every other route. "More" opens this page's own drawer. */}
        <MobileBottomNav pathname="/" hideFrom="md" />
      </main>

      {/* Debug panel */}
      {debugOpen && mode === "chat" && (
        <DebugPanel
          events={debugEvents}
          isLive={isTurnInFlight}
          onClose={() => setDebugOpen(false)}
        />
      )}

    </div>
  );
}