Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ src/
lib/shortcuts.ts atalhos globais (o terminal ignora essas teclas)
lib/suggestions.ts botões ▶/⤓ ao lado dos comandos que o Claude sugeriu (procura o texto na tela)
lib/settings.ts configurações, ditado (voice_*), leitura em voz alta (speak_*) e seletor de arquivos; shellQuote dos caminhos colados
lib/voice.ts palavra-chave do ditado (“enviar” no fim = Enter)
lib/voice.ts frase de enviar do ditado (“term7 pronto” no fim = Enter; aceita as grafias do Whisper)
lib/update.ts confere/instala a versão nova (botão ao lado da versão, na barra)
lib/api.ts, screens.ts API das extensões: atende os pedidos do api.rs (abas, tela, mandar pro Claude com fila)
state/extStatus.ts status publicado por extensões (status.set); ExtStatus.vue desenha na barra de status
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ including its subagents, MCP servers and usage limits.

**Also**
- Voice dictation: any OpenAI-compatible API (Groq is preset) or local [whisper.cpp](https://github.com/ggml-org/whisper.cpp).
End with the Portuguese word “enviar” to send it with Enter.
End with “term7 pronto” (configurable) to send it with Enter.
- Read aloud: Claude's reply is spoken when it finishes (always, or only after a dictation), through the
dictation API or a separate one (OpenAI speaks Portuguese; Groq's voices are English-only).
- Anonymous mode: scrambles all text on screen so you can record without exposing anything.
Expand Down
2 changes: 1 addition & 1 deletion README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ subagentes, os servidores MCP e os limites de uso.
**Também**
- Ditado por voz: qualquer API compatível com a da OpenAI (a Groq vem preenchida) ou o
[whisper.cpp](https://github.com/ggml-org/whisper.cpp) local, sem nada sair da máquina.
Terminar a fala com “enviar” manda com Enter.
Terminar a fala com “term7 pronto” (configurável) manda com Enter.
- Leitura em voz alta: a resposta do Claude é lida quando ele termina (sempre, ou só depois de um ditado),
pela mesma API do ditado ou por outra (a OpenAI fala português; a voz do Groq, só inglês).
- Modo anônimo: embaralha todo o texto da tela, pra gravar sem expor nada.
Expand Down
3 changes: 3 additions & 0 deletions src-tauri/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ pub struct VoiceSettings {
pub language: String,
/// Para de gravar sozinho quando a fala termina (sem o segundo clique).
pub auto_stop: bool,
/// Frase que, no fim do ditado, manda com Enter (o frontend reconhece); vazia desliga.
pub send_phrase: String,
}

impl Default for VoiceSettings {
Expand All @@ -44,6 +46,7 @@ impl Default for VoiceSettings {
local_model: String::new(),
language: "pt".into(),
auto_stop: true,
send_phrase: "term7 pronto".into(),
}
}
}
Expand Down
30 changes: 17 additions & 13 deletions src-tauri/src/speech.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@ const CHUNK_CHARS: usize = 200;
/// Nada toca até o primeiro trecho chegar inteiro: curto, a fala começa logo e
/// os seguintes são gerados enquanto ele toca.
const FIRST_CHUNK_CHARS: usize = 80;
/// Resposta longa vira minutos de áudio, custo e cota (o Groq gratuito dá 100
/// pedidos por dia e 1.200 tokens por minuto): lê só o começo.
const MAX_CHARS: usize = 600;
/// Pela API, resposta longa vira custo e cota (o Groq gratuito dá 100 pedidos por
/// dia e 1.200 tokens por minuto): lê só o começo. A voz local lê tudo: só gera um
/// trecho à frente, então parar no meio não desperdiça nada.
const API_MAX_CHARS: usize = 600;
/// Tentativas por trecho quando a API pede pra esperar (429) ou falha do lado dela (5xx).
const ATTEMPTS: usize = 3;
/// Espera máxima por tentativa: mais que isso, a leitura já perdeu o sentido.
Expand Down Expand Up @@ -411,7 +412,11 @@ fn speak(app: &AppHandle, text: &str) -> Result<(), String> {
let current = || state.generation.load(Ordering::SeqCst) == generation;

let engine = Arc::new(engine(&settings::load(app))?);
let parts = chunks(text, FIRST_CHUNK_CHARS, CHUNK_CHARS, MAX_CHARS);
let limit = match &*engine {
Engine::Api(_) => API_MAX_CHARS,
Engine::Local { .. } => usize::MAX,
};
let parts = chunks(text, FIRST_CHUNK_CHARS, CHUNK_CHARS, limit);
let request = |i: usize| -> Job {
let (app, engine, text, path) = (app.clone(), engine.clone(), parts[i].clone(), tmp_path(&format!("{generation}-{i}.wav")));
thread::spawn(move || {
Expand Down Expand Up @@ -516,16 +521,15 @@ pub async fn speak_text(app: AppHandle, text: String) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || speak(&app, &speakable(&text))).await.map_err(|e| e.to_string())?
}

/// Lê em voz alta a última resposta do Claude da aba.
/// Lê em voz alta a última resposta do Claude da aba. `false` quando não havia
/// o que ler: o "terminou" veio de um Esc ou /comando, ou (no ▶) a pergunta ainda
/// está sem resposta.
#[tauri::command]
pub async fn speak_claude_reply(app: AppHandle, state: State<'_, PtyState>, id: u32) -> Result<(), String> {
let Some(fg) = crate::pty::foreground_pid(&state, id) else { return Ok(()) };
tauri::async_runtime::spawn_blocking(move || {
// Sem resposta em texto (o "terminou" veio de um Esc ou de um /comando): nada a ler.
match last_reply(fg) {
Some(reply) => speak(&app, &speakable(&reply)),
None => Ok(()),
}
pub async fn speak_claude_reply(app: AppHandle, state: State<'_, PtyState>, id: u32) -> Result<bool, String> {
let Some(fg) = crate::pty::foreground_pid(&state, id) else { return Ok(false) };
tauri::async_runtime::spawn_blocking(move || match last_reply(fg) {
Some(reply) => speak(&app, &speakable(&reply)).map(|_| true),
None => Ok(false),
})
.await
.map_err(|e| e.to_string())?
Expand Down
44 changes: 33 additions & 11 deletions src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -480,43 +480,61 @@ let voiceTimer: ReturnType<typeof setInterval> | undefined;
/** Fixado no começo da gravação: trocar o foco enquanto fala não muda o destino. */
let voiceTarget: PtySession | undefined;
let voiceTab: Tab | undefined;
/** Frase de enviar lida no começo da gravação, junto com o resto da configuração. */
let voicePhrase = "";
/** Abas cujo Claude recebeu um ditado: no modo "quando a pergunta foi ditada", a resposta é lida. */
const dictatedTabs = new Set<number>();
/** Só a fala mais recente volta o microfone pro normal (uma nova interrompe a anterior). */
let speakSeq = 0;

/** Claude da aba terminou: lê sozinho, conforme "Ler a resposta" nas configurações. */
async function speakReply(tab: Tab) {
const dictated = dictatedTabs.delete(tab.id);
const session = sessions.get(tab.id);
const speech = (await loadSettings().catch(() => null))?.speech;
if (!session || !speech || speech.mode === "off") return;
if (!speech || speech.mode === "off") return;
if (speech.mode === "dictated" ? !dictated : !isActive(tab)) return;
await speakTab(tab, false);
}

/** Lê a última resposta do Claude da aba. `manual`: pedido pelo ▶, avisa se não tem o que ler. */
async function speakTab(tab: Tab, manual: boolean) {
const session = sessions.get(tab.id);
// Gravando ou transcrevendo: falar por cima atrapalharia o ditado.
if (voice.value === "recording" || voice.value === "transcribing") return;
if (!session || voice.value === "recording" || voice.value === "transcribing") return;
const seq = ++speakSeq;
voice.value = "speaking";
try {
await speakClaudeReply(session.id);
const spoke = await speakClaudeReply(session.id);
if (!spoke && manual && seq === speakSeq) flash("Voz: o Claude desta aba ainda não tem resposta pra ler.");
} catch (err) {
flash(`Voz: ${err}`);
} finally {
if (seq === speakSeq && voice.value === "speaking") voice.value = "idle";
}
}

/** ▶ / Ctrl+Shift+Espaço: lê a última resposta da aba ativa, ou para a leitura. */
function listenReply() {
if (voice.value === "speaking") return stopSpeaking();
const tab = activeTab.value;
if (tab?.process === "claude") speakTab(tab, true);
else if (tab) flash("Voz: não tem Claude rodando nesta aba.");
}

function stopSpeaking() {
speakSeq++;
voice.value = "idle";
speakStop().catch(() => {});
}


async function toggleVoice() {
if (voice.value === "speaking") {
speakSeq++;
voice.value = "idle";
speakStop().catch(() => {});
return;
}
if (voice.value === "speaking") return stopSpeaking();
if (voice.value === "recording") {
clearInterval(voiceTimer);
voice.value = "transcribing";
try {
const { text, send } = voiceCommand(await voiceStop());
const { text, send } = voiceCommand(await voiceStop(), voicePhrase);
pasteInto(voiceTarget, text);
if (voiceTab && voiceTarget && voiceTarget === sessions.get(voiceTab.id)) dictatedTabs.add(voiceTab.id);
if (send && voiceTarget) {
Expand All @@ -539,6 +557,7 @@ async function toggleVoice() {
settingsOpen.value = true;
return flash(`Ditado: falta ${missing}`);
}
voicePhrase = v.send_phrase;
voiceTarget = focusedSession();
voiceTab = activeTab.value ?? undefined;
try {
Expand Down Expand Up @@ -659,6 +678,8 @@ function run(action: Action) {
return togglePanel();
case "toggleVoice":
return void toggleVoice();
case "listenReply":
return listenReply();
}
}

Expand Down Expand Up @@ -709,6 +730,7 @@ const isActive = (tab: Tab) => tab.id === store.activeId;
:voice-secs="voiceSecs"
@toggle-mcp="toggleMcp"
@voice="toggleVoice"
@listen="listenReply"
@attach="attachFiles"
:anon="anon"
:usage="usage"
Expand Down
19 changes: 15 additions & 4 deletions src/components/SettingsPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const voice = reactive<VoiceSettings>({
local_model: "",
language: "",
auto_stop: true,
send_phrase: "term7 pronto",
});
const hasKey = ref(false);
/** Chave digitada agora; vazio = mantém a salva. */
Expand Down Expand Up @@ -189,7 +190,7 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey, true));
<h2>Ditado por voz</h2>
<p class="hint">
O microfone da barra de cima (ou <b>Ctrl+Espaço</b>) grava, transcreve e cola o texto no terminal ativo, inclusive
no Claude (sem Enter). Termine a fala com <b>“enviar”</b> pra mandar com Enter.
no Claude (sem Enter). Termine a fala com a frase de enviar (abaixo) pra mandar com Enter.
</p>

<div class="engines">
Expand Down Expand Up @@ -254,6 +255,15 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey, true));
<small>Código ISO; vazio deixa o serviço detectar.</small>
</label>

<label class="field">
<span>Frase de enviar</span>
<input v-model.trim="voice.send_phrase" placeholder="term7 pronto" spellcheck="false" />
<small>
Dita no fim, manda com Enter. “term7” aceita como o Whisper escreve (Term 7, Terme 7, Term set, term sete);
acento e pontuação não importam. Vazia desliga.
</small>
</label>

<label class="check">
<input v-model="voice.auto_stop" type="checkbox" />
<span>
Expand All @@ -266,14 +276,15 @@ onBeforeUnmount(() => window.removeEventListener("keydown", onKey, true));
<section>
<h2>Leitura em voz alta</h2>
<p class="hint">
Lê a resposta do Claude quando ele termina, sem blocos de código, tabelas e links. Respostas longas são lidas só
no começo. Enquanto fala, o microfone da barra vira o botão de parar.
Lê a resposta do Claude quando ele termina, sem blocos de código, tabelas e links. Pela API, respostas longas são
lidas só no começo (por causa da cota); a voz local lê inteira. O <b>▶</b> ao lado do microfone (ou
<b>Ctrl+Shift+Espaço</b>) lê a última resposta da aba na hora e, falando, vira o botão de parar.
</p>

<label class="field">
<span>Ler a resposta</span>
<select v-model="speech.mode">
<option value="off">Nunca</option>
<option value="off">Só quando eu pedir (▶ ou Ctrl+Shift+Espaço)</option>
<option value="dictated">Quando a pergunta foi ditada</option>
<option value="always">Sempre que o Claude da aba ativa terminar</option>
</select>
Expand Down
19 changes: 17 additions & 2 deletions src/components/TopBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const props = defineProps<{
/** Uso da assinatura do Claude da aba; null = sem Claude ou ainda lendo. */
usage: ClaudeUsage | null;
}>();
defineEmits<{ toggleAgents: []; toggleTasks: []; toggleMcp: []; voice: []; attach: []; settings: []; toggleAnon: []; setupUsage: [] }>();
defineEmits<{ toggleAgents: []; toggleTasks: []; toggleMcp: []; voice: []; listen: []; attach: []; settings: []; toggleAnon: []; setupUsage: [] }>();

const clock = computed(() => `${Math.floor(props.voiceSecs / 60)}:${String(props.voiceSecs % 60).padStart(2, "0")}`);

Expand Down Expand Up @@ -147,7 +147,7 @@ const mcpCounts = computed(() => {
? 'Transcrevendo…'
: voice === 'speaking'
? 'Lendo a resposta do Claude: clique pra parar'
: 'Ditar: clique, fale e clique de novo (termine com “enviar” pra mandar)'
: 'Ditar (Ctrl+Espaço): clique, fale e clique de novo; termine com “term7 pronto” pra mandar'
"
@click="$emit('voice')"
>
Expand All @@ -156,6 +156,17 @@ const mcpCounts = computed(() => {
<span v-else-if="voice === 'transcribing'">Transcrevendo…</span>
<span v-else-if="voice === 'speaking'">Parar voz</span>
</button>
<button
v-if="claude || voice === 'speaking'"
class="btn icon listen"
:class="{ speaking: voice === 'speaking' }"
:disabled="voice === 'recording' || voice === 'transcribing'"
:title="voice === 'speaking' ? 'Parar a leitura (Ctrl+Shift+Espaço)' : 'Ouvir a última resposta do Claude desta aba (Ctrl+Shift+Espaço)'"
@click="$emit('listen')"
>
<svg v-if="voice === 'speaking'" viewBox="0 0 16 16" width="12" height="12"><rect x="4" y="4" width="8" height="8" rx="1.5" fill="currentColor" /></svg>
<svg v-else viewBox="0 0 16 16" width="12" height="12"><path d="M5 3.5v9l7.5-4.5z" fill="currentColor" stroke="currentColor" stroke-width="1" stroke-linejoin="round" /></svg>
</button>
<button
class="btn icon anon-safe"
:class="{ 'anon-on': anon }"
Expand Down Expand Up @@ -270,6 +281,10 @@ const mcpCounts = computed(() => {
.mic.transcribing {
color: var(--accent);
}
.listen.speaking {
background: color-mix(in srgb, var(--accent) 16%, transparent);
color: var(--accent);
}
.mic.speaking {
background: color-mix(in srgb, var(--accent) 16%, transparent);
color: var(--accent);
Expand Down
7 changes: 5 additions & 2 deletions src/lib/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ export interface VoiceSettings {
language: string;
/** Para de gravar sozinho quando a fala termina. */
auto_stop: boolean;
/** Frase que, no fim do ditado, manda com Enter; vazia desliga. */
send_phrase: string;
}
/** Quando ler a resposta do Claude: nunca, só depois de um ditado, ou sempre. */
/** Quando ler a resposta do Claude sozinho: nunca (só pelo ▶), depois de um ditado, ou sempre. */
export type SpeakMode = "off" | "dictated" | "always";
export interface SpeechSettings {
mode: SpeakMode;
Expand Down Expand Up @@ -62,7 +64,8 @@ export const SPEECH_PRESETS = [

/** Voltam quando a fala acaba ou é interrompida. */
export const speakText = (text: string) => invoke<void>("speak_text", { text });
export const speakClaudeReply = (id: number) => invoke<void>("speak_claude_reply", { id });
/** false quando não havia resposta pra ler. */
export const speakClaudeReply = (id: number) => invoke<boolean>("speak_claude_reply", { id });
export const speakStop = () => invoke<void>("speak_stop");
/** Extensões de voz instaladas: [id, nome]. */
export const installedTts = () => invoke<[string, string][]>("extensions_tts");
Expand Down
18 changes: 18 additions & 0 deletions src/lib/shortcuts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { matchShortcut } from "./shortcuts";

// Os testes rodam no Node, sem DOM: só os campos que o matchShortcut lê.
const key = (init: Partial<KeyboardEvent>) =>
({ key: "", code: "", ctrlKey: false, shiftKey: false, altKey: false, metaKey: false, ...init }) as KeyboardEvent;

describe("atalhos de voz", () => {
it("Ctrl+Espaço dita e Ctrl+Shift+Espaço ouve a resposta", () => {
expect(matchShortcut(key({ key: " ", code: "Space", ctrlKey: true }))).toEqual({ type: "toggleVoice" });
expect(matchShortcut(key({ key: " ", code: "Space", ctrlKey: true, shiftKey: true }))).toEqual({ type: "listenReply" });
});

it("espaço sozinho ou com Alt vai pro terminal", () => {
expect(matchShortcut(key({ key: " ", code: "Space" }))).toBeNull();
expect(matchShortcut(key({ key: " ", code: "Space", ctrlKey: true, altKey: true }))).toBeNull();
});
});
5 changes: 4 additions & 1 deletion src/lib/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ export type Action =
| { type: "goTo"; index: number }
| { type: "toggleDiff" }
| { type: "togglePanel" }
| { type: "toggleVoice" };
| { type: "toggleVoice" }
| { type: "listenReply" };

/** Atalhos globais do app. Retorna null quando a tecla deve ir pro shell. */
export function matchShortcut(e: KeyboardEvent): Action | null {
Expand All @@ -19,6 +20,8 @@ export function matchShortcut(e: KeyboardEvent): Action | null {
if (ctrlShift && key === "g") return { type: "toggleDiff" };
// Ditado: mesmo que clicar no microfone (começa, para ou corta a leitura em voz alta).
if (ctrlOnly && (e.code === "Space" || e.key === " ")) return { type: "toggleVoice" };
// Ouvir a última resposta do Claude da aba (ou parar a leitura).
if (ctrlShift && (e.code === "Space" || e.key === " ")) return { type: "listenReply" };
// Ctrl+' (tecla à esquerda do 1 no ABNT2) ou Ctrl+` (layout US).
if (e.ctrlKey && !e.altKey && !e.metaKey && (e.code === "Backquote" || e.key === "`")) {
return { type: "togglePanel" };
Expand Down
Loading