Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

11.0 KB
Raw Blame
import { memo, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  messageHasTranscriptContent,
  vendorAccountOmitsSessionModel,
} from "../lib/chat-launch-error";
import { Composer } from "./Composer";
import { HomeMascotLogo } from "./HomeMascotLogo";
import { HomeProjectSwitcher } from "./HomeProjectSwitcher";
import { IconX } from "./icons";
import { TooltipButton } from "./ui";
import { SessionPane } from "./SessionPane";
import { ConversationWidthHandles } from "./ConversationWidthHandles";
import { useAppStore } from "../stores/app-store";
import { headPermission } from "../lib/pending-permissions";
import { headAsk } from "../lib/pending-asks";

import { isRemoteSession } from "../lib/remote-session-safety";
const StableComposer = memo(Composer);

function i18nHasError(t: (key: string) => string, code: string) {
  const key = `errors.${code}`;
  return t(key) !== key;
}

function projectName(path?: string | null, name?: string | null) {
  if (name) return name;
  if (!path) return null;
  const parts = path.split(/[/\\]/).filter(Boolean);
  return parts[parts.length - 1] || path;
}

/**
 * Top-level chat page surface.
 *
 * Holds the retained session panes (ADR 0137). Every session the user has
 * visited recently keeps its own mounted `SessionPane`, bounded by
 * `RETAINED_SESSION_PANE_LIMIT`; switching reveals the destination pane and
 * hides the others, so no transcript is rebuilt and no frame is dimmed. Only a
 * session with no retained pane has to wait, and that wait is marked by the
 * progress track alone while the current pane stays on screen.
 *
 * The composer is mounted once for the surface rather than per branch: it owns
 * per-session drafts already, and remounting it on every switch discarded its
 * measured metrics and focus.
 */
export const ChatSurface = memo(function ChatSurface({
  visible = true,
}: {
  visible?: boolean;
}) {
  const { t } = useTranslation();
  const activeSessionId = useAppStore((state) => state.activeSessionId);
  const selectingSessionId = useAppStore((state) => state.selectingSessionId);
  const retainedSessionIds = useAppStore((state) => state.retainedSessionIds);
  const messages = useAppStore((state) => state.messages);
  // Only the error layer's retry affordance needs the run state here; each pane
  // reads its own session's flag.
  const isRunning = useAppStore((state) => state.isRunning);
  const workspace = useAppStore((state) => state.workspace);
  const error = useAppStore((state) => state.error);
  const errorCode = useAppStore((state) => state.errorCode);
  const errorRetriable = useAppStore((state) => state.errorRetriable);
  const [hiddenVendorModelKey, setHiddenVendorModelKey] = useState<string | null>(
    null,
  );
  const providers = useAppStore((state) => state.providers);
  const activeSession = useAppStore((state) =>
    state.activeSessionId
      ? state.sessions.find((session) => session.id === state.activeSessionId)
      : undefined,
  );

  // A pending permission or ask is itself transcript content, so the empty
  // state must yield to it. Each pane subscribes to its own queues; the surface
  // only needs the visible session's to choose between empty state and panes.
  const activePermission = useAppStore((state) =>
    state.activeSessionId
      ? headPermission(state.pendingPermissions, state.activeSessionId)
      : undefined,
  );
  const askPending = useAppStore((state) =>
    Boolean(
      state.activeSessionId &&
        headAsk(state.pendingAsks, state.activeSessionId),
    ),
  );

  // The project the empty home names: the session on screen decides when there
  // is one, because a temporary session deliberately belongs to no project. A
  // project the user has just opened has no session yet, so its active
  // workspace names the hero instead of falling back to the generic title.
  const heroProject = useMemo(() => {
    if (isRemoteSession(activeSession)) {
      return projectName(activeSession?.remoteWorkspaceLabel) ?? activeSession?.remoteHostLabel ?? null;
    }
    const path = activeSession
      ? activeSession.projectPath?.trim()
      : workspace?.path?.trim();
    return path ? projectName(path, workspace?.name) : null;
  }, [activeSession, workspace?.path, workspace?.name]);
  const isTemporarySession = Boolean(
    activeSessionId && activeSession && !isRemoteSession(activeSession) && !activeSession.projectPath?.trim(),
  );
  const emptyTitleParts = useMemo(() => {
    const marker = "__PROJECT__";
    const template = t("chat.emptyTitleInProject", { project: marker });
    const [before = "", after = ""] = template.split(marker);
    return { before, after };
  }, [t]);
  // A temporary home names its scope the same way: the scope word ("temporarily")
  // is the switcher, so joining a project needs no extra control (#2455).
  const temporaryTitleParts = useMemo(() => {
    const marker = "__SCOPE__";
    const template = t("chat.emptyTitleTemporaryScoped", { scope: marker });
    const [before = "", after = ""] = template.split(marker);
    return { before, after };
  }, [t]);

  // The head of the retained order is the session on screen. It equals
  // `activeSessionId` except during a cold switch, where the destination has no
  // pane yet: the surface then keeps showing the pane it already has instead of
  // blanking or dimming it, and the store promotes the destination once its
  // transcript commits.
  const visibleSessionId = retainedSessionIds[0];
  // Only a cold switch is a wait worth marking. Once the destination is the
  // visible pane the user is already reading it, so a warm switch (including
  // re-selecting the session already on screen) shows no progress track even
  // though revalidation may still be in flight.
  const sessionSwitching =
    Boolean(selectingSessionId) && selectingSessionId !== visibleSessionId;

  const hasTranscript =
    Boolean(activePermission) ||
    askPending ||
    messages.some((message) => messageHasTranscriptContent(message));
  // The empty state belongs to the session on screen. While a cold switch is
  // still resolving, the visible pane keeps its own transcript, so the hero must
  // not take over just because the destination projection is still empty.
  const showEmptyState =
    !hasTranscript && (!visibleSessionId || visibleSessionId === activeSessionId);
  const vendorModelMissing = !isRemoteSession(activeSession) && vendorAccountOmitsSessionModel(
    activeSession,
    providers,
  );
  const vendorModelKey = vendorModelMissing
    ? `${activeSession?.providerId ?? ""}:${activeSession?.modelId ?? ""}`
    : null;
  const showVendorModelError =
    vendorModelKey !== null && hiddenVendorModelKey !== vendorModelKey;
  const noticeError =
    error ?? (showVendorModelError ? t("errors.MODEL_NOT_CONFIGURED") : null);
  const noticeCode = error
    ? errorCode
    : showVendorModelError
      ? "MODEL_NOT_CONFIGURED"
      : null;
  return (
    <div
      className={`chat-surface route-surface${sessionSwitching ? " session-switching" : ""}`}
      aria-busy={sessionSwitching}
    >
      {sessionSwitching ? (
        <div className="session-switch-progress" aria-hidden>
          <span />
        </div>
      ) : null}
      <ConversationWidthHandles />
      {showEmptyState ? (
        <div
          className="home-main-content"
          data-testid="home-empty"
          data-home-session-kind={
            heroProject ? "project" : isTemporarySession ? "temporary" : "empty"
          }
        >
          <div className="home-scroll">
            <div className="home-stack-inner">
              <div className="empty-hero">
                <div
                  className="empty-hero-icon"
                  data-testid="home-icon"
                  aria-hidden
                >
                  <HomeMascotLogo />
                </div>
                <h1>
                  {heroProject ? (
                    <>
                      {emptyTitleParts.before}
                      <HomeProjectSwitcher name={heroProject} path={isRemoteSession(activeSession) ? null : workspace?.path || activeSession?.projectPath || null} />
                      {emptyTitleParts.after}
                    </>
                  ) : isTemporarySession ? (
                    <>
                      {temporaryTitleParts.before}
                      <HomeProjectSwitcher temporary name={t("chat.temporaryScope")} />
                      {temporaryTitleParts.after}
                    </>
                  ) : (
                    t("chat.emptyTitle")
                  )}
                </h1>
              </div>
            </div>
          </div>
          <div className="home-composer-wrap">
            <StableComposer variant="home" />
          </div>
        </div>
      ) : (
        <>
          <div className="session-panes">
            {retainedSessionIds.map((id) => (
              <SessionPane
                key={id}
                sessionId={id}
                visible={visible && id === visibleSessionId}
              />
            ))}
          </div>
          <StableComposer variant="docked" />
        </>
      )}

      {noticeError ? (
        <div className="chat-error-layer">
          <div className="chat-error-notice">
            <span title={noticeError}>
              {noticeCode && i18nHasError(t, noticeCode)
                ? t(`errors.${noticeCode}`)
                : noticeError}
              {showVendorModelError && !error && activeSession?.modelId ? (
                <>
                  {" "}
                  <code>{activeSession.modelId}</code>
                </>
              ) : null}
            </span>
            {!isRemoteSession(activeSession) && (noticeCode === "MODEL_NOT_CONFIGURED" ||
              noticeCode === "PROVIDER_SECRET_MISSING" ||
              noticeCode === "PROVIDER_UNAUTHORIZED") && (
              <button
                type="button"
                className="chat-error-action"
                onClick={() => {
                  const store = useAppStore.getState();
                  store.setSettingsTab("agent");
                }}
              >
                {t("errors.action.openSettings")}
              </button>
            )}
            {errorRetriable && !isRunning ? (
              <button
                type="button"
                className="chat-error-action"
                onClick={() =>
                  void useAppStore.getState().retryLastPrompt()
                }
              >
                {t("errors.action.retry")}
              </button>
            ) : null}
            <TooltipButton
              type="button"
              tooltip={t("errors.action.dismiss")}
              ariaLabel={t("errors.action.dismiss")}
              className="chat-error-dismiss"
              onClick={() => {
                if (error) {
                  useAppStore.getState().clearError();
                  return;
                }
                if (vendorModelKey) setHiddenVendorModelKey(vendorModelKey);
              }}
            >
              <IconX size={13} />
            </TooltipButton>
          </div>
        </div>
      ) : null}
    </div>
  );
});