Skip to content

The agent that grows with you

14.5 KB
Raw Blame
import { useStore } from '@nanostores/react'

import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
import { Tip, TipKeybindLabel } from '@/components/ui/tooltip'
import { useI18n } from '@/i18n'
import { triggerHaptic } from '@/lib/haptics'
import { hostHas } from '@/lib/host-capabilities'
import { Ear, EarOff, iconSize, Layers3, Loader2, Square } from '@/lib/icons'
import { cn } from '@/lib/utils'
import { recordAction } from '@/store/desktop-metrics'
import { $hudMode, closeHud, resetHudLayout } from '@/store/hud'
import { $wakeWord, toggleWakeWord } from '@/store/wake-word'

import { ACTIVE_ICON_BTN, GHOST_ICON_BTN, PRIMARY_ICON_BTN } from './control-classes'
import type { ConversationStatus } from './hooks/use-voice-conversation'
import { ModelPill } from './model-pill'
import { ReasoningPill } from './reasoning-pill'
import { StartVoiceButton } from './start-voice-button'
import type { ChatBarState, VoiceStatus } from './types'
import { VoiceFan } from './voice-fan'
import { VoiceMenu } from './voice-menu'

// Re-exported: `context-menu.tsx` and other row neighbours have always reached
// for these here, and the row is where they read as belonging.
export { ACTIVE_ICON_BTN, GHOST_ICON_BTN, ICON_BTN, PRIMARY_ICON_BTN } from './control-classes'

// iOS fires mousedown after touchend, and its default blurs the editor before
// submit runs. The browser-hosted Desktop keeps focus where it was so a send
// leaves the keyboard as it was. Native Desktop keeps the press's blur, which
// closes an open completion list and clears a composition the IME never ended.
const keepEditorFocus = (event: { preventDefault: () => void }) => {
  if (hostHas('keepFocusOnPress')) {
    event.preventDefault()
  }
}

interface ConversationProps {
  active: boolean
  level: number
  muted: boolean
  status: ConversationStatus
  onEnd: () => void
  onStart: () => void
  onStopTurn: () => void
  onToggleMute: () => void
}

export function ComposerControls({
  autoSpeak,
  busy,
  busyAction,
  canSubmit,
  cardWaiting = false,
  compactModelPill = false,
  conversation,
  disabled,
  foldVoice = false,
  hasComposerPayload,
  hideModelPill = false,
  minimal = false,
  state,
  voiceStatus,
  onDictate,
  onQueue,
  onSteer,
  onToggleAutoSpeak
}: {
  autoSpeak: boolean
  busy: boolean
  busyAction: 'interrupt' | 'steer' | 'queue' | 'stop'
  canSubmit: boolean
  /** A card parked on the session takes typed text as its answer, so queueing that text would leave the card waiting. */
  cardWaiting?: boolean
  compactModelPill?: boolean
  conversation: ConversationProps
  disabled: boolean
  foldVoice?: boolean
  hasComposerPayload: boolean
  hideModelPill?: boolean
  minimal?: boolean
  state: ChatBarState
  voiceStatus: VoiceStatus
  onDictate: () => void
  onQueue: () => void
  onSteer?: () => void
  onToggleAutoSpeak: () => void
}) {
  const { t } = useI18n()
  const c = t.composer
  const hudMode = useStore($hudMode)

  if (conversation.active) {
    return <ConversationPill {...conversation} disabled={disabled} />
  }

  const showVoicePrimary = !busy && !hasComposerPayload
  // Steer is just send: a payload keeps the Send affordance mid-turn (it answers
  // a waiting card). Stop only when the composer is empty and a turn is running.
  const showStop = busy && !hasComposerPayload

  const showQueueButton = queueButtonVisible(busy, busyAction, hasComposerPayload, cardWaiting)

  // A waiting card takes the draft as its answer through Send, whatever the busy action.
  const sendLabel = composerSendLabel(busy && !cardWaiting, busyAction, c)

  // The HUD is a Spotlight bar a few hundred pixels wide, so the four separate
  // voice toggles fold into one menu there and leave the row to the input. A
  // narrow tile hits the same wall from the other direction and folds for the
  // same reason — same controls, same state, different budget. Below that
  // even the menu goes: at `minimal` the row is the send button and nothing
  // else, which is the one thing that must survive every width.
  const foldedVoice = hudMode || foldVoice

  const voiceControls = foldedVoice ? (
    <VoiceMenu
      autoSpeak={autoSpeak}
      disabled={disabled}
      onDictate={onDictate}
      onStartConversation={conversation.onStart}
      onToggleAutoSpeak={onToggleAutoSpeak}
      state={state}
      voiceStatus={voiceStatus}
    />
  ) : (
    // One mic in the row; hovering it fans the other voice toggles out of it.
    <VoiceFan
      autoSpeak={autoSpeak}
      disabled={disabled}
      onDictate={onDictate}
      onToggleAutoSpeak={onToggleAutoSpeak}
      state={state}
      voiceStatus={voiceStatus}
    />
  )

  // The browser host's touch-size controls can outgrow a minimal row, so there
  // they pack to the end and wrap. Native Desktop keeps main's single row.
  const browserHost = hostHas('touchSizedControls')

  return (
    <div
      className={cn('flex min-w-0 shrink items-center gap-(--composer-control-gap)', browserHost && 'justify-end')}
      style={{ flexWrap: browserHost && minimal ? 'wrap' : undefined }}
    >
      {minimal ? null : (
        <>
          {hideModelPill ? null : (
            <>
              <ModelPill compact={compactModelPill} disabled={disabled} model={state.model} />
              {compactModelPill ? null : <ReasoningPill disabled={disabled} model={state.model} />}
            </>
          )}
          {voiceControls}
        </>
      )}
      {renderSteerButton(busy, busyAction, onSteer, disabled, c.steer)}
      {showQueueButton ? (
        <Tip label={<TipKeybindLabel actionId="composer.queue" text={c.queueMessage} />} placement="control">
          <Button
            aria-label={c.queueMessage}
            className={GHOST_ICON_BTN}
            disabled={disabled}
            onClick={onQueue}
            onMouseDown={keepEditorFocus}
            size="icon"
            type="button"
            variant="ghost"
          >
            <Layers3 className={iconSize.sm} />
          </Button>
        </Tip>
      ) : null}
      {showVoicePrimary ? (
        <StartVoiceButton disabled={disabled} label={c.startVoice} onStart={conversation.onStart} />
      ) : (
        <Tip
          label={
            showStop ? (
              <TipKeybindLabel actionId="composer.send" text={c.stop} />
            ) : (
              <TipKeybindLabel actionId="composer.send" text={sendLabel} />
            )
          }
          placement="control"
        >
          <Button
            aria-label={showStop ? c.stop : sendLabel}
            className={PRIMARY_ICON_BTN}
            disabled={disabled || !canSubmit}
            onClick={() => recordAction(showStop ? 'composer.cancel' : 'composer.send', 'click')}
            onMouseDown={keepEditorFocus}
            type="submit"
          >
            {showStop ? (
              <span className="block size-2.5 rounded-[0.1875rem] bg-current" />
            ) : (
              <Codicon name="arrow-up" size="0.875rem" />
            )}
          </Button>
        </Tip>
      )}
      {/* The way out of HUD mode, riding the controls row rather than floating
          above the bar. The old chip lived in a 26px transparent strip reserved
          over the composer (--hud-chip-strip), which under glass is bare
          untinted material with a hidden button in it — a band of chrome above
          the surface, paid for in every state, for a control that is invisible
          until hovered. Here it costs no reserved space and sits with the other
          things you can press. */}
      {hudMode ? <HudWindowButtons /> : null}
    </div>
  )
}

// Queue is the secondary mid-turn action: never while the primary button already queues or stops, and
// never while a card waits (its Send answers the card).
function queueButtonVisible(
  busy: boolean,
  busyAction: 'interrupt' | 'steer' | 'queue' | 'stop',
  hasPayload: boolean,
  cardWaiting: boolean
): boolean {
  return busy && busyAction !== 'stop' && busyAction !== 'queue' && hasPayload && !cardWaiting
}

function composerSendLabel(
  busy: boolean,
  busyAction: 'interrupt' | 'steer' | 'queue' | 'stop',
  c: { redirect: string; queueMessage: string; send: string; steer: string; stop: string }
): string {
  return busy ? { interrupt: c.redirect, queue: c.queueMessage, steer: c.steer, stop: c.stop }[busyAction] : c.send
}

function renderSteerButton(
  busy: boolean,
  busyAction: 'interrupt' | 'steer' | 'queue' | 'stop',
  onSteer: (() => void) | undefined,
  disabled: boolean,
  label: string
) {
  return busy && busyAction !== 'steer' && onSteer ? (
    <Tip label={label}>
      <Button
        aria-label={label}
        className={GHOST_ICON_BTN}
        disabled={disabled}
        onClick={onSteer}
        size="icon"
        type="button"
        variant="ghost"
      >
        <Codicon name="debug-step-over" size="0.875rem" />
      </Button>
    </Tip>
  ) : null
}

function HudWindowButtons() {
  const { t } = useI18n()

  return (
    <>
      <Tip label={t.titlebar.resetHudLayout} placement="toolbar">
        <Button
          aria-label={t.titlebar.resetHudLayout}
          className={cn(GHOST_ICON_BTN, 'p-0')}
          onClick={resetHudLayout}
          size="icon"
          type="button"
          variant="ghost"
        >
          <Codicon name="discard" size="0.875rem" />
        </Button>
      </Tip>
      <Tip label={t.titlebar.exitHud} placement="toolbar">
        <Button
          aria-label={t.titlebar.exitHud}
          className={cn(GHOST_ICON_BTN, 'p-0')}
          onClick={closeHud}
          size="icon"
          type="button"
          variant="ghost"
        >
          <Codicon name="screen-normal" size="0.875rem" />
        </Button>
      </Tip>
    </>
  )
}

function ConversationPill({
  disabled,
  level,
  muted,
  onEnd,
  onStopTurn,
  onToggleMute,
  status
}: ConversationProps & { disabled: boolean }) {
  const { t } = useI18n()
  const c = t.composer
  const speaking = status === 'speaking'
  const listening = status === 'listening' && !muted

  const label =
    status === 'speaking'
      ? c.speaking
      : status === 'transcribing'
        ? c.transcribing
        : status === 'thinking'
          ? c.thinking
          : muted
            ? c.muted
            : c.listening

  return (
    <div className="ml-auto flex shrink-0 items-center gap-(--composer-control-gap)">
      {/* Keep the ear visible during voice chat — shown paused, since the
          conversation holds the mic (the one time wake must not listen). */}
      <WakeWordButton disabled={disabled} pausedForVoice />
      <Tip label={muted ? c.unmuteMic : c.muteMic} placement="control">
        <Button
          aria-label={muted ? c.unmuteMic : c.muteMic}
          aria-pressed={muted}
          className={cn(GHOST_ICON_BTN, 'p-0', muted && 'bg-muted text-muted-foreground')}
          disabled={disabled}
          onClick={() => {
            triggerHaptic('selection')
            onToggleMute()
          }}
          size="icon"
          type="button"
          variant="ghost"
        >
          <Codicon name={muted ? 'mic-off' : 'mic'} size="1rem" />
        </Button>
      </Tip>
      {listening && (
        <Button
          aria-label={c.stopListening}
          className="h-(--composer-control-size) shrink-0 gap-1.5 rounded-full px-2.5 text-xs text-muted-foreground hover:bg-accent hover:text-foreground"
          disabled={disabled}
          onClick={() => {
            triggerHaptic('submit')
            onStopTurn()
          }}
          type="button"
          variant="ghost"
        >
          <Square className={cn('fill-current', iconSize.xs)} />
          <span>{c.stopShort}</span>
        </Button>
      )}
      <Button
        aria-label={c.endConversation}
        className="h-(--composer-control-size) gap-1.5 rounded-full bg-primary px-3 text-xs font-medium text-primary-foreground hover:bg-primary/90"
        disabled={disabled}
        onClick={() => {
          triggerHaptic('close')
          onEnd()
        }}
        type="button"
      >
        <ConversationIndicator level={level} listening={listening} speaking={speaking} />
        <span>{c.endShort}</span>
      </Button>
      <span className="sr-only" role="status">
        {label}
      </span>
    </div>
  )
}

function ConversationIndicator({
  level,
  listening,
  speaking
}: {
  level: number
  listening: boolean
  speaking: boolean
}) {
  if (speaking) {
    return <Loader2 className={cn('animate-spin', iconSize.xs)} />
  }

  const bars = [0.55, 0.85, 1, 0.85, 0.55]
  const normalized = Math.max(0, Math.min(level, 1))

  return (
    <span aria-hidden="true" className="flex h-3 items-center gap-0.5">
      {bars.map((weight, index) => {
        const height = listening ? 0.3 + Math.min(0.7, normalized * weight) : 0.3

        return <span className="w-0.5 rounded-full bg-current" key={index} style={{ height: `${height * 100}%` }} />
      })}
    </span>
  )
}

// "Hey Hermes" wake-word toggle. ALWAYS rendered — the ear never hides. A
// user must always be able to click it to turn passive listening on; if the
// backend can't start (missing STT/TTS, deps still installing, no mic
// permission, etc.) the click surfaces the reason in the tooltip and the
// toggle stays off. States: listening (accent-highlighted), off (muted
// ear-off), and paused-for-voice (disabled while a voice conversation holds
// the mic — the one time wake genuinely must not listen). Backend refusals
// ({started:false, reason}) keep the toggle off and put the reason/hint in
// the tooltip.
function WakeWordButton({ disabled, pausedForVoice = false }: { disabled: boolean; pausedForVoice?: boolean }) {
  const { t } = useI18n()
  const c = t.composer
  const wake = useStore($wakeWord)

  const phrase = wake.phrase || 'hey hermes'

  const label = pausedForVoice
    ? c.wakeWordPausedVoice(phrase)
    : wake.listening
      ? c.wakeWordListening(phrase)
      : c.wakeWordOff(phrase)

  const tooltip = !pausedForVoice && wake.notice ? `${label} — ${wake.notice}` : label

  return (
    <Tip label={tooltip} placement="control">
      <Button
        aria-label={label}
        aria-pressed={wake.listening && !pausedForVoice}
        className={cn(GHOST_ICON_BTN, 'p-0', wake.listening && !pausedForVoice && ACTIVE_ICON_BTN)}
        disabled={disabled || pausedForVoice || wake.pending}
        onClick={() => {
          triggerHaptic(wake.listening ? 'close' : 'open')
          void toggleWakeWord()
        }}
        size="icon"
        type="button"
        variant="ghost"
      >
        {wake.listening && !pausedForVoice ? <Ear className={iconSize.sm} /> : <EarOff className={iconSize.sm} />}
      </Button>
    </Tip>
  )
}