mirror of
https://github.com/Twigpine/zero.git
synced 2026-11-11 23:40:28 -10:00
* ## Speech-to-text dictation Adds voice dictation to Zero. Run `/voice` to enter hold-to-record mode, then hold **Space** to dictate and release to transcribe (run `/voice` again to turn it off so Space types normally). Pick a backend with `/stt-model`. ### Backends - **Local (sherpa-onnx)** — offline, no API key. Auto-downloads a model via `/stt-model`; the engine binary is fetched once and shared across models. Family auto-detection covers the mainstream offline families (Whisper, transducer/Zipformer, Moonshine, Paraformer, SenseVoice, and the CTC families FireRedASR, NeMo, TeleSpeech, WeNet, Zipformer-CTC, Dolphin, Omnilingual — plus the encoder/decoder families Canary and FireRedASR-AED). - **Cloud batch** — Groq and OpenAI Whisper. Keys resolve from a configured provider, the encrypted credential store, or the env var; a missing/invalid key is entered inline. - **Streaming** — a warm local sherpa-onnx websocket server (live transcript as you speak) on desktop, or Deepgram / OpenAI Realtime. ### Highlights - Live audio-reactive waveform while recording (real mic levels when streaming; a synthesized wave for batch). - `/stt-model` download chooser: recommended models first, Live/Batch tag per row, size + download state, and a search filter. - Streaming transcript is inserted live into the composer and committed on stop; batch inserts on stop. Insert-for-review by default (`stt.autoSubmit` to fire straight at the agent). - The warm streaming server is released when `/voice` is turned off and on exit. ### Implementation notes - No CGO and no bundled runtimes — every OS integration shells out via `exec.Command` with discrete argv (never a shell string). - The streaming server manager mirrors the LSP manager's warm-subprocess lifecycle. - OS-boundary code (recorders, transcribers, server) is unit-tested via injected fakes; real microphone / websocket behavior is covered by env-gated smoke tests. ### Testing - `go build ./...`, `go vet ./...`, and the config / dictation / cli / tui suites pass. - Verified end-to-end against real downloaded binaries + models (offline batch, streaming websocket server, and the model auto-download), including the FireRedASR-CTC and NeMo streaming transducer families. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added speech-to-text dictation with both batch and streaming modes, supporting local (sherpa-onnx) and cloud providers, including WAV/M4A detection. * Introduced voice dictation mode with STT model selection, local engine/model auto-download, and an inline prompt to save cloud API keys. * Added new TUI commands for voice/STT model selection and enabled F1–F12 key bindings. * **Bug Fixes** * Improved streaming dictation to preserve accumulated transcript partials and keep the editor region consistent. * Refined TUI status/picker rendering, including clearer loading/search behavior and more reliable selection alignment. <!-- end of auto-generated comment: release notes by coderabbit.ai --> * fix(dictation): address CodeRabbit review feedback - validateSTTConfig: add NumThreads bounds check - downloadVerifyExtract: stage extraction into a sibling temp dir, atomic-rename into destDir on success so a partial extract cannot leave a truncated engine binary that passes fileExists() on next run - startProcess: close pipe fds when cmd.Start() fails - ServerManager.Shutdown: honor the caller's context deadline - audioSpillDir: tighten any pre-existing directory to 0700 - startVariantDownload: refuse re-entry while a download is in flight - maybeOpenSTTDownloadPicker: defer Provider=local persistence to applyEngineComponents (commit-on-success), matching the cloud flow - fetchSTTModelsCmd: bound with a 30s timeout client+context - newSTTDownloadPickerFrom.isCurrent: compare path segments via filepath.Base to avoid substring false-positives * fix(dictation): harden recorder.Stop, Esc-cancel priority, streaming region Three correctness issues from PR review: 1) recorder.Stop() panicked (nil-deref) when called on a StartStreaming session because StartStreaming intentionally leaves r.proc nil. Reject that misuse with a clear error. Termux's batch path also leaves r.proc nil by design — keep that path working. 2) Esc was consumed by an active dictation session before the confirming second Esc could cancel a pending run, so a user mid-recording who double-Esc's to kill the run found the first Esc swallowed by dictation. Gate dictation-cancel on the Esc not being a pending-run confirm. 3) applyStreamingText hard-reset the cursor to regionStart on every partial, yanking focus away from users editing elsewhere in the composer, and stored regionStart/End as absolute indices that became stale the moment the user typed or pasted before the live region. Preserve the cursor when it's outside the region, and snapshot the prefix BEFORE the region so the next partial can detect external edits and shift [start,end) to stay aligned.
597 lines
19 KiB
Go
597 lines
19 KiB
Go
package tui
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
|
|
tea "charm.land/bubbletea/v2"
|
|
)
|
|
|
|
// parseTracerPid returns true when /proc/self/status contains a non-zero
|
|
// TracerPid. This detects any ptrace tracer (PRoot, gdb, strace, dlv, etc.),
|
|
// not PRoot specifically. That's intentional: under any ptrace tracer the
|
|
// AllMotion (1003) sequence is unreliable, so CellMotion is the safer
|
|
// fallback. The only loss is hover-highlighting, which has no functional
|
|
// impact.
|
|
func parseTracerPid(data []byte) bool {
|
|
for _, line := range strings.Split(string(data), "\n") {
|
|
if strings.HasPrefix(line, "TracerPid:") {
|
|
pid := strings.TrimSpace(line[10:])
|
|
return pid != "0"
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
var isRunningUnderPRoot = sync.OnceValue(func() bool {
|
|
data, err := os.ReadFile("/proc/self/status")
|
|
if err != nil {
|
|
return false
|
|
}
|
|
return parseTracerPid(data)
|
|
})
|
|
|
|
type mouseOverlayHit struct {
|
|
x int
|
|
y int
|
|
}
|
|
|
|
type mouseSelectionTarget struct {
|
|
Scope string
|
|
Kind int
|
|
Value string
|
|
Index int
|
|
}
|
|
|
|
// scrollChatExtendingSelection scrolls the chat and, if a drag-selection is in
|
|
// progress, extends its cursor to the mouse's current position against the
|
|
// POST-scroll viewport — mirroring what a mouseMotion event does. Without this, a
|
|
// selection's cursor is only ever updated by actual mouse movement (see
|
|
// handleTranscriptSelectionMouse's mouseMotion case): a wheel-scroll event is a
|
|
// distinct message type that never reaches that code, so scrolling while
|
|
// selecting left the selection frozen at whatever line the mouse last physically
|
|
// moved over — capped at the viewport that was visible before the scroll.
|
|
func (m model) scrollChatExtendingSelection(delta int, msg tea.MouseMsg) model {
|
|
m = m.scrollChat(delta)
|
|
if !m.transcriptSelection.active {
|
|
return m
|
|
}
|
|
if line, ok := m.nearestTranscriptLineAtMouse(msg); ok {
|
|
m.transcriptSelection.cursor = transcriptSelectionPointForMouse(line, mouseX(msg))
|
|
}
|
|
return m
|
|
}
|
|
|
|
func (m model) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
|
|
// While a provider-wizard OAuth login is in flight, ignore all mouse input
|
|
// (clicks and wheel) so a stray scroll can't change the selected provider
|
|
// mid-login — mirroring the keyboard handler's pending guard.
|
|
if m.providerWizard != nil && m.providerWizard.oauthPending {
|
|
return m, nil
|
|
}
|
|
// A click is a deliberate action, same as a keypress — it means the user
|
|
// moved on to something else, so it disarms a stale Esc cancel-confirmation
|
|
// rather than leaving it armed for some later, unrelated Esc to act on.
|
|
// Scoped to actual clicks (not hover/motion/wheel), since motion events fire
|
|
// continuously while the mouse merely sits over the terminal and would
|
|
// otherwise defeat the confirmation window on every render tick.
|
|
if mouseLeftPress(msg) || mouseRightPress(msg) {
|
|
m = m.disarmCancelConfirmation()
|
|
}
|
|
// A right-click pastes the clipboard straight into the focused field — no
|
|
// menu. pasteFromClipboardCmd reads the clipboard off the Update goroutine; the
|
|
// clipboardReadMsg result is routed by routePaste to wherever input is focused
|
|
// (composer, wizard, setup) or swallowed on a surface with no text field.
|
|
// Keyboard/selection copy-paste keep working unchanged.
|
|
if mouseRightPress(msg) {
|
|
return m, pasteFromClipboardCmd()
|
|
}
|
|
if mouseLeftPress(msg) {
|
|
switch {
|
|
case m.providerWizard != nil:
|
|
if target, ok := m.selectProviderWizardAtMouse(msg); ok {
|
|
if m.repeatMouseSelection(target) {
|
|
m.clearMouseSelection()
|
|
return m.advanceProviderWizard()
|
|
}
|
|
m.lastMouseSelection = target
|
|
return m, nil
|
|
}
|
|
case m.mcpAddWizard != nil:
|
|
if target, ok := m.selectMCPAddWizardAtMouse(msg); ok {
|
|
if m.repeatMouseSelection(target) {
|
|
m.clearMouseSelection()
|
|
return m.handleMCPAddWizardMouseActivate()
|
|
}
|
|
m.lastMouseSelection = target
|
|
return m, nil
|
|
}
|
|
case m.mcpManager != nil:
|
|
if target, ok := m.selectMCPManagerAtMouse(msg); ok {
|
|
if m.repeatMouseSelection(target) {
|
|
m.clearMouseSelection()
|
|
return m.chooseMCPManagerItem()
|
|
}
|
|
m.lastMouseSelection = target
|
|
return m, nil
|
|
}
|
|
case m.picker != nil:
|
|
if target, ok := m.selectPickerAtMouse(msg); ok {
|
|
if m.repeatMouseSelection(target) {
|
|
m.clearMouseSelection()
|
|
return m.choosePicker()
|
|
}
|
|
m.lastMouseSelection = target
|
|
return m, nil
|
|
}
|
|
case m.suggestionsActive():
|
|
if target, ok := m.selectSuggestionAtMouse(msg); ok {
|
|
if m.repeatMouseSelection(target) {
|
|
m.clearMouseSelection()
|
|
return m.chooseSuggestion()
|
|
}
|
|
m.lastMouseSelection = target
|
|
return m, nil
|
|
}
|
|
}
|
|
}
|
|
if next, cmd, ok := m.handleComposerSelectionMouse(msg); ok {
|
|
return next, cmd
|
|
}
|
|
if next, cmd, ok := m.handleTranscriptSelectionMouse(msg); ok {
|
|
return next, cmd
|
|
}
|
|
// A plain hover (cursor moved, no button pressed) never matches the
|
|
// press/drag/release cases above, so it falls through here — resolve what's
|
|
// under the cursor so it can render with the hover highlight.
|
|
if mouseHover(msg) {
|
|
return m.updateHoverTarget(msg), nil
|
|
}
|
|
|
|
switch {
|
|
case mouseWheelUp(msg):
|
|
m.clearMouseSelection()
|
|
m = m.clearHover()
|
|
if m.providerWizard != nil {
|
|
m.providerWizard.move(-1)
|
|
return m, nil
|
|
}
|
|
if m.mcpAddWizard != nil {
|
|
m.mcpAddWizard.move(-1)
|
|
return m, nil
|
|
}
|
|
if m.mcpManager != nil {
|
|
m.moveMCPManager(-1)
|
|
return m, nil
|
|
}
|
|
if m.picker != nil {
|
|
if m.modelPickerIsLoading() {
|
|
return m, nil
|
|
}
|
|
m.pickerMoved(-1)
|
|
return m, nil
|
|
}
|
|
if m.suggestionsActive() {
|
|
m.moveSuggestion(-1)
|
|
return m, nil
|
|
}
|
|
if m.mouseOverComposer(msg) {
|
|
if next, ok := m.moveComposerVisualCursor(-1); ok {
|
|
return next, nil
|
|
}
|
|
}
|
|
return m.scrollChatExtendingSelection(chatWheelScrollLines, msg), nil
|
|
case mouseWheelDown(msg):
|
|
m.clearMouseSelection()
|
|
m = m.clearHover()
|
|
if m.providerWizard != nil {
|
|
m.providerWizard.move(1)
|
|
return m, nil
|
|
}
|
|
if m.mcpAddWizard != nil {
|
|
m.mcpAddWizard.move(1)
|
|
return m, nil
|
|
}
|
|
if m.mcpManager != nil {
|
|
m.moveMCPManager(1)
|
|
return m, nil
|
|
}
|
|
if m.picker != nil {
|
|
if m.modelPickerIsLoading() {
|
|
return m, nil
|
|
}
|
|
m.pickerMoved(1)
|
|
return m, nil
|
|
}
|
|
if m.suggestionsActive() {
|
|
m.moveSuggestion(1)
|
|
return m, nil
|
|
}
|
|
if m.mouseOverComposer(msg) {
|
|
if next, ok := m.moveComposerVisualCursor(1); ok {
|
|
return next, nil
|
|
}
|
|
}
|
|
return m.scrollChatExtendingSelection(-chatWheelScrollLines, msg), nil
|
|
default:
|
|
return m, nil
|
|
}
|
|
}
|
|
|
|
// sidebarLineAtMouse maps a left-click in the AGENTS sidebar column to the swarm
|
|
// member whose row was clicked, when that member's session is known. Geometry:
|
|
// twoColumnTranscriptView is the full screen (sidebarActive ⇒ alt-screen), and
|
|
// joinColumns lays out [chat(chatColumnWidth)][" │ " 3-cell divider][sidebar],
|
|
// zipping row-by-row — so a sidebar line's screen Y equals its sidebar index and
|
|
// the sidebar starts at screen X = chatColumnWidth + 3. Recomputed on demand
|
|
// (View can't persist a registry on the value-receiver model), like
|
|
// transcriptLineAtMouse.
|
|
func (m model) sidebarLineAtMouse(msg tea.MouseMsg) (sidebarAgentHit, bool) {
|
|
if !m.sidebarActive() {
|
|
return sidebarAgentHit{}, false
|
|
}
|
|
if m.setup.visible || m.providerWizard != nil || m.mcpAddWizard != nil || m.mcpManager != nil || m.picker != nil || m.suggestionsActive() {
|
|
return sidebarAgentHit{}, false
|
|
}
|
|
sidebarW := sidebarWidth(m.width)
|
|
if sidebarW <= 0 {
|
|
return sidebarAgentHit{}, false
|
|
}
|
|
x0 := m.chatColumnWidth() + 3 // " │ " divider between the columns
|
|
x, y := mouseX(msg), mouseY(msg)
|
|
if x < x0 || x >= x0+sidebarW {
|
|
return sidebarAgentHit{}, false
|
|
}
|
|
for _, hit := range m.sidebarAgentSelectables(sidebarW) {
|
|
if hit.lineOffset == y && hit.sessionID != "" {
|
|
return hit, true
|
|
}
|
|
}
|
|
return sidebarAgentHit{}, false
|
|
}
|
|
|
|
func (m model) repeatMouseSelection(target mouseSelectionTarget) bool {
|
|
return target.Scope != "" && m.lastMouseSelection == target
|
|
}
|
|
|
|
func (m *model) clearMouseSelection() {
|
|
m.lastMouseSelection = mouseSelectionTarget{}
|
|
}
|
|
|
|
func (m model) wantsMouseCapture() bool {
|
|
if m.mouseReleased {
|
|
return false // user released the mouse for native text selection/copy
|
|
}
|
|
return m.altScreen && (m.setupWantsMouseCapture() || m.chatWantsMouseCapture() || m.providerWizard != nil || m.mcpAddWizard != nil || m.mcpManager != nil || m.picker != nil || m.suggestionsActive())
|
|
}
|
|
|
|
func (m model) setupWantsMouseCapture() bool {
|
|
if !m.setup.visible {
|
|
return false
|
|
}
|
|
return m.setup.stage == setupStageProvider || m.setup.stage == setupStageModel
|
|
}
|
|
|
|
func (m model) chatWantsMouseCapture() bool {
|
|
return !m.setup.visible
|
|
}
|
|
|
|
func (m model) syncMouseCapture() (model, tea.Cmd) {
|
|
want := m.wantsMouseCapture()
|
|
if m.mouseCapture == want {
|
|
return m, nil
|
|
}
|
|
m.mouseCapture = want
|
|
return m, nil
|
|
}
|
|
|
|
func (m model) mouseOverComposer(msg tea.MouseMsg) bool {
|
|
if !m.altScreen || m.height <= 0 || m.transcriptDetailed {
|
|
return false
|
|
}
|
|
width := m.chatColumnWidth()
|
|
frame := m.scrollableTranscriptFrame(m.pinnedTitleBar(width), m.footerView(width))
|
|
return frame.composerRect.contains(mouseX(msg), mouseY(msg))
|
|
}
|
|
|
|
func lineSequenceIndex(lines []string, sequence []string) int {
|
|
if len(sequence) == 0 || len(sequence) > len(lines) {
|
|
return -1
|
|
}
|
|
for index := 0; index+len(sequence) <= len(lines); index++ {
|
|
matched := true
|
|
for offset := range sequence {
|
|
if lines[index+offset] != sequence[offset] {
|
|
matched = false
|
|
break
|
|
}
|
|
}
|
|
if matched {
|
|
return index
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
func (m *model) selectSuggestionAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
if !m.suggestionsActive() || len(m.suggestions) == 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.suggestionOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
maxVisible := minInt(suggestionPaletteMaxVisible, len(m.suggestions))
|
|
start := selectableListStart(len(m.suggestions), maxVisible, clampInt(m.suggestionIdx, 0, len(m.suggestions)-1))
|
|
row := hit.y - 3
|
|
if row < 0 || row >= maxVisible {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
index := start + row
|
|
m.suggestionIdx = index
|
|
scope := "command"
|
|
if m.suggestionsAreFiles {
|
|
scope = "file"
|
|
}
|
|
return mouseSelectionTarget{Scope: scope, Value: m.suggestions[index].Name, Index: index}, true
|
|
}
|
|
|
|
func (m *model) selectPickerAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
if m.picker == nil || len(m.picker.items) == 0 || m.modelPickerIsLoading() {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
if m.picker.kind == pickerModel {
|
|
return m.selectModelPickerAtMouse(msg)
|
|
}
|
|
return m.selectGenericPickerAtMouse(msg)
|
|
}
|
|
|
|
func (m *model) selectMCPManagerAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
if m.mcpManager == nil {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
items := m.mcpManagerItems()
|
|
if len(items) == 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.mcpManagerOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
_, itemRows := m.renderMCPManagerItemLines(maxInt(1, chatWidth(m.width)-4), items)
|
|
baseRow := mcpManagerFirstItemRow(m.mcpViewState())
|
|
row := hit.y - baseRow
|
|
if row < 0 || row >= len(itemRows) || itemRows[row] < 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
index := itemRows[row]
|
|
m.mcpManager.selected = index
|
|
return mouseSelectionTarget{Scope: "mcp-manager", Kind: int(items[index].Kind), Value: items[index].Name, Index: index}, true
|
|
}
|
|
|
|
func (m *model) selectMCPAddWizardAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
if m.mcpAddWizard == nil {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.mcpAddWizardOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
baseRow := 4
|
|
if m.mcpAddWizard.err != "" {
|
|
baseRow += 2
|
|
}
|
|
switch m.mcpAddWizard.step {
|
|
case mcpAddWizardStepType:
|
|
row := hit.y - baseRow
|
|
if row < 0 || row >= len(mcpAddWizardTypes) {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
m.mcpAddWizard.selectedType = row
|
|
m.mcpAddWizard.serverType = mcpAddWizardTypes[row].ID
|
|
return mouseSelectionTarget{Scope: "mcp-add-wizard", Kind: int(m.mcpAddWizard.step), Value: m.mcpAddWizard.serverType, Index: row}, true
|
|
case mcpAddWizardStepResult:
|
|
actions := m.mcpAddWizard.resultActions()
|
|
if len(actions) == 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
rowStart := m.mcpAddWizard.mcpAddWizardResultActionStartRow()
|
|
row := hit.y - rowStart
|
|
if row < 0 || row >= len(actions) {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
m.mcpAddWizard.resultSelected = row
|
|
return mouseSelectionTarget{Scope: "mcp-add-wizard", Kind: int(m.mcpAddWizard.step), Value: actions[row], Index: row}, true
|
|
default:
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
}
|
|
|
|
func (m model) handleMCPAddWizardMouseActivate() (tea.Model, tea.Cmd) {
|
|
if m.mcpAddWizard == nil {
|
|
return m, nil
|
|
}
|
|
if m.mcpAddWizard.step == mcpAddWizardStepResult {
|
|
return m.handleMCPAddWizardResultEnter()
|
|
}
|
|
return m.advanceMCPAddWizard()
|
|
}
|
|
|
|
func (wizard *mcpAddWizardState) mcpAddWizardResultActionStartRow() int {
|
|
if wizard == nil {
|
|
return 0
|
|
}
|
|
row := 7 // top border + step + separator + title + server + transport + saved/tools line
|
|
if wizard.err != "" {
|
|
row += 2
|
|
}
|
|
if wizard.result.Message != "" {
|
|
row++
|
|
}
|
|
row++ // blank line before actions
|
|
return row
|
|
}
|
|
|
|
func (m *model) selectModelPickerAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.modelPickerOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
maxVisible := minInt(pickerOverlayMaxVisible, len(m.picker.items))
|
|
start := selectableListStart(len(m.picker.items), maxVisible, clampInt(m.picker.selected, 0, len(m.picker.items)-1))
|
|
rowStart := 3
|
|
if m.modelPickerLoadError != "" {
|
|
rowStart++
|
|
}
|
|
row := hit.y - rowStart
|
|
if row < 0 || row >= maxVisible {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
index := start + row
|
|
m.picker.selected = index
|
|
return mouseSelectionTarget{Scope: "picker", Kind: int(m.picker.kind), Value: m.picker.items[index].Value, Index: index}, true
|
|
}
|
|
|
|
func (m *model) selectGenericPickerAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.pickerOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
maxVisible := minInt(pickerOverlayMaxVisible, len(m.picker.items))
|
|
selected := clampInt(m.picker.selected, 0, len(m.picker.items)-1)
|
|
start := selectableListStart(len(m.picker.items), maxVisible, selected)
|
|
visible := m.picker.items[start : start+maxVisible]
|
|
// y=0 titled top border, y=1 search line, y=2 separator; rows begin at y=3.
|
|
line := 3
|
|
lastGroup := ""
|
|
for offset, item := range visible {
|
|
if item.Group != "" && item.Group != lastGroup {
|
|
if hit.y == line {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
line++
|
|
lastGroup = item.Group
|
|
}
|
|
if hit.y == line {
|
|
index := start + offset
|
|
m.picker.selected = index
|
|
// Clicking (or hovering onto) a row live-previews it, like arrow keys,
|
|
// so the theme picker repaints before the confirming second click.
|
|
m.previewSelectedTheme()
|
|
return mouseSelectionTarget{Scope: "picker", Kind: int(m.picker.kind), Value: item.Value, Index: index}, true
|
|
}
|
|
line++
|
|
}
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
|
|
func (m *model) selectProviderWizardAtMouse(msg tea.MouseMsg) (mouseSelectionTarget, bool) {
|
|
if m.providerWizard == nil || m.providerWizard.oauthPending {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
width := chatWidth(m.width)
|
|
hit, ok := m.overlayMouseHit(msg, m.providerWizardOverlay(width), width)
|
|
if !ok {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
baseRow := 3
|
|
if m.providerWizard.err != "" {
|
|
baseRow += 2
|
|
}
|
|
switch m.providerWizard.step {
|
|
case providerWizardStepProvider:
|
|
if len(m.providerWizard.providers) == 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
maxVisible := minInt(maxProviderWizardProvidersVisible, len(m.providerWizard.providers))
|
|
selected := clampInt(m.providerWizard.selectedProvider, 0, len(m.providerWizard.providers)-1)
|
|
start := selectableListStart(len(m.providerWizard.providers), maxVisible, selected)
|
|
row := hit.y - (baseRow + 1)
|
|
if row < 0 || row >= maxVisible {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
index := start + row
|
|
m.providerWizard.selectedProvider = index
|
|
m.providerWizard.apiKey = ""
|
|
m.providerWizard.refreshModels()
|
|
return mouseSelectionTarget{Scope: "provider-wizard", Kind: int(m.providerWizard.step), Value: m.providerWizard.providers[index].ID, Index: index}, true
|
|
case providerWizardStepModel:
|
|
if m.providerWizard.modelLoading {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
m.providerWizard.refreshModels()
|
|
models := m.providerWizard.filteredModels()
|
|
if len(models) == 0 {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
maxVisible := minInt(maxProviderWizardModelsVisible, len(models))
|
|
selected := clampInt(m.providerWizard.selectedModel, 0, len(models)-1)
|
|
start := selectableListStart(len(models), maxVisible, selected)
|
|
rowStart := baseRow + 2
|
|
if m.providerWizard.modelStatusText() != "" {
|
|
rowStart++
|
|
}
|
|
row := hit.y - rowStart
|
|
if row < 0 || row >= maxVisible {
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
index := start + row
|
|
m.providerWizard.selectedModel = index
|
|
return mouseSelectionTarget{Scope: "provider-wizard", Kind: int(m.providerWizard.step), Value: models[index].ID, Index: index}, true
|
|
default:
|
|
return mouseSelectionTarget{}, false
|
|
}
|
|
}
|
|
|
|
func (m model) overlayMouseHit(msg tea.MouseMsg, overlay string, width int) (mouseOverlayHit, bool) {
|
|
lines := viewLines(overlay)
|
|
if len(lines) == 0 {
|
|
return mouseOverlayHit{}, false
|
|
}
|
|
left, lines, overlayWidth := normalizeOverlayBlock(lines, width)
|
|
if overlayWidth <= 0 || len(lines) == 0 {
|
|
return mouseOverlayHit{}, false
|
|
}
|
|
rect := m.overlayMouseRect(len(lines), width)
|
|
if rect.height <= 0 || mouseY(msg) < rect.y || mouseY(msg) >= rect.y+rect.height {
|
|
return mouseOverlayHit{}, false
|
|
}
|
|
if mouseX(msg) < left || mouseX(msg) >= left+overlayWidth {
|
|
return mouseOverlayHit{}, false
|
|
}
|
|
return mouseOverlayHit{x: mouseX(msg) - left, y: mouseY(msg) - rect.y}, true
|
|
}
|
|
|
|
func (m model) overlayMouseTop(overlayHeight int, width int) int {
|
|
return m.overlayMouseRect(overlayHeight, width).y
|
|
}
|
|
|
|
func (m model) overlayMouseRect(overlayHeight int, width int) tuiRect {
|
|
if overlayHeight <= 0 {
|
|
return tuiRect{}
|
|
}
|
|
if m.altScreen && m.height > 0 {
|
|
frame := m.scrollableTranscriptFrame(m.pinnedTitleBar(width), m.footerView(width))
|
|
visibleHeight := minInt(overlayHeight, frame.bodyRect.height)
|
|
if visibleHeight <= 0 {
|
|
return tuiRect{}
|
|
}
|
|
return tuiRect{
|
|
y: frame.bodyRect.y + maxInt(0, (frame.bodyRect.height-visibleHeight)/2),
|
|
width: width,
|
|
height: visibleHeight,
|
|
}
|
|
}
|
|
return tuiRect{
|
|
y: maxInt(0, (normalizedStartupHeight(m.height)-overlayHeight)/2),
|
|
width: width,
|
|
height: overlayHeight,
|
|
}
|
|
}
|