Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

9.1 KB
Raw Blame
import { useRef, useState } from 'react'
import { usePopoverPlatz } from '../../hooks/usePopoverPlatz'
import { useDismissOnEscape } from '../../hooks/useDismissOnEscape'
import { ChevronDown, ShieldCheck, Zap, ClipboardList } from 'lucide-react'
import { useChatStore } from '../../stores/chatStore'
import { useCodexStore } from '../../stores/codexStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useGenerationStore } from '../../stores/generationStore'
import { HINWEIS_TEXT, PUNKT_FARBE } from '../../lib/hinweis'
import {
  CODEX_MODES, CODEX_MODE_LABELS, CODEX_MODE_SHORT, CODEX_MODE_DESCRIPTIONS,
  type CodexMode,
} from '../../lib/codex-mode'

/**
 * Ask / Bypass / Plan for the Coding Agent (plan 2.6.6, C1).
 *
 * Lives in the CODE composer only, hooked in through ChatInput's
 * `composerActions` so ChatInput itself stays surface-neutral and the Chat tab
 * inherits nothing. The mode is remembered per conversation; a new one is
 * created in the mode picked on the start screen, else the last Ask/Bypass
 * picked here (codexStore.startConversationMode), otherwise
 * settings.codexDefaultMode applies. The trigger shows codexStore.nextSendMode,
 * the same answer the send reads. Picking one here NEVER writes the global settings,
 * so a running conversation and the Agent surface are untouched.
 *
 * A switch takes effect from the NEXT send. While a run is in flight the
 * trigger says so and the pick is parked, because the running turn resolved its
 * knobs when it started and quietly changing them mid-run is how a read-only
 * guarantee gets lost.
 */
const MODE_ICON: Record<CodexMode, typeof ShieldCheck> = {
  ask: ShieldCheck,
  bypass: Zap,
  plan: ClipboardList,
}

/**
 * Die drei Modi sind eine Kategorie, keine Ampel: eine Farbe pro Modus, damit
 * man den aktiven am Ausloeser erkennt, ohne ihn zu lesen.
 *
 * Bypass stand in Gelb und sah damit aus wie eine Dauerwarnung, obwohl im
 * Betrieb nichts falsch ist, wenn er an ist. Neu ist Blaugruen, und zwar
 * gegen die drei Farben geprueft, die in dieser Datei sonst noch vorkommen:
 * Blau gehoert Ask, Violett gehoert Plan, und das Gruen von `PUNKT_FARBE.an`
 * gehoert dem Punkt, der sagt, dass gerade ein Lauf laeuft.
 */
const MODE_ACCENT: Record<CodexMode, string> = {
  ask: 'text-blue-400',
  bypass: 'text-teal-400',
  plan: 'text-purple-400',
}

const MODE_ACTIVE_ROW: Record<CodexMode, string> = {
  ask: 'bg-blue-500/10 text-blue-600 dark:text-blue-400',
  bypass: 'bg-teal-500/10 text-teal-600 dark:text-teal-400',
  plan: 'bg-purple-500/10 text-purple-600 dark:text-purple-400',
}

export function CodexModeDropdown({ openUpward = false }: { openUpward?: boolean } = {}) {
  const [open, setOpen] = useState(false)
  useDismissOnEscape(open, () => setOpen(false))
  const menuRef = useRef<HTMLDivElement>(null)
  const menu = usePopoverPlatz(menuRef, open, { bevorzugt: openUpward ? 'oben' : 'unten' })
  const activeConvId = useChatStore((s) => s.activeConversationId)
  const defaultMode = useSettingsStore((s) => s.settings.codexDefaultMode)
  const parkedByConversation = useCodexStore((s) => s.parkedModeByConversation)
  const chooseCodexMode = useCodexStore((s) => s.chooseCodexMode)
  const chooseDraftMode = useCodexStore((s) => s.chooseDraftMode)
  const generating = useGenerationStore((s) => s.generating)

  const runActive = !!activeConvId && generating[activeConvId] === true
  // What the trigger shows is what the next send runs under (A37). While a run
  // is in flight that is the running turn's mode with the park beside it;
  // otherwise one store function answers for display and send alike, the
  // start screen without a conversation included.
  const current = useCodexStore((s) => runActive
    ? s.codexModeFor(activeConvId, defaultMode)
    : s.nextSendMode(activeConvId, defaultMode))
  const parked = activeConvId ? parkedByConversation[activeConvId] : undefined
  // Only worth showing while a run holds the change back. Once it is applied,
  // parked and current are the same value.
  const pending = runActive && parked && parked !== current ? parked : null

  const CurrentIcon = MODE_ICON[current]

  const pick = (mode: CodexMode) => {
    // On the start screen the pick waits for the conversation the send
    // creates. It used to be dropped, and the send then ran the last pick.
    if (!activeConvId) chooseDraftMode(mode)
    else chooseCodexMode(activeConvId, mode, runActive)
    setOpen(false)
  }

  return (
    <div className="relative shrink-0">
      <button
        onClick={() => setOpen(!open)}
        aria-haspopup="true"
        aria-expanded={open}
        title={
          runActive
            ? 'A run is in flight. A change here applies to the next message.'
            : CODEX_MODE_DESCRIPTIONS[current]
        }
        // whitespace-nowrap: this trigger grows when a run starts (the dot, or
        // a parked "then bypass"), and it sits in the composer row. Letting its
        // label break would put a second line inside the prompt window, which
        // is the thing the row was fixed for.
        className="flex items-center gap-1 whitespace-nowrap px-2 py-0.5 rounded border border-gray-200 dark:border-white/[0.06] hover:border-gray-400 dark:hover:border-white/15 text-gray-500 transition-colors text-[0.55rem]"
      >
        <CurrentIcon size={10} className={`shrink-0 ${MODE_ACCENT[current]}`} />
        <span className={MODE_ACCENT[current]}>{CODEX_MODE_SHORT[current]}</span>
        {pending ? (
          // Der geparkte Modus steht in SEINER Farbe, nicht in einer eigenen:
          // "then plan" in Violett sagt schon, worauf es hinausgeht. Vorher war
          // dieses Stueck gelb und behauptete damit einen dritten Zustand.
          <span className={`text-[0.5rem] ${MODE_ACCENT[pending]}`}>
            {`then ${CODEX_MODE_SHORT[pending]}`}
          </span>
        ) : runActive ? (
          // A run is in flight and nothing is parked yet. Say it on the
          // trigger, not only in the panel, so "applies to the next message" is
          // visible before the user clicks. Der Punkt sagt "laeuft", also die
          // gruene Stufe der Ampel aus `lib/hinweis.ts`; gelb hiess hier frueher
          // weder an noch aus.
          <span className={`w-1 h-1 shrink-0 rounded-full ${PUNKT_FARBE.an}`} />
        ) : null}
        <ChevronDown size={8} className={`shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          {/* left-0: the trigger sits at the LEFT of the composer row, so a
              menu hung off its right edge ran 240px to the left and the panel
              cut off the first letters ("ypass permissions", Gegenprobe
              01.10.2026). The room is to the right. */}
          <div ref={menuRef} style={menu.style} className={`absolute left-0 z-50 w-60 rounded-lg lu-elevated py-1.5 overflow-y-auto scrollbar-thin ${menu.nachOben ? 'bottom-full mb-1' : 'top-full mt-1'}`}>
            {runActive && (
              // Auskunft, kein Alarm: die Wahl geht nicht verloren, sie
              // wirkt nur spaeter. Ruhiger Ton aus `lib/hinweis.ts`.
              <p className={`px-3 pb-1 text-[0.5rem] leading-snug ${HINWEIS_TEXT.ruhig}`}>
                A run is in flight. Your pick applies from the next message.
              </p>
            )}
            <div className="px-1.5 space-y-0.5">
              {CODEX_MODES.map((mode) => {
                const Icon = MODE_ICON[mode]
                const isActive = mode === current
                const isPending = mode === pending
                return (
                  <button
                    key={mode}
                    onClick={() => pick(mode)}
                    className={`w-full flex items-start gap-1.5 px-2 py-1 rounded text-left transition-colors ${
                      isActive
                        ? MODE_ACTIVE_ROW[mode]
                        : 'text-gray-500 hover:bg-gray-50 dark:hover:bg-white/[0.04] hover:text-gray-700 dark:hover:text-gray-300'
                    }`}
                  >
                    <Icon size={10} className={`mt-px shrink-0 ${isActive ? '' : 'text-gray-400'}`} />
                    <span className="min-w-0">
                      <span className="flex items-center gap-1">
                        <span className="text-[0.55rem] font-medium">{CODEX_MODE_LABELS[mode]}</span>
                        {isActive && <span className="text-[0.45rem] text-gray-400">active</span>}
                        {isPending && (
                          // Wie am Ausloeser: in der Farbe des Modus, um
                          // den es geht, nicht in einer Warnfarbe.
                          <span className={`text-[0.45rem] ${MODE_ACCENT[mode]}`}>next</span>
                        )}
                      </span>
                      <span className="block text-[0.5rem] leading-snug text-gray-400">
                        {CODEX_MODE_DESCRIPTIONS[mode]}
                      </span>
                    </span>
                  </button>
                )
              })}
            </div>
          </div>
        </>
      )}
    </div>
  )
}