Skip to content

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

Go
24.4 KB
Raw Blame
"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { ArrowLeft, Bot, MessageSquare, Plus } from "@multica/ui/icons";
import { toast } from "sonner";
import { Button } from "@multica/ui/components/ui/button";
import { IconButton } from "@multica/ui/components/common/icon-button";
import { useIsCompact } from "@multica/ui/hooks/use-mobile";
import { cn } from "@multica/ui/lib/utils";
import { useReducedMotion } from "@multica/core/appearance";
import { useRequiredWorkspaceSlug, useWorkspacePaths } from "@multica/core/paths";
import { getCurrentSlug } from "@multica/core/platform";
import { useChatStore } from "@multica/core/chat";
import { chatQuickActionsPendingOptions } from "@multica/core/chat/queries";
import { useRegenerateChatQuickActions } from "@multica/core/chat/mutations";
import { useQuickActionsPendingTimeout } from "@multica/core/chat/use-quick-actions-pending-timeout";
import { useQuickActionsFailureToast } from "./components/use-quick-actions-failure-toast";
import { useQuery } from "@tanstack/react-query";
import type { Agent, ChatSession } from "@multica/core/types";
import { CollectionPageState } from "../layout/collection-page";
import { CollapsedNavTrigger, PageHeader } from "../layout/page-header";
import { PanelHeader } from "../layout/panel-nav";
import { useListColumnCollapsed } from "../layout/app-shell-context";
import { ListColumn } from "../layout/list-column";
import { useNavigation } from "../navigation";
import { useT } from "../i18n";
import {
  ChatMessageList,
  ChatMessageSkeleton,
  type ChatMessageEnterTransition,
} from "./components/chat-message-list";
import { ChatInput } from "./components/chat-input";
import { ChatQueue } from "./components/chat-queue";
import { ChatWakeupStrip, useChatWakeups } from "./components/chat-wakeups";
import { ChatThreadList } from "./components/chat-thread-list";
import { ChatSessionHeader } from "./components/chat-session-header";
import { EmptyState } from "./components/chat-empty-state";
import { NewChatButton } from "./components/new-chat-button";
import { useChatController } from "./components/use-chat-controller";
import { useChatAnnotations } from "./components/use-chat-annotations";
import { useChatSessionPrefetch } from "./components/use-chat-session-prefetch";
import { OfflineBanner } from "./components/offline-banner";
import { NoAgentBanner } from "./components/no-agent-banner";
import { ArchivedAgentBanner } from "./components/archived-agent-banner";
import { AgentAccessRevokedBanner } from "./components/agent-access-revoked-banner";
import { RuntimeRequiredBanner } from "./components/runtime-required-banner";
import { ChatAppRequests } from "../common/app-requests";
import { useRegisterCommandBarContext } from "../search/register-context";
import { CollapsibleSlot } from "./components/collapsible-slot";

/**
 * Chat tab — the first-class two-pane surface (thread list on the left,
 * conversation on the right), mirroring the Inbox page layout. Shares all
 * conversation logic with the floating FAB via `useChatController`; the
 * left rail reuses `ChatThreadList`.
 *
 * Selection is URL-addressable via `?session=<id>` so a thread can be
 * deep-linked, opened from a notification, and survive refresh. The chat
 * store's `activeSessionId` stays the source of truth (both surfaces read
 * it); the URL is kept in sync in both directions. `?agent=<id>` is the
 * complementary one-shot deep link for a NEW chat: it starts a fresh compose
 * bound to that agent and is then stripped from the URL.
 *
 * Starting a chat is where the agent is chosen: the header ⊕ opens an agent
 * picker (see NewChatButton), so the compose box no longer needs its own
 * agent selector. Unlike the FAB, this page passes no `contextItems` to
 * `ChatInput`, so its `@` mentions fall back to manual search (issue-comment
 * style).
 */
export function ChatPage() {
  const { t } = useT("chat");
  const { pathname, searchParams, push, replace } = useNavigation();
  const workspaceSlug = useRequiredWorkspaceSlug();
  const wsPaths = useWorkspacePaths();
  // App Router can retain this page after navigation. Once the URL belongs
  // to another route, this instance must stop reconciling shared chat state.
  // Also check the live workspace mirror in each effect: the incoming layout
  // can rehydrate the store before this page observes the destination URL.
  const isCurrentChatRoute = pathname === wsPaths.chat();
  const isCompact = useIsCompact();

  const isSurfaceActive = isCurrentChatRoute && getCurrentSlug() === workspaceSlug;
  const c = useChatController({
    isActive: isSurfaceActive,
  });
  const prefetchSession = useChatSessionPrefetch({
    wsId: c.wsId,
    sessions: c.sessions,
    activeSessionId: c.activeSessionId,
    isActive: isSurfaceActive,
  });
  const reduceMotion = useReducedMotion();
  const { data: quickActionsPending = null } = useQuery(
    chatQuickActionsPendingOptions(c.activeSessionId ?? ""),
  );
  // Drop a stuck pending marker (dead daemon / failed supplement) so the pill
  // spinner stops and a later refresh starts clean (MUL-5149).
  useQuickActionsPendingTimeout(c.activeSessionId ?? null, quickActionsPending);
  // Toast when an accepted refresh later fails in the daemon (async half).
  useQuickActionsFailureToast(c.activeSessionId ?? null);
  const wakeups = useChatWakeups(c.activeSessionId);
  const regenerateQuickActions = useRegenerateChatQuickActions();
  const annotations = useChatAnnotations({
    sessionId: c.activeSessionId,
    agentName: c.activeAgent?.name,
    enabled: !c.isSessionArchived && !c.isAgentArchived && !c.isAgentAccessRevoked && c.isAgentRuntimeBound && !c.noAgent,
  });
  const urlSession = searchParams.get("session") || null;
  const urlAgent = searchParams.get("agent") || null;

  // "Composing a brand-new chat" — the user hit ⊕ but hasn't sent yet, so no
  // session exists. At compact widths this decides list-vs-conversation; on desktop the
  // conversation pane is always mounted so it only needs to reset itself once a
  // real session takes over.
  const [composingNew, setComposingNew] = useState(false);
  useEffect(() => {
    // Read the LIVE store value for the same reason as the session sync
    // effects below: under StrictMode's double-invoke this effect replays
    // with the render-captured snapshot, and a stale non-null session (a
    // persisted chat the URL→store effect already cleared) would revert the
    // composingNew=true that the later `?agent=` intent effect just set.
    if (useChatStore.getState().activeSessionId) setComposingNew(false);
  }, [c.activeSessionId]);

  // Two-way sync between the URL (`?session=`) and the chat store's
  // activeSessionId. Both effects read the LIVE store value via
  // `useChatStore.getState()` rather than the render-captured `c.activeSessionId`.
  // That is what keeps them from fighting on mount: a naive mirror effect fires
  // with the stale (null) snapshot and "corrects" the URL by stripping the
  // session before the URL→store effect has applied — breaking deep links and
  // making selection / new-chat feel unresponsive. Reading getState() sees the
  // value the sibling effect just wrote, so the reconciliation converges in one
  // pass and is idempotent under StrictMode's double-invoke.

  // URL → store: deep link, refresh, notification click, back/forward.
  useEffect(() => {
    if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;
    if (urlSession !== useChatStore.getState().activeSessionId) {
      c.setActiveSession(urlSession);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reconcile URL/route changes, not store updates
  }, [isCurrentChatRoute, workspaceSlug, urlSession]);

  // store → URL: thread selection, "new chat", and sessions created by sending.
  useEffect(() => {
    if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;
    const live = useChatStore.getState().activeSessionId;
    const current = searchParams.get("session") || null;
    if (live !== current) {
      const base = wsPaths.chat();
      replace(live ? `${base}?session=${live}` : base);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reconcile store/route changes, not URL updates
  }, [isCurrentChatRoute, workspaceSlug, c.activeSessionId]);

  const listCollapsed = useListColumnCollapsed();

  // `?agent=` intent bookkeeping. The ref holds the param value already
  // consumed (or superseded) so the effect below fires at most once per deep
  // link — it also bridges the async window between replace() and the
  // searchParams actually dropping the param. Any explicit user action must
  // supersede a still-pending intent: agent/member queries can resolve late,
  // and a deferred intent firing after the user picked a thread (or started
  // another chat) would clobber that choice.
  const consumedAgentIntent = useRef<string | null>(null);
  const supersedeAgentIntent = () => {
    if (urlAgent) consumedAgentIntent.current = urlAgent;
  };

  // Directional hint for in-page session transitions: archiving the current
  // thread plays a subtle directional glide aligned with list order ("next" or
  // "prev"); direct clicks or URL switches use a gentle opacity fade. Initial
  // page load has no transition so first paint lands immediately.
  const [sessionTransition, setSessionTransition] = useState<{
    sessionId: string | null;
    direction: ChatMessageEnterTransition;
  } | null>(null);
  const [prevActiveSessionId, setPrevActiveSessionId] = useState<string | null>(
    c.activeSessionId,
  );
  if (c.activeSessionId !== prevActiveSessionId) {
    setPrevActiveSessionId(c.activeSessionId);
    if (
      prevActiveSessionId !== null &&
      c.activeSessionId !== null &&
      sessionTransition?.sessionId !== c.activeSessionId
    ) {
      setSessionTransition({ sessionId: c.activeSessionId, direction: "fade" });
    }
  }
  const activeTransition: ChatMessageEnterTransition | null =
    sessionTransition?.sessionId === c.activeSessionId
      ? sessionTransition.direction
      : null;

  const handleSelect = (session: ChatSession) => {
    supersedeAgentIntent();
    if (session.id !== c.activeSessionId) {
      setSessionTransition({ sessionId: session.id, direction: "fade" });
    }
    c.handleSelectSession(session);
    setComposingNew(false);
  };

  // Single archive path for both entry points (thread-list row + conversation
  // header). When the archived chat is the one in view, move the pane off it:
  // on desktop advance to the next chat (Inbox-style); when compact drop back to
  // the list, which reads more naturally than being thrown into an unrelated
  // conversation full-screen. Archiving any other chat leaves the view put.
  const handleArchive = (session: ChatSession) => {
    supersedeAgentIntent();
    if (session.id === c.activeSessionId) {
      if (isCompact) {
        setSessionTransition(null);
        c.setActiveSession(null);
        setComposingNew(false);
      } else {
        const result = c.advanceSelectionAfterArchive(session);
        if (result?.moved) {
          setSessionTransition({
            sessionId: result.targetSessionId,
            direction: result.direction ?? "fade",
          });
        }
      }
    }
    c.archiveSession(session.id);
  };

  const startNewChat = (agent: Agent | null) => {
    // A manual ⊕ pick outranks a pending deep link; when called FROM the
    // intent effect the ref is already set to this param, so this is a no-op.
    supersedeAgentIntent();
    setSessionTransition(null);
    if (agent) c.handleStartNewChat(agent);
    else c.handleNewChat();
    setComposingNew(true);
  };

  const changeProjectContext = (projectId: string | null) => {
    if (projectId === c.activeProjectId) return;
    c.handleProjectChange(projectId);
    // Removing a project stays in the current conversation. Choosing a
    // project for an existing conversation starts a clean session, and a
    // compact layout must stay in the compose pane after activeSessionId is
    // cleared.
    if (!c.currentSession || projectId !== null) setComposingNew(true);
  };

  // The command bar calls the page's own handlers so archiving or re-scoping
  // from it moves the pane exactly like the header controls do.
  const commandBarHandlersRef = useRef({ handleArchive, changeProjectContext });
  useEffect(() => {
    commandBarHandlersRef.current = { handleArchive, changeProjectContext };
  });
  const commandBarSession = c.currentSession ?? null;
  useRegisterCommandBarContext(
    useMemo(
      () =>
        commandBarSession
          ? {
              kind: "chat",
              session: commandBarSession,
              archive: (session: ChatSession) => commandBarHandlersRef.current.handleArchive(session),
              changeProject: (projectId: string | null) =>
                commandBarHandlersRef.current.changeProjectContext(projectId),
            }
          : null,
      [commandBarSession],
    ),
  );

  // URL → new chat: `?agent=<id>` is the deep link used by "DM" entry points
  // (e.g. the agent detail page) to land on a fresh compose bound to that
  // agent. The permission-filtered agent list loads async, so the intent is
  // consumed on the render where the agent resolves, then the param is
  // stripped so refresh / the session sync above don't replay it. The ref
  // resets once the param is gone so a later identical deep link fires again.
  // A settled miss (access revoked, agent archived, bad id) is a denial: it
  // explains itself with a toast and consumes the intent so a later refetch
  // that surfaces the agent cannot start a chat without a fresh click. While
  // the queries are still loading the intent simply stays pending.
  useEffect(() => {
    if (!isCurrentChatRoute || getCurrentSlug() !== workspaceSlug) return;
    if (!urlAgent) {
      consumedAgentIntent.current = null;
      return;
    }
    if (consumedAgentIntent.current === urlAgent) return;
    const agent = c.availableAgents.find((a) => a.id === urlAgent);
    if (agent) {
      consumedAgentIntent.current = urlAgent;
      startNewChat(agent);
      replace(wsPaths.chat());
      return;
    }
    if (c.agentsSettled) {
      consumedAgentIntent.current = urlAgent;
      toast.error(t(($) => $.page.agent_link_no_access));
      replace(wsPaths.chat());
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- consume when the URL param or the resolving agent list changes
  }, [isCurrentChatRoute, workspaceSlug, urlAgent, c.availableAgents, c.agentsSettled]);

  const newChatButton = (
    <NewChatButton
      agents={c.availableAgents}
      userId={c.user?.id}
      onStart={startNewChat}
      side="bottom"
    />
  );

  const listHeader = (
    <PanelHeader as="h1" title={t(($) => $.page.title)} leading={<CollapsedNavTrigger />}>
      {newChatButton}
    </PanelHeader>
  );

  const listBody = (
    <div className="min-h-0 flex-1 px-2 py-1">
      <ChatThreadList
        sessions={c.sessions}
        agents={c.agents}
        activeSessionId={c.activeSessionId}
        onSelectSession={handleSelect}
        onArchive={handleArchive}
        onPrefetchSession={prefetchSession}
      />
    </div>
  );

  const compactConversation = isCompact && (!!c.activeSessionId || composingNew);
  // Nothing to talk to and nothing to reread: the composer would only be a
  // disabled box, so the page explains the prerequisite instead.
  const noAgentPage = c.noAgent && c.sessions.length === 0;
  const noAgentState = (
    <CollectionPageState
      icon={Bot}
      title={t(($) => $.page.no_agent_title)}
      description={t(($) => $.page.no_agent_description)}
      actions={
        <Button size="sm" onClick={() => push(wsPaths.newAgent())}>
          <Plus aria-hidden="true" />
          {t(($) => $.page.no_agent_action)}
        </Button>
      }
    />
  );
  const backToList = () => {
    setSessionTransition(null);
    c.setActiveSession(null);
    setComposingNew(false);
  };

  // The conversation pane: message list / skeleton / empty above a persistent
  // banner + input. Identical composition to the floating window's body, so a
  // brand-new chat (no active session) shows the agent-aware empty state + input.
  // No compose-box agent selector — the agent is fixed when the chat starts.
  // `@container`: the conversation column's gutter (CHAT_GUTTER) widens with
  // THIS pane, which the user resizes independently of the browser window.
  const queuedTasks = c.pendingTask?.queued_tasks ?? [];
  const statusBanner = c.isAgentAccessRevoked ? (
    <AgentAccessRevokedBanner agentName={c.activeAgent?.name} />
  ) : c.noAgent ? (
    <NoAgentBanner />
  ) : c.isAgentArchived ? (
    <ArchivedAgentBanner agentName={c.activeAgent?.name} />
  ) : !c.isAgentRuntimeBound && c.activeAgent ? (
    <RuntimeRequiredBanner
      agentId={c.activeAgent.id}
      agentName={c.activeAgent.name}
    />
  ) : c.availability === "offline" || c.availability === "unstable" ? (
    <OfflineBanner agentName={c.activeAgent?.name} availability={c.availability} />
  ) : null;
  const hasActiveWakeup =
    !!c.activeSessionId && wakeups.some((w) => w.status === "active");
  const emptyEnterClass =
    activeTransition && !reduceMotion
      ? activeTransition === "next"
        ? "animate-chat-enter-next"
        : activeTransition === "prev"
          ? "animate-chat-enter-prev"
          : "animate-chat-enter-fade"
      : undefined;
  const conversation = (
    <div className="flex flex-1 flex-col min-h-0 @container">
      {c.currentSession ? (
        <ChatSessionHeader
          leading={
            compactConversation ? (
              <IconButton
                label={t(($) => $.page.title)}
                tooltipSide="bottom"
                className="text-muted-foreground"
                onClick={backToList}
              >
                <ArrowLeft />
              </IconButton>
            ) : listCollapsed ? (
              <CollapsedNavTrigger />
            ) : undefined
          }
          session={c.currentSession}
          agent={c.activeAgent}
          onArchive={handleArchive}
        />
      ) : !isCompact && !listCollapsed && c.activeSessionId ? (
        // Keep the 48px header band reserved while the active session row
        // resolves from the sessions query so the message area never drops
        // down when metadata lands. When `listCollapsed` is true, the desktop
        // wrapper below already renders a 48px `<PageHeader>` above `conversation`.
        <PageHeader leading={false} className="bg-background">
          {null}
        </PageHeader>
      ) : null}
      {c.showSkeleton ? (
        <ChatMessageSkeleton />
      ) : c.hasMessages ? (
        <ChatMessageList
          key={c.activeSessionId}
          revealKey={c.activeSessionId}
          enterTransition={activeTransition}
          messages={c.messages}
          pendingTask={c.pendingTask}
          availability={c.availability}
          firstItemIndex={c.firstItemIndex}
          hasOlderMessages={c.hasOlderMessages}
          isFetchingOlderMessages={c.isFetchingOlderMessages}
          onLoadOlderMessages={() => void c.fetchOlderMessages()}
          onQuickAction={(action) => c.handleSend(action.prompt)}
          quickActionsDisabled={
            !!c.pendingTaskId ||
            c.isSessionArchived ||
            c.isAgentArchived ||
            c.isAgentAccessRevoked ||
            !c.isAgentRuntimeBound ||
            c.noAgent
          }
          onRegenerateQuickActions={(message) =>
            c.activeSessionId
              ? regenerateQuickActions.mutateAsync({
                  sessionId: c.activeSessionId,
                  messageId: message.id,
                })
              : undefined
          }
          quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}
          annotations={annotations}
          wakeups={wakeups}
        />
      ) : (
        <div
          key={c.activeSessionId ?? "new"}
          className={cn("flex min-h-0 flex-1 flex-col overflow-hidden", emptyEnterClass)}
        >
          <EmptyState
            agent={c.activeAgent}
            hasSessions={c.sessions.length > 0}
            onPickPrompt={c.sendConversationStarter}
          />
        </div>
      )}

      <CollapsibleSlot slotKey="chat-status-banner" visible={statusBanner !== null}>
        {statusBanner}
      </CollapsibleSlot>

      <div className="px-4">
        <ChatAppRequests sessionId={c.activeSessionId} />
      </div>

      <CollapsibleSlot slotKey="chat-wakeup-slot" visible={hasActiveWakeup}>
        <ChatWakeupStrip sessionId={c.activeSessionId} wakeups={wakeups} />
      </CollapsibleSlot>

      <ChatQueue
        tasks={queuedTasks}
        wakeups={wakeups}
        headStatus={c.pendingTask?.status}
        onSendNow={c.handleSendQueuedTaskNow}
        sendNowDisabled={c.isAgentAccessRevoked}
        onEdit={c.handleEditQueuedTask}
        onRemove={c.handleRemoveQueuedTask}
        onClear={c.handleClearQueuedTasks}
      />

      <ChatInput
        onSend={c.handleSend}
        restoreDraftRequest={c.restoreDraftRequest}
        conversationStarterRequest={c.conversationStarterRequest}
        onConversationStarterApplied={c.handleConversationStarterApplied}
        onRestoreDraftApplied={c.handleRestoreDraftApplied}
        uploadEnabled={c.uploadEnabled && !c.isAgentAccessRevoked}
        onStop={c.handleStop}
        isRunning={!!c.pendingTaskId}
        allowSubmitWhileRunning={c.pendingTask?.supports_queue === true}
        canSteerWhileRunning={c.pendingTask?.can_supplement}
        disabled={
          c.isSessionArchived ||
          c.isAgentArchived ||
          c.isAgentAccessRevoked ||
          !c.isAgentRuntimeBound
        }
        noAgent={c.noAgent}
        agentArchived={c.isAgentArchived}
        agentAccessRevoked={c.isAgentAccessRevoked}
        agentRuntimeRequired={!c.isAgentRuntimeBound}
        agentName={c.activeAgent?.name}
        projects={c.projects}
        projectId={c.activeProjectId}
        projectContextUnsupported={c.projectContextUnsupported}
        onProjectChange={changeProjectContext}
        isProjectUpdating={c.isProjectUpdating}
        focusRequest={c.focusInputRequest}
        annotations={annotations}
      />
    </div>
  );

  // -- Compact: list / conversation toggle -----------------------------------
  if (isCompact) {
    if (compactConversation) {
      // An open session carries the way back in its own header; a new chat
      // has no session header yet, so it gets a bar of its own.
      return (
        <div className="flex flex-1 flex-col min-h-0">
          {!c.currentSession && (
            <div className="flex h-12 shrink-0 items-center border-b px-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={backToList}
                className="gap-1.5 text-muted-foreground"
              >
                <ArrowLeft className="h-4 w-4" />
                {t(($) => $.page.title)}
              </Button>
            </div>
          )}
          {conversation}
        </div>
      );
    }
    return (
      <div className="flex flex-1 flex-col min-h-0">
        {listHeader}
        {noAgentPage ? (
          noAgentState
        ) : (
          <div className="flex min-h-0 flex-1 flex-col">{listBody}</div>
        )}
      </div>
    );
  }

  // -- Desktop: list column + conversation. The conversation pane appears only once
  // there is a chat target — an open thread or a new chat whose agent was just
  // picked via ⊕. With nothing selected there is no agent, so we show a neutral
  // prompt instead of an orphaned compose box. -------------------------------
  const hasTarget = !!c.activeSessionId || composingNew;
  return (
    <div className="flex min-h-0 flex-1">
      <ListColumn collapsed={listCollapsed} width="list">
        {listHeader}
        <div className="flex min-h-0 flex-1 flex-col">{listBody}</div>
      </ListColumn>
      <div className="flex h-full min-h-0 min-w-0 flex-1 flex-col">
        {listCollapsed && !c.currentSession && <PageHeader>{newChatButton}</PageHeader>}
        {hasTarget ? (
          conversation
        ) : noAgentPage ? (
          noAgentState
        ) : (
          <div
            className={cn(
              "flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-muted-foreground",
              activeTransition && !reduceMotion && "animate-chat-enter-fade",
            )}
          >
            <MessageSquare className="h-10 w-10 text-faint-foreground" />
            <p className="text-body">{t(($) => $.page.select_prompt)}</p>
          </div>
        )}
      </div>
    </div>
  );
}