Skip to content

The agent that grows with you

38.1 KB
Raw Blame
import { type AppendMessage, AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react'
import { useStore } from '@nanostores/react'
import type { ReadableAtom } from 'nanostores'
import type * as React from 'react'
import { memo, Suspense, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useLocation } from 'react-router'

import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils'
import { sessionShouldHaveTranscript } from '@/app/session/hooks/use-session-actions/utils'
import { Thread } from '@/components/assistant-ui/thread'
import { TranscriptWindowProvider } from '@/components/assistant-ui/thread/transcript-window'
import { Backdrop } from '@/components/Backdrop'
import { COMPOSER_HEART_CONFIG, HeartField } from '@/components/chat/vibe-hearts'
import { useSetupChatView } from '@/components/onboarding/first-run/assembly'
import { $introHoldsThread } from '@/components/onboarding/first-run/intro'
import { IntroCopy } from '@/components/onboarding/first-run/intro-copy'
import { usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibility'
import { $hoveredTreeGroup, $sessionTileDragging, $sessionTileEdgeHover } from '@/components/pane-shell/tree/store'
import { PromptOverlays } from '@/components/prompt-overlays'
import { TitleMenuTrigger } from '@/components/ui/title-menu-trigger'
import { type HermesGateway, type ResolvedOwner } from '@/hermes'
import { useI18n } from '@/i18n'
import type { ChatMessage } from '@/lib/chat-messages'
import { NEW_SESSION_TITLE, sessionTitle } from '@/lib/chat-runtime'
import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'
import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { migrateSessionDraft } from '@/store/composer'
import { migrateQueuedPrompts, parkQueuedPrompts } from '@/store/composer-queue'
import { $introSplash } from '@/store/intro-splash'
import { $pinnedSessionIds } from '@/store/layout'
import { $introView } from '@/store/onboarding-intro'
import { $petActive } from '@/store/pet'
import { $petOverlayActive } from '@/store/pet-overlay'
import { $activeGatewayProfile, $gatewaySwapTarget, $hydrationSyncProfile, $profiles } from '@/store/profile'
import {
  $connection,
  $contextSuggestions,
  $freshDraftKey,
  $freshDraftReady,
  $gatewayState,
  $introPersonality,
  $introSeed,
  $resumeExhaustedSessionId,
  $sessions,
  getSessionOwnerHint,
  resolveComposerSessionKey,
  sessionMatchesStoredId,
  sessionPinId,
  shouldMigrateComposerScope
} from '@/store/session'
import { $focusedStoredSessionId } from '@/store/session-focus'
import { $sessionStates, sessionTileDelegate } from '@/store/session-states'
import { $transcriptTailBySessionId, transcriptTailState } from '@/store/transcript-tail'
import { isAuxiliaryWindow, isMainWindow } from '@/store/windows'

import { primaryRouteSelectedSessionId, routeSessionId } from '../routes'
import { titlebarHeaderBaseClass, titlebarHeaderShadowClass, titlebarHeaderTitleClass } from '../shell/titlebar'

import { ChatDropOverlay } from './chat-drop-overlay'
import { dropOverlayKind, useShowChatBar } from './chat-surface-state'
import { ChatSwapOverlay, ChatSyncBadge } from './chat-swap-overlay'
import { ChatBar, ChatBarFallback } from './composer'
import { FloatingComposerSurface } from './composer/floating-surface'
import { requestComposerInsert } from './composer/focus'
import { droppedFileInlineRefs } from './composer/inline-refs'
import {
  ComposerScopeProvider,
  ComposerSurfaceProvider,
  useComposerScope,
  useComposerSurfaceId
} from './composer/scope'
import { useHistoryWindow } from './history-window'
import { type DroppedFile, partitionDroppedFiles } from './hooks/use-composer-actions'
import { useFileDropZone } from './hooks/use-file-drop-zone'
import { shouldShowIntro } from './intro-visibility'
import { ProfileTag } from './profile-tag'
import { ResumeExhaustedOverlay } from './resume-exhausted-overlay'
import { isRouteSessionMismatch } from './route-session-state'
import { useRuntimeMessageRepository } from './runtime-repository'
import { ScrollToBottomButton } from './scroll-to-bottom-button'
import { useSessionView } from './session-view'
import { SessionActionsMenu } from './sidebar/session-actions-menu'
import { routedSessionIsLoading, threadLoadingState } from './thread-loading'
import {
  backfillOlderTranscriptPage,
  mergeOlderTranscriptPage,
  transcriptBackfillAvailable
} from './transcript-backfill'
import { advanceSessionTranscriptWindow, type SessionWindowMemo } from './transcript-window'
import { useChatBarState } from './use-chat-bar-state'
import { useTranscriptRetention } from './use-transcript-retention'

interface ChatViewProps extends Omit<React.ComponentProps<'div'>, 'onSubmit'> {
  gateway: HermesGateway | null
  modelOptionsOwnerConnectionId?: string
  modelOptionsProfile?: string
  modelMenuContent?: React.ReactNode
  reasoningMenuContent?: React.ReactNode
  requestModelOptionsForOwner?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>
  onToggleSelectedPin: () => void
  onDeleteSelectedSession: () => void
  onCancel: () => Promise<void> | void
  onAddContextRef: (refText: string, label?: string, detail?: string) => void
  onAddUrl: (url: string) => void
  onBranchInNewChat?: (messageId: string) => void
  maxVoiceRecordingSeconds?: number
  onAttachImageBlob: (blob: Blob, isCurrent?: () => boolean) => Promise<boolean | void> | boolean | void
  onAttachDroppedItems: (candidates: DroppedFile[]) => Promise<boolean | void> | boolean | void
  onAttachPastedText?: (text: string) => Promise<boolean> | boolean
  onPasteClipboardImage: (opts?: { silent?: boolean }) => Promise<boolean> | void
  onPickFiles: () => void
  onPickFolders: () => void
  onPickImages: () => void
  onRemoveAttachment: (id: string) => void
  onSteer: (text: string, mode?: 'interrupt' | 'steer') => Promise<boolean> | boolean
  onSteerHidden?: (text: string) => Promise<boolean> | boolean
  onSubmit: (text: string, options?: SubmitTextOptions) => Promise<boolean> | boolean
  onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
  onEdit: (message: AppendMessage) => Promise<void>
  onReload: (parentId: string | null) => Promise<void>
  onRestoreToMessage?: (messageId: string, target?: { text?: string; userOrdinal?: number | null }) => Promise<void>
  onRetryResume: (sessionId: string) => void
  onTranscribeAudio?: (audio: Blob, owner?: ResolvedOwner) => Promise<string>
  onDismissError?: (messageId: string) => void
}

interface ChatHeaderProps {
  activeSessionId: null | string
  isRoutedSessionView: boolean
  onDeleteSelectedSession: () => void
  onToggleSelectedPin: () => void
  selectedSessionId: null | string
}

function ChatHeader({
  activeSessionId,
  isRoutedSessionView,
  onDeleteSelectedSession,
  onToggleSelectedPin,
  selectedSessionId
}: ChatHeaderProps) {
  const sessions = useStore($sessions)
  const pinnedSessionIds = useStore($pinnedSessionIds)
  const profiles = useStore($profiles)

  const activeStoredSession =
    ((selectedSessionId || activeSessionId) &&
      sessions.find(session => sessionMatchesStoredId(session, selectedSessionId || activeSessionId || ''))) ||
    null

  const title = activeStoredSession ? sessionTitle(activeStoredSession) : NEW_SESSION_TITLE

  // Which agent/persona owns this chat — glanceable in the header once a
  // second profile exists, so the open session's ownership is never ambiguous
  // (#66003). Single-profile users see the unchanged header.
  const showProfileTag = profiles.length > 1 && Boolean(activeStoredSession)

  // Pins live on the durable lineage-root id, but selectedSessionId is the live
  // (tip) id — resolve through the loaded row so the menu reflects the pin
  // state after auto-compression rotates the id.
  const selectedIsPinned = activeStoredSession
    ? pinnedSessionIds.includes(sessionPinId(activeStoredSession))
    : selectedSessionId
      ? pinnedSessionIds.includes(selectedSessionId)
      : false

  // Secondary windows (new-session scratch, subagent watch, cmd-click pop-out)
  // are compact side panels — they drop the session-actions header + border
  // entirely. A brand-new draft has nothing to pin/delete/rename either.
  if (isAuxiliaryWindow() || (!selectedSessionId && !activeSessionId && !isRoutedSessionView)) {
    return null
  }

  return (
    <header className={cn(titlebarHeaderBaseClass, isRoutedSessionView && titlebarHeaderShadowClass)}>
      <div
        className={cn(titlebarHeaderTitleClass, showProfileTag && 'flex items-center')}
        style={{
          maxWidth:
            'calc(100vw - var(--titlebar-content-inset,0px) - var(--titlebar-tools-right) - var(--titlebar-tools-width) - 1.5rem)'
        }}
      >
        {showProfileTag && <ProfileTag className="pointer-events-auto mr-1.5" profile={activeStoredSession?.profile} />}
        <SessionActionsMenu
          align="start"
          onDelete={selectedSessionId ? onDeleteSelectedSession : undefined}
          onPin={selectedSessionId ? onToggleSelectedPin : undefined}
          pinned={selectedIsPinned}
          profile={activeStoredSession?.profile}
          sessionId={selectedSessionId || activeSessionId || ''}
          sideOffset={8}
          title={title}
        >
          <TitleMenuTrigger>{title}</TitleMenuTrigger>
        </SessionActionsMenu>
      </div>
    </header>
  )
}

interface ChatRuntimeBoundaryProps {
  busy: boolean
  children: React.ReactNode
  onCancel: () => Promise<void> | void
  onEdit: (message: AppendMessage) => Promise<void>
  onReload: (parentId: string | null) => Promise<void>
  onThreadMessagesChange: (messages: readonly ThreadMessage[]) => void
  /** Route points at an unloaded session — render empty until resume swaps in
   *  the new transcript, so the previous session's messages don't linger. */
  suppressMessages: boolean
}

const NO_MESSAGES: ChatMessage[] = []

/**
 * The view's $messages, live only while this surface is the VISIBLE tab.
 *
 * Keep-alive keeps every ever-active tab MOUNTED (tree-group.tsx), so without
 * this gate a hidden tab re-renders its entire thread on every streaming
 * delta flush (~30×/s) — five busy tabs quintuple the per-token render cost
 * and the app crawls. Hidden tabs freeze their transcript instead (status
 * dots stay live through the separate status atoms) and catch up in one
 * commit on reveal — the subscribe fires immediately with the current value.
 */
function useMessagesWhileVisible($messages: ReadableAtom<ChatMessage[]>, enabled = true): ChatMessage[] {
  const visible = usePaneVisible()
  const [messages, setMessages] = useState(() => $messages.get())

  // nanostores types the listener value ReadonlyIfObject; the store publishes
  // a fresh array per flush, so the cast is safe and avoids a per-token clone.
  useEffect(
    () => (visible && enabled ? $messages.subscribe(value => setMessages(value as ChatMessage[])) : undefined),
    [$messages, visible, enabled]
  )

  return messages
}

/**
 * Owns the $messages subscription and the assistant-ui external-store runtime.
 *
 * Isolated from ChatView so the per-token delta flush (which replaces the
 * $messages atom ~30×/s during streaming) only re-renders this component and
 * the runtime provider. The children (Thread, ChatBar) are created by
 * ChatView, whose render output is stable across flushes — so React bails out
 * of re-rendering them by element identity and the stream's render cost stays
 * confined to the streaming message's own subtree.
 */
export function ChatRuntimeBoundary({
  busy,
  children,
  onCancel,
  onEdit,
  onReload,
  onThreadMessagesChange,
  suppressMessages
}: ChatRuntimeBoundaryProps) {
  const view = useSessionView()
  const runtimeId = useStore(view.$runtimeId)
  const storedId = useStore(view.$storedId)
  const connection = useStore($connection)
  const activeProfile = useStore($activeGatewayProfile)
  const connectionId = connection?.connectionId || (connection?.mode === 'local' ? 'local' : '')

  const ownerRoute = storedId
    ? getSessionOwnerHint(storedId, connectionId ? { connectionId, profile: activeProfile } : undefined)
    : undefined

  const ownerConnection = ownerRoute?.connectionId
  const ownerProfile = ownerRoute?.targetProfile || ownerRoute?.profile

  const tailProfile = useMemo(
    () => (ownerProfile ? { connectionId: ownerConnection, profile: ownerProfile } : undefined),
    [ownerConnection, ownerProfile]
  )

  // A Bot chat opened IN PLACE in the main pane (openStoredBotChat) keeps the
  // active profile, so the ambient scope carries no owner. Publish the session
  // owner hint's (connection, profile) here so voice playback speaks with the
  // Bot's own voice; a tile's scope already names its owner and is kept as is.
  const parentScope = useComposerScope()

  const composerScope = useMemo(
    () =>
      parentScope.profile || !ownerProfile
        ? parentScope
        : { ...parentScope, connectionId: ownerConnection || undefined, profile: ownerProfile },
    [ownerConnection, ownerProfile, parentScope]
  )

  const history = useHistoryWindow({
    scopeKey: JSON.stringify([runtimeId, storedId, tailProfile, connectionId, activeProfile, suppressMessages]),
    storedId,
    scope: tailProfile ?? { connectionId: connectionId || undefined, profile: activeProfile },
    isCurrent: () => !suppressMessages && view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId
  })

  // History is a static display page. The live store continues streaming but
  // no delta subscribes/reconverts this historical runtime until return.
  const storeMessages = useMessagesWhileVisible(view.$messages, !history.page)
  const messages = suppressMessages ? NO_MESSAGES : storeMessages

  const [windowPages, setWindowPages] = useState(1)
  const [windowSessionKey, setWindowSessionKey] = useState(runtimeId)
  // Per-session sticky-cut continuity (advanceSessionTranscriptWindow). A ref,
  // not state: it is derived from `messages` and must never trigger a render.
  // Keyed by runtime id so a warm switch back to a session whose transcript
  // is unchanged reuses the previous windowed slice BY REFERENCE — no window
  // re-index, no runtime-repository rebuild, no per-row re-parse/re-highlight
  // (#95595). Bounded internally (oldest session evicted).
  const windowStateRef = useRef(new Map<string, SessionWindowMemo>())
  // The memo below intentionally skips `runtimeId` in its deps (a switch
  // always changes the messages array too, which re-runs it), so the current
  // value must come from a ref rather than the stale render closure.
  const runtimeIdRef = useRef(runtimeId)
  runtimeIdRef.current = runtimeId

  // Reset the window on session swap during RENDER, so a large expand from the
  // previous chat can't leak into the next one's first paint (#55191). The
  // per-session map above keeps each session's own cut; only the page count
  // resets on a switch.
  if (windowSessionKey !== runtimeId) {
    setWindowSessionKey(runtimeId)
    setWindowPages(1)
  }

  const { messages: windowedMessages, windowed } = useMemo(() => {
    const next = advanceSessionTranscriptWindow(
      windowStateRef.current,
      // Draft state has no runtime id yet; a single shared slot is fine there
      // (mirrors the old single-slot behaviour for the no-runtime case).
      runtimeIdRef.current ?? '',
      messages,
      windowPages
    )

    return next.window
  }, [messages, windowPages])

  const currentMessages = history.page?.messages ?? windowedMessages
  // Release the store's paged-through history (persisted rows older than the
  // window) instead of retaining it for the window's lifetime (#77311). A
  // static history page is not the live store, and neither is a suppressed
  // transcript, so both opt out.
  useTranscriptRetention({
    anchorId: windowed ? (windowedMessages[0]?.id ?? null) : null,
    enabled: !suppressMessages && !history.page,
    profile: tailProfile,
    runtimeId,
    storedSessionId: storedId
  })
  const runtimeMessageRepository = useRuntimeMessageRepository(currentMessages)
  // Subscribed (not read imperatively) so the "Show earlier" affordance
  // appears/retires as tail hydrations and backfill pages record their state.
  const transcriptTailStates = useStore($transcriptTailBySessionId)
  const tailState = storedId && transcriptTailStates ? transcriptTailState(storedId, tailProfile) : undefined
  const restBackfillAvailable = Boolean(tailState?.possiblyTruncated)

  const expandWindow = useCallback(
    async (beforePrepend?: () => void) => {
      // A historical page is not the live tail: its older neighbours come from
      // the prompt range the rail already draws, never from store backfill.
      if (history.page) {
        return history.revealOlder(beforePrepend)
      }

      // Network latency is not scroll intent. Capture at arrival, immediately
      // before the store prepend, and only grow a window that has a page to show.
      if (
        !windowStateRef.current.get(runtimeIdRef.current ?? '')?.state.window.windowed &&
        runtimeId &&
        storedId &&
        transcriptBackfillAvailable(storedId, tailProfile)
      ) {
        let grew = false
        await backfillOlderTranscriptPage({
          storedSessionId: storedId,
          profile: tailProfile,
          // Stale-response guard: a session switch remounts/re-keys this view;
          // checking the live atoms (not captured props) discards a page that
          // resolves after the user moved on — same pattern as isCurrentResume.
          isCurrent: () => view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId,
          applyOlderPage: olderPage => {
            const current = view.$messages.get()

            if (mergeOlderTranscriptPage(current, olderPage) === current) {
              return
            }

            beforePrepend?.()
            setWindowPages(pages => pages + 1)
            sessionTileDelegate()?.updateSession(runtimeId, state => {
              const merged = mergeOlderTranscriptPage(state.messages, olderPage)
              grew = merged !== state.messages

              return grew ? { ...state, messages: merged } : state
            })
          }
        })

        // Exhaustion and overlapping-only pages have no structural publication.
        // Do not leave the list waiting for a commit that will never arrive.
        return grew
      }

      beforePrepend?.()
      setWindowPages(pages => pages + 1)

      return true
    },
    [runtimeId, storedId, tailProfile, view, history.page, history.revealOlder]
  )

  // An open history page carries its own reach: its first prompt is the anchor,
  // and the around window reports whether rows precede it. Reading that as
  // "nothing earlier" (the live-tail flags) retired every way back — the rail
  // still names older marks, so the entry point must stay live here too.
  const olderAvailable = history.page ? history.page.olderAvailable : windowed || restBackfillAvailable
  const isHistorical = Boolean(history.page)
  const newerAvailable = history.page?.newerAvailable ?? false
  const { revealRow, returnToLatest } = history
  const historicalMessages = history.page?.messages

  const transcriptWindow = useMemo(
    () => ({
      olderAvailable,
      expandWindow,
      revealRow,
      returnToLatest,
      // Live navigation reads the session store. Broadcasting the changing
      // live tail here invalidates the entire transcript's navigation context.
      currentMessages: historicalMessages ?? [],
      isHistorical,
      newerAvailable
    }),
    [expandWindow, olderAvailable, revealRow, returnToLatest, historicalMessages, isHistorical, newerAvailable]
  )

  const runtime = useIncrementalExternalStoreRuntime<ThreadMessage>({
    messageRepository: runtimeMessageRepository,
    isRunning: !isHistorical && busy,
    isDisabled: isHistorical,
    setMessages: isHistorical ? undefined : onThreadMessagesChange,
    onNew: async () => {
      // Submission is handled explicitly by ChatBar.
      // Keeping this no-op avoids duplicate prompt.submit calls.
    },
    // Editing stays AVAILABLE on a history page. `isDisabled` above blocks
    // submit/reload/branch and keeps the page static, but the rail jump is
    // the only way into that page and it has no in-thread exit — so dropping
    // `onEdit` left the inline composer unopenable after ANY far rail jump
    // (the throw "Runtime does not support editing", infectious downward,
    // healed only by the floating jump button's returnToLatest). `editMessage`
    // already resolves its target against the live session store
    // (use-prompt-actions), never the display page, so the edit is correct;
    // sending one rewinds the live transcript and drops the page.
    onEdit,
    onCancel: isHistorical ? undefined : async () => onCancel(),
    onReload: isHistorical ? undefined : onReload
  })

  return (
    <ComposerScopeProvider value={composerScope}>
      <TranscriptWindowProvider value={transcriptWindow}>
        <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>
      </TranscriptWindowProvider>
    </ComposerScopeProvider>
  )
}

// Memoized: the tile caller (session-tile.tsx) and the contrib surface re-render
// on idle ticks unrelated to the chat; with stable callback props (hoisted to
// useCallback at the call sites) memo() lets the whole chat shell skip those.
export const ChatView = memo(function ChatView(props: ChatViewProps) {
  const composerSurfaceId = useId()

  return (
    <ComposerSurfaceProvider value={composerSurfaceId}>
      <ChatViewContent {...props} />
    </ComposerSurfaceProvider>
  )
})

const ChatViewContent = memo(function ChatViewContent({
  className,
  gateway,
  modelOptionsOwnerConnectionId,
  modelOptionsProfile,
  modelMenuContent,
  reasoningMenuContent,
  requestModelOptionsForOwner,
  onToggleSelectedPin,
  onDeleteSelectedSession,
  onCancel,
  onAddContextRef,
  onAddUrl,
  onAttachImageBlob,
  onAttachDroppedItems,
  onAttachPastedText,
  onBranchInNewChat,
  maxVoiceRecordingSeconds,
  onPasteClipboardImage,
  onPickFiles,
  onPickFolders,
  onPickImages,
  onRemoveAttachment,
  onSteer,
  onSteerHidden,
  onSubmit,
  onThreadMessagesChange,
  onEdit,
  onReload,
  onRestoreToMessage,
  onRetryResume,
  onTranscribeAudio,
  onDismissError
}: ChatViewProps) {
  const location = useLocation()
  const { t } = useI18n()
  // The view this surface renders: the primary route-driven session (global
  // atoms) or a tile's session slice — same component either way.
  const view = useSessionView()
  const composerScope = useComposerScope()
  const composerSurfaceId = useComposerSurfaceId()
  const isPrimary = view.kind === 'primary'
  const introHoldsThread = useStore($introHoldsThread) && isPrimary && isMainWindow()
  const guideStarted = useStoreSelector($introView, introView => introView === 'intro' || introView === 'ended')
  const activeSessionId = useStore(view.$runtimeId)

  const transcriptStoredSessionId = useStoreSelector($sessionStates, states =>
    activeSessionId ? (states[activeSessionId]?.storedSessionId ?? null) : null
  )

  const storedId = useStore(view.$storedId)
  const setupChat = useSetupChatView()
  // Multi-pane dimming: only the focused surface paints at full strength, so
  // two sessions side by side read as "this one, and that one over there".
  // A selector, not a plain useStore — the focused id changes on click, and a
  // boolean bails every other surface out of the re-render. Sole surface ⇒
  // always focused (the atom falls back to the primary's selection), so a
  // single-pane workspace never dims.
  const surfaceFocused = useStoreSelector($focusedStoredSessionId, focused => focused === storedId)
  const groupId = usePaneGroup()
  const surfaceHovered = useStoreSelector($hoveredTreeGroup, hovered => hovered === groupId)
  // Dock anchor for a session drop onto this surface: the workspace pane for the
  // primary, this tile's pane id for a tile. Read by the session-drop bridge.
  const sessionAnchor = isPrimary ? 'workspace' : `session-tile:${storedId ?? ''}`
  const awaitingResponse = useStore(view.$awaitingResponse)
  const busy = useStore(view.$busy)
  const activeGatewayProfile = useStore($activeGatewayProfile)
  const contextSuggestions = useStore($contextSuggestions)
  // Per-session (SessionView) reads — a tile IS its session, so these come
  // from the view slice, not the global atoms (which track the primary only).
  const currentCwd = useStore(view.$cwd)
  const currentModel = useStore(view.$model)
  const currentProvider = useStore(view.$provider)
  // A pet anywhere (in-window or popped out) owns the hearts; composer only when none.
  const petActive = useStore($petActive)
  const petOverlayActive = useStore($petOverlayActive)
  const petPresent = petActive || petOverlayActive
  const freshDraftReady = useStore($freshDraftReady)
  const freshDraftKey = useStore($freshDraftKey)
  const gatewayState = useStore($gatewayState)
  const gatewaySwapTarget = useStore($gatewaySwapTarget)
  const hydrationSyncProfile = useStore($hydrationSyncProfile)
  const gatewayOpen = gatewayState === 'open'
  const introPersonality = useStore($introPersonality)
  const introSeed = useStore($introSeed)
  const introSplash = useStore($introSplash)
  // PERF: ChatView must not subscribe to the view's $messages — the atom is
  // replaced on every streaming delta flush (~30×/s) and a subscription here
  // re-renders the entire chat shell (header, chat bar, thread wrapper) per
  // token. The runtime that DOES need the messages lives in
  // ChatRuntimeBoundary below; this component only needs streaming-stable
  // derivations.
  const messagesEmpty = useStore(view.$messagesEmpty)
  const lastVisibleIsUser = useStore(view.$lastVisibleIsUser)
  const selectedSessionId = useStore(view.$storedId)
  const sessions = useStore($sessions)
  const resumeExhaustedSessionId = useStore($resumeExhaustedSessionId)

  // Durable composer/queue scope (lineage root) so auto-compression tip rotation
  // does not wipe an in-progress draft or orphan /queue entries. For the
  // primary view, the route is authoritative over the store selection — the
  // latter can be momentarily null/stale mid-switch, which used to leak into
  // the composer's scope key (#59305). A tile has no route, so it always uses
  // its own selection directly.
  const queueSessionKey = useMemo(() => {
    const effectiveSelectedSessionId = isPrimary
      ? primaryRouteSelectedSessionId(location.pathname, selectedSessionId)
      : selectedSessionId

    return resolveComposerSessionKey(effectiveSelectedSessionId, sessions)
  }, [isPrimary, location.pathname, selectedSessionId, sessions])

  // When the tip row arrives after compression, migrate any tip-keyed stash onto
  // the durable lineage key before the composer remounts onto that key.
  //
  // ONLY same-conversation rekeys (tip → root). The route-driven queueSessionKey
  // can flip to Session B a frame before the store selection leaves Session A;
  // migrating on bare inequality would re-home A's queued prompts onto B and
  // auto-drain them into the wrong chat.
  useEffect(() => {
    if (!shouldMigrateComposerScope(selectedSessionId, queueSessionKey, sessions)) {
      return
    }

    migrateSessionDraft(selectedSessionId, queueSessionKey)
    migrateQueuedPrompts(selectedSessionId, queueSessionKey)
  }, [queueSessionKey, selectedSessionId, sessions])

  // Transcript-side stops (the streaming message's hover Stop, the runtime's
  // cancel) are explicit halts, same as the composer's Stop button: park any
  // queued turns so the interrupt doesn't roll straight into the next one.
  // ChatBar wraps its own onCancel internally — its send-now-while-busy path
  // needs the raw interrupt — so it still receives the unwrapped prop.
  const haltRun = useCallback(() => {
    parkQueuedPrompts(queueSessionKey || activeSessionId)

    return onCancel()
  }, [activeSessionId, onCancel, queueSessionKey])

  // A tile IS its session — no route involved, never "mismatched".
  const routedSessionId = isPrimary ? routeSessionId(location.pathname) : selectedSessionId
  const isRoutedSessionView = Boolean(routedSessionId)

  // The URL points at a session the store hasn't loaded yet (sidebar / cmd-K /
  // direct nav). Derived in render so the swap reads instantly: the same frame
  // the id changes we drop the old transcript and show the loader, instead of
  // waiting for the resume effect (which paints a frame later) to clear them.
  const routeSessionMismatch = isPrimary
    ? isRouteSessionMismatch(routedSessionId, selectedSessionId, sessions, {
        activeRuntimeId: activeSessionId,
        contextSwitching: Boolean(gatewaySwapTarget),
        messagesEmpty,
        transcriptStoredSessionId
      })
    : false

  // The compact new-session pop-out skips the wordmark/tagline intro — it's a
  // scratch window, not the full-height empty state. The Appearance toggle
  // turns it off everywhere else.
  const showIntro = shouldShowIntro({
    activeSessionId,
    auxiliaryWindow: isAuxiliaryWindow(),
    enabled: introSplash,
    freshDraftReady,
    messagesEmpty,
    primary: isPrimary,
    routedSessionView: isRoutedSessionView,
    selectedSessionId
  })

  // Session is still loading if the route references a session we haven't
  // resumed yet. Brand-new routed drafts are empty on purpose once a runtime
  // is bound. A session the list already knows has history must keep the
  // loader up until a display-authoritative transcript arrives — including
  // the unproven warm-cache hold, where the runtime is bound but messages
  // are still suppressed.
  //
  // resumeExhausted: the bounded auto-retry in use-route-resume gave up on this
  // routed session (gateway RPC + REST fallback failed through every attempt).
  // Suppress the loader and show an explicit error + manual Retry instead of
  // spinning forever. Gated on the route matching so a stale latch from another
  // session can't blank the current one.
  const resumeExhausted = isPrimary && isRoutedSessionView && resumeExhaustedSessionId === routedSessionId

  const routedHasHistory = Boolean(
    routedSessionId &&
    sessions.some(session => sessionMatchesStoredId(session, routedSessionId) && sessionShouldHaveTranscript(session))
  )

  const loadingSession = routedSessionIsLoading({
    activeSessionId,
    knownHistory: routedHasHistory,
    messagesEmpty,
    resumeExhausted,
    routeSessionMismatch,
    routedSessionView: isRoutedSessionView
  })

  const threadLoading = threadLoadingState(loadingSession, busy, awaitingResponse, lastVisibleIsUser)

  const showChatBar = useShowChatBar({
    loadingSession,
    resumeExhausted,
    routedSessionId,
    routedSessionView: isRoutedSessionView
  })

  const threadKey = selectedSessionId || activeSessionId || (isRoutedSessionView ? location.pathname : 'new')

  const chatBarState = useChatBarState({
    activeGatewayProfile,
    activeSessionId,
    contextSuggestions,
    currentModel,
    currentProvider,
    gateway,
    gatewayOpen,
    modelMenuContent,
    modelOptionsOwnerConnectionId,
    modelOptionsProfile,
    reasoningMenuContent,
    requestModelOptionsForOwner
  })

  // Drop files anywhere in the conversation area, not just on the composer
  // input. In-app drags (project tree / gutter) carry workspace-relative paths
  // the gateway resolves directly, so they stay inline `@file:` refs. OS/Finder
  // drops carry absolute local paths that don't exist on a remote gateway (and
  // images need byte upload for vision), so route them through the attachment
  // pipeline — otherwise the local path leaks into the prompt verbatim.
  const onDropFiles = useCallback(
    (candidates: DroppedFile[]) => {
      const { inAppRefs, osDrops } = partitionDroppedFiles(candidates)
      const refs = droppedFileInlineRefs(inAppRefs, currentCwd)

      if (refs.length) {
        requestComposerInsert(refs.join(' '), { mode: 'inline', target: composerScope.target })
      }

      if (osDrops.length) {
        void onAttachDroppedItems(osDrops)
      }
    },
    [composerScope.target, currentCwd, onAttachDroppedItems]
  )

  // Session drags are POINTER drags (session-drag.ts) — never native DnD.
  // The drop zone below only handles files; session drops commit through the
  // drag session itself, which routes a center/link drop to this surface's
  // composer via `data-composer-target`.
  const { dragKind, dropHandlers } = useFileDropZone({ enabled: showChatBar, onDropFiles })

  // While a session drag targets one of this surface's EDGES or a tab strip,
  // the zone overlay/caret owns the visual — the link overlay stands down.
  // It shows for the whole drag on every chat surface otherwise (the drag
  // session's global sentinel, not a per-surface hover chain).
  // COMPUTED booleans, never the raw `$dropHint`: the hint churns on every
  // pointer-crossing of every drag (pane drags included), and a re-render
  // here is the WHOLE surface — thread, composer, header — per mounted tile.
  const sessionDragging = useStore($sessionTileDragging)
  const sessionEdgeHover = useStore($sessionTileEdgeHover)

  const overlayKind = dropOverlayKind(dragKind, sessionDragging, sessionEdgeHover)

  return (
    <div
      className={cn(
        'relative isolate flex h-full min-w-0 flex-col overflow-hidden bg-(--ui-chat-surface-background)',
        className
      )}
      data-chat-surface=""
      data-chat-unfocused={surfaceFocused || surfaceHovered ? undefined : ''}
      data-composer-surface-id={composerSurfaceId}
      data-composer-target={composerScope.target}
      data-guide-arrived={isPrimary && guideStarted ? '' : undefined}
      data-session-anchor={sessionAnchor}
      data-setup-chat={setupChat ? '' : undefined}
    >
      <Backdrop />
      {/* Tiles get their chrome from the layout zone (chip strip); the modal
          prompt overlays stay active-session-scoped in the primary surface. */}
      {isPrimary && (
        <ChatHeader
          activeSessionId={activeSessionId}
          isRoutedSessionView={isRoutedSessionView}
          onDeleteSelectedSession={onDeleteSelectedSession}
          onToggleSelectedPin={onToggleSelectedPin}
          selectedSessionId={selectedSessionId}
        />
      )}

      {/* Mounted for the primary AND every tile, each scoped to its own session
          so a tiled/background session's blocking prompt surfaces instead of
          stalling to timeout. */}
      <PromptOverlays sessionId={activeSessionId} />

      <ChatRuntimeBoundary
        busy={busy}
        onCancel={haltRun}
        onEdit={onEdit}
        onReload={onReload}
        onThreadMessagesChange={onThreadMessagesChange}
        suppressMessages={routeSessionMismatch}
      >
        <div
          className="relative min-h-0 max-w-full flex-1 overflow-hidden bg-(--ui-chat-surface-background) contain-[layout_paint]"
          data-intro-holding={introHoldsThread ? '' : undefined}
          data-slot="composer-bounds"
          {...dropHandlers}
        >
          <Thread
            clampToComposer={showChatBar}
            cwd={currentCwd}
            gateway={gateway}
            intro={showIntro ? { personality: introPersonality, seed: introSeed } : undefined}
            loading={threadLoading}
            onBranchInNewChat={onBranchInNewChat}
            onCancel={haltRun}
            onDismissError={onDismissError}
            onRestoreToMessage={onRestoreToMessage}
            scrollProfile={modelOptionsProfile || activeGatewayProfile}
            sessionId={activeSessionId}
            sessionKey={threadKey}
          />
          {isPrimary && isMainWindow() && <IntroCopy />}
          {resumeExhausted && routedSessionId && (
            <ResumeExhaustedOverlay onRetryResume={onRetryResume} sessionId={routedSessionId} />
          )}
          {showChatBar && <ScrollToBottomButton sessionId={activeSessionId} />}
          {/* Vibe hearts rise from the composer only when no pet is out (else
              they play on the pet). Fired by the core `reaction` event. */}
          {!petPresent && (
            <HeartField
              className="absolute inset-x-0 z-30"
              config={COMPOSER_HEART_CONFIG}
              style={{
                top: 0,
                bottom: 'calc(var(--composer-measured-height) + 0.25rem)'
              }}
            />
          )}
          {/* A session drag hovering an EDGE hands the visual to the zone
              target; the link overlay shows only for the center region. */}
          <ChatDropOverlay kind={overlayKind} />
          <ChatSwapOverlay profile={gatewaySwapTarget} />
          {/* Paint-first wake (#89843): transcript is live, profile gate still
              settling in the background — subtle badge, not an overlay. */}
          {isPrimary && !gatewaySwapTarget && <ChatSyncBadge profile={hydrationSyncProfile} />}
        </div>
        {/* Docked composers overlay their pane; the shared float escapes pane
            clipping through a stable portal host without remounting its editor. */}
        {showChatBar && (
          <FloatingComposerSurface>
            <Suspense fallback={<ChatBarFallback />}>
              <ChatBar
                busy={busy}
                cwd={currentCwd}
                disabled={!gatewayOpen}
                focusKey={activeSessionId}
                freshDraftKey={freshDraftKey}
                gateway={gateway}
                maxRecordingSeconds={maxVoiceRecordingSeconds}
                onAddContextRef={onAddContextRef}
                onAddUrl={onAddUrl}
                onAttachDroppedItems={onAttachDroppedItems}
                onAttachImageBlob={onAttachImageBlob}
                onAttachPastedText={onAttachPastedText}
                onCancel={onCancel}
                onPasteClipboardImage={onPasteClipboardImage}
                onPickFiles={onPickFiles}
                onPickFolders={onPickFolders}
                onPickImages={onPickImages}
                onRemoveAttachment={onRemoveAttachment}
                onSteer={onSteer}
                onSteerHidden={onSteerHidden}
                onSubmit={onSubmit}
                onTranscribeAudio={onTranscribeAudio}
                profile={modelOptionsProfile || activeGatewayProfile}
                queueSessionKey={queueSessionKey}
                sessionId={activeSessionId}
                state={chatBarState}
              />
            </Suspense>
          </FloatingComposerSurface>
        )}
      </ChatRuntimeBoundary>
    </div>
  )
})