Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(whatsapp): explain voice failures; keep pairing codes visible; test messages

Salman Qureshic64aaaf88102
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
index a6eafd6c..78412e3a 100644
--- a/plugins/whatsapp/companion/src/main.rs
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -346,6 +346,9 @@ async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()>
st.out.status("starting", json!({}));
let (o1, o2, o3, o4, o5) = (st.out.clone(), st.out.clone(), st.out.clone(), st.out.clone(), st.out.clone());
+ // When linking by code, the library still issues QR codes alongside it; showing those
+ // would replace the code the owner is typing, so only the code is reported.
+ let code_mode = phone.is_some();
let st_conn = st.clone();
let st_msg = st.clone();
let st_call = st.clone();
@@ -353,7 +356,11 @@ async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()>
.with_backend(store)
.on_qr_code(move |code, _ttl| {
let o = o1.clone();
- async move { o.status("pairing", json!({ "qr": code })) }
+ async move {
+ if !code_mode {
+ o.status("pairing", json!({ "qr": code }))
+ }
+ }
})
.on_pair_code(move |code, _ttl| {
let o = o2.clone();
diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rs
index 3bb6ff82..f55a2501 100644
--- a/plugins/whatsapp/companion/src/voice.rs
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -343,7 +343,10 @@ async fn bridge(
_ = &mut deadline => { hang_up = true; break Ok(()) }
msg = ws_rx.next() => {
let Some(Ok(msg)) = msg else { break Err("the voice model disconnected".to_string()) };
- if msg.is_close() { break Err("the voice model closed the session".to_string()); }
+ if msg.is_close() {
+ let reason = msg.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();
+ break Err(explain_close(&reason));
+ }
let Some(text) = msg.as_text() else { continue };
let Ok(ev) = serde_json::from_str::<Value>(text) else { continue };
let kind = ev.get("type").and_then(Value::as_str).unwrap_or("");
@@ -413,6 +416,24 @@ async fn bridge(
result
}
+/// Turn the voice provider's close reason into something the owner can act on.
+fn explain_close(reason: &str) -> String {
+ let r = reason.to_ascii_lowercase();
+ if r.contains("insufficient_quota") || r.contains("credit_balance") || r.contains("billing") {
+ "your OpenAI account is out of credit. Add credit at platform.openai.com → Settings → Billing, then call again".into()
+ } else if r.contains("invalid_api_key") || r.contains("unauthorized") || r.contains("401") {
+ "OpenAI rejected the API key. Check the OpenAI provider in Mercury's dashboard (Providers)".into()
+ } else if r.contains("model_not_found") || r.contains("does not exist") || r.contains("access") {
+ format!("this OpenAI account can't use the realtime voice model ({reason}). Try another voiceModel setting")
+ } else if r.contains("rate_limit") {
+ "OpenAI is rate-limiting this account right now. Try again in a minute".into()
+ } else if reason.is_empty() {
+ "the voice model closed the session".into()
+ } else {
+ format!("the voice model closed the session ({reason})")
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -423,6 +444,12 @@ mod tests {
assert_eq!(resample(&[0i16; 1440], AI_RATE, WA_RATE).len(), 960);
}
+ #[test]
+ fn close_reasons_are_explained() {
+ assert!(explain_close("insufficient_quota.credit_balance_exhausted").contains("out of credit"));
+ assert!(explain_close("").contains("closed"));
+ }
+
#[test]
fn pcm_round_trip() {
let s = vec![0i16, 1, -1, i16::MAX, i16::MIN];
diff --git a/src/cli/plugins-cli.ts b/src/cli/plugins-cli.ts
index a94c99d0..c33e605c 100644
--- a/src/cli/plugins-cli.ts
+++ b/src/cli/plugins-cli.ts
@@ -72,6 +72,19 @@ export function registerPluginsCli(program: Command): void {
setTimeout(() => process.exit(process.exitCode ?? 0), 50).unref();
});
+ plugins
+ .command('test <id>')
+ .description('Send the owner a test message through a channel plugin (e.g. WhatsApp)')
+ .action(async (id: string) => {
+ const { getPluginService } = await import('../plugins/service.js');
+ try {
+ console.log(chalk.green(` ✓ ${await getPluginService().testChannel(id)}`));
+ } catch (err) {
+ console.error(chalk.red(` ✗ ${(err as Error).message}`));
+ process.exitCode = 1;
+ }
+ });
+
plugins
.command('unlink <id>')
.description('Log a channel plugin out of its account (you can pair again later)')
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index bc5aa2c8..51f218ff 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -548,6 +548,15 @@ export class PluginManager {
return ready;
}
+ /** Send the owner a test message through a channel plugin. */
+ async testChannel(id: string): Promise<string> {
+ const channel = this.liveChannel(id);
+ const st = channel.getStatus();
+ if (st.state !== 'connected') throw new Error(`"${id}" isn't linked yet (${st.state}). Pair it first: mercury plugins pair ${id}`);
+ await channel.send(`☿ Hi, it's Mercury. This is a test message from ${channel.type === 'whatsapp' ? 'WhatsApp' : channel.type}: reply to chat with me${channel.type === 'whatsapp' ? ', or call this number to talk' : ''}.`);
+ return `Sent a test message to the owner${st.account ? ` from +${st.account}` : ''}.`;
+ }
+
async unlinkChannel(id: string): Promise<void> {
await this.liveChannel(id).unlink();
}
diff --git a/src/plugins/service.ts b/src/plugins/service.ts
index f5d9a631..b3664957 100644
--- a/src/plugins/service.ts
+++ b/src/plugins/service.ts
@@ -48,6 +48,7 @@ export interface PluginService {
pair(id: string, opts: { method: 'qr' | 'code'; phone?: string }): Promise<ChannelStatus>;
channelStatus(id: string): Promise<ChannelStatus | null>;
unlink(id: string): Promise<void>;
+ testChannel(id: string): Promise<string>;
}
export function localService(mgr: PluginManager, mode: 'local' | 'offline' = 'local'): PluginService {
@@ -68,6 +69,7 @@ export function localService(mgr: PluginManager, mode: 'local' | 'offline' = 'lo
pair: (id, opts) => mgr.pair(id, opts),
channelStatus: async (id) => mgr.channelStatus(id),
unlink: (id) => mgr.unlinkChannel(id),
+ testChannel: (id) => mgr.testChannel(id),
};
}
@@ -106,6 +108,7 @@ export function daemonService(): PluginService {
pair: async (id, opts) => (await call<{ status: ChannelStatus }>('POST', `/api/plugins/${enc(id)}/pair`, opts, 60_000)).status,
channelStatus: async (id) => (await call<{ status: ChannelStatus | null }>('GET', `/api/plugins/${enc(id)}/channel`)).status,
unlink: async (id) => { await call('POST', `/api/plugins/${enc(id)}/unlink`, {}); },
+ testChannel: async (id) => (await call<{ message: string }>('POST', `/api/plugins/${enc(id)}/test`, {})).message,
};
}
diff --git a/src/web/api/plugins.ts b/src/web/api/plugins.ts
index 97c0e24e..501e71db 100644
--- a/src/web/api/plugins.ts
+++ b/src/web/api/plugins.ts
@@ -134,6 +134,16 @@ plugins.post('/api/plugins/:id/pair', async (c) => {
}
});
+plugins.post('/api/plugins/:id/test', async (c) => {
+ const denied = localOnly(c);
+ if (denied) return denied;
+ try {
+ return c.json({ message: await svc().testChannel(c.req.param('id')) });
+ } catch (err) {
+ return fail(c, err);
+ }
+});
+
plugins.post('/api/plugins/:id/unlink', async (c) => {
const denied = localOnly(c);
if (denied) return denied;