Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

37.6 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-explicit-any */
import { memo, useState, useCallback, useEffect, useMemo } from 'react'
import type { UIMessage, ChatStatus } from 'ai'
import { RenderMarkdown } from './RenderMarkdown'
import { cn } from '@/lib/utils'
import { usedSkillNames } from '@/lib/agentActivity'

import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'
import { AskSummaryCard } from './message/AskSummaryCard'
import { summarizeAsk } from '@/lib/coworkAsk'
import { ASK_TOOL_NAME } from '@/lib/coworkTools'
import { extensionAuthorOf } from '@/lib/extensions/authorship'
import { withRemoteImages } from '@/lib/extensions/remoteImages'
import { isExtensionToolName } from '@/lib/extensions/tools'
import {
  CHAT_STATUS,
  CONTENT_TYPE,
  type MessagePartLike,
  type PartEntry,
} from './message/types'
import { CopyButton } from './CopyButton'
import { RememberButton } from './RememberButton'
import { toast } from 'sonner'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { formatDate, formatMessageTime } from '@/utils/formatDate'
import { useTouchDevice } from '@/hooks/useMediaQuery'
import { Link } from '@tanstack/react-router'
import { route } from '@/constants/routes'
import { useModelProvider } from '@/hooks/useModelProvider'
import { useInterfaceSettings } from '@/hooks/useInterfaceSettings'
import { useMessageErrors } from '@/stores/message-errors'
import {
  IconRefresh,
  IconPlayerPlay,
  IconPaperclip,
  IconAlertTriangle,
  IconCopy,
  IconChevronLeft,
  IconChevronRight,
  IconBellRinging,
} from '@tabler/icons-react'
import { PING_OPEN, PING_CLOSE, isSystemNotice } from '@/lib/coworkPing'
import { EditMessageDialog } from '@/containers/dialogs/EditMessageDialog'
import { DeleteMessageDialog } from '@/containers/dialogs/DeleteMessageDialog'
import TokenSpeedIndicator from '@/containers/TokenSpeedIndicator'
import { extractFilesFromPrompt, FileMetadata } from '@/lib/fileMetadata'
import { Button } from '@/components/ui/button'
import { PromptProgress } from '@/components/PromptProgress'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
import { parseCitationsFromToolOutput } from '@/lib/citation-parser'
import type { RagCitation, WebCitation } from '@/components/Citations'
import { useGroundingStore } from '@/stores/grounding-store'
import { useWebCitationStore } from '@/stores/web-citation-store'
import { WebSourcesRow } from '@/components/WebSourcesRow'
import { injectCitationMarkers } from '@/lib/grounding'
import { ContributedOverflowMenu } from '@/containers/extensions/ContributedMenuItems'

export type MessageItemProps = {
  message: UIMessage
  isFirstMessage: boolean
  isLastMessage: boolean
  status: ChatStatus
  reasoningContainerRef?: React.RefObject<HTMLDivElement | null>
  isReasoningAtBottom?: boolean
  onReasoningScroll?: () => void
  onReasoningScrollToBottom?: () => void
  onRegenerate?: (messageId: string) => void
  onContinue?: (messageId: string) => void
  onEdit?: (messageId: string, newText: string) => void
  onDelete?: (messageId: string) => void
  /** Ask this question again, unchanged, dropping whatever it produced. Only
   * offered where re-running from partway up the transcript is meaningful --
   * the agent surfaces, where a turn is a chain of tool calls rather than a
   * single reply. */
  onRetry?: (messageId: string, text: string) => void
  versionInfo?: { index: number; count: number }
  onSwitchVersion?: (messageId: string, dir: -1 | 1) => void
  isAnimating?: boolean
  /** Suppress the per-message action buttons (regenerate/continue/edit/...),
   * e.g. while a continue is pending and re-running would be ambiguous. */
  hideActions?: boolean
  highlightedPrefix?: string | null
  /** The thread the message belongs to; extension message actions need it. */
  threadId?: string
}

// Footer icon buttons: 28px boxes (a roomier hover highlight at the same pitch
// as 24px + gap-1), and keyboard focus shown as that soft highlight plus a 1px
// neutral-500 ring (the fill alone is ~1.2:1 on the page; neutral-500 clears
// 3:1 in both themes, the light --ring token does not). The shared Button's 3px focus
// ring is far heavier than a 16px icon.
// Dialog triggers swap data-slot to "dialog-trigger", hence both.
const FOOTER_ICON_BUTTONS =
  '[&_:is([data-slot=button],[data-slot=dialog-trigger])]:size-7 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:ring-1 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:ring-neutral-500 [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:bg-accent [&_:is([data-slot=button],[data-slot=dialog-trigger]):focus-visible]:text-accent-foreground'

export const MessageItem = memo(
  ({
    message,
    isFirstMessage,
    isLastMessage,
    status,
    isAnimating,
    hideActions,
    reasoningContainerRef,
    isReasoningAtBottom,
    onReasoningScroll,
    onReasoningScrollToBottom,
    onRegenerate,
    onContinue,
    onEdit,
    onDelete,
    onRetry,
    versionInfo,
    onSwitchVersion,
    highlightedPrefix,
    threadId,
  }: MessageItemProps) => {
    const { t } = useTranslation()
    // Footer controls fade in on hover or keyboard focus. Keyboard only
    // (:focus-visible): a mouse click also focuses the button, and with plain
    // focus-within the footer stayed shown after the pointer left. A touch
    // screen has no hover, so there they are always shown rather than
    // unreachable.
    const isTouch = useTouchDevice()
    const hoverReveal = isTouch
      ? 'opacity-100'
      : // will-change keeps each group on its own layer at all times. Without
        // it WebKit promotes the group only while the fade runs, snapping its
        // fractional position to a whole pixel, so the controls jumped ~1px
        // as they appeared and again as they settled.
        'opacity-0 transition-opacity will-change-[opacity] group-hover/message:opacity-100 group-has-[:focus-visible]/message:opacity-100'
    const selectedModel = useModelProvider((state) => state.selectedModel)
    const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)
    const metadata = message.metadata as Record<string, unknown> | undefined
    // Written by a third-party extension: nothing in it may load from the
    // network (see lib/extensions/authorship).
    const extensionAuthored = extensionAuthorOf(metadata) !== undefined
    const messageError = useMessageErrors((s) => s.errors[message.id])
    const loadReport = useMessageErrors((s) => s.reports[message.id])
    // Recorded only when the failed turn ran on llama.cpp; the current
    // selection would name a model that had nothing to do with the failure.
    const diagnoseModel = loadReport?.model
    const canRegenerate =
      !!selectedModel &&
      !!onRegenerate &&
      status !== CHAT_STATUS.STREAMING &&
      status !== CHAT_STATUS.SUBMITTED
    const createdAt = (metadata?.createdAt as Date) ?? new Date()
    // Machine-readable stamp for <time>; toISOString throws on an invalid date,
    // which a malformed stored value must not turn into a crashed message.
    const createdAtMs = new Date(createdAt).getTime()
    const createdAtIso = Number.isNaN(createdAtMs)
      ? undefined
      : new Date(createdAtMs).toISOString()
    const [previewImage, setPreviewImage] = useState<{
      url: string
      filename?: string
    } | null>(null)

    const handleRegenerate = useCallback(() => {
      onRegenerate?.(message.id)
    }, [onRegenerate, message.id])

    const handleContinue = useCallback(() => {
      onContinue?.(message.id)
    }, [onContinue, message.id])

    const isStopped = metadata?.stopped === true
    // Continue extends partial text; a turn stopped before it wrote any (a tool
    // call was all it had) has nothing to resume, so offering it would do
    // nothing.
    const canContinue =
      isStopped &&
      message.parts.some(
        (p) =>
          (p.type === 'text' || p.type === 'reasoning') && !!p.text?.trim()
      )

    const handleEdit = useCallback(
      (newText: string) => {
        onEdit?.(message.id, newText)
      },
      [onEdit, message.id]
    )

    const handleDelete = useCallback(() => {
      onDelete?.(message.id)
    }, [onDelete, message.id])

    // Get image URLs from file parts for the edit dialog
    const imageUrls = useMemo(() => {
      return message.parts
        .filter((part) => {
          if (part.type !== 'file') return false
          const filePart = part as {
            type: 'file'
            url?: string
            mediaType?: string
          }
          return filePart.url && filePart.mediaType?.startsWith('image/')
        })
        .map((part) => (part as { url: string }).url)
    }, [message.parts])

    // A tool part is "pending" until it reaches a terminal state. While any
    // tool on the last assistant message is still pending the turn isn't
    // done — the model will resume once the tool result arrives, even if the
    // SDK briefly reports status as 'ready' between the tool-call stream and
    // the follow-up request.
    const hasPendingToolCall = useMemo(() => {
      if (!isLastMessage || message.role !== 'assistant') return false
      return message.parts.some((part) => {
        if (!part.type?.startsWith('tool-')) return false
        const state = (part as { state?: string }).state
        return (
          state !== 'output-available' &&
          state !== 'output-error' &&
          state !== 'output-denied'
        )
      })
    }, [isLastMessage, message.role, message.parts])

    const pendingApprovals = useToolApprovalRequests((s) => s.pending)
    const awaitingApproval = useMemo(() => {
      if (!hasPendingToolCall) return false
      return message.parts.some((part) => {
        const toolCallId = (part as { toolCallId?: string }).toolCallId
        return Boolean(toolCallId && pendingApprovals[toolCallId])
      })
    }, [hasPendingToolCall, message.parts, pendingApprovals])

    const usedSkills = useMemo(
      () => usedSkillNames(message.parts as never),
      [message.parts]
    )

    const isStreaming =
      (isLastMessage &&
        (status === CHAT_STATUS.STREAMING ||
          status === CHAT_STATUS.SUBMITTED)) ||
      hasPendingToolCall

    // Aggregate RAG citations in part order and record each rag tool part's
    // base offset, so its card numbers/anchors continue the same global
    // sequence the inline superscript markers use.
    const { ragCitations, citationOffsets, webCitations } = useMemo(() => {
      const out: RagCitation[] = []
      const web: WebCitation[] = []
      const offsets = new Map<number, number>()
      if (message.role === 'assistant') {
        const parts = message.parts as any[]
        for (let i = 0; i < parts.length; i++) {
          const part = parts[i]
          if (!part.type?.startsWith('tool-')) continue
          if (part.state !== 'output-available') continue
          // A contributed tool's output is its extension's text: citations in
          // it would put favicons from any host in the footer and the chips.
          if (isExtensionToolName(part.type.slice('tool-'.length))) continue
          const parsed = parseCitationsFromToolOutput(part.output)
          if (parsed?.kind === 'rag') {
            offsets.set(i, out.length)
            out.push(...parsed.citations)
          } else if (parsed?.kind === 'web') {
            web.push(...parsed.citations)
          }
        }
      }
      return { ragCitations: out, citationOffsets: offsets, webCitations: web }
    }, [message.parts, message.role])

    const serviceHub = useServiceHub()
    const grounding = useGroundingStore((s) => s.byMessageId[message.id])
    const ensureGrounding = useGroundingStore((s) => s.ensure)

    const assistantText = useMemo(() => {
      if (message.role !== 'assistant') return ''
      return (message.parts as any[])
        .filter((p) => p.type === CONTENT_TYPE.TEXT && p.text)
        .map((p) => p.text)
        .join('\n')
    }, [message.parts, message.role])

    useEffect(() => {
      if (isStreaming) return
      if (!assistantText || !ragCitations.length) return
      const rag = serviceHub.rag()
      if (!rag.embed) return
      ensureGrounding(
        message.id,
        assistantText,
        ragCitations,
        rag.embed.bind(rag)
      )
    }, [
      isStreaming,
      assistantText,
      ragCitations,
      message.id,
      ensureGrounding,
      serviceHub,
    ])

    const setWebCitations = useWebCitationStore((s) => s.setForMessage)
    useEffect(() => {
      if (!webCitations.length) return
      setWebCitations(message.id, webCitations)
    }, [webCitations, message.id, setWebCitations])

    // Extract file metadata from message text (for user messages with attachments)
    const attachedFiles = useMemo(() => {
      if (message.role !== 'user') return []

      const textParts = message.parts.filter(
        (part): part is { type: 'text'; text: string } =>
          part.type === CONTENT_TYPE.TEXT
      )

      if (textParts.length === 0) return []

      const { files } = extractFilesFromPrompt(textParts[0].text)
      return files
    }, [message.parts, message.role])

    // Get full text content for copy button
    const getFullTextContent = useCallback(() => {
      return message.parts
        .filter(
          (part): part is { type: 'text'; text: string } =>
            part.type === CONTENT_TYPE.TEXT
        )
        .map((part) => part.text)
        .join('\n')
    }, [message.parts])

    // Copy stays visible on the last message, the one most often copied, and
    // on any message with versions, where it anchors the always-visible
    // version switcher beside it. Elsewhere it joins the hover reveal so the
    // history stays uncluttered.
    const hasVersions = Boolean(
      versionInfo && versionInfo.count > 1 && onSwitchVersion
    )
    const copyButton = (
      <div
        className={cn(
          'flex items-center',
          !isLastMessage && !hasVersions && hoverReveal
        )}
      >
        <CopyButton text={getFullTextContent()} />
      </div>
    )

    const renderTextPart = (
      part: { type: 'text'; text: string },
      partIndex: number
    ) => {
      if (!part.text || part.text.trim() === '') {
        return null
      }

      const isLastPart = partIndex === message.parts.length - 1

      // For user messages, extract and clean the text from file metadata
      const displayText =
        message.role === 'user'
          ? extractFilesFromPrompt(part.text).cleanPrompt
          : part.text

      if (
        !displayText.trim() &&
        message.role === 'user' &&
        attachedFiles.length === 0
      ) {
        return null
      }

      return (
        <div key={`${message.id}-${partIndex}`} className="w-full">
          {message.role === 'user' ? (
            <div className="flex justify-end w-full h-full text-start wrap-break-word whitespace-normal">
              <div
                className={cn(
                  'relative p-2 rounded-md inline-block max-w-[80%]',
                  coloredUserBubble
                    ? 'bg-primary text-primary-foreground'
                    : 'bg-secondary text-foreground'
                )}
              >
                {/* Show attached files if any */}
                {attachedFiles.length > 0 && (
                  <div className="flex flex-wrap gap-2 mb-3">
                    {attachedFiles.map((file: FileMetadata, idx: number) => (
                      <div
                        key={`file-${idx}-${file.id}`}
                        className="flex items-center gap-1.5 px-2 py-1 rounded-sm bg-secondary text-secondary-foreground border text-xs"
                      >
                        <IconPaperclip
                          size={14}
                          className="text-muted-foreground"
                        />
                        <span className="font-medium">{file.name}</span>
                        {file.injectionMode && (
                          <span className="text-muted-foreground">
                            ({file.injectionMode})
                          </span>
                        )}
                      </div>
                    ))}
                  </div>
                )}
                {displayText && (
                  <div dir="auto" className="select-text whitespace-pre-wrap">
                    {highlightedPrefix && displayText.startsWith(highlightedPrefix) ? (
                      <>
                        <span
                          data-testid="skill-command-prefix"
                          className="rounded-sm bg-primary-foreground/20 px-1 font-medium"
                        >
                          {highlightedPrefix}
                        </span>
                        {displayText.slice(highlightedPrefix.length)}
                      </>
                    ) : (
                      displayText
                    )}
                  </div>
                )}
              </div>
            </div>
          ) : (
            <>
              <RenderMarkdown
                content={
                  grounding && !isStreaming
                    ? injectCitationMarkers(
                        part.text,
                        grounding.sentenceCitations,
                        `cite-${message.id}`
                      )
                    : part.text
                }
                isStreaming={isStreaming && isLastPart}
                messageId={message.id}
                isAnimating={isAnimating}
                noRemoteImages={extensionAuthored}
              />
            </>
          )}
        </div>
      )
    }

    const renderFilePart = (part: MessagePartLike, partIndex: number) => {
      const isImage = part.mediaType?.startsWith('image/')
      const isAudio =
        part.mediaType === 'audio/wav' || part.mediaType === 'audio/mpeg'
      const isVideo = part.mediaType?.startsWith('video/')
      // Only inline media for extension-authored messages: a URL would be
      // fetched from whatever host it names.
      if (
        extensionAuthored &&
        part.url &&
        !/^(data|blob):/i.test(part.url)
      )
        return null

      if (isAudio && part.url) {
        const justify =
          message.role === 'user' ? 'justify-end' : 'justify-start'
        return (
          <div
            key={`${message.id}-${partIndex}`}
            className={`flex ${justify} w-full my-2`}
          >
            <audio controls src={part.url} className="max-w-[80%] rounded-md" />
          </div>
        )
      }

      if (isVideo && part.url) {
        const justify =
          message.role === 'user' ? 'justify-end' : 'justify-start'
        return (
          <div
            key={`${message.id}-${partIndex}`}
            className={`flex ${justify} w-full my-2`}
          >
            <video
              controls
              src={part.url}
              className="max-w-[80%] max-h-80 rounded-md border"
            />
          </div>
        )
      }

      if (message.role === 'user' && isImage && part.url) {
        return (
          <div
            key={`${message.id}-${partIndex}`}
            className="flex justify-end w-full my-2"
          >
            <div className="flex flex-wrap gap-2 max-w-[80%] justify-end">
              <div className="relative">
                <img
                  src={part.url}
                  alt={part.filename || 'Uploaded attachment'}
                  className="size-20 rounded-lg object-cover border cursor-pointer"
                  onClick={() =>
                    setPreviewImage({ url: part.url!, filename: part.filename })
                  }
                />
              </div>
            </div>
          </div>
        )
      }

      if (message.role === 'assistant' && isImage && part.url) {
        return (
          <div key={`${message.id}-${partIndex}`} className="my-2">
            <img
              src={part.url}
              alt={part.filename || 'Generated image'}
              className="max-w-full rounded-md cursor-pointer"
              onClick={() =>
                setPreviewImage({ url: part.url!, filename: part.filename })
              }
            />
          </div>
        )
      }

      return null
    }

    const renderedParts = useMemo(() => {
      const parts = message.parts as MessagePartLike[]
      const elements: React.ReactNode[] = []
      const isCotPart = (t: string) =>
        t === CONTENT_TYPE.REASONING || t.startsWith('tool-')

      // Walk parts sequentially and flush the reasoning/tool trace whenever a
      // non-empty answer (text/file) interrupts it, so content emitted between
      // two reasoning blocks renders as a normal message.
      let cotEntries: PartEntry[] = []
      let groupSeq = 0
      const flushCot = (hasFollowing: boolean) => {
        if (cotEntries.length === 0) return
        elements.push(
          <ChainOfThoughtGroup
            key={`${message.id}-cot-${groupSeq++}`}
            entries={cotEntries}
            messageId={message.id}
            totalParts={parts.length}
            isStreaming={isStreaming}
            hasFollowingContent={hasFollowing}
            awaitingApproval={awaitingApproval}
            citationOffsets={citationOffsets}
            reasoningContainerRef={reasoningContainerRef}
            isReasoningAtBottom={isReasoningAtBottom}
            onReasoningScroll={onReasoningScroll}
            onReasoningScrollToBottom={onReasoningScrollToBottom}
          />
        )
        cotEntries = []
      }

      for (let i = 0; i < parts.length; i++) {
        const part = parts[i]
        const t = part.type
        // A settled ask leaves the trace as a Q&A card, so the answers stay in
        // view instead of being folded into "Worked for…".
        if (t === `tool-${ASK_TOOL_NAME}` && part.state === 'output-available') {
          const rows = summarizeAsk(part.input, part.output)
          if (rows) {
            flushCot(true)
            elements.push(
              <AskSummaryCard key={`${message.id}-ask-${i}`} rows={rows} />
            )
            continue
          }
        }
        if (isCotPart(t)) {
          cotEntries.push({ part, index: i })
          continue
        }
        if (t === CONTENT_TYPE.TEXT) {
          if (!part.text || part.text.trim() === '') continue
          flushCot(true)
          elements.push(
            renderTextPart(part as { type: 'text'; text: string }, i)
          )
          continue
        }
        if (t === CONTENT_TYPE.FILE) {
          flushCot(true)
          elements.push(renderFilePart(part, i))
        }
      }
      flushCot(false)
      return elements
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
      message.parts,
      isStreaming,
      isReasoningAtBottom,
      grounding,
      awaitingApproval,
      citationOffsets,
      extensionAuthored,
    ])

    const versionNav =
      versionInfo && versionInfo.count > 1 && onSwitchVersion ? (
        <div className="flex items-center gap-0.5 text-muted-foreground">
          <button
            type="button"
            data-testid="message-version-prev"
            className="hover:text-foreground disabled:opacity-40"
            disabled={versionInfo.index <= 1}
            onClick={() => onSwitchVersion(message.id, -1)}
            title="Previous version"
          >
            <IconChevronLeft size={14} />
          </button>
          <span data-testid="message-version-counter" className="tabular-nums">
            {versionInfo.index}/{versionInfo.count}
          </span>
          <button
            type="button"
            data-testid="message-version-next"
            className="hover:text-foreground disabled:opacity-40"
            disabled={versionInfo.index >= versionInfo.count}
            onClick={() => onSwitchVersion(message.id, 1)}
            title="Next version"
          >
            <IconChevronRight size={14} />
          </button>
        </div>
      ) : null

    // A note the run folded into the conversation, not something either party
    // said: no actions, no trace, no timestamp. It is on screen because it is
    // what the next turn is replying to -- a turn that reacts to a subagent
    // finishing reads as a non sequitur without it.
    // A migrated Cowork ping is stored as the user turn the model saw and
    // flagged (see SYSTEM_NOTICE_KEY), so it takes the same template.
    if (message.role === 'system' || isSystemNotice(message)) {
      const note = getFullTextContent()
        .split(PING_OPEN)
        .join('')
        .split(PING_CLOSE)
        .join('')
        .trim()
      return (
        <div className="mb-4 inline-flex w-fit max-w-full items-center gap-2 self-start rounded-full border border-border/50 bg-main-view-fg/2 px-2.5 py-1 text-xs text-muted-foreground">
          <IconBellRinging size={14} className="shrink-0" />
          <span className="min-w-0 truncate">{note}</span>
        </div>
      )
    }

    // Off for a message an extension authored: every widget below that would
    // fetch an image by URL (citation favicons, the web tool bar) reads it.
    return withRemoteImages(
      !extensionAuthored,
      <div
        data-testid="message-item"
        data-message-role={message.role}
        // Kept tight: every message now carries a footer row (hidden until
        // hover), and that row already separates one turn from the next.
        className={cn(
          'w-full mb-2 group/message',
          message.role === 'user' && !isFirstMessage && 'mt-4'
        )}
      >
        {/* Render message parts. A turn alternates collapsed traces with
            answer paragraphs, and with no gap the two read as one block. */}
        <div className="flex flex-col gap-3">{renderedParts}</div>

        {message.role === 'assistant' &&
          !isStreaming &&
          webCitations.length > 0 && <WebSourcesRow citations={webCitations} />}

        {message.role === 'assistant' &&
          !isStreaming &&
          usedSkills.length > 0 && (
            <div
              aria-label={t('common:skillsUsedLabel')}
              className="mt-3 inline-flex rounded-full border border-border bg-muted/40 px-2.5 py-1 text-xs font-medium text-muted-foreground"
            >
              {t('common:skillsUsed', { skills: usedSkills.join(', ') })}
            </div>
          )}

        {/* Model-load and prompt-reading progress only: a running tool call
            reports itself on its own card, and a running subagent on the chip
            beside the composer. */}
        {isLastMessage &&
          message.role === 'assistant' &&
          !awaitingApproval &&
          (hasPendingToolCall || status === CHAT_STATUS.SUBMITTED) && (
            <div className="mt-3">
              <PromptProgress hideIdle={hasPendingToolCall} />
            </div>
          )}

        {typeof messageError === 'string' && messageError.length > 0 && (
          <div className="mt-3 flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-sm">
            <IconAlertTriangle
              size={16}
              className="mt-0.5 shrink-0 text-destructive"
            />
            <div className="flex-1 min-w-0">
              <div className="font-medium text-destructive">
                Generation failed
              </div>
              <div className="text-muted-foreground break-words">
                {messageError}
              </div>
              {/* Below the text rather than beside it: three actions in one
                  row squeezed the error into a narrow column. */}
              {(loadReport || canRegenerate) && (
                <div className="mt-2 flex flex-wrap items-center gap-2">
                  {loadReport && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        navigator.clipboard
                          .writeText(loadReport.text)
                          .then(() =>
                            toast.success(t('model-errors:diagnosticsCopied'))
                          )
                          .catch(() =>
                            toast.error(t('common:toast.errorCopyFailed.title'))
                          )
                      }}
                    >
                      <IconCopy size={14} />
                      <span>{t('model-errors:copyDiagnostics')}</span>
                    </Button>
                  )}
                  {canRegenerate && (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleRegenerate}
                    >
                      <IconRefresh size={14} />
                      <span>Regenerate</span>
                    </Button>
                  )}
                  {/* A load report is only built for a llama.cpp engine
                      failure, so its presence is what says the hardware check
                      has something to say about this message. The check itself
                      lives on the provider page; this carries the model over
                      rather than being a second place a minutes-long run can
                      start from. */}
                  {loadReport && diagnoseModel && (
                    <Link
                      to={route.settings.providers}
                      params={{ providerName: 'llamacpp' }}
                      search={{ diagnoseModel }}
                      className="whitespace-nowrap text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
                    >
                      {t('providers:diagnostics.checkThisModel')}
                    </Link>
                  )}
                </div>
              )}
            </div>
          </div>
        )}

        {/* Message actions for user messages. The bubble is right-aligned, so
            the row mirrors the assistant one: the date sits on the left and the
            actions on the right, with copy last so it stays at the bubble's edge.
            Only copy on the last message is always visible; the rest appear on
            hover or focus. */}
        {message.role === 'user' && !hideActions && (
          <div className="-mr-1.5 mt-0.5 flex items-center justify-end gap-2.5 text-muted-foreground text-xs">
            <time
              className={cn('text-muted-foreground', hoverReveal)}
              dateTime={createdAtIso}
              title={formatDate(createdAt)}
            >
              {formatMessageTime(createdAt)}
            </time>
            <div className={cn('flex items-center', FOOTER_ICON_BUTTONS)}>
              <div className={cn('flex items-center', hoverReveal)}>
                {/* Editing re-runs the turn, so with no model it is hidden
                    rather than shown disabled. */}
                {onEdit &&
                  selectedModel &&
                  status !== CHAT_STATUS.STREAMING &&
                  status !== CHAT_STATUS.SUBMITTED && (
                    <EditMessageDialog
                      message={getFullTextContent()}
                      imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
                      onSave={handleEdit}
                    />
                  )}

                {onRetry &&
                  status !== CHAT_STATUS.STREAMING &&
                  status !== CHAT_STATUS.SUBMITTED && (
                    <Button
                      variant="ghost"
                      size="icon-xs"
                      onClick={() => onRetry(message.id, getFullTextContent())}
                      title={t('chat:actions.askAgain')}
                    >
                      <IconRefresh size={16} className="text-muted-foreground" />
                    </Button>
                  )}

                {onDelete &&
                  status !== CHAT_STATUS.STREAMING &&
                  status !== CHAT_STATUS.SUBMITTED && (
                    <DeleteMessageDialog onDelete={handleDelete} />
                  )}

                {threadId && (
                  <ContributedOverflowMenu
                    location="message/actions"
                    context={{
                      location: 'message/actions',
                      threadId,
                      messageId: message.id,
                      role: 'user',
                    }}
                  />
                )}
              </div>
              {/* Shown at rest when there are versions, beside copy. */}
              {versionNav}
              {copyButton}
            </div>
          </div>
        )}

        {/* Message actions for assistant messages (non-tool). Mirrors the user
            row: the actions, then the date and token speed beside them, all
            hugging the message's leading edge. The icon buttons are 28px and
            butt together (same 28px pitch as 24px + gap-1, but a roomier hover
            highlight); -ml-1.5 cancels their padding so the first glyph lines
            up with the text above, and gap-2.5 between groups evens the
            visible gaps against the icon spacing. Only copy on the last message is
            always visible; everything else appears on hover or keyboard focus.
            The hidden controls keep their space (opacity, not display) so the
            row never shifts as the pointer moves in and out. */}
        {message.role === 'assistant' && !hideActions && (
          <div className="@container -ml-1.5 mt-1.5 flex items-center gap-2.5 text-muted-foreground text-xs">
            <div
              className={cn(
                'flex items-center',
                FOOTER_ICON_BUTTONS,
                (isStreaming || hideActions) && 'hidden'
              )}
            >
              {copyButton}
              {/* Shown at rest: it only appears on a stopped reply, and it is
                  the one way to resume it. */}
              {selectedModel &&
                onContinue &&
                !isStreaming &&
                isLastMessage &&
                canContinue && (
                  <Button
                    variant="ghost"
                    size="icon-xs"
                    data-testid="continue-message"
                    onClick={handleContinue}
                    title={t('chat:actions.continue')}
                    aria-label={t('chat:actions.continue')}
                  >
                    <IconPlayerPlay size={16} aria-hidden="true" />
                  </Button>
                )}
              {/* Shown at rest when there are versions (copy is then shown
                  too, so the pair sits at the leading edge together). */}
              {versionNav}
              <div className={cn('flex items-center', hoverReveal)}>
                <RememberButton text={getFullTextContent()} />

                {onEdit && selectedModel && !isStreaming && (
                  <EditMessageDialog
                    message={getFullTextContent()}
                    onSave={handleEdit}
                  />
                )}

                {onDelete && !isStreaming && (
                  <DeleteMessageDialog onDelete={handleDelete} />
                )}

                {selectedModel &&
                  onRegenerate &&
                  !isStreaming &&
                  isLastMessage && (
                    <Button
                      variant="ghost"
                      size="icon-xs"
                      data-testid="regenerate-message"
                      onClick={handleRegenerate}
                      title={t('chat:actions.regenerate')}
                    >
                      <IconRefresh size={16} />
                    </Button>
                  )}

                {threadId && (
                  <ContributedOverflowMenu
                    location="message/actions"
                    context={{
                      location: 'message/actions',
                      threadId,
                      messageId: message.id,
                      role: 'assistant',
                    }}
                  />
                )}
              </div>
            </div>

            <div
              className={cn(
                'flex items-center gap-4',
                hoverReveal
              )}
            >
              {!isStreaming && (
                <time
                  className="text-muted-foreground"
                  dateTime={createdAtIso}
                  title={formatDate(createdAt)}
                >
                  {formatMessageTime(createdAt)}
                </time>
              )}
              <TokenSpeedIndicator streaming={isStreaming} metadata={metadata} />
            </div>
          </div>
        )}

        {/* Image Preview Dialog */}
        {previewImage && (
          <div
            className="fixed inset-0 z-100 bg-black/50 backdrop-blur-md flex items-center justify-center cursor-pointer"
            onClick={() => setPreviewImage(null)}
          >
            <img
              src={previewImage.url}
              alt={previewImage.filename || 'Preview'}
              className="max-h-[90vh] max-w-[90vw] object-contain"
              onClick={(e) => e.stopPropagation()}
            />
          </div>
        )}
      </div>
    )
  },
  (prevProps, nextProps) => {
    // Always re-render if the last message is in-flight (streaming or submitted)
    if (
      nextProps.isLastMessage &&
      (nextProps.status === CHAT_STATUS.STREAMING ||
        nextProps.status === CHAT_STATUS.SUBMITTED)
    ) {
      return false
    }

    return (
      prevProps.message === nextProps.message &&
      prevProps.isFirstMessage === nextProps.isFirstMessage &&
      prevProps.isLastMessage === nextProps.isLastMessage &&
      prevProps.status === nextProps.status &&
      prevProps.hideActions === nextProps.hideActions &&
      prevProps.threadId === nextProps.threadId &&
      prevProps.versionInfo?.index === nextProps.versionInfo?.index &&
      prevProps.versionInfo?.count === nextProps.versionInfo?.count
    )
  }
)

MessageItem.displayName = 'MessageItem'