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.

design(W3): Kommandopalette und Kontextmenues — Desktop-Nativeness

Davidf265078809c0
diff --git a/src/components/__tests__/kommandopalette-aktionsherkunft.test.ts b/src/components/__tests__/kommandopalette-aktionsherkunft.test.ts
new file mode 100644
index 00000000..37efe102
--- /dev/null
+++ b/src/components/__tests__/kommandopalette-aktionsherkunft.test.ts
@@ -0,0 +1,316 @@
+/**
+ * Die Kommandopalette „über die VORHANDENEN Aktionen" — Audit Welle 3,
+ * Achse 11.
+ *
+ * Der teuerste Fehler wäre nicht ein hässlicher Dialog, sondern eine Palette,
+ * die die Aktionen NACHBAUT: ein zweiter Aufrufweg zu „Neuer Chat", der beim
+ * nächsten Umbau von Ctrl+N zurückbleibt. Der Kern dieser Datei ist deshalb
+ * ein Identitätsvergleich — `toBe`, nicht `toEqual`, nicht „ruft etwas
+ * Ähnliches": das `run` eines Eintrags MUSS dieselbe Funktion sein, die auch
+ * an der Taste bzw. am Knopf hängt.
+ *
+ * Was hier nicht geprüft werden kann: wie die Palette aussieht und ob der
+ * Fokus wirklich zurückkommt. Die Testumgebung ist `environment: 'node'`,
+ * es gibt kein Dokument. Alles Tastatur-, Rollen- und Fokusverhalten kommt
+ * darum aus `ui/Modal` bzw. `ui/dialog-a11y`, die eigene Tests haben; die
+ * letzten beiden Blöcke unten belegen nur noch, dass die Palette diesen Weg
+ * benutzt und keinen eigenen danebenstellt.
+ *
+ * Run: npx vitest run src/components/__tests__/kommandopalette-aktionsherkunft.test.ts
+ */
+import { describe, it, expect, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import {
+ buildCommands,
+ matchCommands,
+ resolveActiveIndex,
+ type Command,
+ type CommandContext,
+} from '../ui/command-actions'
+import { SHORTCUT_ACTIONS, shortcutKeys, type ShortcutId } from '../../hooks/useKeyboardShortcuts'
+
+const SRC = resolve(__dirname, '..', '..')
+const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')
+
+function ctxWith(over: Partial<CommandContext> = {}) {
+ const base: CommandContext = {
+ shortcuts: SHORTCUT_ACTIONS,
+ keysFor: shortcutKeys,
+ setView: vi.fn(),
+ openCompare: vi.fn(),
+ toggleSidebar: vi.fn(),
+ setActiveModel: vi.fn(),
+ models: [{ name: 'qwen3:4b' }, { name: 'hermes-3' }],
+ activeModel: 'hermes-3',
+ localViewsAvailable: true,
+ quit: vi.fn(),
+ }
+ return { ...base, ...over }
+}
+
+const byId = (cmds: readonly Command[], id: string) => cmds.find(c => c.id === id)
+
+describe('jeder Eintrag hat eine vorhandene Aktion dahinter', () => {
+ it('die Kürzel-Einträge SIND die Kürzel-Aktionen, keine Kopie', () => {
+ const cmds = buildCommands(ctxWith())
+ const pairs: [string, ShortcutId][] = [
+ ['new-conversation', 'new-conversation'],
+ ['focus-chat-input', 'focus-chat-input'],
+ ['export-chat', 'export-chat'],
+ ['toggle-theme', 'toggle-theme'],
+ ['show-shortcuts', 'show-shortcuts'],
+ ]
+ for (const [cmdId, shortcutId] of pairs) {
+ expect(byId(cmds, cmdId)?.run).toBe(SHORTCUT_ACTIONS[shortcutId])
+ }
+ })
+
+ it('und sie zeigen die Beschriftung aus DERSELBEN Liste', () => {
+ const cmds = buildCommands(ctxWith())
+ expect(byId(cmds, 'new-conversation')?.keys).toBe(shortcutKeys('new-conversation'))
+ expect(byId(cmds, 'toggle-theme')?.keys).toBe('Ctrl+Shift+D')
+ })
+
+ it('Navigation ruft setView der Kopfzeile, mit dem richtigen Ziel', () => {
+ const ctx = ctxWith()
+ const cmds = buildCommands(ctx)
+ for (const [id, view] of [['view-chat', 'chat'], ['view-create', 'create'], ['view-models', 'models'], ['view-benchmark', 'benchmark'], ['view-settings', 'settings']] as const) {
+ byId(cmds, id)?.run()
+ expect(ctx.setView).toHaveBeenLastCalledWith(view)
+ }
+ })
+
+ it('Compare ist der gemeinsame openCompare, nicht zwei eigene Zeilen', () => {
+ const ctx = ctxWith()
+ expect(byId(buildCommands(ctx), 'view-compare')?.run).toBe(ctx.openCompare)
+ })
+
+ it('Sidebar ist toggleSidebar des Stores', () => {
+ const ctx = ctxWith()
+ expect(byId(buildCommands(ctx), 'toggle-sidebar')?.run).toBe(ctx.toggleSidebar)
+ })
+
+ it('Modellwechsel ruft setActiveModel mit dem Namen der Karte', () => {
+ const ctx = ctxWith()
+ byId(buildCommands(ctx), 'model:qwen3:4b')?.run()
+ expect(ctx.setActiveModel).toHaveBeenCalledWith('qwen3:4b')
+ })
+
+ it('das bereits aktive Modell bekommt keinen Eintrag, der nichts tut', () => {
+ const cmds = buildCommands(ctxWith())
+ expect(byId(cmds, 'model:hermes-3')).toBeUndefined()
+ expect(byId(cmds, 'model:qwen3:4b')).toBeDefined()
+ })
+
+ it('Quit ist der Tray-Eintrag — und fehlt, wo es ihn nicht gibt', () => {
+ const ctx = ctxWith()
+ expect(byId(buildCommands(ctx), 'quit')?.run).toBe(ctx.quit)
+ // Im Browser (kein Tauri) gibt es die Backend-Aktion nicht. Ein Eintrag
+ // ohne Aktion dahinter wäre eine Attrappe, also gibt es ihn dort nicht.
+ expect(byId(buildCommands(ctxWith({ quit: null })), 'quit')).toBeUndefined()
+ })
+
+ it('Cloud-Modus zeigt keine Ziele, die die Kopfzeile dort ausblendet', () => {
+ const cloud = buildCommands(ctxWith({ localViewsAvailable: false }))
+ expect(byId(cloud, 'view-models')).toBeUndefined()
+ expect(byId(cloud, 'view-benchmark')).toBeUndefined()
+ expect(byId(cloud, 'view-settings')).toBeDefined()
+ })
+
+ it('kein Eintrag ohne ausführbares run — nirgends eine Attrappe', () => {
+ for (const cmd of buildCommands(ctxWith())) {
+ expect(cmd.run).toBeTypeOf('function')
+ expect(cmd.label.trim().length).toBeGreaterThan(0)
+ }
+ })
+})
+
+describe('Suche: Teilwort-Treffer, mehrere Wörter, sinnvolle Reihenfolge', () => {
+ const cmds = buildCommands(ctxWith())
+ const ids = (q: string) => matchCommands(q, cmds).map(c => c.id)
+
+ it('leere Anfrage zeigt alles — bis auf das, was nur gesucht erscheint', () => {
+ const shown = matchCommands('', cmds)
+ expect(shown.length).toBe(cmds.length - 1)
+ expect(shown.some(c => c.id === 'quit')).toBe(false)
+ })
+
+ it('Teilwort in der Mitte trifft', () => {
+ expect(ids('conversation')).toContain('new-conversation')
+ expect(ids('sidebar')).toContain('toggle-sidebar')
+ })
+
+ it('mehrere Wörter müssen ALLE treffen', () => {
+ expect(ids('toggle dark')).toContain('toggle-theme')
+ expect(ids('toggle zzz')).toHaveLength(0)
+ })
+
+ it('der Wortanfang steht vor dem Treffer mitten im Wort', () => {
+ // „Export chat as Markdown" beginnt mit dem Wort, „Focus chat input" hat
+ // es in der Mitte — also kommt Export zuerst.
+ const order = ids('export')
+ expect(order[0]).toBe('export-chat')
+ })
+
+ it('Modellnamen mit Doppelpunkt zerfallen in benutzbare Stücke', () => {
+ expect(ids('qwen3')).toContain('model:qwen3:4b')
+ expect(ids('4b')).toContain('model:qwen3:4b')
+ })
+
+ it('Quit erscheint erst, wenn danach gesucht wird', () => {
+ expect(ids('quit')).toContain('quit')
+ })
+
+ it('keine Treffer heißt leere Liste, nicht die volle', () => {
+ expect(ids('xyzzy')).toHaveLength(0)
+ })
+
+ it('Groß/Kleinschreibung ist egal', () => {
+ expect(ids('SETTINGS')).toContain('view-settings')
+ })
+})
+
+describe('die Auswahl zeigt immer auf einen Eintrag, den es wirklich gibt', () => {
+ const cmds = (models: { name: string }[]) => buildCommands(ctxWith({ models, activeModel: null }))
+ const FIVE = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' }, { name: 'e' }]
+
+ it('die Liste schrumpft unter einer gehaltenen Auswahl — kein Griff ins Leere', () => {
+ // Der Fall aus der echten App: `buildCommands` haengt an der Modellliste,
+ // und die trifft ASYNCHRON ein. Bei offener Palette wird die Liste also
+ // laenger oder kuerzer, waehrend der Nutzer schon eine Zeile gewaehlt hat.
+ const lang = matchCommands('', cmds(FIVE))
+ const gehalten = lang.length - 2
+ expect(lang[gehalten]).toBeDefined()
+
+ // Jetzt faellt die Modellliste weg (Moduswechsel, oder sie kam neu).
+ const kurz = matchCommands('', cmds([]))
+ expect(kurz.length).toBeLessThan(lang.length)
+ expect(kurz[gehalten]).toBeUndefined() // ohne Klemmung genau hier der Fehler
+
+ const i = resolveActiveIndex({ active: gehalten, forQuery: '' }, '', kurz.length)
+
+ // Die FOLGE, nicht die Formel: es gibt einen Eintrag, und zwar den, den
+ // ein Nutzer nach dem Zusammenschrumpfen unten erwartet.
+ expect(kurz[i]).toBeDefined()
+ expect(i).toBe(kurz.length - 1)
+ expect(kurz[i].label).toBe('Keyboard shortcuts')
+ })
+
+ it('auch ein weit ueberzaehliger Index landet auf der letzten Zeile', () => {
+ const kurz = matchCommands('', cmds([]))
+ const i = resolveActiveIndex({ active: 999, forQuery: '' }, '', kurz.length)
+ expect(kurz[i]).toBeDefined()
+ expect(i).toBe(kurz.length - 1)
+ })
+
+ it('solange die Liste reicht, bleibt die Wahl unangetastet', () => {
+ // Die Gegenprobe zur Klemmung: sie darf nicht einfach immer nach unten
+ // ziehen, sonst koennte man mit den Pfeiltasten nicht navigieren.
+ const lang = matchCommands('', cmds(FIVE))
+ expect(resolveActiveIndex({ active: 3, forQuery: '' }, '', lang.length)).toBe(3)
+ })
+
+ it('eine leere Trefferliste ergibt 0 statt einer negativen Zahl', () => {
+ expect(resolveActiveIndex({ active: 5, forQuery: 'xyzzy' }, 'xyzzy', 0)).toBe(0)
+ })
+})
+
+describe('eine neue Suchanfrage waehlt den ersten Treffer', () => {
+ const cmds = buildCommands(ctxWith())
+
+ // Wichtig fuer die Aussagekraft: die neue Trefferliste muss LAENGER sein als
+ // der gehaltene Index. Sonst faengt die Klemmung den Index ohnehin auf 0 ab
+ // und der Test wuerde gruen bleiben, auch wenn das Zuruecksetzen fehlt —
+ // er wuerde dann etwas anderes pruefen, als sein Name behauptet.
+
+ it('die alte Wahl galt einer anderen Liste und wird nicht mitgeschleppt', () => {
+ const vorher = matchCommands('', cmds)
+ expect(vorher[2]).toBeDefined()
+
+ const treffer = matchCommands('chat', cmds)
+ expect(treffer.length).toBeGreaterThan(2) // sonst beweist der Test nichts
+
+ const i = resolveActiveIndex({ active: 2, forQuery: '' }, 'chat', treffer.length)
+
+ // Die FOLGE: ausgewaehlt ist der erste Treffer der NEUEN Anfrage.
+ expect(i).toBe(0)
+ expect(treffer[i].label).toBe('Chat')
+ })
+
+ it('und beim Loeschen der Anfrage zurueck an den Anfang der vollen Liste', () => {
+ const alle = matchCommands('', cmds)
+ expect(alle.length).toBeGreaterThan(3)
+
+ const i = resolveActiveIndex({ active: 3, forQuery: 'chat' }, '', alle.length)
+ expect(i).toBe(0)
+ expect(alle[i].label).toBe('New conversation')
+ })
+
+ it('auch von einer Anfrage direkt in die naechste', () => {
+ const treffer = matchCommands('to', cmds)
+ expect(treffer.length).toBeGreaterThan(2)
+
+ const i = resolveActiveIndex({ active: 2, forQuery: 'chat' }, 'to', treffer.length)
+ expect(i).toBe(0)
+ expect(treffer[i].label).toBe('Toggle sidebar')
+ })
+
+ it('dieselbe Anfrage laesst die Wahl stehen — sonst waere Navigieren unmoeglich', () => {
+ const treffer = matchCommands('chat', cmds)
+ expect(resolveActiveIndex({ active: 2, forQuery: 'chat' }, 'chat', treffer.length)).toBe(2)
+ })
+})
+
+describe('die Palette benutzt den Dialog-Hausstandard, statt ihn nachzubauen', () => {
+ const palette = read('components', 'ui', 'CommandPalette.tsx')
+
+ it('sie rendert in ui/Modal — dort sitzen Escape, Fokusfalle und Fokusrückgabe', () => {
+ expect(palette).toContain("import { Modal } from './Modal'")
+ expect(palette).toMatch(/<Modal\b/)
+ })
+
+ it('und hat KEINEN eigenen Escape-Pfad und keine eigene Fokusfalle', () => {
+ expect(palette).not.toMatch(/key === 'Escape'/)
+ expect(palette).not.toMatch(/key === 'Tab'/)
+ })
+
+ it('Suchfeld und Liste sind als Combobox ausgezeichnet', () => {
+ expect(palette).toContain('role="combobox"')
+ expect(palette).toContain('role="listbox"')
+ expect(palette).toContain('role="option"')
+ expect(palette).toContain('aria-activedescendant')
+ // Ohne sichtbaren Titel braucht der Dialog eine Beschriftung.
+ expect(palette).toContain('ariaLabel="Command palette"')
+ })
+
+ it('Pfeiltasten laufen über dieselbe zyklische Rechnung wie die Fokusfalle', () => {
+ expect(palette).toContain("import { nextFocusIndex } from './dialog-a11y'")
+ })
+
+ it('sie ist auch wirklich eingehängt', () => {
+ expect(read('components', 'layout', 'AppShell.tsx')).toContain('<CommandPalette />')
+ })
+
+ it('die Auswahl kommt aus resolveActiveIndex — sonst pruefen die zwei Bloecke darueber ins Leere', () => {
+ // QUELLTEXT-Zusicherung, ausdruecklich: dass die Komponente die geprueften
+ // Regeln auch BENUTZT, laesst sich ohne DOM nicht als Verhalten zeigen.
+ // Die Regeln selbst sind oben als Verhalten geprueft, diese Zeile haelt
+ // nur die Verdrahtung fest.
+ expect(palette).toContain('resolveActiveIndex(selection, query, shown.length)')
+ // Und dass die alte Buchfuehrung nicht heimlich zurueckkommt.
+ expect(palette).not.toMatch(/useEffect\(\(\) => \{ setActive\(0\) \}/)
+ expect(palette).not.toContain('Math.min(active,')
+ })
+
+ it('der Befehl wird NICHT an einen Animationsframe gehängt', () => {
+ // Live gemessen (2026-09-01): in einem verdeckten Fenster feuert
+ // `requestAnimationFrame` nicht — die Palette ging zu und der Befehl
+ // passierte nie. Diese App legt sich beim Schließen in den Tray,
+ // „verdeckt" ist hier also der Normalfall und kein Sonderfall.
+ // Auf den AUFRUF geprüft, nicht auf das Wort: im Kommentar darüber steht
+ // absichtlich, warum hier mal ein Animationsframe stand.
+ expect(palette).not.toMatch(/requestAnimationFrame\s*\(/)
+ expect(palette).toContain('setTimeout(() => cmd.run(), 0)')
+ })
+})
diff --git a/src/components/__tests__/kontextmenue-nachricht-und-modellkarte.test.ts b/src/components/__tests__/kontextmenue-nachricht-und-modellkarte.test.ts
new file mode 100644
index 00000000..dab2a015
--- /dev/null
+++ b/src/components/__tests__/kontextmenue-nachricht-und-modellkarte.test.ts
@@ -0,0 +1,223 @@
+/**
+ * Kontextmenüs auf Nachricht und Modellkarte — Audit Welle 3, Achse 11.
+ *
+ * Die Regel, um die es geht, ist nicht „es gibt ein Menü", sondern: ein Menü,
+ * das dieselbe Aktion anbietet wie ein sichtbarer Knopf, muss sie über
+ * DENSELBEN Code auslösen. Zwei Aufrufwege zur selben Aktion sind der Anfang
+ * des Musters, an dem dieses Projekt schon mehrfach gelitten hat.
+ *
+ * Prüfbar gemacht ist das über die Bauform: `buildMessageMenu` und
+ * `buildModelCardMenu` bekommen die Handler herein und reichen sie
+ * unverändert als `run` weiter — der Identitätsvergleich unten kann also
+ * scheitern, sobald jemand im Menü etwas nachbaut. Dazu kommt die Gegenprobe
+ * an der Quelle: die sichtbare Leiste liest aus demselben `actions`-Objekt,
+ * das ins Menü geht.
+ *
+ * Was hier NICHT geprüft werden kann: das gerenderte Menü. `environment:
+ * 'node'`, kein Dokument, kein Rechtsklick. Escape, Pfeiltasten und
+ * Fokusrückgabe von `ui/ContextMenu` sind unten nur als Quelltext belegt;
+ * die Rechnung dahinter (`nextFocusIndex`, Dialog-Stapel) hat eigene Tests
+ * in `ui/__tests__`.
+ *
+ * Run: npx vitest run src/components/__tests__/kontextmenue-nachricht-und-modellkarte.test.ts
+ */
+import { describe, it, expect, vi } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import {
+ buildMessageMenu,
+ buildModelCardMenu,
+ clampMenuPosition,
+ type MenuAction,
+ type MessageMenuHandlers,
+ type ModelMenuHandlers,
+} from '../ui/menu-actions'
+
+const SRC = resolve(__dirname, '..', '..')
+const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')
+
+const byId = (items: readonly MenuAction[], id: string) => items.find(i => i.id === id)
+
+function messageHandlers(over: Partial<MessageMenuHandlers> = {}): MessageMenuHandlers {
+ return { copy: vi.fn(), edit: vi.fn(), regenerate: vi.fn(), remove: vi.fn(), ...over }
+}
+
+describe('Nachricht: das Menü ruft die Funktionen der Aktionsleiste', () => {
+ const state = { copied: false, confirmDelete: false }
+
+ it('jede Aktion ist identisch mit dem Handler des Knopfes', () => {
+ const h = messageHandlers()
+ const items = buildMessageMenu(h, state)
+ expect(byId(items, 'copy')?.run).toBe(h.copy)
+ expect(byId(items, 'edit')?.run).toBe(h.edit)
+ expect(byId(items, 'regenerate')?.run).toBe(h.regenerate)
+ expect(byId(items, 'delete')?.run).toBe(h.remove)
+ })
+
+ it('das Menü bietet nichts an, was die Leiste nicht auch zeigt', () => {
+ // Eigene Nachricht: kein Regenerate. Genau wie in der Leiste.
+ const noRegen = buildMessageMenu(messageHandlers({ regenerate: null }), state)
+ expect(byId(noRegen, 'regenerate')).toBeUndefined()
+ // Antwort, die (noch) nicht bearbeitbar ist: kein Edit.
+ const noEdit = buildMessageMenu(messageHandlers({ edit: null }), state)
+ expect(byId(noEdit, 'edit')).toBeUndefined()
+ // Kopieren und Löschen kann man immer.
+ expect(byId(noEdit, 'copy')).toBeDefined()
+ expect(byId(noEdit, 'delete')).toBeDefined()
+ })
+
+ it('Löschen ist als zerstörend markiert — nichts anderes ist es', () => {
+ const items = buildMessageMenu(messageHandlers(), state)
+ expect(byId(items, 'delete')?.destructive).toBe(true)
+ for (const item of items) {
+ if (item.id !== 'delete') expect(item.destructive).toBeFalsy()
+ }
+ })
+
+ it('die Beschriftung sagt dasselbe wie der Knopf, auch im Zwischenzustand', () => {
+ // Der Löschknopf ist zweistufig (D#81): der erste Klick schärft nur.
+ const armed = buildMessageMenu(messageHandlers(), { copied: false, confirmDelete: true })
+ expect(byId(armed, 'delete')?.label).toBe('Click again to delete')
+ const copied = buildMessageMenu(messageHandlers(), { copied: true, confirmDelete: false })
+ expect(byId(copied, 'copy')?.label).toBe('Copied')
+ })
+})
+
+describe('Modellkarte: das Menü ruft die Prop-Handler der Karte', () => {
+ const handlers = (): ModelMenuHandlers => ({ select: vi.fn(), info: vi.fn(), remove: vi.fn() })
+
+ it('Details und Löschen sind identisch mit onInfo/onDelete', () => {
+ const h = handlers()
+ const items = buildModelCardMenu(h, { isActive: false, canDelete: true })
+ expect(byId(items, 'info')?.run).toBe(h.info)
+ expect(byId(items, 'delete')?.run).toBe(h.remove)
+ expect(byId(items, 'select')?.run).toBe(h.select)
+ })
+
+ it('nicht löschbare Modelle bekommen keinen Löschen-Eintrag', () => {
+ // Die Karte blendet den Knopf über `canDelete` aus; ein Menü, das ihn
+ // trotzdem zeigte, böte eine Aktion an, die es nicht gibt.
+ const items = buildModelCardMenu(handlers(), { isActive: false, canDelete: false })
+ expect(byId(items, 'delete')).toBeUndefined()
+ })
+
+ it('auf der aktiven Karte fehlt „Use this model" — es täte nichts', () => {
+ const items = buildModelCardMenu(handlers(), { isActive: true, canDelete: true })
+ expect(byId(items, 'select')).toBeUndefined()
+ expect(byId(items, 'info')).toBeDefined()
+ })
+})
+
+describe('Platzierung: das Menü bleibt im Fenster', () => {
+ const box = { width: 160, height: 120 }
+ const vp = { width: 1000, height: 800 }
+
+ it('normalerweise genau am Zeiger', () => {
+ expect(clampMenuPosition(300, 200, box, vp)).toEqual({ left: 300, top: 200 })
+ })
+
+ it('am rechten/unteren Rand kippt es vor den Zeiger statt hinauszuragen', () => {
+ expect(clampMenuPosition(980, 780, box, vp)).toEqual({ left: 820, top: 660 })
+ })
+
+ it('und rutscht nie ins Negative — der Fehler der Sidebar-Fassung', () => {
+ // `Math.min(x, innerWidth - 160)` ohne untere Schranke ergibt in einem
+ // schmalen Fenster ein negatives `left`, und das Menü hängt links raus.
+ const narrow = { width: 120, height: 100 }
+ const p = clampMenuPosition(10, 10, box, narrow)
+ expect(p.left).toBeGreaterThanOrEqual(0)
+ expect(p.top).toBeGreaterThanOrEqual(0)
+ })
+
+ it('auch wenn das Menü größer ist als das Fenster', () => {
+ const p = clampMenuPosition(50, 50, { width: 400, height: 400 }, { width: 200, height: 200 })
+ expect(p.left).toBeGreaterThanOrEqual(0)
+ expect(p.top).toBeGreaterThanOrEqual(0)
+ })
+})
+
+describe('ein Menü, ein Aufrufweg — Gegenprobe an der Quelle', () => {
+ it('MessageBubble: Leiste und Menü lesen aus DEMSELBEN actions-Objekt', () => {
+ const src = read('components', 'chat', 'MessageBubble.tsx')
+ expect(src).toContain('const actions: MessageMenuHandlers = {')
+ expect(src).toContain('buildMessageMenu(actions,')
+ // Die vier sichtbaren Knöpfe hängen an `actions.*`, nicht mehr an den
+ // Handlern direkt — sonst gäbe es wieder zwei Wege zur selben Aktion.
+ for (const call of ['onClick={actions.copy}', 'onClick={actions.remove}', 'onClick={actions.edit}', 'onClick={actions.regenerate}']) {
+ expect(src).toContain(call)
+ }
+ // Und die alten Direktaufrufe stehen nicht mehr in der Leiste.
+ expect(src).not.toContain('onClick={handleCopy}')
+ expect(src).not.toContain('onClick={handleDelete}')
+ expect(src).not.toContain('onClick={startEdit}')
+ })
+
+ it('MessageBubble: Menü und Leiste stehen unter derselben Bedingung', () => {
+ const src = read('components', 'chat', 'MessageBubble.tsx')
+ // Während des Streamens und beim Bearbeiten zeigt die Leiste nichts —
+ // dann darf auch der Rechtsklick nichts anbieten.
+ expect(src).toContain('const actionsAvailable = !isEditing && !isStreaming')
+ expect(src).toContain('if (!actionsAvailable) return')
+ })
+
+ it('ModelCard: Knöpfe und Menü lesen aus DEMSELBEN actions-Objekt', () => {
+ const src = read('components', 'models', 'ModelCard.tsx')
+ expect(src).toContain('const actions: ModelMenuHandlers = { select: onSelect, info: onInfo, remove: onDelete }')
+ expect(src).toContain('buildModelCardMenu(actions,')
+ expect(src).toContain('actions.info()')
+ expect(src).toContain('actions.remove()')
+ expect(src).toContain('onClick={actions.select}')
+ })
+
+ it('beide benutzen dasselbe ui/ContextMenu, nicht je ein eigenes', () => {
+ for (const [dir, file] of [['chat', 'MessageBubble.tsx'], ['models', 'ModelCard.tsx']] as const) {
+ expect(read('components', dir, file)).toContain("import { ContextMenu } from '../ui/ContextMenu'")
+ }
+ })
+})
+
+describe('ui/ContextMenu folgt dem vorhandenen Muster und schließt seine Lücken', () => {
+ const src = read('components', 'ui', 'ContextMenu.tsx')
+
+ it('Aufbau und Rollen wie im einzigen Menü, das es vorher gab', () => {
+ expect(src).toContain('role="menu"')
+ expect(src).toContain('role="menuitem"')
+ expect(src).toContain('aria-label={label}')
+ // Overlay fängt Klick UND Rechtsklick ab — genau wie Sidebar.tsx:693.
+ expect(src).toContain('onClick={onClose}')
+ expect(src).toMatch(/onContextMenu=\{\(e\) => \{ e\.preventDefault\(\); onClose\(\) \}\}/)
+ })
+
+ it('Tastatur: Escape, Pfeiltasten, Home/End', () => {
+ for (const k of ["case 'Escape':", "case 'ArrowDown':", "case 'ArrowUp':", "case 'Home':", "case 'End':"]) {
+ expect(src).toContain(k)
+ }
+ expect(src).toContain('nextFocusIndex(items.length')
+ })
+
+ it('Fokus geht hinein und kommt beim Schließen zurück', () => {
+ expect(src).toContain('restoreRef.current')
+ expect(src).toContain('if (target && target.isConnected) target.focus()')
+ })
+
+ it('der Auslöser wird bei `mousedown` gemerkt, nicht erst beim Mounten', () => {
+ // Live gemessen (2026-09-01): das Verschieben des Fokus ist die
+ // Default-Aktion von `mousedown` und läuft NACH allen Listenern.
+ // mousedown → activeElement = der Knopf
+ // contextmenu → activeElement = <body>
+ // Wer erst beim Mounten `document.activeElement` liest — der Weg, den
+ // ui/Modal gehen darf, weil es per Tastatur geöffnet wird — findet den
+ // Auslöser nie mehr und lässt den Fokus auf <body> zurück.
+ expect(src).toContain("document.addEventListener(\n 'mousedown',")
+ expect(src).toContain('lastFocusedBeforePointer')
+ // Per Tastatur geöffnet gibt es kein mousedown — dort hat der lebende
+ // Fokus Vorrang.
+ expect(src).toMatch(/live instanceof HTMLElement && live !== document\.body \? live : lastFocusedBeforePointer/)
+ })
+
+ it('Escape trifft nur die oberste Ebene — der Dialog-Stapel des Hauses', () => {
+ expect(src).toContain("from './dialog-a11y'")
+ expect(src).toContain('isTopDialog(dialogId)')
+ expect(src).toContain('openDialog(dialogId)')
+ })
+})
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 5e36d7fe..176d62ef 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -19,6 +19,8 @@ import { useModelStore } from '../../stores/modelStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { extractToolCallsFromContent, looksLikeToolIntent } from '../../lib/tool-call-repair'
import { isAgentCompatible } from '../../lib/model-compatibility'
+import { ContextMenu } from '../ui/ContextMenu'
+import { buildMessageMenu, type MessageMenuHandlers } from '../ui/menu-actions'
interface Props {
message: Message
@@ -45,6 +47,7 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
const [isEditing, setIsEditing] = useState(false)
const [editContent, setEditContent] = useState('')
const [confirmDelete, setConfirmDelete] = useState(false)
+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)
const editRef = useRef<HTMLTextAreaElement>(null)
const isUser = message.role === 'user'
@@ -185,9 +188,33 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
deleteMessage(activeConversationId, message.id)
}
+ // EIN Satz Aktionen fuer diese Nachricht. Die Leiste unter der Nachricht
+ // liest daraus, und das Kontextmenue bekommt DASSELBE Objekt gereicht
+ // (`buildMessageMenu` gibt die Funktionen unveraendert als `run` weiter).
+ // Rechtsklick und Knopf koennen damit nicht auseinanderlaufen — genau die
+ // Doppelung, die dieses Projekt schon mehrfach bezahlt hat.
+ //
+ // `edit` und `regenerate` sind `null`, wo die Leiste den Knopf auch nicht
+ // zeigt; das Menue laesst den Eintrag dann ebenfalls weg.
+ const canEdit = (isUser && !!onEdit) || canEditAssistant
+ const actions: MessageMenuHandlers = {
+ copy: handleCopy,
+ edit: canEdit ? startEdit : null,
+ regenerate: !isUser && onRegenerate ? () => onRegenerate(message.id) : null,
+ remove: handleDelete,
+ }
+ // Die Leiste haengt an `!isEditing && !isStreaming` — das Menue bietet
+ // dieselben Aktionen an, also gilt fuer es dieselbe Bedingung.
+ const actionsAvailable = !isEditing && !isStreaming
+
return (
<motion.div
className={'flex gap-2 px-3 py-1 group ' + (isUser ? 'flex-row-reverse' : '')}
+ onContextMenu={(e) => {
+ if (!actionsAvailable) return
+ e.preventDefault()
+ setMenu({ x: e.clientX, y: e.clientY })
+ }}
initial={{ opacity: 0, y: 6 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.15 }}
@@ -471,27 +498,38 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
half-written answer from the first token on. Gated on the live
generating flag rather than on `usage`, because a backend that
never reports usage would otherwise lose the bar for good. */}
- {!isEditing && !isStreaming && (
+ {actionsAvailable && (
<div className={'flex items-center gap-0.5 ' + (isUser ? 'justify-end pr-0.5' : 'justify-start pl-0.5')}>
- {isUser && onEdit && (
- <button onClick={startEdit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit message" title="Edit"><Pencil size={12} /></button>
+ {isUser && actions.edit && (
+ <button onClick={actions.edit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit message" title="Edit"><Pencil size={12} /></button>
)}
- {canEditAssistant && (
- <button onClick={startEdit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit response" title="Edit"><Pencil size={12} /></button>
+ {!isUser && actions.edit && (
+ <button onClick={actions.edit} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Edit response" title="Edit"><Pencil size={12} /></button>
)}
- {!isUser && onRegenerate && (
- <button onClick={() => onRegenerate(message.id)} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title="Regenerate"><RefreshCw size={12} /></button>
+ {actions.regenerate && (
+ <button onClick={actions.regenerate} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Regenerate response" title="Regenerate"><RefreshCw size={12} /></button>
)}
- <button onClick={handleCopy} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Copy message" title={copied ? 'Copied' : 'Copy'}>
+ <button onClick={actions.copy} className="p-1 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/10 transition-colors" aria-label="Copy message" title={copied ? 'Copied' : 'Copy'}>
{copied ? <Check size={12} className="text-green-500" /> : <Copy size={12} />}
</button>
{!isUser && <SpeakerButton text={message.content} />}
- <button onClick={handleDelete} className={'p-1 rounded-md transition-colors hover:bg-gray-100 dark:hover:bg-white/10 ' + (confirmDelete ? 'text-red-500' : 'text-gray-400 dark:text-gray-500 hover:text-red-500')} aria-label="Delete message" title={confirmDelete ? 'Click again to delete' : 'Delete message'}>
+ <button onClick={actions.remove} className={'p-1 rounded-md transition-colors hover:bg-gray-100 dark:hover:bg-white/10 ' + (confirmDelete ? 'text-red-500' : 'text-gray-400 dark:text-gray-500 hover:text-red-500')} aria-label="Delete message" title={confirmDelete ? 'Click again to delete' : 'Delete message'}>
<Trash2 size={12} />
</button>
</div>
)}
+ {/* Rechtsklick auf die Nachricht — dieselben Aktionen, derselbe Code. */}
+ {menu && (
+ <ContextMenu
+ items={buildMessageMenu(actions, { copied, confirmDelete })}
+ x={menu.x}
+ y={menu.y}
+ label={isUser ? 'Message actions' : 'Response actions'}
+ onClose={() => setMenu(null)}
+ />
+ )}
+
{/* RAG sources */}
{!isUser && message.sources && message.sources.length > 0 && (
<div className="pt-1 border-t border-white/[0.04]">
diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx
index e58e9813..227a3444 100644
--- a/src/components/layout/AppShell.tsx
+++ b/src/components/layout/AppShell.tsx
@@ -42,6 +42,7 @@ import { CloudGateModal } from '../cloud/CloudGateModal'
import { CloudTeaserModal } from '../cloud/CloudTeaserModal'
import { ReleaseNotesModal } from '../release/ReleaseNotesModal'
import { ShortcutsModal } from './ShortcutsModal'
+import { CommandPalette } from '../ui/CommandPalette'
import { CreditsExhaustedModal } from './CreditsExhaustedModal'
import { Titlebar } from './Titlebar'
@@ -974,6 +975,10 @@ function AppShellTree() {
it can never stack on top of the onboarding wizard. */}
<ReleaseNotesModal />
<ShortcutsModal />
+ {/* Cmd/Ctrl+K. Hoert auf `lu-command-palette`, genau wie die
+ Kuerzel-Uebersicht darueber auf `lu-show-shortcuts` hoert — kein
+ zweiter Tastatur-Handler. */}
+ <CommandPalette />
{/* Out-of-credits purchase prompt: opens when LU Cloud answers
code:'credits_exhausted' (monthly budget + top-up wallet empty). */}
<CreditsExhaustedModal />
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx
index 905105de..0a5078bd 100644
--- a/src/components/layout/Header.tsx
+++ b/src/components/layout/Header.tsx
@@ -3,7 +3,7 @@ import { Menu, Loader2, Sun, Moon, RefreshCw, X, MoreVertical } from 'lucide-rea
import { useUIStore } from '../../stores/uiStore'
import { useSettingsStore } from '../../stores/settingsStore'
import { useChatStore } from '../../stores/chatStore'
-import { useCompareStore } from '../../stores/compareStore'
+import { useCompareStore, openCompare } from '../../stores/compareStore'
import { useModelStore } from '../../stores/modelStore'
import { useProviderStore } from '../../stores/providerStore'
import { UpdateBadge } from './UpdateBadge'
@@ -288,10 +288,7 @@ export function Header() {
{textNav('create', 'Create')}
<button
- onClick={() => {
- useCompareStore.getState().setComparing(true)
- setView('chat')
- }}
+ onClick={openCompare}
className={navClass(isComparing)}
>
Compare
@@ -326,11 +323,7 @@ export function Header() {
{dropdownNav('create', 'Create')}
<button
- onClick={() => {
- useCompareStore.getState().setComparing(true)
- setView('chat')
- setShowMoreMenu(false)
- }}
+ onClick={() => { openCompare(); setShowMoreMenu(false) }}
className={navClass(isComparing, true)}
>
Compare
diff --git a/src/components/models/ModelCard.tsx b/src/components/models/ModelCard.tsx
index d5aa3bc1..c6667e64 100644
--- a/src/components/models/ModelCard.tsx
+++ b/src/components/models/ModelCard.tsx
@@ -1,6 +1,9 @@
import { Trash2, Info, MessageSquare, Image, Video } from 'lucide-react'
+import { useState } from 'react'
import { formatBytes } from '../../lib/formatters'
import { BenchmarkButton } from './ModelBenchmark'
+import { ContextMenu } from '../ui/ContextMenu'
+import { buildModelCardMenu, type ModelMenuHandlers } from '../ui/menu-actions'
import type { AIModel } from '../../types/models'
interface Props {
@@ -21,10 +24,21 @@ const TYPE_CONFIG = {
export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDelete = true }: Props) {
const typeInfo = TYPE_CONFIG[model.type] || TYPE_CONFIG.text
const TypeIcon = typeInfo.icon
+ const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)
+
+ // EIN Satz Aktionen fuer die Karte. Die sichtbaren Knoepfe unten lesen aus
+ // diesem Objekt, das Kontextmenue bekommt dasselbe Objekt gereicht — es gibt
+ // also keinen zweiten Aufrufweg, der irgendwann anders werden koennte.
+ const actions: ModelMenuHandlers = { select: onSelect, info: onInfo, remove: onDelete }
return (
+ <>
<div
- onClick={onSelect}
+ onClick={actions.select}
+ onContextMenu={(e) => {
+ e.preventDefault()
+ setMenu({ x: e.clientX, y: e.clientY })
+ }}
className={`flex items-center gap-2.5 px-3 py-1.5 rounded-lg border cursor-pointer transition-all group ${
isActive
? 'bg-blue-50 dark:bg-white/[0.05] border-blue-400/40 ring-1 ring-blue-400/40'
@@ -61,7 +75,7 @@ export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDele
</div>
)}
<button
- onClick={(e) => { e.stopPropagation(); onInfo() }}
+ onClick={(e) => { e.stopPropagation(); actions.info() }}
className="p-1 rounded hover:bg-gray-100 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
title="Details"
>
@@ -69,7 +83,7 @@ export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDele
</button>
{canDelete && (
<button
- onClick={(e) => { e.stopPropagation(); onDelete() }}
+ onClick={(e) => { e.stopPropagation(); actions.remove() }}
className="p-1 rounded hover:bg-red-500/20 text-gray-400 hover:text-red-400 transition-colors"
title="Delete"
>
@@ -78,5 +92,16 @@ export function ModelCard({ model, isActive, onSelect, onDelete, onInfo, canDele
)}
</div>
</div>
+
+ {menu && (
+ <ContextMenu
+ items={buildModelCardMenu(actions, { isActive, canDelete })}
+ x={menu.x}
+ y={menu.y}
+ label={`Actions for ${model.name}`}
+ onClose={() => setMenu(null)}
+ />
+ )}
+ </>
)
}
diff --git a/src/components/ui/CommandPalette.tsx b/src/components/ui/CommandPalette.tsx
new file mode 100644
index 00000000..67bdf211
--- /dev/null
+++ b/src/components/ui/CommandPalette.tsx
@@ -0,0 +1,249 @@
+/**
+ * Cmd/Ctrl+K — die Kommandopalette (Audit Welle 3, Achse 11).
+ *
+ * Zwei Regeln haben die Form dieser Datei bestimmt:
+ *
+ * 1. KEIN zweiter Tastatur-Handler. Das Öffnen entscheidet
+ * `shortcutCommandFor` in `hooks/useKeyboardShortcuts.ts`, also dieselbe
+ * Besitz-Entscheidung, die auch Ctrl+N und Cmd+A regelt. Hierher kommt nur
+ * das Ereignis `lu-command-palette` — genau der Weg, den die
+ * Kürzel-Übersicht seit jeher geht (`lu-show-shortcuts`).
+ * 2. KEINE nachgebauten Aktionen. Der Inhalt kommt aus
+ * `command-actions.ts`; jeder Eintrag trägt die Funktion, die auch am
+ * Knopf hängt.
+ *
+ * Dialogverhalten (Escape, Fokusfalle, Fokusrückgabe, `role="dialog"`,
+ * Hintergrund inert) kommt vollständig von `ui/Modal` — hier steht davon
+ * nichts nach, damit es auch nichts geben kann, was auseinanderläuft.
+ * Darin sitzt das übliche Combobox-Paar: der Fokus bleibt im Suchfeld, die
+ * Liste wird über `aria-activedescendant` geführt.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'
+import { Modal } from './Modal'
+import {
+ buildCommands,
+ matchCommands,
+ resolveActiveIndex,
+ type Command,
+ type CommandContext,
+ type Selection,
+} from './command-actions'
+import { nextFocusIndex } from './dialog-a11y'
+import { SHORTCUT_ACTIONS, shortcutKeys } from '../../hooks/useKeyboardShortcuts'
+import { useUIStore } from '../../stores/uiStore'
+import { useModelStore } from '../../stores/modelStore'
+import { useSettingsStore } from '../../stores/settingsStore'
+import { openCompare } from '../../stores/compareStore'
+import { backendCall, isTauri } from '../../api/backend'
+
+export function CommandPalette() {
+ const [open, setOpen] = useState(false)
+ const [query, setQuery] = useState('')
+ const [selection, setSelection] = useState<Selection>({ active: 0, forQuery: '' })
+ const listRef = useRef<HTMLDivElement>(null)
+
+ const setView = useUIStore((s) => s.setView)
+ const toggleSidebar = useUIStore((s) => s.toggleSidebar)
+ const setActiveModel = useModelStore((s) => s.setActiveModel)
+ const models = useModelStore((s) => s.models)
+ const activeModel = useModelStore((s) => s.activeModel)
+ const appMode = useSettingsStore((s) => s.settings.appMode)
+
+ useEffect(() => {
+ const handler = () => { setQuery(''); setSelection({ active: 0, forQuery: '' }); setOpen(true) }
+ window.addEventListener('lu-command-palette', handler)
+ return () => window.removeEventListener('lu-command-palette', handler)
+ }, [])
+
+ const commands = useMemo<Command[]>(() => {
+ const ctx: CommandContext = {
+ shortcuts: SHORTCUT_ACTIONS,
+ keysFor: shortcutKeys,
+ setView,
+ openCompare,
+ toggleSidebar,
+ setActiveModel,
+ models,
+ activeModel,
+ // Models/Benchmark existieren im Cloud-Modus nicht (Header.tsx:301,
+ // dazu der Umleitungs-Effekt in AppShell). Eine Palette, die trotzdem
+ // dorthin führte, würde den Nutzer sofort wieder hinausbefördern.
+ localViewsAvailable: appMode !== 'cloud',
+ quit: isTauri() ? () => { void backendCall('exit_app') } : null,
+ }
+ return buildCommands(ctx)
+ }, [setView, toggleSidebar, setActiveModel, models, activeModel, appMode])
+
+ const shown = useMemo(() => matchCommands(query, commands), [query, commands])
+
+ /**
+ * Die tatsaechlich ausgewaehlte Zeile — ABGELEITET, nicht nachgepflegt.
+ *
+ * Hier standen vorher zwei Stuecke Buchfuehrung: ein Effekt, der beim
+ * Tippen auf 0 zuruecksetzte (`react-hooks/set-state-in-effect`), und danach
+ * eine Klemmung von Hand. Beide Faelle beantwortet jetzt
+ * `resolveActiveIndex` in `command-actions.ts` — und zwar dort, wo sie ohne
+ * DOM pruefbar sind. Die Auswahl merkt sich, zu WELCHER Anfrage sie gehoert;
+ * damit ergibt sich das Zuruecksetzen von selbst und muss nicht bei jedem
+ * Ereignis mitgeschrieben werden, das `query` aendert.
+ */
+ const activeIndex = resolveActiveIndex(selection, query, shown.length)
+
+ /** Eine Zeile waehlen — immer zusammen mit der Anfrage, fuer die sie gilt. */
+ const select = useCallback(
+ (active: number) => setSelection({ active, forQuery: query }),
+ [query],
+ )
+
+ const run = useCallback((cmd: Command) => {
+ // Erst zu, dann ausführen. `ui/Modal` gibt beim Schließen den Fokus an das
+ // auslösende Element zurück; liefe die Aktion vorher, würde diese Rückgabe
+ // zum Beispiel „Focus chat input" sofort wieder überschreiben. Der Timer
+ // wartet genau diesen Commit ab.
+ //
+ // Hier stand `requestAnimationFrame`, und das war falsch: in einem
+ // Fenster, das gerade nicht sichtbar ist, feuert kein Animationsframe.
+ // Live gemessen im verdeckten Fenster (2026-09-01) — die Palette ging zu
+ // und der Befehl passierte NIE. Bei einer App, die sich beim Schließen in
+ // den Tray legt, ist „verdeckt" kein Sonderfall. Ein Timer läuft auch
+ // dann, notfalls gedrosselt, aber er läuft.
+ setOpen(false)
+ setTimeout(() => cmd.run(), 0)
+ }, [])
+
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault()
+ select(Math.max(0, nextFocusIndex(shown.length, activeIndex, e.key === 'ArrowUp')))
+ return
+ }
+ if (e.key === 'Home') { e.preventDefault(); select(0); return }
+ if (e.key === 'End') { e.preventDefault(); select(Math.max(0, shown.length - 1)); return }
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ const cmd = shown[activeIndex]
+ if (cmd) run(cmd)
+ return
+ }
+ // Escape steht hier BEWUSST nicht: es gehört dem Dialog-Stapel in
+ // `ui/Modal`, und ein zweiter Escape-Pfad wäre genau der Fehler, den die
+ // Kopfzeile von `useKeyboardShortcuts.ts` beschreibt.
+ }
+
+ // Den ausgewählten Eintrag im Blick behalten.
+ useEffect(() => {
+ listRef.current?.querySelector<HTMLElement>('[data-active="true"]')?.scrollIntoView({ block: 'nearest' })
+ }, [activeIndex, shown])
+
+ const listId = 'lu-command-list'
+ const optionId = (i: number) => `${listId}-option-${i}`
+
+ /**
+ * Die Liste, wie sie gezeichnet wird: je Eintrag steht schon fest, ob eine
+ * Gruppen-Ueberschrift davorgehoert.
+ *
+ * Hier stand eine Variable, die im `map` WAEHREND des Renderns
+ * fortgeschrieben wurde (`lastGroup = cmd.group`). Das ist das Muster, das
+ * der React-Compiler nicht mehr erlaubt (`react-hooks/immutability`) — und
+ * es war auch der falsche Ort: ob ein Kopf davorgehoert, ist eine
+ * Eigenschaft der LISTE und laesst sich ableiten, statt sie beim Zeichnen
+ * mitzuzaehlen. Der Vergleich laeuft deshalb gegen den VORIGEN Eintrag;
+ * damit braucht es gar keinen veraenderlichen Zwischenwert mehr, auch
+ * keinen in einem anderen Scope versteckten.
+ *
+ * Gruppen-Ueberschriften gibt es nur in der ungefilterten Liste: sobald
+ * gesucht wird, stehen die Treffer nach Guete und nicht mehr nach Gruppe,
+ * und eine Ueberschrift koennte mehrfach auftauchen.
+ */
+ const rows = useMemo(() => {
+ const showGroups = query.trim() === ''
+ return shown.map((cmd, index) => ({
+ cmd,
+ index,
+ head: showGroups && cmd.group !== shown[index - 1]?.group ? cmd.group : null,
+ }))
+ }, [shown, query])
+
+ return (
+ <Modal
+ open={open}
+ onClose={() => setOpen(false)}
+ title=""
+ hideHeader
+ ariaLabel="Command palette"
+ maxWidth="max-w-xl"
+ panelRadius="rounded-xl"
+ panelPad="p-0"
+ >
+ <div className="border-b border-gray-200 dark:border-white/10 px-3 py-2.5">
+ <input
+ type="text"
+ data-autofocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={onKeyDown}
+ placeholder="Search actions…"
+ aria-label="Search actions"
+ role="combobox"
+ aria-expanded="true"
+ aria-controls={listId}
+ aria-autocomplete="list"
+ aria-activedescendant={shown[activeIndex] ? optionId(activeIndex) : undefined}
+ /* pr-10: `hideHeader` legt oben rechts den Schließen-Knopf des
+ Dialogs ab, der sonst auf dem Text säße. */
+ className="w-full bg-transparent pr-10 text-[0.8rem] text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-500 outline-none"
+ />
+ </div>
+
+ <div
+ ref={listRef}
+ id={listId}
+ role="listbox"
+ aria-label="Actions"
+ className="max-h-[19rem] overflow-y-auto scrollbar-thin py-1"
+ >
+ {shown.length === 0 && (
+ <p className="px-3 py-6 text-center text-[0.7rem] text-gray-500">No matching action</p>
+ )}
+
+ {rows.map(({ cmd, head, index }) => {
+ const isActive = index === activeIndex
+ return (
+ <div key={cmd.id}>
+ {head && (
+ <p className="px-3 pt-2 pb-1 text-[0.55rem] font-medium uppercase tracking-wide text-gray-400 dark:text-gray-500">
+ {head}
+ </p>
+ )}
+ <div
+ id={optionId(index)}
+ role="option"
+ aria-selected={isActive}
+ data-active={isActive}
+ onMouseMove={() => select(index)}
+ /* Der Fokus bleibt im Suchfeld — sonst zerfällt das
+ Combobox-Paar und `aria-activedescendant` zeigt ins Leere. */
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => run(cmd)}
+ className={
+ 'mx-1 flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 text-[0.72rem] ' +
+ (isActive
+ ? 'bg-gray-100 dark:bg-white/[0.08] text-gray-900 dark:text-white'
+ : 'text-gray-600 dark:text-gray-300')
+ }
+ >
+ <span className="min-w-0 flex-1 truncate">{cmd.label}</span>
+ {cmd.keys && (
+ <kbd className="shrink-0 rounded border border-gray-200 px-1.5 py-0.5 font-mono text-[0.55rem] text-gray-500 dark:border-white/15 dark:text-gray-400">
+ {cmd.keys}
+ </kbd>
+ )}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ </Modal>
+ )
+}
diff --git a/src/components/ui/ContextMenu.tsx b/src/components/ui/ContextMenu.tsx
new file mode 100644
index 00000000..2ae39b09
--- /dev/null
+++ b/src/components/ui/ContextMenu.tsx
@@ -0,0 +1,208 @@
+/**
+ * Das Kontextmenü dieses Hauses.
+ *
+ * Vor Welle 3 gab es genau eins (`layout/Sidebar.tsx:690`), fest in die
+ * Sidebar eingebaut. Aufbau und Rollen von dort sind übernommen — ein
+ * Vollflächen-Overlay fängt Klick und Rechtsklick ab, darin ein
+ * `role="menu"` mit `role="menuitem"`-Knöpfen, Escape schließt. Ergänzt sind
+ * die drei Dinge, die dort fehlen und ohne die ein Menü mit der Tastatur
+ * nicht bedienbar ist:
+ *
+ * 1. Pfeiltasten/Home/End über `nextFocusIndex` — dieselbe zyklische
+ * Rechnung, die die Fokusfalle der Modals benutzt.
+ * 2. Fokusrückgabe an das Element, das beim Öffnen den Fokus hatte.
+ * 3. Der Escape-Stapel aus `dialog-a11y`: liegt das Menü über einem Dialog,
+ * schließt Escape NUR das Menü, nicht beides auf einmal.
+ *
+ * Was hier NICHT drin ist: die Einträge. Die kommen als `MenuAction[]` von
+ * `menu-actions.ts` und tragen die Funktionen des Aufrufers — dieselben, die
+ * auch am sichtbaren Knopf hängen.
+ */
+
+import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'
+import { clampMenuPosition, type MenuAction } from './menu-actions'
+import { closeDialog, isTopDialog, nextFocusIndex, openDialog } from './dialog-a11y'
+
+export interface ContextMenuProps {
+ readonly items: readonly MenuAction[]
+ /** Zeigerposition des Rechtsklicks (`clientX`/`clientY`). */
+ readonly x: number
+ readonly y: number
+ /** `aria-label` des Menüs — es hat keine sichtbare Überschrift. */
+ readonly label: string
+ readonly onClose: () => void
+}
+
+/** Schätzmaße für den ERSTEN Anstrich, bevor gemessen werden kann. Der
+ * Layout-Effekt unten korrigiert sie noch vor dem Zeichnen, es blitzt also
+ * nichts. */
+const EST_WIDTH = 176
+const EST_ROW = 28
+const EST_PAD = 8
+
+/**
+ * Wer hatte den Fokus, bevor der Rechtsklick kam?
+ *
+ * `document.activeElement` beim Mounten des Menüs zu lesen — der naheliegende
+ * Weg, den `ui/Modal` benutzen darf — kann den Auslöser NICHT mehr finden. Das
+ * Verschieben des Fokus ist die Default-Aktion von `mousedown` und läuft erst,
+ * nachdem alle Listener durch sind. Am laufenden Fenster gemessen
+ * (2026-09-01, Rechtsklick auf eine Nachricht bei fokussiertem Kopieren-Knopf):
+ *
+ * mousedown → activeElement = Knopf „Copy message"
+ * focusout → weg vom Knopf
+ * contextmenu → activeElement = <body>
+ *
+ * `mousedown` ist also der letzte Moment, in dem der alte Fokus noch steht.
+ * Beim Öffnen per Tastatur (Kontextmenü-Taste) gibt es kein `mousedown`, dort
+ * stimmt `document.activeElement` weiterhin — deshalb hat es unten Vorrang.
+ */
+let lastFocusedBeforePointer: HTMLElement | null = null
+
+if (typeof document !== 'undefined') {
+ document.addEventListener(
+ 'mousedown',
+ () => {
+ const el = document.activeElement
+ lastFocusedBeforePointer = el instanceof HTMLElement && el !== document.body ? el : null
+ },
+ true,
+ )
+}
+
+export function ContextMenu({ items, x, y, label, onClose }: ContextMenuProps) {
+ const dialogId = useId()
+ const menuRef = useRef<HTMLDivElement>(null)
+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([])
+ /** Wohin der Fokus beim Schließen zurückkehrt. */
+ const restoreRef = useRef<HTMLElement | null>(null)
+
+ const [active, setActive] = useState(0)
+ const [pos, setPos] = useState(() =>
+ clampMenuPosition(x, y, { width: EST_WIDTH, height: items.length * EST_ROW + EST_PAD }, viewport()),
+ )
+
+ // (1) Stapel-Anmeldung, vor den Tastatur-Effekten — wie in ui/Modal.
+ useEffect(() => {
+ openDialog(dialogId)
+ return () => closeDialog(dialogId)
+ }, [dialogId])
+
+ // (2) Echte Maße statt Schätzung. `useLayoutEffect`, damit die Korrektur
+ // vor dem Zeichnen sitzt.
+ useLayoutEffect(() => {
+ const el = menuRef.current
+ if (!el) return
+ const r = el.getBoundingClientRect()
+ const next = clampMenuPosition(x, y, { width: r.width, height: r.height }, viewport())
+ setPos(prev => (prev.left === next.left && prev.top === next.top ? prev : next))
+ }, [x, y, items.length])
+
+ // (3) Fokus hinein und beim Schließen zurück. Ohne die Rückgabe landet der
+ // Fokus auf <body> und die nächste Tab-Taste fängt oben in der App an.
+ useEffect(() => {
+ const live = document.activeElement
+ restoreRef.current =
+ live instanceof HTMLElement && live !== document.body ? live : lastFocusedBeforePointer
+ itemRefs.current[0]?.focus()
+ return () => {
+ const target = restoreRef.current
+ restoreRef.current = null
+ if (target && target.isConnected) target.focus()
+ }
+ }, [])
+
+ // (4) Fokus dem ausgewählten Eintrag nachführen.
+ useEffect(() => {
+ itemRefs.current[active]?.focus()
+ }, [active])
+
+ // (5) Ein gescrolltes oder verkleinertes Fenster lässt das Menü neben seinem
+ // Anker stehen. Native Menüs schließen dann; das ist auch hier das
+ // ehrlichste Verhalten.
+ useEffect(() => {
+ const close = () => onClose()
+ window.addEventListener('resize', close)
+ window.addEventListener('wheel', close, { passive: true })
+ return () => {
+ window.removeEventListener('resize', close)
+ window.removeEventListener('wheel', close)
+ }
+ }, [onClose])
+
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ // Liegen mehrere Ebenen übereinander, reagiert nur die oberste.
+ if (!isTopDialog(dialogId)) return
+
+ switch (e.key) {
+ case 'Escape':
+ e.preventDefault()
+ e.stopPropagation()
+ onClose()
+ return
+ case 'ArrowDown':
+ case 'ArrowUp':
+ e.preventDefault()
+ setActive(i => Math.max(0, nextFocusIndex(items.length, i, e.key === 'ArrowUp')))
+ return
+ case 'Home':
+ e.preventDefault()
+ setActive(0)
+ return
+ case 'End':
+ e.preventDefault()
+ setActive(items.length - 1)
+ return
+ case 'Tab':
+ // Ein Menü fängt Tab nicht ein — es macht zu und gibt den Fokus
+ // zurück, so wie die Menüs des Betriebssystems.
+ e.preventDefault()
+ onClose()
+ return
+ default:
+ }
+ }
+
+ return (
+ <div
+ data-lu-dialog
+ className="fixed inset-0 z-[110]"
+ onClick={onClose}
+ onContextMenu={(e) => { e.preventDefault(); onClose() }}
+ >
+ <div
+ ref={menuRef}
+ role="menu"
+ aria-label={label}
+ className="absolute min-w-[9rem] py-1 rounded-md bg-white dark:bg-[#141414] border border-gray-200 dark:border-white/10 shadow-lg text-[0.7rem]"
+ style={{ left: pos.left, top: pos.top }}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={onKeyDown}
+ >
+ {items.map((item, i) => (
+ <button
+ key={item.id}
+ ref={(el) => { itemRefs.current[i] = el }}
+ role="menuitem"
+ type="button"
+ tabIndex={i === active ? 0 : -1}
+ onMouseEnter={() => setActive(i)}
+ onClick={() => { onClose(); item.run() }}
+ className={
+ 'w-full flex items-center gap-2 px-3 py-1.5 text-left ' +
+ (item.destructive
+ ? 'text-red-600 dark:text-red-500 hover:bg-red-500/10'
+ : 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-white/[0.06]')
+ }
+ >
+ <span className="truncate">{item.label}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+}
+
+function viewport() {
+ return { width: window.innerWidth, height: window.innerHeight }
+}
diff --git a/src/components/ui/command-actions.ts b/src/components/ui/command-actions.ts
new file mode 100644
index 00000000..257ae958
--- /dev/null
+++ b/src/components/ui/command-actions.ts
@@ -0,0 +1,197 @@
+/**
+ * Der Inhalt der Kommandopalette — als reine Funktionen, damit er ohne DOM
+ * prüfbar ist (`environment: 'node'`).
+ *
+ * Das Wort aus dem Audit ist „über die VORHANDENEN Aktionen". Die Palette
+ * erfindet deshalb nichts: jeder Eintrag hier bekommt seine Funktion von außen
+ * hereingereicht und gibt sie unverändert als `run` weiter. Wo eine Aktion
+ * schon ein Tastenkürzel hat, ist es buchstäblich dieselbe Funktion —
+ * `SHORTCUT_ACTIONS` aus `hooks/useKeyboardShortcuts.ts`, nicht eine Kopie
+ * davon. Der Test belegt das mit `toBe`, nicht mit „tut dasselbe".
+ *
+ * Woher jeder Eintrag stammt, steht am Eintrag selbst.
+ */
+
+import type { ShortcutId } from '../../hooks/useKeyboardShortcuts'
+import type { View } from '../../stores/uiStore'
+
+export interface Command {
+ readonly id: string
+ readonly label: string
+ /** Überschrift der Gruppe, in der der Eintrag steht. */
+ readonly group: string
+ /** Beschriftung des Kürzels, falls es eins gibt (rechte Spalte). */
+ readonly keys?: string
+ readonly run: () => void
+ /**
+ * Erst sichtbar, wenn wirklich gesucht wurde. Genau ein Eintrag trägt das:
+ * „Quit LU". Er steht sonst in einer Liste, in der man mit Pfeil-hoch und
+ * Enter navigiert, und ein versehentliches Beenden ist der einzige Fehler
+ * dieser Palette, den man nicht rückgängig machen kann.
+ */
+ readonly hiddenUntilSearched?: boolean
+}
+
+/**
+ * Alles, was die Palette braucht, wird hereingereicht — sie greift auf keinen
+ * Store selbst zu. Das ist nicht Zeremonie: nur so kann der Test die Herkunft
+ * jedes `run` gegen die übergebene Funktion prüfen.
+ */
+export interface CommandContext {
+ /** Die Kürzel-Aktionen SELBST (`SHORTCUT_ACTIONS`), nicht nachgebaut. */
+ readonly shortcuts: Readonly<Record<ShortcutId, () => void>>
+ /** Beschriftung je Kürzel (`shortcutKeys`), damit es nur eine Liste gibt. */
+ readonly keysFor: (id: ShortcutId) => string | undefined
+ /** `useUIStore.setView` — die Funktion, die die Kopfzeile ruft. */
+ readonly setView: (view: View) => void
+ /** Compare ist kein View, sondern Flag + `setView('chat')`
+ * (`stores/compareStore.ts: openCompare`, den auch der Header ruft). */
+ readonly openCompare: () => void
+ /** `useUIStore.toggleSidebar` — der Hamburger links oben. */
+ readonly toggleSidebar: () => void
+ /** `useModelStore.setActiveModel` — dieselbe Funktion wie `ModelCard.onSelect`. */
+ readonly setActiveModel: (name: string) => void
+ /** Installierte Modelle, für je einen „Use …"-Eintrag. */
+ readonly models: readonly { readonly name: string }[]
+ readonly activeModel: string | null
+ /** Cloud-Modus blendet Models/Benchmark aus (`Header.tsx:301`), die Palette
+ * darf dann nicht dorthin führen. */
+ readonly localViewsAvailable: boolean
+ /** Der zweite Tray-Eintrag (`src-tauri/src/main.rs:502`) über dieselbe
+ * Backend-Aktion wie der Updater (`stores/updateStore.ts:338`).
+ * `null` außerhalb von Tauri — dort gibt es die Aktion nicht, und ein
+ * Eintrag ohne Aktion dahinter wäre eine Attrappe. */
+ readonly quit: (() => void) | null
+}
+
+const GROUP_CHAT = 'Chat'
+const GROUP_VIEW = 'Go to'
+const GROUP_MODEL = 'Models'
+const GROUP_APP = 'App'
+
+export function buildCommands(ctx: CommandContext): Command[] {
+ const withKeys = (id: ShortcutId, label: string, group: string): Command => ({
+ id,
+ label,
+ group,
+ keys: ctx.keysFor(id),
+ run: ctx.shortcuts[id],
+ })
+
+ const out: Command[] = [
+ // Die vier Kürzel-Aktionen, die etwas im Chat tun.
+ withKeys('new-conversation', 'New conversation', GROUP_CHAT),
+ withKeys('focus-chat-input', 'Focus chat input', GROUP_CHAT),
+ withKeys('export-chat', 'Export chat as Markdown', GROUP_CHAT),
+
+ // Navigation — dieselben Ziele wie die Kopfzeile (`Header.tsx:287-304`).
+ { id: 'view-chat', label: 'Chat', group: GROUP_VIEW, run: () => ctx.setView('chat') },
+ { id: 'view-create', label: 'Create', group: GROUP_VIEW, run: () => ctx.setView('create') },
+ { id: 'view-compare', label: 'Compare models', group: GROUP_VIEW, run: ctx.openCompare },
+ ]
+
+ if (ctx.localViewsAvailable) {
+ out.push({ id: 'view-benchmark', label: 'Benchmark', group: GROUP_VIEW, run: () => ctx.setView('benchmark') })
+ out.push({ id: 'view-models', label: 'Models', group: GROUP_VIEW, run: () => ctx.setView('models') })
+ }
+ out.push({ id: 'view-settings', label: 'Settings', group: GROUP_VIEW, run: () => ctx.setView('settings') })
+ out.push({ id: 'toggle-sidebar', label: 'Toggle sidebar', group: GROUP_VIEW, run: ctx.toggleSidebar })
+ out.push(withKeys('toggle-theme', 'Toggle dark/light mode', GROUP_VIEW))
+
+ // Modellwechsel. Das aktive Modell bekommt keinen Eintrag — er täte nichts.
+ for (const m of ctx.models) {
+ if (m.name === ctx.activeModel) continue
+ out.push({
+ id: `model:${m.name}`,
+ label: `Use ${m.name}`,
+ group: GROUP_MODEL,
+ run: () => ctx.setActiveModel(m.name),
+ })
+ }
+
+ out.push(withKeys('show-shortcuts', 'Keyboard shortcuts', GROUP_APP))
+ if (ctx.quit) {
+ out.push({ id: 'quit', label: 'Quit LU', group: GROUP_APP, run: ctx.quit, hiddenUntilSearched: true })
+ }
+
+ return out
+}
+
+/* ── Suche ───────────────────────────────────────────────────────────────── */
+
+/**
+ * Teilwort-Treffer, mehrere Wörter erlaubt, kein Fuzzy-Zauber: „tog dark"
+ * findet „Toggle dark/light mode", „qwen" findet das Modell. Jedes Wort der
+ * Anfrage muss irgendwo treffen; die Reihenfolge richtet sich danach, WIE gut
+ * es trifft, und bei Gleichstand bleibt die gebaute Reihenfolge erhalten
+ * (die Gruppen also beieinander).
+ */
+export function matchCommands(query: string, commands: readonly Command[]): Command[] {
+ const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
+
+ if (tokens.length === 0) return commands.filter(c => !c.hiddenUntilSearched)
+
+ const hits: { cmd: Command; score: number; order: number }[] = []
+ commands.forEach((cmd, order) => {
+ let score = 0
+ for (const t of tokens) {
+ const s = scoreToken(t, cmd)
+ if (s === 0) return
+ score += s
+ }
+ hits.push({ cmd, score, order })
+ })
+
+ hits.sort((a, b) => b.score - a.score || a.order - b.order)
+ return hits.map(h => h.cmd)
+}
+
+/** Wortgrenzen: alles, was kein Buchstabe und keine Ziffer ist. Modellnamen
+ * wie `qwen3:4b-instruct` zerfallen damit in benutzbare Stücke. */
+const WORD_SPLIT = /[^\p{L}\p{N}]+/u
+
+function scoreToken(token: string, cmd: Command): number {
+ const label = cmd.label.toLowerCase()
+ if (label.startsWith(token)) return 4
+ if (label.split(WORD_SPLIT).some(w => w.startsWith(token))) return 3
+ if (label.includes(token)) return 2
+ if (cmd.group.toLowerCase().includes(token)) return 1
+ return 0
+}
+
+/* ── Auswahl ─────────────────────────────────────────────────────────────── */
+
+/**
+ * Welche Zeile ist ausgewählt — und zu WELCHER Suchanfrage gehört diese Wahl?
+ *
+ * Das zweite Feld ist der Kern. Ohne es ist `active` ein nackter Index in eine
+ * Liste, die sich unter ihm ändert, und die Komponente muss ihn per Ereignis
+ * nachpflegen: einmal beim Tippen zurücksetzen, einmal beim Schrumpfen der
+ * Liste einfangen. Beides ist Buchführung, die schiefgehen kann, und beides
+ * war in `CommandPalette` nur mit einem DOM prüfbar.
+ */
+export interface Selection {
+ readonly active: number
+ /** Die Anfrage, für die `active` gewählt wurde. */
+ readonly forQuery: string
+}
+
+/**
+ * Auf welchen Eintrag zeigt die Auswahl JETZT?
+ *
+ * Zwei Fälle, beide abgeleitet statt nachgepflegt:
+ *
+ * (1) Die Anfrage hat gewechselt — die alte Wahl galt einer anderen Liste und
+ * wäre jetzt ein zufälliger Eintrag. Also der erste Treffer.
+ * (2) Gleiche Anfrage, aber die Liste kann trotzdem kürzer geworden sein: die
+ * Modelle treffen ASYNCHRON ein, `buildCommands` liefert also bei
+ * offener Palette plötzlich mehr oder weniger Zeilen. Ein gehaltener
+ * Index zeigt dann ins Leere — `shown[i]` wäre `undefined`, Enter täte
+ * nichts und `aria-activedescendant` zeigte auf eine ID, die es nicht
+ * gibt. Also in die Liste klemmen.
+ */
+export function resolveActiveIndex(sel: Selection, query: string, count: number): number {
+ if (count <= 0) return 0
+ if (sel.forQuery !== query) return 0
+ return Math.min(Math.max(0, sel.active), count - 1)
+}
diff --git a/src/components/ui/menu-actions.ts b/src/components/ui/menu-actions.ts
new file mode 100644
index 00000000..969c4ffb
--- /dev/null
+++ b/src/components/ui/menu-actions.ts
@@ -0,0 +1,139 @@
+/**
+ * Kontextmenü-Modelle und die Geometrie, an der sie hängen — als reine
+ * Funktionen, weil die Testumgebung `environment: 'node'` ist und ein
+ * gerendertes Menü sich dort nicht anklicken lässt.
+ *
+ * Der Zweck dieser Datei ist NICHT, Menüs zu beschreiben. Der Zweck ist die
+ * Regel „ein Kontextmenü löst seine Aktionen über denselben Code aus wie der
+ * sichtbare Knopf". Sie ist hier prüfbar gemacht: `buildMessageMenu` und
+ * `buildModelCardMenu` bekommen die Handler HEREIN und reichen sie
+ * unverändert als `run` weiter. Sie können also gar nichts nachbauen — und
+ * der Test kann das mit einem Identitätsvergleich (`toBe`) belegen, nicht nur
+ * mit „ruft irgendwas Ähnliches auf".
+ *
+ * Vorbild ist das einzige Kontextmenü, das es vor Welle 3 gab
+ * (`layout/Sidebar.tsx:690`): Vollflächen-Overlay, `role="menu"` mit
+ * `role="menuitem"`-Knöpfen, Escape schließt. Übernommen sind Aufbau und
+ * Rollen; ergänzt sind die drei Dinge, die dort fehlen — Pfeiltasten,
+ * Fokusrückgabe, und eine Platzierung, die auch nach links/oben ausweicht.
+ */
+
+/** Ein Eintrag eines Kontextmenüs. `run` ist die Funktion des Aufrufers,
+ * niemals eine hier gebaute. */
+export interface MenuAction {
+ readonly id: string
+ readonly label: string
+ readonly run: () => void
+ /** Rot einfärben und beim Öffnen nie vorausgewählt (vgl. `dialog-a11y`). */
+ readonly destructive?: boolean
+}
+
+/* ── Nachricht ───────────────────────────────────────────────────────────── */
+
+/**
+ * Die Aktionen, die die Aktionsleiste unter einer Nachricht schon hat
+ * (`chat/MessageBubble.tsx`). Genau diese vier, keine erfundene fünfte.
+ * `regenerate` ist `null`, wo die Leiste den Knopf auch nicht zeigt (eigene
+ * Nachricht, oder es läuft gerade eine Antwort).
+ */
+export interface MessageMenuHandlers {
+ readonly copy: () => void
+ readonly edit: (() => void) | null
+ readonly regenerate: (() => void) | null
+ readonly remove: () => void
+}
+
+export interface MessageMenuState {
+ /** Kopieren wurde eben gedrückt — die Leiste zeigt dann einen Haken. */
+ readonly copied: boolean
+ /** Löschen ist scharf (zweiter Klick löscht wirklich, D#81). */
+ readonly confirmDelete: boolean
+}
+
+export function buildMessageMenu(h: MessageMenuHandlers, s: MessageMenuState): MenuAction[] {
+ const out: MenuAction[] = []
+ if (h.edit) out.push({ id: 'edit', label: 'Edit', run: h.edit })
+ if (h.regenerate) out.push({ id: 'regenerate', label: 'Regenerate', run: h.regenerate })
+ out.push({ id: 'copy', label: s.copied ? 'Copied' : 'Copy text', run: h.copy })
+ // Die Beschriftung sagt dasselbe wie der `title` des Knopfes: der erste
+ // Aufruf schärft nur, gelöscht wird erst beim zweiten.
+ out.push({
+ id: 'delete',
+ label: s.confirmDelete ? 'Click again to delete' : 'Delete message',
+ run: h.remove,
+ destructive: true,
+ })
+ return out
+}
+
+/* ── Modellkarte ─────────────────────────────────────────────────────────── */
+
+/**
+ * Was die Karte schon kann (`models/ModelCard.tsx`): auswählen (Klick auf die
+ * Zeile), Details, Löschen. Der Benchmark-Knopf der Karte fehlt hier bewusst —
+ * er ist eine eigene Komponente mit eigenem Zustand (`ModelBenchmark`), und ihn
+ * ins Menü zu holen hieße, seinen Klickpfad ein zweites Mal zu schreiben.
+ */
+export interface ModelMenuHandlers {
+ readonly select: () => void
+ readonly info: () => void
+ readonly remove: () => void
+}
+
+export interface ModelMenuState {
+ readonly isActive: boolean
+ readonly canDelete: boolean
+}
+
+export function buildModelCardMenu(h: ModelMenuHandlers, s: ModelMenuState): MenuAction[] {
+ const out: MenuAction[] = []
+ // Auf der bereits aktiven Karte wäre „Use this model" ein Eintrag, der
+ // nichts tut — die Karte zeigt an derselben Stelle ihr ACTIVE-Etikett.
+ if (!s.isActive) out.push({ id: 'select', label: 'Use this model', run: h.select })
+ out.push({ id: 'info', label: 'Details', run: h.info })
+ if (s.canDelete) out.push({ id: 'delete', label: 'Delete model', run: h.remove, destructive: true })
+ return out
+}
+
+/* ── Platzierung ─────────────────────────────────────────────────────────── */
+
+export interface MenuBox {
+ readonly width: number
+ readonly height: number
+}
+
+export interface MenuPosition {
+ readonly left: number
+ readonly top: number
+}
+
+/**
+ * Wohin kommt das Menü, wenn an (x|y) rechtsgeklickt wurde?
+ *
+ * Die Fassung in `Sidebar.tsx:701` rechnet `Math.min(x, innerWidth - 160)` mit
+ * geratenen Maßen und ohne untere Schranke: in einem schmalen Fenster wird
+ * daraus ein negatives `left` und das Menü hängt links aus dem Bild. Hier
+ * kippt es stattdessen auf die andere Seite des Zeigers — so machen es
+ * native Menüs — und wird erst danach in den Rahmen geklemmt.
+ */
+export function clampMenuPosition(
+ x: number,
+ y: number,
+ box: MenuBox,
+ viewport: MenuBox,
+ margin = 8,
+): MenuPosition {
+ return { left: place(x, box.width, viewport.width, margin), top: place(y, box.height, viewport.height, margin) }
+}
+
+function place(at: number, size: number, limit: number, margin: number): number {
+ // Passt es hinter den Zeiger? Dann dorthin.
+ if (at + size + margin <= limit) return Math.max(margin, at)
+ // Sonst davor kippen — aber nur, wenn davor mehr Platz ist als dahinter.
+ const flipped = at - size
+ if (flipped >= margin) return flipped
+ // Beides zu eng: an den Rahmen klemmen. `Math.max` steht zuletzt, damit ein
+ // Menü, das höher/breiter ist als das Fenster, oben/links anliegt statt
+ // hinter dem oberen Rand zu verschwinden.
+ return Math.max(margin, limit - size - margin)
+}
diff --git a/src/hooks/__tests__/cmd-k-tastaturbesitz.test.ts b/src/hooks/__tests__/cmd-k-tastaturbesitz.test.ts
new file mode 100644
index 00000000..758c7e34
--- /dev/null
+++ b/src/hooks/__tests__/cmd-k-tastaturbesitz.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Cmd+K gehört der App, Cmd+A gehört dem Feld — Audit Welle 3, Achse 11.
+ *
+ * Eine Kommandopalette scheitert fast immer an derselben Stelle: sie macht
+ * einen ZWEITEN `keydown`-Listener auf. Dann streiten zwei Handler um
+ * dasselbe Ereignis, und wer im Composer steht, bekommt entweder seine
+ * Palette nicht oder verliert Cmd+A/C/V.
+ *
+ * Dieser Test prüft beide Richtungen an DER Funktion, die es entscheidet, und
+ * belegt zusätzlich, dass es die einzige Entscheidung geblieben ist.
+ *
+ * Run: npx vitest run src/hooks/__tests__/cmd-k-tastaturbesitz.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import {
+ SHORTCUTS,
+ SHORTCUT_ACTIONS,
+ shortcutCommandFor,
+ shortcutKeys,
+ type ShortcutId,
+} from '../useKeyboardShortcuts'
+
+const chord = (k: string, mods: { ctrl?: boolean; meta?: boolean; shift?: boolean } = {}) => ({
+ key: k,
+ ctrlKey: mods.ctrl ?? false,
+ metaKey: mods.meta ?? false,
+ shiftKey: mods.shift ?? false,
+})
+
+const WIN = false
+const MAC = true
+const IN_FIELD = true
+const FREE = false
+
+const SRC = resolve(__dirname, '..', '..')
+const read = (...p: string[]) => readFileSync(resolve(SRC, ...p), 'utf8')
+
+describe('Cmd+K wird vom Composer nicht geschluckt', () => {
+ it('öffnet die Palette auch aus einem Textfeld heraus', () => {
+ expect(shortcutCommandFor(chord('k', { meta: true }), IN_FIELD, MAC)).toBe('command-palette')
+ expect(shortcutCommandFor(chord('k', { ctrl: true }), IN_FIELD, WIN)).toBe('command-palette')
+ })
+
+ it('und erst recht außerhalb', () => {
+ expect(shortcutCommandFor(chord('k', { meta: true }), FREE, MAC)).toBe('command-palette')
+ expect(shortcutCommandFor(chord('k', { ctrl: true }), FREE, WIN)).toBe('command-palette')
+ })
+
+ it('ein blankes k tippt weiterhin ein k', () => {
+ expect(shortcutCommandFor(chord('k'), IN_FIELD, MAC)).toBeNull()
+ expect(shortcutCommandFor(chord('k'), IN_FIELD, WIN)).toBeNull()
+ })
+
+ it('macOS: Ctrl+K im Feld bleibt die Emacs-Bindung (Zeile ab Cursor löschen)', () => {
+ // Das ist kein Versehen: die App-Kürzel laufen auf dem Mac über Cmd.
+ expect(shortcutCommandFor(chord('k', { ctrl: true }), IN_FIELD, MAC)).toBeNull()
+ })
+})
+
+describe('die Palette schluckt ihrerseits nichts', () => {
+ it('Cmd/Ctrl + A C V X Z Y bleiben im Feld unbeantwortet', () => {
+ for (const k of ['a', 'c', 'v', 'x', 'z', 'y']) {
+ expect(shortcutCommandFor(chord(k, { meta: true }), IN_FIELD, MAC)).toBeNull()
+ expect(shortcutCommandFor(chord(k, { ctrl: true }), IN_FIELD, WIN)).toBeNull()
+ }
+ })
+
+ it('auch Cmd+Shift+Z und die Navigationstasten', () => {
+ expect(shortcutCommandFor(chord('Z', { meta: true, shift: true }), IN_FIELD, MAC)).toBeNull()
+ for (const k of ['ArrowUp', 'ArrowDown', 'Home', 'End', 'Backspace', 'Delete']) {
+ expect(shortcutCommandFor(chord(k, { meta: true }), IN_FIELD, MAC)).toBeNull()
+ expect(shortcutCommandFor(chord(k, { ctrl: true }), IN_FIELD, WIN)).toBeNull()
+ }
+ })
+
+ it('kein Buchstabe ohne Modifier löst je etwas aus', () => {
+ for (const k of 'abcdefghijklmnopqrstuvwxyz') {
+ expect(shortcutCommandFor(chord(k), FREE, WIN)).toBeNull()
+ }
+ })
+})
+
+describe('die alten Kürzel sind beim Umbau nicht verlorengegangen', () => {
+ it('Ctrl+N / Ctrl+L / Ctrl+E / Ctrl+Shift+D / Ctrl+/', () => {
+ expect(shortcutCommandFor(chord('n', { ctrl: true }), IN_FIELD, WIN)).toBe('new-conversation')
+ expect(shortcutCommandFor(chord('l', { ctrl: true }), IN_FIELD, WIN)).toBe('focus-chat-input')
+ expect(shortcutCommandFor(chord('e', { ctrl: true }), IN_FIELD, WIN)).toBe('export-chat')
+ expect(shortcutCommandFor(chord('D', { ctrl: true, shift: true }), IN_FIELD, WIN)).toBe('toggle-theme')
+ expect(shortcutCommandFor(chord('/', { ctrl: true }), IN_FIELD, WIN)).toBe('show-shortcuts')
+ })
+
+ it('Ctrl+/ überlebt das deutsche Layout, wo `/` selbst Shift+7 ist', () => {
+ // Eine `!shiftKey`-Sperre vor der Tabelle hätte Ctrl+/ auf jeder
+ // deutschen Tastatur getötet — und das ist die Tastatur dieses Hauses.
+ expect(shortcutCommandFor(chord('/', { ctrl: true, shift: true }), FREE, WIN)).toBe('show-shortcuts')
+ })
+
+ it('Escape bleibt beim Dialog-Stapel und nicht bei diesem Handler', () => {
+ expect(shortcutCommandFor(chord('Escape'), IN_FIELD, MAC)).toBeNull()
+ expect(shortcutCommandFor(chord('Escape'), FREE, WIN)).toBeNull()
+ })
+})
+
+describe('eine Taste, eine Aktion, eine Liste', () => {
+ const ids: ShortcutId[] = [
+ 'command-palette', 'new-conversation', 'focus-chat-input',
+ 'export-chat', 'toggle-theme', 'show-shortcuts',
+ ]
+
+ it('jede Aktion ist ausführbar und steht in der Kürzel-Übersicht', () => {
+ for (const id of ids) {
+ expect(typeof SHORTCUT_ACTIONS[id]).toBe('function')
+ expect(shortcutKeys(id)).toBeTruthy()
+ }
+ })
+
+ it('die Übersicht erfindet keine Aktion, die es nicht gibt', () => {
+ for (const entry of SHORTCUTS) {
+ if (entry.id === null) continue
+ expect(SHORTCUT_ACTIONS[entry.id]).toBeTypeOf('function')
+ }
+ })
+
+ it('Ctrl+K steht mit drin — ein unsichtbares Kürzel ist ein totes Kürzel', () => {
+ expect(SHORTCUTS.find(s => s.id === 'command-palette')?.keys).toBe('Ctrl+K')
+ })
+})
+
+describe('es gibt weiterhin GENAU EINEN Tastatur-Handler', () => {
+ it('nur useKeyboardShortcuts hängt an keydown auf window', () => {
+ const hook = read('hooks', 'useKeyboardShortcuts.ts')
+ expect(hook.match(/window\.addEventListener\('keydown'/g)).toHaveLength(1)
+ })
+
+ it('die Palette macht keinen zweiten auf — sie hört auf ihr Ereignis', () => {
+ const palette = read('components', 'ui', 'CommandPalette.tsx')
+ expect(palette).not.toMatch(/addEventListener\(\s*'keydown'/)
+ expect(palette).toContain("window.addEventListener('lu-command-palette'")
+ })
+
+ it('und der Handler ruft die Aktion über die Tabelle, nicht über eine if-Kette', () => {
+ const hook = read('hooks', 'useKeyboardShortcuts.ts')
+ expect(hook).toContain('const id = shortcutCommandFor(e, inInput, IS_MAC)')
+ expect(hook).toContain('SHORTCUT_ACTIONS[id]()')
+ })
+})
diff --git a/src/hooks/useKeyboardShortcuts.ts b/src/hooks/useKeyboardShortcuts.ts
index 77d5804c..5de59d15 100644
--- a/src/hooks/useKeyboardShortcuts.ts
+++ b/src/hooks/useKeyboardShortcuts.ts
@@ -1,6 +1,7 @@
/**
* Global keyboard shortcuts.
*
+ * Ctrl+K — Command palette
* Ctrl+N — New conversation
* Ctrl+L — Focus chat input
* Ctrl+E — Export chat
@@ -11,6 +12,14 @@
* Escape wird NICHT hier behandelt: seit Welle 2 schließt ui/Modal sich selbst
* und kennt dabei den Dialog-Stapel, schließt also nur den obersten. Ein
* zweiter Escape-Handler an dieser Stelle würde zwei Ebenen auf einmal zumachen.
+ *
+ * DIE Regel dieser Datei (Welle 3, Achse 11): es gibt genau EINEN
+ * Tastatur-Handler und genau EINE Zuordnung Taste → Aktion. Die Kommandopalette
+ * hängt sich deshalb NICHT mit einem zweiten `keydown`-Listener daneben,
+ * sondern bekommt hier ihren Eintrag (`command-palette`) und ruft für alles
+ * Weitere dieselben Funktionen aus `SHORTCUT_ACTIONS`, die auch die Taste ruft.
+ * Zwei Handler auf demselben Ereignis sind das Muster, das dieses Projekt
+ * schon mehrfach bezahlt hat: einer wird gepflegt, der andere driftet.
*/
import { useEffect, useCallback } from 'react'
@@ -70,59 +79,109 @@ export function shortcutOwner(e: ShortcutKeyEvent, inInput: boolean, isMac: bool
const IS_MAC = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.userAgent || '')
-export function useKeyboardShortcuts() {
- const handleKeyDown = useCallback((e: KeyboardEvent) => {
- const isCtrl = e.ctrlKey || e.metaKey
- const isShift = e.shiftKey
- const tag = (e.target as HTMLElement).tagName
-
- // Don't interfere with input fields — but a shortcut WITH a modifier is not
- // typing, so it is decided by shortcutOwner() instead of a blanket return.
- const inInput = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement).isContentEditable
- if (shortcutOwner(e, inInput, IS_MAC) === 'field') return
-
- // Ctrl+N — New conversation
- if (isCtrl && e.key === 'n') {
- e.preventDefault()
- const model = useModelStore.getState().activeModel
- const persona = useSettingsStore.getState().getActivePersona()
- if (model) {
- // Same field mix-up as useABCompare had: `Persona.systemPrompt`.
- // Ctrl+N used to open every chat with an empty system prompt.
- useChatStore.getState().createConversation(model, persona?.systemPrompt || '')
- }
- useUIStore.getState().setView('chat')
- }
+/** Jede Aktion, die dieser App über eine Taste erreichbar ist. */
+export type ShortcutId =
+ | 'command-palette'
+ | 'new-conversation'
+ | 'focus-chat-input'
+ | 'export-chat'
+ | 'toggle-theme'
+ | 'show-shortcuts'
+
+/** Ein Tastendruck, soweit die Zuordnung ihn liest. */
+export interface ShortcutChord extends ShortcutKeyEvent {
+ readonly shiftKey: boolean
+}
- // Ctrl+L — Focus chat input
- if (isCtrl && e.key === 'l') {
- e.preventDefault()
- const input = document.querySelector<HTMLTextAreaElement>('textarea[placeholder*="Message"]')
- input?.focus()
- }
+/**
+ * Welche Aktion löst dieser Tastendruck aus — oder keine?
+ *
+ * Die Besitz-Entscheidung aus `shortcutOwner` steht als erstes darin, damit es
+ * unmöglich wird, ein Kürzel hinzuzufügen, das den Guard umgeht. Vorher lag die
+ * Zuordnung als Kette von `if`s im `keydown`-Handler und war damit nur mit
+ * einem DOM prüfbar; hier ist sie eine reine Funktion und wird im Test
+ * durchgerechnet.
+ */
+export function shortcutCommandFor(e: ShortcutChord, inInput: boolean, isMac: boolean): ShortcutId | null {
+ if (shortcutOwner(e, inInput, isMac) === 'field') return null
+ if (!(e.ctrlKey || e.metaKey)) return null
+
+ // Das einzige Kürzel, das Shift BRAUCHT. `e.key` ist das geschaltete
+ // Zeichen, also das große D — genau wie in der Fassung davor.
+ if (e.shiftKey && e.key === 'D') return 'toggle-theme'
+
+ switch (e.key) {
+ case 'k': return 'command-palette'
+ case 'n': return 'new-conversation'
+ case 'l': return 'focus-chat-input'
+ case 'e': return 'export-chat'
+ // Auf dem deutschen Layout IST `/` bereits Shift+7. Dieser Fall darf
+ // deshalb nicht hinter einer `!shiftKey`-Sperre liegen, sonst wäre Ctrl+/
+ // dort tot — und die Tastatur dieses Hauses ist deutsch.
+ case '/': return 'show-shortcuts'
+ default: return null
+ }
+}
- // Ctrl+E — Export chat
- if (isCtrl && e.key === 'e') {
- e.preventDefault()
- const state = useChatStore.getState()
- const conv = state.conversations.find(c => c.id === state.activeConversationId)
- if (conv) exportConversation(conv, 'markdown')
+/**
+ * Was die Aktionen TUN. Eine Funktion je Aktion, und zwar die einzige:
+ * der Tastatur-Handler unten ruft sie, und die Kommandopalette
+ * (`ui/command-actions.ts`) reicht dieselben Funktionsobjekte als ihr `run`
+ * weiter. Es gibt bewusst keine zweite Fassung „für die Palette".
+ */
+export const SHORTCUT_ACTIONS: Readonly<Record<ShortcutId, () => void>> = {
+ 'command-palette': () => {
+ window.dispatchEvent(new CustomEvent('lu-command-palette'))
+ },
+
+ 'new-conversation': () => {
+ const model = useModelStore.getState().activeModel
+ const persona = useSettingsStore.getState().getActivePersona()
+ if (model) {
+ // Same field mix-up as useABCompare had: `Persona.systemPrompt`.
+ // Ctrl+N used to open every chat with an empty system prompt.
+ useChatStore.getState().createConversation(model, persona?.systemPrompt || '')
}
+ useUIStore.getState().setView('chat')
+ },
+
+ 'focus-chat-input': () => {
+ const input = document.querySelector<HTMLTextAreaElement>('textarea[placeholder*="Message"]')
+ input?.focus()
+ },
+
+ 'export-chat': () => {
+ const state = useChatStore.getState()
+ const conv = state.conversations.find(c => c.id === state.activeConversationId)
+ if (conv) void exportConversation(conv, 'markdown')
+ },
+
+ 'toggle-theme': () => {
+ const settings = useSettingsStore.getState().settings
+ useSettingsStore.getState().updateSettings({
+ theme: settings.theme === 'dark' ? 'light' : 'dark',
+ })
+ },
+
+ 'show-shortcuts': () => {
+ window.dispatchEvent(new CustomEvent('lu-show-shortcuts'))
+ },
+}
- // Ctrl+Shift+D — Toggle theme
- if (isCtrl && isShift && e.key === 'D') {
- e.preventDefault()
- const settings = useSettingsStore.getState().settings
- useSettingsStore.getState().updateSettings({
- theme: settings.theme === 'dark' ? 'light' : 'dark',
- })
- }
+export function useKeyboardShortcuts() {
+ const handleKeyDown = useCallback((e: KeyboardEvent) => {
+ const target = e.target as HTMLElement | null
+ const tag = target?.tagName ?? ''
- // Ctrl+/ — Show shortcuts help (dispatches custom event)
- if (isCtrl && e.key === '/') {
- e.preventDefault()
- window.dispatchEvent(new CustomEvent('lu-show-shortcuts'))
- }
+ // Don't interfere with input fields — but a shortcut WITH a modifier is not
+ // typing, so it is decided by shortcutOwner() (inside shortcutCommandFor)
+ // instead of a blanket return.
+ const inInput = tag === 'INPUT' || tag === 'TEXTAREA' || target?.isContentEditable === true
+
+ const id = shortcutCommandFor(e, inInput, IS_MAC)
+ if (!id) return
+ e.preventDefault()
+ SHORTCUT_ACTIONS[id]()
}, [])
useEffect(() => {
@@ -131,11 +190,26 @@ export function useKeyboardShortcuts() {
}, [handleKeyDown])
}
-export const SHORTCUTS = [
- { keys: 'Ctrl+N', description: 'New conversation' },
- { keys: 'Ctrl+L', description: 'Focus chat input' },
- { keys: 'Ctrl+E', description: 'Export chat as Markdown' },
- { keys: 'Ctrl+Shift+D', description: 'Toggle dark/light mode' },
- { keys: 'Ctrl+/', description: 'Show keyboard shortcuts' },
- { keys: 'Escape', description: 'Close panel or modal' },
+/** Ein Eintrag der Kürzel-Übersicht. `id` fehlt nur, wo keine Aktion dahinter
+ * steht (Escape gehört dem Dialog, nicht diesem Handler). */
+export interface ShortcutEntry {
+ readonly id: ShortcutId | null
+ readonly keys: string
+ readonly description: string
+}
+
+export const SHORTCUTS: readonly ShortcutEntry[] = [
+ { id: 'command-palette', keys: 'Ctrl+K', description: 'Command palette' },
+ { id: 'new-conversation', keys: 'Ctrl+N', description: 'New conversation' },
+ { id: 'focus-chat-input', keys: 'Ctrl+L', description: 'Focus chat input' },
+ { id: 'export-chat', keys: 'Ctrl+E', description: 'Export chat as Markdown' },
+ { id: 'toggle-theme', keys: 'Ctrl+Shift+D', description: 'Toggle dark/light mode' },
+ { id: 'show-shortcuts', keys: 'Ctrl+/', description: 'Show keyboard shortcuts' },
+ { id: null, keys: 'Escape', description: 'Close panel or modal' },
]
+
+/** Die Beschriftung eines Kürzels — EINE Liste, keine zweite Tabelle für die
+ * Palette. */
+export function shortcutKeys(id: ShortcutId): string | undefined {
+ return SHORTCUTS.find(s => s.id === id)?.keys
+}
diff --git a/src/stores/compareStore.ts b/src/stores/compareStore.ts
index 45965d76..a6499f67 100644
--- a/src/stores/compareStore.ts
+++ b/src/stores/compareStore.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import type { Message } from '../types/chat'
+import { useUIStore } from './uiStore'
interface ModelStats {
tokens: number
@@ -102,3 +103,15 @@ export const useCompareStore = create<CompareState>()((set) => ({
isStreamingB: false,
}),
}))
+
+/**
+ * „Compare" einschalten. Das ist kein View, sondern ein Flag PLUS ein Wechsel
+ * nach Chat — die A/B-Spalten übernehmen den Chatbereich. Diese zwei Zeilen
+ * standen im Header zweimal wörtlich da (Leiste und Überlaufmenü); die
+ * Kommandopalette wäre die dritte Abschrift geworden. Jetzt rufen alle drei
+ * dieselbe Funktion.
+ */
+export function openCompare(): void {
+ useCompareStore.getState().setComparing(true)
+ useUIStore.getState().setView('chat')
+}