From 423a612cfb567e5549d2496fe2aab517da7b7d44 Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Thu, 22 Oct 2026 22:54:45 -0700 Subject: [PATCH 1/7] feat(desktop): call an agent from its 1:1 DM A Call button in a 1:1 agent DM header places a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. The host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. - agent_voice_request: one native command that signs NIP-98 as the signed-in user (exact URL, method, body hash) with X-Buzz-Community and reaches only the host's call routes (allowlisted, https, size and time caps). - AgentCallController: a port of the host's web call controller (mic, offer, data channel, time limit, disconnect grace, mute, stop, hang-up that never cancels work) following the host's call screen feed by long-poll. - AgentCallDock (mounted once in AppShell): timer, mute, hang up, stop, the call's asks, the open question's option taps, cancel/archive and the recap. - A community switch hangs up and clears the call. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- desktop/src-tauri/Info.plist | 2 +- .../src/extensions/agent_voice/mod.rs | 277 +++++++ desktop/src-tauri/src/extensions/mod.rs | 3 + desktop/src-tauri/src/lib.rs | 3 +- desktop/src/app/AppShell.tsx | 2 + .../agent-call/lib/agentCallApi.test.mjs | 105 +++ .../features/agent-call/lib/agentCallApi.ts | 222 ++++++ .../lib/agentCallController.test.mjs | 194 +++++ .../agent-call/lib/agentCallController.ts | 685 ++++++++++++++++++ .../agent-call/lib/agentCallFeed.test.mjs | 146 ++++ .../features/agent-call/lib/agentCallFeed.ts | 218 ++++++ .../agent-call/ui/AgentCallButton.tsx | 64 ++ .../features/agent-call/ui/AgentCallDock.tsx | 409 +++++++++++ .../features/agent-call/ui/useAgentCall.ts | 33 + .../channels/ui/ChannelScreenHeader.tsx | 7 + .../features/communities/useCommunityInit.ts | 2 + docs/kiingo-fork-inventory.json | 28 +- 17 files changed, 2395 insertions(+), 5 deletions(-) create mode 100644 desktop/src-tauri/src/extensions/agent_voice/mod.rs create mode 100644 desktop/src/features/agent-call/lib/agentCallApi.test.mjs create mode 100644 desktop/src/features/agent-call/lib/agentCallApi.ts create mode 100644 desktop/src/features/agent-call/lib/agentCallController.test.mjs create mode 100644 desktop/src/features/agent-call/lib/agentCallController.ts create mode 100644 desktop/src/features/agent-call/lib/agentCallFeed.test.mjs create mode 100644 desktop/src/features/agent-call/lib/agentCallFeed.ts create mode 100644 desktop/src/features/agent-call/ui/AgentCallButton.tsx create mode 100644 desktop/src/features/agent-call/ui/AgentCallDock.tsx create mode 100644 desktop/src/features/agent-call/ui/useAgentCall.ts diff --git a/desktop/src-tauri/Info.plist b/desktop/src-tauri/Info.plist index 7d29c433358..494508c373b 100644 --- a/desktop/src-tauri/Info.plist +++ b/desktop/src-tauri/Info.plist @@ -7,7 +7,7 @@ CFBundleName Buzz NSMicrophoneUsageDescription - Buzz needs microphone access for voice huddles and voice notes. + Buzz needs microphone access for voice huddles, voice notes and calls with agents. NSCameraUsageDescription Buzz needs camera access to record animated avatars. NSLocalNetworkUsageDescription diff --git a/desktop/src-tauri/src/extensions/agent_voice/mod.rs b/desktop/src-tauri/src/extensions/agent_voice/mod.rs new file mode 100644 index 00000000000..d89e155f428 --- /dev/null +++ b/desktop/src-tauri/src/extensions/agent_voice/mod.rs @@ -0,0 +1,277 @@ +//! Native transport for 1:1 agent calls from an agent DM. +//! +//! A call is the agent host's own voice call (the same voice core as its +//! phone apps), not a huddle: audio runs WebRTC between this webview and the +//! host's realtime voice provider, and the host answers the SDP offer. This +//! module carries the host's call routes (`/api/buzz-voice/desktop/…`, +//! the origin taken from the guest route URL, or +//! `BUZZ_DESKTOP_AGENT_VOICE_URL`): +//! +//! - every request is NIP-98 (kind 27235, exact URL with query, method and +//! the SHA-256 of the exact body bytes) signed by the signed-in user, with +//! `X-Buzz-Community`, so the key never reaches the webview; +//! - only the call routes are reachable (start, view, feed long-poll, end, +//! stop, answers and the per-ask routes, preferences), nothing else; +//! - the answer is returned as `{ status, body }` for every HTTP status, so +//! the webview can show the host's error codes; transport failures are +//! errors. +//! +//! The host proves the caller is the verified requester of this private 1:1 +//! DM with the agent before a call starts, and serves each call to its own +//! caller only. + +use std::time::Duration; + +use serde_json::Value; +use tauri::State; + +use crate::app_state::AppState; +use crate::commands::{acceptable_base_url, community_id_for_relay, nip98_header}; +use crate::managed_agents::access_policy::guest_route_url; +use crate::relay::relay_ws_url_with_override; + +/// The feed long-poll waits up to 20 s on the host. +const REQUEST_TIMEOUT: Duration = Duration::from_secs(35); +const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024; +const MAX_BODY_BYTES: usize = 60 * 1024; +const MOUNT: &str = "/api/buzz-voice/desktop"; + +fn error(status: Option, code: &str) -> String { + serde_json::json!({ "status": status, "error": code }).to_string() +} + +fn is_uuid(value: &str) -> bool { + value.len() == 36 + && value.char_indices().all(|(index, c)| match index { + 8 | 13 | 18 | 23 => c == '-', + _ => c.is_ascii_hexdigit(), + }) +} + +fn is_ask_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 190 + && !value.bytes().all(|b| b == b'.') + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-' | b'%')) +} + +/// The call route `path` (relative to the mount) if it is one this command +/// may reach, else `None`. The query string is allowed only on the feed. +fn allowed_path(method: &str, path: &str) -> Option { + let (route, query) = match path.split_once('?') { + Some((route, query)) => (route, Some(query)), + None => (path, None), + }; + let parts: Vec<&str> = route.split('/').collect(); + let get = method == "GET"; + let post = method == "POST"; + let ok = match parts.as_slice() { + ["calls"] => post, + ["calls", "live"] => get, + ["preferences"] => get || method == "PUT", + ["calls", id] => get && is_uuid(id), + ["calls", id, "feed"] => get && is_uuid(id), + ["calls", id, "end" | "stop" | "focus" | "text" | "caption-corrections"] => { + post && is_uuid(id) + } + ["calls", id, "asks", "state" | "cancel" | "tell-more" | "reply"] => post && is_uuid(id), + ["calls", id, "human-asks", ask, "answer"] => post && is_uuid(id) && is_ask_id(ask), + _ => false, + }; + if !ok { + return None; + } + match query { + None => Some(route.to_string()), + Some(query) + if parts.last() == Some(&"feed") + && query.len() <= 200 + && query.bytes().all(|b| { + b.is_ascii_alphanumeric() + || matches!(b, b'=' | b'&' | b'.' | b'_' | b'-' | b'%') + }) => + { + Some(format!("{route}?{query}")) + } + Some(_) => None, + } +} + +/// `https://host` of the call routes: the override, else the guest route's +/// origin. HTTPS only (HTTP on loopback for development). +fn voice_origin(override_url: Option, guest_route: Option) -> Option { + let raw = override_url + .map(|url| url.trim().to_string()) + .filter(|url| !url.is_empty()) + .or(guest_route)?; + if !acceptable_base_url(&raw) { + return None; + } + let parsed = url::Url::parse(&raw).ok()?; + let origin = parsed.origin().ascii_serialization(); + (origin != "null").then_some(origin) +} + +fn request_url(origin: &str, path: &str) -> String { + format!("{}{MOUNT}/{path}", origin.trim_end_matches('/')) +} + +/// One signed request to the host's call routes as the signed-in user. +/// Returns `{ "status": , "body": }`. +#[tauri::command] +pub async fn agent_voice_request( + method: String, + path: String, + body: Option, + state: State<'_, AppState>, +) -> Result { + let method = method.trim().to_ascii_uppercase(); + let path = allowed_path(&method, path.trim().trim_start_matches('/')) + .ok_or_else(|| error(None, "path_not_allowed"))?; + let body = body.filter(|body| !body.is_empty()); + if body + .as_ref() + .is_some_and(|body| body.len() > MAX_BODY_BYTES) + { + return Err(error(None, "body_too_large")); + } + if method == "GET" && body.is_some() { + return Err(error(None, "body_not_allowed")); + } + let origin = voice_origin( + std::env::var("BUZZ_DESKTOP_AGENT_VOICE_URL").ok(), + guest_route_url(), + ) + .ok_or_else(|| error(None, "voice_route_unavailable"))?; + let community_id = community_id_for_relay(&relay_ws_url_with_override(&state)); + if community_id.is_empty() { + return Err(error(None, "community_invalid")); + } + let keys = state.signing_keys()?; + let url = request_url(&origin, &path); + let authorization = nip98_header(&keys, &method, &url, body.as_deref().map(str::as_bytes))?; + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(REQUEST_TIMEOUT) + .build() + .map_err(|_| error(None, "client_failed"))?; + let http_method = reqwest::Method::from_bytes(method.as_bytes()) + .map_err(|_| error(None, "method_invalid"))?; + let mut request = client + .request(http_method, &url) + .header("Accept", "application/json") + .header("Authorization", authorization) + .header("X-Buzz-Community", community_id); + request = match body { + Some(body) => request + .header("Content-Type", "application/json") + .body(body), + None if method == "GET" => request, + None => request.header("Content-Length", "0"), + }; + let response = request.send().await.map_err(|e| { + error( + None, + if e.is_timeout() { + "voice_route_timeout" + } else { + "voice_route_unreachable" + }, + ) + })?; + let status = response.status().as_u16(); + let bytes = response + .bytes() + .await + .map_err(|_| error(Some(status), "response_unreadable"))?; + if bytes.len() > MAX_RESPONSE_BYTES { + return Err(error(Some(status), "response_too_large")); + } + let body = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap_or(Value::Null) + }; + Ok(serde_json::json!({ "status": status, "body": body })) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CALL: &str = "0192a6b0-0000-7000-8000-0000000000ac"; + + #[test] + fn only_call_routes_are_reachable() { + assert_eq!(allowed_path("POST", "calls").as_deref(), Some("calls")); + assert!(allowed_path("GET", &format!("calls/{CALL}")).is_some()); + assert_eq!( + allowed_path("GET", &format!("calls/{CALL}/feed?rev=l4.live.1&wait=20")), + Some(format!("calls/{CALL}/feed?rev=l4.live.1&wait=20")) + ); + assert!(allowed_path("POST", &format!("calls/{CALL}/end")).is_some()); + assert!(allowed_path("POST", &format!("calls/{CALL}/asks/cancel")).is_some()); + assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/q:1-a/answer")).is_some()); + assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/q%3A1/answer")).is_some()); + assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/../answer")).is_none()); + assert!(allowed_path("PUT", "preferences").is_some()); + // Anything else, another method, a query off the feed, or traversal. + assert!(allowed_path("GET", "calls").is_none()); + assert!(allowed_path("DELETE", &format!("calls/{CALL}")).is_none()); + assert!(allowed_path("POST", &format!("calls/{CALL}/end?x=1")).is_none()); + assert!(allowed_path("GET", &format!("calls/{CALL}/../../identity")).is_none()); + assert!(allowed_path("GET", "calls/not-a-call/feed").is_none()); + assert!(allowed_path("GET", &format!("calls/{CALL}/feed?rev=a b")).is_none()); + assert!(allowed_path("POST", "owner/agents/list").is_none()); + } + + #[test] + fn the_origin_comes_from_the_guest_route_and_is_https() { + assert_eq!( + voice_origin( + None, + Some("https://api.example.com/api/buzz-guest/v1".into()) + ) + .as_deref(), + Some("https://api.example.com") + ); + assert_eq!( + voice_origin( + Some("https://voice.example.com/x".into()), + Some("https://api.example.com/api/buzz-guest/v1".into()) + ) + .as_deref(), + Some("https://voice.example.com") + ); + assert_eq!( + voice_origin(None, Some("http://api.example.com".into())), + None + ); + assert_eq!(voice_origin(None, None), None); + assert_eq!( + request_url( + "https://api.example.com", + &format!("calls/{CALL}/feed?rev=a") + ), + format!("https://api.example.com/api/buzz-voice/desktop/calls/{CALL}/feed?rev=a") + ); + } + + #[test] + fn a_body_is_bound_by_its_payload_hash() { + let keys = nostr::Keys::parse(&"1".repeat(64)).expect("keys"); + let url = request_url("https://api.example.com", "calls"); + let header = + nip98_header(&keys, "POST", &url, Some(br#"{"sdpOffer":"v=0"}"#)).expect("header"); + let encoded = header.strip_prefix("Nostr ").expect("scheme"); + let json = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded) + .expect("base64"); + let event: Value = serde_json::from_slice(&json).expect("event"); + let tags = event["tags"].as_array().expect("tags"); + assert!(tags.contains(&serde_json::json!(["u", url]))); + assert!(tags.iter().any(|tag| tag[0] == "payload")); + assert_eq!(event["content"], ""); + } +} diff --git a/desktop/src-tauri/src/extensions/mod.rs b/desktop/src-tauri/src/extensions/mod.rs index 663690d754d..c3cba540698 100644 --- a/desktop/src-tauri/src/extensions/mod.rs +++ b/desktop/src-tauri/src/extensions/mod.rs @@ -22,6 +22,9 @@ pub(crate) use identity_rotation::{ pub(crate) mod agent_summary; pub(crate) use agent_summary::{agent_prewarm, agent_summary_fetch}; +pub(crate) mod agent_voice; +pub(crate) use agent_voice::agent_voice_request; + pub(crate) fn try_handle_deep_link(app: &tauri::AppHandle, url: &url::Url) -> bool { identity_rotation::try_handle_deep_link(app, url) } diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index c554a2f9bbc..32b4936f04a 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -80,7 +80,7 @@ use extensions::{ inspect_identity_rotation_handoff, run_identity_rotation, take_pending_identity_rotation, IdentityRotationExtensionState, }; -use extensions::{agent_prewarm, agent_summary_fetch}; +use extensions::{agent_prewarm, agent_summary_fetch, agent_voice_request}; use extensions::{ confirm_key_replacement, key_replacement_confirmed, key_replacement_status, old_owner_key_removed, remove_old_owner_key, @@ -574,6 +574,7 @@ pub fn run() { identity_rotation_status, agent_summary_fetch, agent_prewarm, + agent_voice_request, inspect_identity_rotation_handoff, run_identity_rotation, abort_identity_rotation, diff --git a/desktop/src/app/AppShell.tsx b/desktop/src/app/AppShell.tsx index e0ac4f8190f..b5e481e0ae5 100644 --- a/desktop/src/app/AppShell.tsx +++ b/desktop/src/app/AppShell.tsx @@ -8,6 +8,7 @@ import { AppShellProvider } from "@/app/AppShellContext"; import { AppShellOverlays, TerminalBootstrap } from "@/app/AppShellOverlays"; import { AppShellChannelSurface } from "@/app/AppShellChannelSurface"; import { AppHuddleShell } from "@/app/AppHuddleShell"; +import { AgentCallDock } from "@/features/agent-call/ui/AgentCallDock"; import { AppTopChrome } from "@/app/AppTopChrome"; import { type TerminalContextOverride, @@ -992,6 +993,7 @@ export function AppShell() { }} relayUrl={communitiesHook.activeCommunity?.relayUrl} /> + {}; +afterEach(() => restore()); + +function harness(answer) { + const sent = []; + restore = setAgentCallSendForTests(async (method, path, body) => { + sent.push({ method, path, body }); + return answer({ method, path, body }); + }); + return sent; +} + +test("a call starts from the DM with the agent key, channel and offer", async () => { + const sent = harness(() => ({ + status: 201, + body: { callId: CALL, sdpAnswer: "v=0", executeUntil: null }, + })); + const started = await startAgentCall({ + agentPubkey: "b".repeat(64), + channelId: "0192a6b0-0000-7000-8000-0000000000af", + sdpOffer: "v=0 offer", + }); + assert.equal(started.callId, CALL); + assert.equal(sent[0].method, "POST"); + assert.equal(sent[0].path, "calls"); + assert.deepEqual(sent[0].body, { + agentPubkey: "b".repeat(64), + channelId: "0192a6b0-0000-7000-8000-0000000000af", + sdpOffer: "v=0 offer", + clientDiagnostics: { systemCallUI: "in_app" }, + }); +}); + +test("host error codes become plain sentences", async () => { + harness(() => ({ status: 409, body: { error: "voice_buzz_dm_required" } })); + await assert.rejects( + startAgentCall({ + agentPubkey: "b".repeat(64), + channelId: "x", + sdpOffer: "v", + }), + (error) => { + assert.ok(error instanceof AgentCallApiError); + assert.equal(error.status, 409); + assert.equal(error.code, "voice_buzz_dm_required"); + assert.match(describeAgentCallError(error), /private DM/); + return true; + }, + ); + restore(); + restore = setAgentCallSendForTests(async () => { + throw new Error( + JSON.stringify({ status: null, error: "voice_route_timeout" }), + ); + }); + await assert.rejects(getAgentCallFeed(CALL, null, 20), (error) => { + assert.equal(error.code, "voice_route_timeout"); + assert.match(describeAgentCallError(error), /reach the call service/); + return true; + }); +}); + +test("the feed long-poll carries rev and a bounded wait", async () => { + const sent = harness(() => ({ + status: 200, + body: { rev: "r1", unchanged: true }, + })); + await getAgentCallFeed(CALL, "l4.live.1", 99); + assert.equal(sent[0].method, "GET"); + assert.equal(sent[0].path, `calls/${CALL}/feed?rev=l4.live.1&wait=20`); + assert.equal(sent[0].body, undefined); +}); + +test("stop reports nothing to stop; a tap names the open question", async () => { + harness(() => ({ status: 409, body: { error: "voice_nothing_to_stop" } })); + assert.equal(await stopAgentCallWork(CALL), "nothing_to_stop"); + restore(); + const sent = harness(() => ({ status: 202, body: {} })); + assert.equal(await stopAgentCallWork(CALL), "stopped"); + await answerAgentCallQuestion({ + callId: CALL, + humanAskId: "q:1", + questionId: "q1", + optionIndex: 0, + }); + assert.equal(sent[1].path, `calls/${CALL}/human-asks/q%3A1/answer`); + assert.equal(sent[1].body.optionIndex, 0); + assert.equal(sent[1].body.questionId, "q1"); + assert.equal(typeof sent[1].body.idempotencyKey, "string"); +}); diff --git a/desktop/src/features/agent-call/lib/agentCallApi.ts b/desktop/src/features/agent-call/lib/agentCallApi.ts new file mode 100644 index 00000000000..00989eb3027 --- /dev/null +++ b/desktop/src/features/agent-call/lib/agentCallApi.ts @@ -0,0 +1,222 @@ +import { invokeTauri } from "@/shared/api/tauri"; + +import type { AgentCallFeed } from "./agentCallFeed"; + +/** + * The agent host's call routes, reached through the native + * `agent_voice_request` command (NIP-98 signed by the signed-in user; the + * key never enters the webview). Every route is the caller's own: the host + * starts a call only from the caller's private 1:1 DM with the agent and + * serves each call to its caller only. + */ + +type Raw = { status: number; body: unknown }; +type Send = (method: string, path: string, body?: unknown) => Promise; + +export class AgentCallApiError extends Error { + readonly status: number | null; + readonly code: string | null; + constructor(status: number | null, code: string | null) { + super(code ?? `status_${status ?? "unknown"}`); + this.name = "AgentCallApiError"; + this.status = status; + this.code = code; + } +} + +const tauriSend: Send = async (method, path, body) => { + const raw = await invokeTauri("agent_voice_request", { + method, + path, + body: body === undefined ? null : JSON.stringify(body), + }); + return raw; +}; + +let send: Send = tauriSend; + +/** Test seam: replace the native request. Returns a restore function. */ +export function setAgentCallSendForTests(next: Send) { + const previous = send; + send = next; + return () => { + send = previous; + }; +} + +function codeOf(body: unknown): string | null { + if (body && typeof body === "object" && "error" in body) { + const code = (body as { error?: unknown }).error; + return typeof code === "string" ? code : null; + } + return null; +} + +function nativeCode(error: unknown): string | null { + const message = error instanceof Error ? error.message : String(error); + try { + const parsed = JSON.parse(message) as { error?: unknown }; + return typeof parsed.error === "string" ? parsed.error : null; + } catch { + return null; + } +} + +async function request( + method: string, + path: string, + body?: unknown, +): Promise { + let raw: Raw; + try { + raw = await send(method, path, body); + } catch (error) { + throw new AgentCallApiError(null, nativeCode(error) ?? "network"); + } + if (raw.status < 200 || raw.status >= 300) { + throw new AgentCallApiError(raw.status, codeOf(raw.body)); + } + return raw.body as T; +} + +const call = (callId: string) => `calls/${encodeURIComponent(callId)}`; + +export function newIdempotencyKey(): string { + return typeof crypto !== "undefined" && + typeof crypto.randomUUID === "function" + ? crypto.randomUUID() + : `k-${Date.now()}-${Math.random().toString(36).slice(2)}`; +} + +export type StartAgentCallResponse = { + callId: string; + sdpAnswer: string; + executeUntil: string | null; +}; + +export function startAgentCall(input: { + agentPubkey: string; + channelId: string; + sdpOffer: string; + clientTapAt?: string; +}): Promise { + return request("POST", "calls", { + ...input, + clientDiagnostics: { systemCallUI: "in_app" }, + }); +} + +export function endAgentCall(callId: string, reason: string): Promise { + return request("POST", `${call(callId)}/end`, { reason }); +} + +export type StopAgentCallWorkOutcome = "stopped" | "nothing_to_stop"; + +/** Stops the agent's current work (its Run stop control); the call goes on. */ +export async function stopAgentCallWork( + callId: string, +): Promise { + try { + await request("POST", `${call(callId)}/stop`, { + idempotencyKey: newIdempotencyKey(), + }); + return "stopped"; + } catch (error) { + if ( + error instanceof AgentCallApiError && + error.code === "voice_nothing_to_stop" + ) { + return "nothing_to_stop"; + } + throw error; + } +} + +/** Feed v2 long-poll: the whole snapshot, or `{ rev, unchanged: true }`. */ +export function getAgentCallFeed( + callId: string, + rev: string | null, + waitSeconds: number, +): Promise { + const query = new URLSearchParams(); + if (rev) query.set("rev", rev); + query.set("wait", String(Math.max(0, Math.min(20, waitSeconds)))); + return request("GET", `${call(callId)}/feed?${query.toString()}`); +} + +/** Tap an option of the call's open question (exactly the ask that asked). */ +export function answerAgentCallQuestion(input: { + callId: string; + humanAskId: string; + questionId: string | null; + optionIndex: number; +}): Promise { + return request( + "POST", + `${call(input.callId)}/human-asks/${encodeURIComponent(input.humanAskId)}/answer`, + { + ...(input.questionId ? { questionId: input.questionId } : {}), + optionIndex: input.optionIndex, + idempotencyKey: newIdempotencyKey(), + }, + ); +} + +/** Stop one ask's work, silently; the call goes on. */ +export function cancelAgentCallAsk( + callId: string, + askKey: string, +): Promise { + return request("POST", `${call(callId)}/asks/cancel`, { + askKey, + idempotencyKey: newIdempotencyKey(), + }); +} + +/** Archive hides a card (the work goes on); pin keeps it on top. */ +export function setAgentCallAskState( + callId: string, + askKey: string, + action: "archive" | "unarchive" | "pin" | "unpin", +): Promise { + return request("POST", `${call(callId)}/asks/state`, { + askKey, + action, + idempotencyKey: newIdempotencyKey(), + }); +} + +/** A plain sentence for a failed request (codes only, never content). */ +export function describeAgentCallError(error: unknown): string { + const code = error instanceof AgentCallApiError ? error.code : null; + const status = error instanceof AgentCallApiError ? error.status : null; + switch (code) { + case "voice_call_in_progress": + return "You're already on a call. Hang up there first."; + case "voice_buzz_dm_required": + return "Calls work only in your private DM with this agent."; + case "voice_buzz_dm_unverified": + return "Couldn't confirm this DM with the relay. Try again."; + case "caller_not_allowed": + return "Your account isn't linked for calls with this agent."; + case "agent_not_found": + return "This agent can't take calls."; + case "voice_disabled": + return "Calls are turned off for this agent."; + case "voice_conversation_unavailable": + return "This agent can't open a conversation with you yet."; + case "rate_limited": + case "voice_daily_limit": + return "You've reached the call limit for now. Try again later."; + case "voice_route_unavailable": + case "voice_route_unreachable": + case "voice_route_timeout": + case "network": + return "Couldn't reach the call service. Check your connection."; + case "nip98_expired": + return "The call request expired. Check your computer's clock."; + default: + if (status === 401) return "Couldn't sign the call request. Try again."; + return "Calls are unavailable right now. Try again."; + } +} diff --git a/desktop/src/features/agent-call/lib/agentCallController.test.mjs b/desktop/src/features/agent-call/lib/agentCallController.test.mjs new file mode 100644 index 00000000000..b78aa35b5d9 --- /dev/null +++ b/desktop/src/features/agent-call/lib/agentCallController.test.mjs @@ -0,0 +1,194 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { AgentCallApiError } from "./agentCallApi.ts"; +import { AgentCallController, feedRetryDelay } from "./agentCallController.ts"; + +const CALL = "0192a6b0-0000-7000-8000-0000000000ac"; +const AGENT = "b".repeat(64); +const CHANNEL = "0192a6b0-0000-7000-8000-0000000000af"; + +const tick = () => new Promise((resolve) => setImmediate(resolve)); + +function fakeMedia() { + const track = { + enabled: true, + stopped: false, + stop() { + this.stopped = true; + }, + }; + return { + track, + stream: { getAudioTracks: () => [track], getTracks: () => [track] }, + }; +} + +function fakePeer() { + const peer = { + connectionState: "new", + closed: false, + tracks: [], + ontrack: null, + onconnectionstatechange: null, + remote: null, + addTrack(track) { + this.tracks.push(track); + }, + createDataChannel() { + const channel = { onmessage: null, onclose: null, close() {} }; + peer.channel = channel; + return channel; + }, + async createOffer() { + return { type: "offer", sdp: "v=0 offer" }; + }, + async setLocalDescription() {}, + async setRemoteDescription(answer) { + this.remote = answer; + }, + close() { + this.closed = true; + }, + connect(state) { + this.connectionState = state; + this.onconnectionstatechange?.(); + }, + }; + return peer; +} + +function harness(overrides = {}) { + const media = fakeMedia(); + const peer = fakePeer(); + const log = { starts: [], ends: [], feeds: [] }; + const feedAnswers = overrides.feedAnswers ?? []; + const controller = new AgentCallController({ + isSupported: () => true, + getUserMedia: overrides.getUserMedia ?? (async () => media.stream), + createPeerConnection: () => peer, + createAudioElement: () => ({ + play: async () => {}, + pause() {}, + remove() {}, + srcObject: null, + }), + startCall: + overrides.startCall ?? + (async (input) => { + log.starts.push(input); + return { callId: CALL, sdpAnswer: "v=0 answer", executeUntil: null }; + }), + endCall: async (callId, reason) => { + log.ends.push({ callId, reason }); + }, + stopWork: overrides.stopWork ?? (async () => "stopped"), + getFeed: async (callId, rev, wait) => { + log.feeds.push({ callId, rev, wait }); + if (feedAnswers.length > 0) return feedAnswers.shift(); + // Park like a long-poll that has not answered yet. + return new Promise(() => {}); + }, + now: () => 1_000, + }); + return { controller, peer, media, log }; +} + +test("a call starts from the DM, connects and follows the feed", async () => { + const snapshot = { + callId: CALL, + rev: "r1", + state: "live", + agent: { id: "a", name: "Alfred" }, + destination: { kind: "buzz_dm", label: "your Buzz chat with Alfred" }, + asks: [], + humanAsk: null, + endedAt: null, + }; + const h = harness({ feedAnswers: [snapshot] }); + await h.controller.start({ + agentPubkey: AGENT, + channelId: CHANNEL, + agentName: "Alfred", + }); + assert.equal(h.log.starts.length, 1); + assert.equal(h.log.starts[0].agentPubkey, AGENT); + assert.equal(h.log.starts[0].channelId, CHANNEL); + assert.equal(h.log.starts[0].sdpOffer, "v=0 offer"); + assert.equal(h.peer.remote.sdp, "v=0 answer"); + assert.equal(h.controller.getState().phase, "connecting"); + h.peer.connect("connected"); + assert.equal(h.controller.getState().phase, "live"); + await tick(); + assert.equal(h.controller.getState().feed?.rev, "r1"); + assert.deepEqual(h.log.feeds[0], { callId: CALL, rev: null, wait: 20 }); + assert.equal(h.log.feeds[1].rev, "r1"); +}); + +test("hang-up ends the call only and releases the mic", async () => { + const h = harness(); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + h.peer.connect("connected"); + await h.controller.hangUp(); + assert.deepEqual(h.log.ends, [{ callId: CALL, reason: "hangup" }]); + assert.equal(h.controller.getState().phase, "ended"); + assert.equal(h.media.track.stopped, true); + assert.equal(h.peer.closed, true); + h.controller.dismiss(); + assert.equal(h.controller.getState().phase, "idle"); +}); + +test("mute toggles the mic track; stop reports its outcome", async () => { + const h = harness({ stopWork: async () => "nothing_to_stop" }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + h.peer.connect("connected"); + h.controller.toggleMute(); + assert.equal(h.media.track.enabled, false); + assert.equal(h.controller.getState().muted, true); + await h.controller.stopAgentWork(); + assert.equal(h.controller.getState().stop.status, "nothing_to_stop"); + h.controller.reset(); +}); + +test("a refused start shows the host's reason and holds no mic", async () => { + const h = harness({ + startCall: async () => { + throw new AgentCallApiError(403, "caller_not_allowed"); + }, + }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + const state = h.controller.getState(); + assert.equal(state.phase, "error"); + assert.equal(state.error?.kind, "request_failed"); + assert.match(state.error?.message ?? "", /isn't linked/); + assert.equal(h.media.track.stopped, true); +}); + +test("a denied microphone never reaches the host", async () => { + const h = harness({ + getUserMedia: async () => { + const error = new Error("denied"); + error.name = "NotAllowedError"; + throw error; + }, + }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + assert.equal(h.controller.getState().error?.kind, "mic_denied"); + assert.equal(h.log.starts.length, 0); +}); + +test("a community switch hangs up and clears the screen", async () => { + const h = harness(); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + h.peer.connect("connected"); + h.controller.reset(); + assert.deepEqual(h.log.ends, [{ callId: CALL, reason: "community_changed" }]); + assert.equal(h.controller.getState().phase, "idle"); +}); + +test("feed retries back off from 1 s to 15 s", () => { + assert.equal(feedRetryDelay(1), 1_000); + assert.equal(feedRetryDelay(2), 2_000); + assert.equal(feedRetryDelay(4), 8_000); + assert.equal(feedRetryDelay(9), 15_000); +}); diff --git a/desktop/src/features/agent-call/lib/agentCallController.ts b/desktop/src/features/agent-call/lib/agentCallController.ts new file mode 100644 index 00000000000..af7b11a6deb --- /dev/null +++ b/desktop/src/features/agent-call/lib/agentCallController.ts @@ -0,0 +1,685 @@ +import { + type StartAgentCallResponse, + describeAgentCallError, + endAgentCall, + getAgentCallFeed, + startAgentCall, + stopAgentCallWork, +} from "./agentCallApi"; +import { + type AgentCallFeed, + feedWantsMore, + isFeedSnapshot, +} from "./agentCallFeed"; + +/** + * The app's one live 1:1 agent call (the host allows one per person). + * + * Ported from the agent host's web dashboard call controller so desktop calls + * behave like the phone and web calls of the same voice core: this module + * captures the mic, makes the WebRTC SDP offer, has the host answer it from + * the caller's private DM with the agent, and applies the answer. Audio then + * runs between this webview and the host's realtime voice provider. It lives + * outside React so a call survives changing channel; components read it + * through `useAgentCall`. + * + * Differences from the web dashboard: the call starts from a DM (agent key + + * channel id), and the call screen follows the host's feed long-poll + * (`GET calls/:id/feed?rev&wait=20`, backing off 1 s → 15 s on errors) + * instead of a 1.5 s status poll. After hang-up the feed is followed until + * the recap is written (at most 90 s) and the screen keeps it until closed. + * + * Hang-up ends the call only. It never cancels the agent's work; its answers + * land in the DM. Stop does that, through the host's stop control. + */ + +export type AgentCallPhase = + | "idle" + | "requesting_mic" + | "connecting" + | "live" + | "ending" + | "ended" + | "error"; + +export type AgentCallClientErrorKind = + | "request_failed" + | "mic_denied" + | "mic_unavailable" + | "unsupported" + | "connection_failed"; + +export type AgentCallEndReason = + | "hangup" + | "time_limit" + | "remote" + | "connection_lost" + | "community_changed"; + +export type AgentCallStopState = + | { status: "idle" } + | { status: "stopping" } + | { status: "stopped" } + | { status: "nothing_to_stop" } + | { status: "failed"; message: string }; + +export type AgentCallState = { + phase: AgentCallPhase; + agentPubkey: string | null; + agentName: string | null; + channelId: string | null; + callId: string | null; + /** Epoch ms when audio connected; the live timer counts from here. */ + connectedAt: number | null; + endedAt: number | null; + executeUntil: string | null; + muted: boolean; + stop: AgentCallStopState; + error: { kind: AgentCallClientErrorKind; message: string } | null; + endReason: AgentCallEndReason | null; + /** The host's call screen feed (latest snapshot), or null before it. */ + feed: AgentCallFeed | null; +}; + +const IDLE: AgentCallState = { + phase: "idle", + agentPubkey: null, + agentName: null, + channelId: null, + callId: null, + connectedAt: null, + endedAt: null, + executeUntil: null, + muted: false, + stop: { status: "idle" }, + error: null, + endReason: null, + feed: null, +}; + +/** How long a `disconnected` peer may take to recover before the call ends. */ +const DISCONNECT_GRACE_MS = 5_000; +/** How long "Call ended" stays when the call had nothing on its screen. */ +const ENDED_DISMISS_MS = 4_000; +const STOP_STATUS_RESET_MS = 4_000; +/** The feed long-poll's wait, and how long it is followed after hang-up. */ +const FEED_WAIT_S = 20; +const FEED_AFTER_END_MS = 90_000; + +export function feedRetryDelay(failures: number): number { + return Math.min(15_000, 1_000 * 2 ** Math.max(0, failures - 1)); +} + +type Transport = { + getUserMedia: (constraints: MediaStreamConstraints) => Promise; + createPeerConnection: () => RTCPeerConnection; + createAudioElement: () => HTMLAudioElement; + startCall: typeof startAgentCall; + endCall: typeof endAgentCall; + stopWork: typeof stopAgentCallWork; + getFeed: typeof getAgentCallFeed; + isSupported: () => boolean; + now: () => number; +}; + +/** Whether this webview can place a call at all (WebRTC and a mic API). */ +export function isAgentCallSupported(): boolean { + return ( + typeof window !== "undefined" && + typeof RTCPeerConnection !== "undefined" && + Boolean(navigator.mediaDevices?.getUserMedia) + ); +} + +const webviewTransport = (): Transport => ({ + getUserMedia: (constraints) => + navigator.mediaDevices.getUserMedia(constraints), + createPeerConnection: () => new RTCPeerConnection(), + createAudioElement: () => { + const audio = document.createElement("audio"); + audio.autoplay = true; + audio.setAttribute("playsinline", ""); + audio.setAttribute("data-agent-call-audio", ""); + audio.style.display = "none"; + document.body.appendChild(audio); + return audio; + }, + startCall: startAgentCall, + endCall: endAgentCall, + stopWork: stopAgentCallWork, + getFeed: getAgentCallFeed, + isSupported: isAgentCallSupported, + now: () => Date.now(), +}); + +function describeMicError(error: unknown): { + kind: AgentCallClientErrorKind; + message: string; +} { + const name = error instanceof Error ? error.name : ""; + if (name === "NotAllowedError" || name === "SecurityError") { + return { + kind: "mic_denied", + message: + "Microphone access is off for this app. Allow it in System Settings → Privacy & Security → Microphone, then call again.", + }; + } + if ( + name === "NotFoundError" || + name === "NotReadableError" || + name === "OverconstrainedError" || + name === "AbortError" + ) { + return { + kind: "mic_unavailable", + message: + "No microphone is available. Connect one or close other apps using it, then call again.", + }; + } + return { + kind: "mic_unavailable", + message: "The microphone couldn't start. Try again.", + }; +} + +export class AgentCallController { + private state: AgentCallState = IDLE; + private readonly listeners = new Set<() => void>(); + private readonly transport: Transport; + private attempt = 0; + /** Bumped to stop the feed loop (dismiss, a new call, a community switch). */ + private feedToken = 0; + private feedUntil: number | null = null; + private stream: MediaStream | null = null; + private peer: RTCPeerConnection | null = null; + private channel: RTCDataChannel | null = null; + private audio: HTMLAudioElement | null = null; + private timers = new Set>(); + private disconnectTimer: ReturnType | null = null; + + constructor(transport?: Partial) { + this.transport = { + ...(typeof window !== "undefined" ? webviewTransport() : {}), + ...transport, + } as Transport; + } + + getState = (): AgentCallState => this.state; + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => { + this.listeners.delete(listener); + }; + }; + + private set(patch: Partial) { + this.state = { ...this.state, ...patch }; + for (const listener of this.listeners) { + listener(); + } + } + + private later(callback: () => void, ms: number) { + const timer = setTimeout(() => { + this.timers.delete(timer); + callback(); + }, ms); + this.timers.add(timer); + return timer; + } + + get isBusy(): boolean { + return ( + this.state.phase === "requesting_mic" || + this.state.phase === "connecting" || + this.state.phase === "live" || + this.state.phase === "ending" + ); + } + + /** Starts a call from the caller's 1:1 DM with the agent. Run it from the + * click handler, so playback and the mic open inside the gesture. */ + start = async (input: { + agentPubkey: string; + channelId: string; + agentName?: string | null; + }) => { + if (this.isBusy) { + return; + } + this.clearTimers(); + this.feedToken++; + const attempt = ++this.attempt; + const tapAt = new Date(this.transport.now()).toISOString(); + this.set({ + ...IDLE, + phase: "requesting_mic", + agentPubkey: input.agentPubkey, + agentName: input.agentName ?? null, + channelId: input.channelId, + }); + if (!this.transport.isSupported()) { + this.fail({ + kind: "unsupported", + message: "Calls aren't available in this version of the app.", + }); + return; + } + // Unlock playback inside the gesture; the stream is attached later. + this.audio = this.transport.createAudioElement(); + void this.audio.play().catch(() => undefined); + + try { + this.stream = await this.transport.getUserMedia({ + audio: { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + }, + video: false, + }); + } catch (error) { + if (attempt === this.attempt) { + this.fail(describeMicError(error)); + } + return; + } + if (attempt !== this.attempt) { + this.releaseMedia(); + return; + } + this.set({ phase: "connecting" }); + + let offerSdp: string; + try { + const peer = this.transport.createPeerConnection(); + this.peer = peer; + for (const track of this.stream.getAudioTracks()) { + peer.addTrack(track, this.stream); + } + peer.ontrack = (event) => { + if (!this.audio) { + return; + } + this.audio.srcObject = + event.streams[0] ?? new MediaStream([event.track]); + void this.audio.play().catch(() => undefined); + }; + peer.onconnectionstatechange = () => this.onPeerState(attempt); + this.channel = peer.createDataChannel("oai-events"); + this.channel.onmessage = (event) => this.onChannelMessage(event.data); + this.channel.onclose = () => { + if (attempt === this.attempt && this.state.phase === "live") { + void this.finish("remote"); + } + }; + const offer = await peer.createOffer(); + await peer.setLocalDescription(offer); + offerSdp = offer.sdp ?? ""; + if (!offerSdp) { + throw new Error("empty_offer"); + } + } catch { + if (attempt === this.attempt) { + this.fail({ + kind: "connection_failed", + message: "The call couldn't be set up. Try again.", + }); + } + return; + } + + let response: StartAgentCallResponse; + try { + response = await this.transport.startCall({ + agentPubkey: input.agentPubkey, + channelId: input.channelId, + sdpOffer: offerSdp, + clientTapAt: tapAt, + }); + } catch (error) { + if (attempt === this.attempt) { + this.fail({ + kind: "request_failed", + message: describeAgentCallError(error), + }); + } + return; + } + if (attempt !== this.attempt) { + // Hung up while the host was answering: end the call it opened. + void this.transport + .endCall(response.callId, "hangup") + .catch(() => undefined); + return; + } + this.set({ callId: response.callId, executeUntil: response.executeUntil }); + this.followFeed(response.callId); + + try { + await this.peer?.setRemoteDescription({ + type: "answer", + sdp: response.sdpAnswer, + }); + } catch { + if (attempt === this.attempt) { + void this.transport + .endCall(response.callId, "media_failed") + .catch(() => undefined); + this.fail({ + kind: "connection_failed", + message: "The call connected but audio couldn't start. Try again.", + }); + } + return; + } + this.scheduleLimit(attempt, response.executeUntil); + }; + + private scheduleLimit(attempt: number, executeUntil: string | null) { + const until = executeUntil ? Date.parse(executeUntil) : Number.NaN; + if (!Number.isFinite(until)) { + return; + } + this.later( + () => { + if (attempt === this.attempt && this.isBusy) { + void this.finish("time_limit"); + } + }, + Math.max(0, until - this.transport.now()), + ); + } + + private onPeerState(attempt: number) { + const peer = this.peer; + if (!peer || attempt !== this.attempt) { + return; + } + const state = peer.connectionState; + if (state === "connected") { + if (this.disconnectTimer) { + clearTimeout(this.disconnectTimer); + this.disconnectTimer = null; + } + if (this.state.phase === "connecting") { + this.set({ phase: "live", connectedAt: this.transport.now() }); + } + return; + } + if (state === "failed") { + if (this.state.phase === "connecting") { + if (this.state.callId) { + void this.transport + .endCall(this.state.callId, "media_failed") + .catch(() => undefined); + } + this.fail({ + kind: "connection_failed", + message: + "Audio couldn't connect. A firewall or VPN may be blocking calls.", + }); + return; + } + void this.finish("connection_lost"); + return; + } + if (state === "disconnected" && !this.disconnectTimer) { + this.disconnectTimer = setTimeout(() => { + this.disconnectTimer = null; + if ( + attempt === this.attempt && + this.peer?.connectionState !== "connected" && + this.isBusy + ) { + void this.finish("connection_lost"); + } + }, DISCONNECT_GRACE_MS); + } + } + + private onChannelMessage(data: unknown) { + if (typeof data !== "string") { + return; + } + let type: unknown; + try { + type = (JSON.parse(data) as { type?: unknown }).type; + } catch { + return; + } + if (type === "session.closed" && this.isBusy) { + void this.finish("remote"); + } + } + + /** + * One long-poll loop per call: `wait=20`, again at once after each answer, + * backing off 1 s → 15 s on errors. It stops on a dismiss or a new call, + * on `404` (not this caller's call), and after hang-up once the recap is + * written or 90 s have passed. + */ + private followFeed(callId: string) { + const token = ++this.feedToken; + this.feedUntil = null; + void this.runFeed(token, callId); + } + + private async runFeed(token: number, callId: string) { + let rev: string | null = null; + let failures = 0; + while (token === this.feedToken) { + const ended = !this.isBusy; + if (ended) { + if (!feedWantsMore(this.state.feed)) return; + if (this.feedUntil === null) { + this.feedUntil = this.transport.now() + FEED_AFTER_END_MS; + } + if (this.transport.now() > this.feedUntil) return; + } + try { + const answer = await this.transport.getFeed( + callId, + rev, + ended ? 5 : FEED_WAIT_S, + ); + failures = 0; + if (token !== this.feedToken) return; + if (isFeedSnapshot(answer)) { + rev = answer.rev; + if (answer.callId === callId) this.set({ feed: answer }); + } else if (answer && typeof answer.rev === "string") { + rev = answer.rev; + } + } catch (error) { + if (token !== this.feedToken) return; + const status = (error as { status?: unknown }).status; + if (status === 404 || status === 403 || status === 401) return; + failures++; + await new Promise((resolve) => + setTimeout(resolve, feedRetryDelay(failures)), + ); + } + } + } + + toggleMute = () => { + const tracks = this.stream?.getAudioTracks() ?? []; + const muted = !this.state.muted; + for (const track of tracks) { + track.enabled = !muted; + } + this.set({ muted }); + }; + + /** Stops the agent's current work (host stop control); the call goes on. */ + stopAgentWork = async () => { + const callId = this.state.callId; + if (!callId || this.state.stop.status === "stopping") { + return; + } + const attempt = this.attempt; + this.set({ stop: { status: "stopping" } }); + let next: AgentCallStopState; + try { + next = { status: await this.transport.stopWork(callId) }; + } catch { + next = { + status: "failed", + message: "Couldn't stop the agent. Try again, or say “stop”.", + }; + } + if (attempt !== this.attempt) { + return; + } + this.set({ stop: next }); + this.later(() => { + if (attempt === this.attempt && this.state.stop === next) { + this.set({ stop: { status: "idle" } }); + } + }, STOP_STATUS_RESET_MS); + }; + + /** Hangs up. The agent keeps working; its answers land in the DM. */ + hangUp = () => this.finish("hangup"); + + /** Hangs up when the window closes: best effort, nothing waits on it. */ + hangUpOnUnload = () => { + if (!this.isBusy) { + return; + } + const callId = this.state.callId; + this.attempt++; + this.feedToken++; + this.releaseMedia(); + if (callId) { + void this.transport.endCall(callId, "page_closed").catch(() => undefined); + } + }; + + /** A community or identity switch: hang up and clear the screen. */ + reset = () => { + if (this.isBusy) { + const callId = this.state.callId; + if (callId) { + void this.transport + .endCall(callId, "community_changed") + .catch(() => undefined); + } + } + this.attempt++; + this.feedToken++; + this.clearTimers(); + this.releaseMedia(); + this.set(IDLE); + }; + + private async finish(reason: AgentCallEndReason) { + if (!this.isBusy) { + return; + } + const callId = this.state.callId; + this.attempt++; + const attempt = this.attempt; + this.clearTimers(); + this.releaseMedia(); + this.set({ + phase: "ending", + endReason: reason, + endedAt: this.transport.now(), + }); + if (callId) { + await this.transport.endCall(callId, reason).catch(() => undefined); + } + if (attempt !== this.attempt) { + return; + } + this.set({ phase: "ended" }); + // A call with something on its screen keeps it (the recap) until + // closed; an empty one goes away (after one more feed answer). + this.later(() => { + if ( + attempt === this.attempt && + this.state.phase === "ended" && + (this.state.feed?.asks.length ?? 0) === 0 + ) { + this.dismiss(); + } + }, ENDED_DISMISS_MS); + } + + private fail(error: { kind: AgentCallClientErrorKind; message: string }) { + this.attempt++; + this.feedToken++; + this.clearTimers(); + this.releaseMedia(); + this.set({ + phase: "error", + error, + endedAt: this.transport.now(), + }); + } + + /** Closes the error or "Call ended" screen. */ + dismiss = () => { + if (this.isBusy) { + return; + } + this.attempt++; + this.feedToken++; + this.clearTimers(); + this.set(IDLE); + }; + + private clearTimers() { + for (const timer of this.timers) { + clearTimeout(timer); + } + this.timers.clear(); + if (this.disconnectTimer) { + clearTimeout(this.disconnectTimer); + this.disconnectTimer = null; + } + } + + private releaseMedia() { + for (const track of this.stream?.getTracks() ?? []) { + track.stop(); + } + this.stream = null; + if (this.channel) { + this.channel.onmessage = null; + this.channel.onclose = null; + try { + this.channel.close(); + } catch { + // Already closed. + } + this.channel = null; + } + if (this.peer) { + this.peer.ontrack = null; + this.peer.onconnectionstatechange = null; + try { + this.peer.close(); + } catch { + // Already closed. + } + this.peer = null; + } + if (this.audio) { + this.audio.pause(); + this.audio.srcObject = null; + this.audio.remove(); + this.audio = null; + } + } +} + +export const agentCallController = new AgentCallController(); + +/** Community switch seam (`resetCommunityState`). */ +export function resetAgentCall() { + agentCallController.reset(); +} diff --git a/desktop/src/features/agent-call/lib/agentCallFeed.test.mjs b/desktop/src/features/agent-call/lib/agentCallFeed.test.mjs new file mode 100644 index 00000000000..c8665dc4ff3 --- /dev/null +++ b/desktop/src/features/agent-call/lib/agentCallFeed.test.mjs @@ -0,0 +1,146 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { + askKeyOf, + askNowLine, + askStatusLabel, + askTitle, + feedWantsMore, + isFeedSnapshot, + openHumanAsk, + safeHttpsUrl, + visibleAsks, +} from "./agentCallFeed.ts"; + +const ask = (overrides = {}) => ({ + askId: null, + utteranceId: "d1", + kind: "ask", + text: "email Nicole the Q3 deck before the board meeting on Thursday please", + status: "submitted", + statusReason: null, + createdAt: "2026-10-23T12:00:00.000Z", + closedAt: null, + progress: null, + result: null, + links: [], + ...overrides, +}); + +const feed = (overrides = {}) => ({ + callId: "c1", + rev: "r1", + state: "live", + agent: { id: "a", name: "Alfred" }, + destination: null, + asks: [], + humanAsk: null, + endedAt: null, + ...overrides, +}); + +test("ask keys, titles and live lines follow the host's ledger", () => { + assert.equal(askKeyOf(ask()), "d1"); + assert.equal(askKeyOf(ask({ askKey: "k1" })), "k1"); + assert.equal( + askTitle(ask({ title: { text: "Email Nicole", source: "model" } })), + "Email Nicole", + ); + assert.equal(askTitle(ask()), "email Nicole the Q3 deck before the board…"); + assert.equal( + askNowLine(ask({ progress: { text: "drafting", at: "x" } })), + "drafting", + ); + assert.equal( + askNowLine( + ask({ + nowLine: { text: "now", at: "x" }, + progress: { text: "old", at: "x" }, + }), + ), + "now", + ); + assert.equal( + askNowLine(ask({ status: "answered", progress: { text: "x", at: "x" } })), + null, + ); + assert.equal(askStatusLabel(ask()), "Working"); + assert.equal(askStatusLabel(ask({ status: "answered" })), "Done"); + assert.equal( + askStatusLabel(ask({ status: "failed", cancelledAt: "x" })), + "Cancelled", + ); +}); + +test("pinned asks first (newest pin first), archived apart, answers folded", () => { + const list = visibleAsks( + feed({ + asks: [ + ask({ utteranceId: "a" }), + ask({ utteranceId: "b", pinnedAt: "2026-10-23T12:01:00.000Z" }), + ask({ utteranceId: "c", archivedAt: "2026-10-23T12:02:00.000Z" }), + ask({ utteranceId: "d", pinnedAt: "2026-10-23T12:03:00.000Z" }), + ask({ utteranceId: "e", kind: "answer" }), + ], + }), + ); + assert.deepEqual( + list.shown.map((a) => a.utteranceId), + ["d", "b", "a"], + ); + assert.deepEqual( + list.archived.map((a) => a.utteranceId), + ["c"], + ); +}); + +test("only https links open", () => { + assert.equal(safeHttpsUrl("https://example.com/x"), "https://example.com/x"); + assert.equal(safeHttpsUrl("http://example.com"), null); + assert.equal(safeHttpsUrl("javascript:alert(1)"), null); + assert.equal(safeHttpsUrl("not a url"), null); + assert.equal(safeHttpsUrl(null), null); +}); + +test("snapshots, the open question and when to keep following", () => { + assert.equal(isFeedSnapshot(feed()), true); + assert.equal(isFeedSnapshot({ rev: "r1", unchanged: true }), false); + assert.equal(isFeedSnapshot(null), false); + + assert.equal(openHumanAsk(feed()), null); + const question = { + humanAskId: "h1", + state: "open", + answeredBy: null, + answerText: null, + questions: [ + { id: "q1", question: "Send it?", options: [], allowsText: false }, + ], + }; + assert.equal(openHumanAsk(feed({ humanAsk: question }))?.humanAskId, "h1"); + assert.equal( + openHumanAsk(feed({ humanAsk: { ...question, state: "answered" } })), + null, + ); + + assert.equal(feedWantsMore(null), true); + assert.equal(feedWantsMore(feed()), true); + assert.equal(feedWantsMore(feed({ state: "ended" })), false); + assert.equal( + feedWantsMore(feed({ state: "ended", contract: 2, recap: null })), + true, + ); + assert.equal( + feedWantsMore( + feed({ state: "ended", contract: 2, recap: { summary: null } }), + ), + true, + ); + assert.equal( + feedWantsMore( + feed({ state: "ended", contract: 2, recap: { summary: "- Sent" } }), + ), + false, + ); +}); diff --git a/desktop/src/features/agent-call/lib/agentCallFeed.ts b/desktop/src/features/agent-call/lib/agentCallFeed.ts new file mode 100644 index 00000000000..b9f28cdfe89 --- /dev/null +++ b/desktop/src/features/agent-call/lib/agentCallFeed.ts @@ -0,0 +1,218 @@ +/** + * The agent host's call screen feed (contract v1 plus the additive v2 + * fields): the whole current state of the caller's own call, keyed by ask. + * Status is the host's ledger, never inferred here. Every v2 field is + * optional; a snapshot without `contract: 2` shows only v1 content. + */ + +export type AgentCallAskStatus = + | "open" + | "submitted" + | "still_working" + | "answered" + | "not_answered" + | "failed"; + +export type AgentCallLink = { url: string; title: string | null }; + +export type AgentCallResultCard = { + id: string; + kind: "email" | "event" | "file" | "link" | "draft" | "task"; + title: string; + subtitle: string | null; + url: string | null; +}; + +export type AgentCallStep = { + id: string; + at: string; + line: string; + state: "running" | "done" | "failed"; +}; + +export type AgentCallAsk = { + askId: string | null; + utteranceId: string; + askKey?: string; + kind: "ask" | "answer"; + text: string; + status: AgentCallAskStatus; + statusReason: string | null; + createdAt: string; + closedAt: string | null; + progress: { text: string; at: string } | null; + result: { + text: string | null; + format: "text" | "markdown"; + sentTo?: { label: string; state: "pending" | "delivered" } | null; + } | null; + links: AgentCallLink[]; + answersHumanAsk?: string | null; + request?: { text: string; at: string; source: string } | null; + title?: { text: string; source: string } | null; + humanAskId?: string | null; + nowLine?: { text: string; at: string } | null; + steps?: AgentCallStep[]; + results?: AgentCallResultCard[]; + archivedAt?: string | null; + pinnedAt?: string | null; + cancelledAt?: string | null; + actions?: { cancel?: boolean; tellMore?: boolean; openChat?: boolean }; +}; + +export type AgentCallQuestion = { + id: string; + question: string; + options: { index: number; label: string }[]; + allowsText: boolean; +}; + +export type AgentCallHumanAsk = { + humanAskId: string; + state: "open" | "answered" | "closed"; + askingAskId?: string | null; + answeredBy: "voice" | "tap" | null; + answerText: string | null; + questions: AgentCallQuestion[]; +}; + +export type AgentCallFeed = { + callId: string; + rev: string; + state: "live" | "ended"; + agent: { id: string; name: string } | null; + working?: { since: string; open: number } | null; + destination: { + kind: "buzz_dm" | "sidebar" | "none"; + label: string | null; + } | null; + asks: AgentCallAsk[]; + humanAsk: AgentCallHumanAsk | null; + endedAt: string | null; + contract?: number; + counts?: { open: number; needsYou: number; archived: number; total: number }; + recap?: AgentCallRecap | null; +}; + +export type AgentCallRecapItem = { + askKey: string; + title: string; + status: AgentCallAskStatus; + archived?: boolean; + reason?: string | null; +}; + +/** Set once the call has ended (`summary` is null while it is written). */ +export type AgentCallRecap = { + summary: string | null; + done?: AgentCallRecapItem[]; + stillOpen?: AgentCallRecapItem[]; + notDone?: AgentCallRecapItem[]; + links?: { label: string; url: string }[]; +}; + +const TERMINAL: ReadonlySet = new Set([ + "answered", + "not_answered", + "failed", +]); + +export function isAskTerminal(ask: AgentCallAsk): boolean { + return TERMINAL.has(ask.status); +} + +/** The ask's key for the per-ask routes (v2 `askKey`, else v1 utteranceId). */ +export function askKeyOf(ask: AgentCallAsk): string { + return ask.askKey ?? ask.utteranceId; +} + +/** A short title: the host's title, else the caller's first words. */ +export function askTitle(ask: AgentCallAsk): string { + const title = ask.title?.text?.trim(); + if (title) return title; + const words = ask.text.trim().split(/\s+/).slice(0, 8).join(" "); + return words.length < ask.text.trim().length ? `${words}…` : words; +} + +/** One live line: the host's now line or last progress, while working. */ +export function askNowLine(ask: AgentCallAsk): string | null { + if (isAskTerminal(ask)) return null; + return ask.nowLine?.text ?? ask.progress?.text ?? null; +} + +export function askStatusLabel(ask: AgentCallAsk): string { + if (ask.cancelledAt) return "Cancelled"; + switch (ask.status) { + case "open": + case "submitted": + case "still_working": + return "Working"; + case "answered": + return "Done"; + case "not_answered": + return "Not done"; + case "failed": + return "Failed"; + } +} + +/** + * The visible list: answers fold under the question card, archived asks are + * listed apart, pinned asks first (newest pin first), then oldest first. + */ +export function visibleAsks(feed: AgentCallFeed): { + shown: AgentCallAsk[]; + archived: AgentCallAsk[]; +} { + const asks = feed.asks.filter((ask) => ask.kind === "ask"); + const shown = asks.filter((ask) => !ask.archivedAt); + const pinned = shown + .filter((ask) => ask.pinnedAt) + .sort((a, b) => String(b.pinnedAt).localeCompare(String(a.pinnedAt))); + const rest = shown.filter((ask) => !ask.pinnedAt); + return { + shown: [...pinned, ...rest], + archived: asks.filter((ask) => ask.archivedAt), + }; +} + +/** Only https links are opened from the call screen. */ +export function safeHttpsUrl(url: string | null | undefined): string | null { + if (!url) return null; + try { + const parsed = new URL(url); + return parsed.protocol === "https:" ? parsed.toString() : null; + } catch { + return null; + } +} + +/** Whether a long-poll answer is a full snapshot (not `unchanged`). */ +export function isFeedSnapshot(value: unknown): value is AgentCallFeed { + return ( + Boolean(value) && + typeof value === "object" && + !(value as { unchanged?: unknown }).unchanged && + typeof (value as { callId?: unknown }).callId === "string" && + Array.isArray((value as { asks?: unknown }).asks) + ); +} + +/** Whether the call screen should wait for more: live, or ended without a + * recap summary yet (it is written a few seconds after hang-up). */ +export function feedWantsMore(feed: AgentCallFeed | null): boolean { + if (!feed) return true; + if (feed.state === "live") return true; + if (feed.contract !== undefined && feed.contract >= 2) { + return !feed.recap || feed.recap.summary === null; + } + return false; +} + +/** The one open question, if it is still open. */ +export function openHumanAsk( + feed: AgentCallFeed | null, +): AgentCallHumanAsk | null { + const ask = feed?.humanAsk ?? null; + return ask && ask.state === "open" && ask.questions.length > 0 ? ask : null; +} diff --git a/desktop/src/features/agent-call/ui/AgentCallButton.tsx b/desktop/src/features/agent-call/ui/AgentCallButton.tsx new file mode 100644 index 00000000000..e32ac2962cb --- /dev/null +++ b/desktop/src/features/agent-call/ui/AgentCallButton.tsx @@ -0,0 +1,64 @@ +import { Phone } from "lucide-react"; + +import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys"; +import type { Channel } from "@/shared/api/types"; +import { normalizePubkey } from "@/shared/lib/pubkey"; +import { Button } from "@/shared/ui/button"; + +import { agentCallController } from "../lib/agentCallController"; +import { useAgentCall } from "./useAgentCall"; + +/** + * "Call " in a 1:1 agent DM header: a proper voice call with the + * agent (its host's voice core), not a huddle. The host checks that this is + * the caller's own private DM with the agent before it answers. + */ +export function AgentCallButton({ + agentName, + agentPubkey, + channel, + isAgentHint, +}: { + agentName: string; + agentPubkey: string; + channel: Channel; + isAgentHint: boolean; +}) { + const knownAgents = useKnownAgentPubkeys(); + const call = useAgentCall(); + const key = normalizePubkey(agentPubkey); + const isAgent = isAgentHint || knownAgents.has(key); + if (channel.channelType !== "dm" || !isAgent) return null; + + const busy = + call.phase === "requesting_mic" || + call.phase === "connecting" || + call.phase === "live" || + call.phase === "ending"; + const withThisAgent = busy && call.agentPubkey === key; + const label = withThisAgent + ? `On a call with ${agentName}` + : busy + ? "You're already on a call" + : `Call ${agentName}`; + + return ( + + ); +} diff --git a/desktop/src/features/agent-call/ui/AgentCallDock.tsx b/desktop/src/features/agent-call/ui/AgentCallDock.tsx new file mode 100644 index 00000000000..cfaa3299ede --- /dev/null +++ b/desktop/src/features/agent-call/ui/AgentCallDock.tsx @@ -0,0 +1,409 @@ +import { openUrl } from "@tauri-apps/plugin-opener"; +import { Archive, Mic, MicOff, Phone, PhoneOff, Square, X } from "lucide-react"; +import * as React from "react"; +import { toast } from "sonner"; + +import { Button } from "@/shared/ui/button"; + +import { + answerAgentCallQuestion, + cancelAgentCallAsk, + describeAgentCallError, + setAgentCallAskState, +} from "../lib/agentCallApi"; +import { + type AgentCallState, + agentCallController, +} from "../lib/agentCallController"; +import { + type AgentCallAsk, + type AgentCallFeed, + askKeyOf, + askNowLine, + askStatusLabel, + askTitle, + isAskTerminal, + openHumanAsk, + safeHttpsUrl, + visibleAsks, +} from "../lib/agentCallFeed"; +import { + formatCallDuration, + useAgentCall, + useElapsedSeconds, +} from "./useAgentCall"; + +/** + * The in-call screen of a 1:1 agent call, docked bottom-right over the app + * so the call survives changing channel: who, how long, mute, stop the + * agent's work, hang up, and the host's feed of the call's asks (working, + * done, the open question with its options) and, after hang-up, the recap. + */ +export function AgentCallDock() { + const call = useAgentCall(); + + React.useEffect(() => { + const onUnload = () => agentCallController.hangUpOnUnload(); + window.addEventListener("pagehide", onUnload); + window.addEventListener("beforeunload", onUnload); + return () => { + window.removeEventListener("pagehide", onUnload); + window.removeEventListener("beforeunload", onUnload); + }; + }, []); + + if (call.phase === "idle") return null; + return ( +
+ + {call.phase === "error" ? ( +

+ {call.error?.message ?? "The call couldn't start."} +

+ ) : ( + + )} +
+ ); +} + +function statusLine(call: AgentCallState, elapsed: number): string { + switch (call.phase) { + case "requesting_mic": + return "Waiting for the microphone…"; + case "connecting": + return "Connecting…"; + case "live": + return formatCallDuration(elapsed); + case "ending": + return "Hanging up…"; + case "ended": + return call.endReason === "time_limit" + ? "Call ended (time limit)" + : call.endReason === "connection_lost" + ? "Call ended (connection lost)" + : "Call ended"; + case "error": + return "Couldn't call"; + default: + return ""; + } +} + +function CallHeader({ call }: { call: AgentCallState }) { + const elapsed = useElapsedSeconds( + call.phase === "live" ? call.connectedAt : null, + ); + const busy = + call.phase === "requesting_mic" || + call.phase === "connecting" || + call.phase === "live"; + return ( +
+ +
+

+ {call.agentName ?? "Agent"} +

+

+ {statusLine(call, elapsed)} +

+
+ {busy ? ( + <> + + + + ) : call.phase === "ended" || call.phase === "error" ? ( + + ) : null} +
+ ); +} + +function CallBody({ call }: { call: AgentCallState }) { + const feed = call.feed; + const { shown, archived } = feed + ? visibleAsks(feed) + : { shown: [], archived: [] }; + const question = openHumanAsk(feed); + const live = call.phase === "live"; + return ( +
+ {live ? : null} + {question && feed ? : null} + {shown.length > 0 ? ( +
    + {shown.map((ask) => ( + = 2} + /> + ))} +
+ ) : live ? ( +

+ Talk to {call.agentName ?? "the agent"}. What you ask shows up here. +

+ ) : null} + {archived.length > 0 ? ( +

+ Archived ({archived.length}) +

+ ) : null} + {call.phase === "ended" && feed ? : null} + {feed?.destination?.label ? ( +

+ Answers go to {feed.destination.label}. +

+ ) : null} +
+ ); +} + +function StopControl({ call }: { call: AgentCallState }) { + const stop = call.stop; + const working = Boolean( + call.feed?.asks.some((ask) => ask.kind === "ask" && !isAskTerminal(ask)), + ); + const note = + stop.status === "stopped" + ? "Stopped." + : stop.status === "nothing_to_stop" + ? "Nothing to stop." + : stop.status === "failed" + ? stop.message + : null; + if (!working && !note) return null; + return ( +
+ {working ? ( + + ) : null} + {note ? ( + + {note} + + ) : null} +
+ ); +} + +function QuestionCard({ feed }: { feed: AgentCallFeed }) { + const ask = openHumanAsk(feed); + const [sending, setSending] = React.useState(null); + if (!ask) return null; + return ( +
+ {ask.questions.map((question) => ( +
+

{question.question}

+
+ {question.options.map((option) => { + const id = `${question.id}:${option.index}`; + return ( + + ); + })} +
+
+ ))} +
+ ); +} + +function AskRow({ + ask, + callId, + live, + v2, +}: { + ask: AgentCallAsk; + callId: string; + live: boolean; + /** Per-ask controls (cancel, archive) are feed v2 routes. */ + v2: boolean; +}) { + const key = askKeyOf(ask); + const nowLine = askNowLine(ask); + const resultText = ask.result?.text?.trim() ?? ""; + const canCancel = + v2 && + live && + !ask.cancelledAt && + (ask.actions?.cancel ?? !isAskTerminal(ask)); + const run = (action: () => Promise) => { + void action().catch((error: unknown) => { + toast.error(describeAgentCallError(error)); + }); + }; + return ( +
  • +
    +
    +

    {askTitle(ask)}

    +

    + {askStatusLabel(ask)} + {nowLine ? ` · ${nowLine}` : ""} +

    +
    + {canCancel ? ( + + ) : null} + {v2 ? ( + + ) : null} +
    + {resultText ? ( +

    + {resultText} +

    + ) : ask.status === "not_answered" || ask.status === "failed" ? ( + ask.statusReason ? ( +

    + {ask.statusReason} +

    + ) : null + ) : null} + ({ + label: link.title ?? link.url, + url: link.url, + }))} + /> +
  • + ); +} + +function Recap({ feed }: { feed: AgentCallFeed }) { + const recap = feed.recap; + if (feed.contract === undefined || feed.contract < 2) return null; + if (!recap || recap.summary === null) { + return ( +

    + Writing the recap… +

    + ); + } + return ( +
    +

    Recap

    +

    {recap.summary}

    + +
    + ); +} + +function LinkList({ links }: { links: { label: string; url: string }[] }) { + const safe = links + .map((link) => ({ label: link.label, url: safeHttpsUrl(link.url) })) + .filter((link): link is { label: string; url: string } => !!link.url); + if (safe.length === 0) return null; + return ( +
      + {safe.slice(0, 10).map((link) => ( +
    • + +
    • + ))} +
    + ); +} diff --git a/desktop/src/features/agent-call/ui/useAgentCall.ts b/desktop/src/features/agent-call/ui/useAgentCall.ts new file mode 100644 index 00000000000..8407afda7aa --- /dev/null +++ b/desktop/src/features/agent-call/ui/useAgentCall.ts @@ -0,0 +1,33 @@ +import * as React from "react"; + +import { + type AgentCallState, + agentCallController, +} from "../lib/agentCallController"; + +/** The app's one agent call, as React state. */ +export function useAgentCall(): AgentCallState { + return React.useSyncExternalStore( + agentCallController.subscribe, + agentCallController.getState, + agentCallController.getState, + ); +} + +/** Seconds since `since` (epoch ms), ticking once a second while set. */ +export function useElapsedSeconds(since: number | null): number { + const [now, setNow] = React.useState(() => Date.now()); + React.useEffect(() => { + if (since === null) return; + setNow(Date.now()); + const timer = setInterval(() => setNow(Date.now()), 1_000); + return () => clearInterval(timer); + }, [since]); + return since === null ? 0 : Math.max(0, Math.floor((now - since) / 1_000)); +} + +export function formatCallDuration(seconds: number): string { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, "0")}`; +} diff --git a/desktop/src/features/channels/ui/ChannelScreenHeader.tsx b/desktop/src/features/channels/ui/ChannelScreenHeader.tsx index f12aefa1eca..081a24764b6 100644 --- a/desktop/src/features/channels/ui/ChannelScreenHeader.tsx +++ b/desktop/src/features/channels/ui/ChannelScreenHeader.tsx @@ -17,6 +17,7 @@ import { import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; import { AgentSessionsPicker } from "@/features/agent-dm/ui/AgentSessionsPicker"; import { AgentDmPrewarm } from "@/features/agent-dm/ui/AgentDmPrewarm"; +import { AgentCallButton } from "@/features/agent-call/ui/AgentCallButton"; import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; import { UserNameIndicators } from "@/features/user-status/ui/UserNameIndicators"; import { Button } from "@/shared/ui/button"; @@ -141,6 +142,12 @@ export function ChannelScreenHeader({ channel={activeChannel} isAgentHint={activeDmParticipant.isAgent === true} /> + ) : null; const actions = diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index 44939645cc8..7e005e4d626 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -42,6 +42,7 @@ import { import { resetAgentWorkingSignal } from "@/features/agents/agentWorkingSignal"; import { resetAgentSummaryCache } from "@/features/agent-dm/lib/agentSummary"; import { resetAgentPrewarm } from "@/features/agent-dm/lib/agentPrewarm"; +import { resetAgentCall } from "@/features/agent-call/lib/agentCallController"; import { resetAgentObserverStore } from "@/features/agents/observerRelayStore"; import { resetGuestAccessState } from "@/features/guest-access/lib/reset"; import { resetAgentDmState } from "@/features/agent-dm/lib/registry"; @@ -92,6 +93,7 @@ async function resetCommunityState({ resetSidebarRelayConnectionCardState(); resetAgentSummaryCache(); resetAgentPrewarm(); + resetAgentCall(); resetMediaCaches(); resetLinkPreviewMetadataCache(); resetVideoPlayerState(); diff --git a/docs/kiingo-fork-inventory.json b/docs/kiingo-fork-inventory.json index c0e9ff5357c..c0f342dfe7f 100644 --- a/docs/kiingo-fork-inventory.json +++ b/docs/kiingo-fork-inventory.json @@ -429,13 +429,15 @@ "hook": "desktop/src/app/AppShell.tsx", "implementations": [ "desktop/src/extensions/identity-rotation/IdentityRotationExtension.tsx", - "desktop/src/features/hosted-owner-relink/ui/HostedAutoLinkExtension.tsx" + "desktop/src/features/hosted-owner-relink/ui/HostedAutoLinkExtension.tsx", + "desktop/src/features/agent-call/ui/AgentCallDock.tsx" ], - "contract": "Provider-neutral rendering seam for a self-contained identity lifecycle dialog with no configured coordinator or tenant knowledge. The same seam mounts a renderless provider-neutral runner for the owner's hosted-agent auto-link setting.", + "contract": "Provider-neutral rendering seam for a self-contained identity lifecycle dialog with no configured coordinator or tenant knowledge. The same seam mounts a renderless provider-neutral runner for the owner's hosted-agent auto-link setting, and the self-contained dock of the app's one 1:1 agent call.", "focusedTests": [ "desktop/src/extensions/identity-rotation/IdentityRotationExtension.test.mjs", "desktop/src/shared/lib/ncryptsecSourceScan.test.mjs", - "desktop/src/features/hosted-owner-relink/lib/autoLink.test.mjs" + "desktop/src/features/hosted-owner-relink/lib/autoLink.test.mjs", + "desktop/src/features/agent-call/lib/agentCallController.test.mjs" ] }, { @@ -1773,6 +1775,26 @@ "desktop/src/features/profile/ui/UserProfilePanelSections.tsx" ] }, + { + "classification": "retain-generic", + "owner": "Buzz messaging maintainers", + "purpose": "Desktop 1:1 agent calls from an agent DM: a proper voice call with the agent through its host's voice core (WebRTC between the webview and the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call button beside the sessions picker in a 1:1 agent DM header (known agents only) starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent (never channels, group DMs or guests). Every request goes through one native command, agent_voice_request, that signs NIP-98 (kind 27235, exact URL with query, method, SHA-256 payload of the exact body) as the signed-in user with X-Buzz-Community, reaches only the host's call routes under /api/buzz-voice/desktop (allowlisted paths, https only, 35 s timeout, size caps, no redirects) and returns {status, body}. The call controller is a port of the host's web call controller: mic with echo cancellation, an oai-events data channel, the time limit, a 5 s disconnect grace, mute, stop the agent's work, hang-up that never cancels work, and the host's call screen feed long-polled (wait 20 s, 1 s to 15 s backoff) for asks, the open question's option taps, per-ask cancel and archive (feed v2) and the post-call recap (followed at most 90 s after hang-up). The dock is mounted once in AppShell; a community switch hangs up and clears it (resetCommunityState()). Hooks: one module plus re-export in extensions/mod.rs, one use item and one command registration in lib.rs, one element and import in ChannelScreenHeader.tsx, one element and import in AppShell.tsx, one reset line and import in useCommunityInit.ts, and the microphone usage string in Info.plist.", + "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", + "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", + "paths": [ + "desktop/src-tauri/Info.plist", + "desktop/src-tauri/src/extensions/agent_voice/mod.rs", + "desktop/src/features/agent-call/lib/agentCallApi.test.mjs", + "desktop/src/features/agent-call/lib/agentCallApi.ts", + "desktop/src/features/agent-call/lib/agentCallController.test.mjs", + "desktop/src/features/agent-call/lib/agentCallController.ts", + "desktop/src/features/agent-call/lib/agentCallFeed.test.mjs", + "desktop/src/features/agent-call/lib/agentCallFeed.ts", + "desktop/src/features/agent-call/ui/AgentCallButton.tsx", + "desktop/src/features/agent-call/ui/AgentCallDock.tsx", + "desktop/src/features/agent-call/ui/useAgentCall.ts" + ] + }, { "classification": "retain-generic", "owner": "Buzz messaging maintainers", From 545239137566f7512bdd37b8c22afc92526a540a Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Thu, 22 Oct 2026 23:11:11 -0700 Subject: [PATCH 2/7] fix(desktop): report no system call UI for desktop agent calls Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- desktop/src/features/agent-call/lib/agentCallApi.test.mjs | 2 +- desktop/src/features/agent-call/lib/agentCallApi.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/desktop/src/features/agent-call/lib/agentCallApi.test.mjs b/desktop/src/features/agent-call/lib/agentCallApi.test.mjs index 06d9a00d9f2..00558df5f95 100644 --- a/desktop/src/features/agent-call/lib/agentCallApi.test.mjs +++ b/desktop/src/features/agent-call/lib/agentCallApi.test.mjs @@ -42,7 +42,7 @@ test("a call starts from the DM with the agent key, channel and offer", async () agentPubkey: "b".repeat(64), channelId: "0192a6b0-0000-7000-8000-0000000000af", sdpOffer: "v=0 offer", - clientDiagnostics: { systemCallUI: "in_app" }, + clientDiagnostics: { systemCallUI: "none" }, }); }); diff --git a/desktop/src/features/agent-call/lib/agentCallApi.ts b/desktop/src/features/agent-call/lib/agentCallApi.ts index 00989eb3027..f17563c7fa9 100644 --- a/desktop/src/features/agent-call/lib/agentCallApi.ts +++ b/desktop/src/features/agent-call/lib/agentCallApi.ts @@ -102,7 +102,7 @@ export function startAgentCall(input: { }): Promise { return request("POST", "calls", { ...input, - clientDiagnostics: { systemCallUI: "in_app" }, + clientDiagnostics: { systemCallUI: "none" }, }); } From d237c18a6b26549cddb61811f651483164e87a0a Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Thu, 22 Oct 2026 23:11:13 -0700 Subject: [PATCH 3/7] feat(mobile): call an agent from its 1:1 DM on iOS A Call action in a 1:1 agent DM header places a proper voice call with the agent through its host's voice core, the same as desktop: the host answers the WebRTC offer only after proving the signer is the verified requester of that private 1:1 DM with the agent. - AgentCallPlugin (buzz/agent_call): stasel/WebRTC 154.0.0 pinned exactly, an outgoing CallKit call from a provider created at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app fallback when CallKit refuses, and interruption, route-change and media-reset handling. - Info.plist: UIBackgroundModes audio and voip; the microphone string mentions calls. - Dart: a NIP-98 client for /api/buzz-voice/ios, the call screen feed model, a controller that follows the feed long-poll (asks, option taps, cancel and archive, recap), refuses while a huddle holds the audio and hangs up on a community switch, and the call screen. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- docs/kiingo-fork-inventory.json | 18 + mobile/ios/Runner.xcodeproj/project.pbxproj | 24 + .../xcshareddata/swiftpm/Package.resolved | 9 + mobile/ios/Runner/AgentCallPlugin.swift | 541 ++++++++++++++++++ mobile/ios/Runner/AppDelegate.swift | 3 + mobile/ios/Runner/Info.plist | 7 +- .../features/agent_call/agent_call_api.dart | 252 ++++++++ .../agent_call/agent_call_controller.dart | 482 ++++++++++++++++ .../features/agent_call/agent_call_feed.dart | 249 ++++++++ .../features/agent_call/agent_call_media.dart | 156 +++++ .../agent_call/agent_call_screen.dart | 473 +++++++++++++++ .../channels/channel_detail_page.dart | 15 + .../features/agent_call/agent_call_test.dart | 320 +++++++++++ 13 files changed, 2548 insertions(+), 1 deletion(-) create mode 100644 mobile/ios/Runner/AgentCallPlugin.swift create mode 100644 mobile/lib/features/agent_call/agent_call_api.dart create mode 100644 mobile/lib/features/agent_call/agent_call_controller.dart create mode 100644 mobile/lib/features/agent_call/agent_call_feed.dart create mode 100644 mobile/lib/features/agent_call/agent_call_media.dart create mode 100644 mobile/lib/features/agent_call/agent_call_screen.dart create mode 100644 mobile/test/features/agent_call/agent_call_test.dart diff --git a/docs/kiingo-fork-inventory.json b/docs/kiingo-fork-inventory.json index c0f342dfe7f..5dc3212d4f3 100644 --- a/docs/kiingo-fork-inventory.json +++ b/docs/kiingo-fork-inventory.json @@ -1795,6 +1795,24 @@ "desktop/src/features/agent-call/ui/useAgentCall.ts" ] }, + { + "classification": "retain-generic", + "owner": "Buzz mobile maintainers", + "purpose": "iOS 1:1 agent calls from an agent DM, matching the desktop call: a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call action beside the sessions action in a 1:1 agent DM header (native navigation action and Flutter button) opens the call screen and starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. Requests go to /api/buzz-voice/ios, NIP-98 signed by the signed-in user over the exact URL, method and body bytes, with X-Buzz-Community. AgentCallPlugin (method channel buzz/agent_call) owns the media: the stasel/WebRTC 154.0.0 binary package pinned exactly (revision 0c0ad84d, binary checksum a2bcdda9...), an outgoing CallKit call created from a provider built at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app audio fallback when CallKit refuses, and interruption, route-change and media-services-reset handling; UIBackgroundModes audio and voip keep the call alive on the lock screen. The Dart controller follows the host's call screen feed by long-poll (asks, the open question's option taps, per-ask cancel and archive, the recap), refuses while a huddle holds the audio, and hangs up on a community switch. Hooks: one plugin property and construction in AppDelegate.swift, the plugin file, the WebRTC package reference and product in project.pbxproj and Package.resolved, the background modes and microphone string in Info.plist, and one native action plus one button in channel_detail_page.dart.", + "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", + "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", + "paths": [ + "mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved", + "mobile/ios/Runner/AgentCallPlugin.swift", + "mobile/ios/Runner/Info.plist", + "mobile/lib/features/agent_call/agent_call_api.dart", + "mobile/lib/features/agent_call/agent_call_controller.dart", + "mobile/lib/features/agent_call/agent_call_feed.dart", + "mobile/lib/features/agent_call/agent_call_media.dart", + "mobile/lib/features/agent_call/agent_call_screen.dart", + "mobile/test/features/agent_call/agent_call_test.dart" + ] + }, { "classification": "retain-generic", "owner": "Buzz messaging maintainers", diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index 170c9caccdd..8d58b6da219 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + BZZ00000000000000000030 /* AgentCallPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = BZZ00000000000000000031 /* AgentCallPlugin.swift */; }; + BZZ00000000000000000034 /* WebRTC in Frameworks */ = {isa = PBXBuildFile; productRef = BZZ00000000000000000033 /* WebRTC */; }; DAAB00000000000000000001 /* NativeTabler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAAB00000000000000000002; }; 4A71C0192F40D00100A17E02 /* MeAvatarLoader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4A71C01A2F40D00100A17E02 /* MeAvatarLoader.swift */; }; C0AF00000000000000000001 /* NativeConfirmationDialog.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0AF00000000000000000002 /* NativeConfirmationDialog.swift */; }; @@ -95,6 +97,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + BZZ00000000000000000031 /* AgentCallPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentCallPlugin.swift; sourceTree = ""; }; DAAB00000000000000000002 /* NativeTabler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeTabler.swift; sourceTree = ""; }; 4A71C01A2F40D00100A17E02 /* MeAvatarLoader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeAvatarLoader.swift; sourceTree = ""; }; C0AF00000000000000000002 /* NativeConfirmationDialog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeConfirmationDialog.swift; sourceTree = ""; }; @@ -185,6 +188,7 @@ buildActionMask = 2147483647; files = ( BZZ00000000000000000025 /* BuzzPushKit in Frameworks */, + BZZ00000000000000000034 /* WebRTC in Frameworks */, 33ADD70AB275E0EC81295559 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; @@ -290,6 +294,7 @@ 4A71C0102F40800100A17E01 /* NativeEmojiPickerModel.swift */, 4A71C0122F40900100A17E01 /* NativeEmojiPickerView.swift */, 4A71C0142F40A00100A17E01 /* NativeMessageActionSurface.swift */, + BZZ00000000000000000031 /* AgentCallPlugin.swift */, 4A71C0162F40B00100A17E01 /* HuddleMediaPlugin.swift */, 4A71C0182F40C00100A17E01 /* HuddleAudioEngine.swift */, C0AF00000000000000000002 /* NativeConfirmationDialog.swift */, @@ -373,6 +378,7 @@ name = Runner; packageProductDependencies = ( BZZ00000000000000000022 /* BuzzPushKit */, + BZZ00000000000000000033 /* WebRTC */, ); productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; @@ -432,6 +438,7 @@ mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( BZZ00000000000000000021 /* XCLocalSwiftPackageReference "BuzzPushKit" */, + BZZ00000000000000000032 /* XCRemoteSwiftPackageReference "WebRTC" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -629,6 +636,7 @@ 4A71C00F2F40800100A17E01 /* NativeEmojiPickerModel.swift in Sources */, 4A71C0112F40900100A17E01 /* NativeEmojiPickerView.swift in Sources */, 4A71C0132F40A00100A17E01 /* NativeMessageActionSurface.swift in Sources */, + BZZ00000000000000000030 /* AgentCallPlugin.swift in Sources */, 4A71C0152F40B00100A17E01 /* HuddleMediaPlugin.swift in Sources */, 4A71C0172F40C00100A17E01 /* HuddleAudioEngine.swift in Sources */, C0AF00000000000000000001 /* NativeConfirmationDialog.swift in Sources */, @@ -665,12 +673,28 @@ }; /* End XCLocalSwiftPackageReference section */ +/* Begin XCRemoteSwiftPackageReference section */ + BZZ00000000000000000032 /* XCRemoteSwiftPackageReference "WebRTC" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/stasel/WebRTC"; + requirement = { + kind = exactVersion; + version = 154.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + /* Begin XCSwiftPackageProductDependency section */ BZZ00000000000000000022 /* BuzzPushKit */ = { isa = XCSwiftPackageProductDependency; package = BZZ00000000000000000021 /* XCLocalSwiftPackageReference "BuzzPushKit" */; productName = BuzzPushKit; }; + BZZ00000000000000000033 /* WebRTC */ = { + isa = XCSwiftPackageProductDependency; + package = BZZ00000000000000000032 /* XCRemoteSwiftPackageReference "WebRTC" */; + productName = WebRTC; + }; /* End XCSwiftPackageProductDependency section */ /* Begin PBXVariantGroup section */ diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved index 81798e1ed83..7f577e354c6 100644 --- a/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -9,6 +9,15 @@ "revision" : "82699f4bdf2f075793cfa0d392eb27c59b41a3fe", "version" : "0.29.0" } + }, + { + "identity" : "webrtc", + "kind" : "remoteSourceControl", + "location" : "https://github.com/stasel/WebRTC", + "state" : { + "revision" : "0c0ad84dac6c1941c16a414dfcfba94691866e4c", + "version" : "154.0.0" + } } ], "version" : 3 diff --git a/mobile/ios/Runner/AgentCallPlugin.swift b/mobile/ios/Runner/AgentCallPlugin.swift new file mode 100644 index 00000000000..1488a5b79d6 --- /dev/null +++ b/mobile/ios/Runner/AgentCallPlugin.swift @@ -0,0 +1,541 @@ +import AVFoundation +import CallKit +import Flutter +import UIKit +import os +@preconcurrency import WebRTC + +/// Native media for 1:1 agent calls from an agent DM (`buzz/agent_call`). +/// +/// A proper voice call with the agent through its host's voice core, not a +/// huddle: one WebRTC peer connection to the host's realtime voice provider +/// (a microphone track out, the agent's voice in, and the `oai-events` data +/// channel watched only for the session closing). Dart sends the SDP offer +/// to the host, which answers it; no secret is on the phone. +/// +/// The call is an outgoing CallKit call, so it keeps going on the lock +/// screen and in other apps and the system's mute and end buttons work. It +/// is kept out of Recents. CallKit owns the audio session; WebRTC runs in +/// manual-audio mode, its audio unit starting only when CallKit activates +/// the session. If CallKit refuses, the same call runs on the app's own +/// audio session. Interruptions, route changes and media-service resets are +/// watched: when an interruption ends the session is reactivated; if audio +/// never comes back the Dart controller ends the call. +/// +/// The provider is created when the plugin is (at engine start), not at the +/// first call, mirroring the host's own phone apps. +@MainActor +final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDelegate, + RTCDataChannelDelegate +{ + private static let factory: RTCPeerConnectionFactory = { + RTCInitializeSSL() + return RTCPeerConnectionFactory( + encoderFactory: RTCDefaultVideoEncoderFactory(), + decoderFactory: RTCDefaultVideoDecoderFactory()) + }() + + private let channel: FlutterMethodChannel + private let provider: CXProvider + private let callController = CXCallController() + private let log = Logger(subsystem: "buzz", category: "agent-call") + private var observers: [NSObjectProtocol] = [] + + /// The one call: its CallKit id, and whether it runs without CallKit. + private var callId: UUID? + private var inApp = false + private var connection: RTCPeerConnection? + private var dataChannel: RTCDataChannel? + private var track: RTCAudioTrack? + private var connected = false + private var closed = true + + init(messenger: FlutterBinaryMessenger) { + channel = FlutterMethodChannel(name: "buzz/agent_call", binaryMessenger: messenger) + let configuration = CXProviderConfiguration() + configuration.supportsVideo = false + configuration.maximumCallGroups = 1 + configuration.maximumCallsPerCallGroup = 1 + configuration.supportedHandleTypes = [.generic] + configuration.includesCallsInRecents = false + provider = CXProvider(configuration: configuration) + super.init() + provider.setDelegate(self, queue: .main) + RTCAudioSessionConfiguration.setWebRTC(Self.audioConfiguration()) + let audio = RTCAudioSession.sharedInstance() + audio.useManualAudio = true + audio.isAudioEnabled = false + channel.setMethodCallHandler { [weak self] call, result in + MainActor.assumeIsolated { self?.handle(call, result: result) } + } + watchAudioSession() + } + + // MARK: Method channel + + private func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + let arguments = call.arguments as? [String: Any] ?? [:] + switch call.method { + case "begin": + let name = (arguments["agentName"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "Agent" + Task { @MainActor in await self.begin(agentName: name, result: result) } + case "accept": + guard let sdp = arguments["sdp"] as? String, !sdp.isEmpty else { + result(FlutterError(code: "invalid_arguments", message: nil, details: nil)) + return + } + Task { @MainActor in await self.accept(answer: sdp, result: result) } + case "setMuted": + setMuted(arguments["muted"] as? Bool ?? false) + result(nil) + case "end": + Task { @MainActor in + await self.end() + result(nil) + } + default: + result(FlutterMethodNotImplemented) + } + } + + private func emit(_ type: String, _ extra: [String: Any] = [:]) { + var payload = extra + payload["type"] = type + channel.invokeMethod("event", arguments: payload) + } + + // MARK: Call lifecycle + + private func begin(agentName: String, result: @escaping FlutterResult) async { + if !closed || callId != nil { + result(FlutterError(code: "call_in_progress", message: nil, details: nil)) + return + } + guard await Self.requestMicrophone() else { + result(FlutterError(code: "mic_denied", message: nil, details: nil)) + return + } + let id = UUID() + callId = id + closed = false + connected = false + let handle = CXHandle(type: .generic, value: agentName) + let action = CXStartCallAction(call: id, handle: handle) + action.isVideo = false + do { + try await request(action) + inApp = false + let update = CXCallUpdate() + update.remoteHandle = handle + update.localizedCallerName = agentName + update.hasVideo = false + update.supportsHolding = false + update.supportsGrouping = false + update.supportsUngrouping = false + update.supportsDTMF = false + provider.reportCall(with: id, updated: update) + } catch { + let nsError = error as NSError + log.error( + "CallKit refused the call: \(nsError.domain, privacy: .public) \(nsError.code, privacy: .public)" + ) + guard Self.reactivateAudio() else { + reset() + result(FlutterError(code: "audio_unavailable", message: nil, details: nil)) + return + } + inApp = true + } + do { + let sdp = try await makeOffer() + result(["sdp": sdp, "systemCallUI": inApp ? "in_app" : "callkit"]) + } catch { + await end() + result(FlutterError(code: "media_failed", message: nil, details: nil)) + } + } + + private func accept(answer: String, result: @escaping FlutterResult) async { + guard let connection, !closed, let callId else { + result(FlutterError(code: "no_call", message: nil, details: nil)) + return + } + do { + try await connection.setRemoteDescription( + RTCSessionDescription(type: .answer, sdp: answer)) + if !inApp { + provider.reportOutgoingCall(with: callId, startedConnectingAt: Date()) + } + result(nil) + } catch { + result(FlutterError(code: "media_failed", message: nil, details: nil)) + } + } + + private func setMuted(_ muted: Bool) { + track?.isEnabled = !muted + guard let callId, !inApp else { return } + Task { @MainActor in + try? await self.request(CXSetMutedCallAction(call: callId, muted: muted)) + } + } + + /// Hangs up: closes the media and ends the system call. + private func end() async { + let id = callId + let wasInApp = inApp + closeMedia() + // Our own hang-up: CallKit's end action that follows is not news. + closed = true + guard let id else { + reset() + return + } + if wasInApp { + endInAppAudio() + reset() + return + } + do { + try await request(CXEndCallAction(call: id)) + } catch { + provider.reportCall(with: id, endedAt: Date(), reason: .remoteEnded) + } + reset() + } + + /// The call ended from the network side: tell CallKit, then Dart. + private func endedRemotely(_ type: String) { + guard !closed, let id = callId else { return } + closeMedia() + if inApp { + endInAppAudio() + } else { + provider.reportCall( + with: id, endedAt: Date(), reason: type == "connectionLost" ? .failed : .remoteEnded) + } + reset() + emit(type) + } + + private func reset() { + callId = nil + inApp = false + connected = false + closed = true + } + + private func endInAppAudio() { + let rtc = RTCAudioSession.sharedInstance() + rtc.isAudioEnabled = false + rtc.lockForConfiguration() + try? rtc.setActive(false) + rtc.unlockForConfiguration() + } + + // MARK: WebRTC + + private func makeOffer() async throws -> String { + let configuration = RTCConfiguration() + configuration.sdpSemantics = .unifiedPlan + configuration.bundlePolicy = .maxBundle + configuration.rtcpMuxPolicy = .require + let constraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil) + guard + let connection = Self.factory.peerConnection( + with: configuration, constraints: constraints, delegate: self) + else { throw MediaError.noConnection } + self.connection = connection + let audioConstraints = RTCMediaConstraints( + mandatoryConstraints: nil, + optionalConstraints: ["googEchoCancellation": "true", "googNoiseSuppression": "true"]) + let source = Self.factory.audioSource(with: audioConstraints) + let track = Self.factory.audioTrack(with: source, trackId: "mic") + self.track = track + connection.add(track, streamIds: ["call"]) + dataChannel = connection.dataChannel( + forLabel: "oai-events", configuration: RTCDataChannelConfiguration()) + dataChannel?.delegate = self + let offerConstraints = RTCMediaConstraints( + mandatoryConstraints: ["OfferToReceiveAudio": "true", "OfferToReceiveVideo": "false"], + optionalConstraints: nil) + let offer = try await connection.offer(for: offerConstraints) + try await connection.setLocalDescription(offer) + return offer.sdp + } + + private func closeMedia() { + dataChannel?.delegate = nil + dataChannel?.close() + connection?.close() + dataChannel = nil + connection = nil + track = nil + } + + enum MediaError: Error { + case noConnection + } + + private func peerConnected() { + guard !closed, !connected, let callId else { return } + connected = true + if !inApp { + provider.reportOutgoingCall(with: callId, connectedAt: Date()) + } + emit("connected") + } + + // MARK: Audio session + + private func watchAudioSession() { + let center = NotificationCenter.default + let session = AVAudioSession.sharedInstance() + observers = [ + center.addObserver( + forName: AVAudioSession.interruptionNotification, object: session, queue: .main + ) { [weak self] note in + let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt + let began = raw.flatMap(AVAudioSession.InterruptionType.init(rawValue:)) == .began + MainActor.assumeIsolated { self?.interruption(began: began) } + }, + center.addObserver( + forName: AVAudioSession.routeChangeNotification, object: session, queue: .main + ) { [weak self] note in + let reason = note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt ?? 0 + MainActor.assumeIsolated { + guard let self, self.connected else { return } + self.log.info("audio route changed, reason \(reason, privacy: .public)") + } + }, + center.addObserver( + forName: AVAudioSession.mediaServicesWereResetNotification, object: session, + queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { + guard let self, self.connected else { return } + self.log.notice("audio media services were reset") + self.emit("interrupted") + self.resumeAudio() + } + }, + ] + } + + private func interruption(began: Bool) { + guard connected else { return } + log.notice("audio interruption \(began ? "began" : "ended", privacy: .public)") + if began { + emit("interrupted") + } else { + resumeAudio() + } + } + + /// Reactivates the session, retrying each second; Dart ends the call if + /// audio never comes back. + private func resumeAudio() { + let id = callId + Task { @MainActor [weak self] in + for _ in 0..<6 { + guard let self, self.callId == id, self.connected else { return } + if Self.reactivateAudio() { + self.log.notice("audio resumed after interruption") + self.emit("resumed") + return + } + try? await Task.sleep(nanoseconds: 1_000_000_000) + } + self?.log.error("audio didn't resume after interruption") + } + } + + nonisolated static func reactivateAudio() -> Bool { + let rtc = RTCAudioSession.sharedInstance() + rtc.lockForConfiguration() + defer { rtc.unlockForConfiguration() } + do { + try rtc.setConfiguration(audioConfiguration(), active: true) + } catch { + return false + } + rtc.isAudioEnabled = false + rtc.isAudioEnabled = true + return true + } + + /// `playAndRecord` in `voiceChat` mode (echo cancellation), on the + /// speaker unless headphones or Bluetooth are connected. + nonisolated static func audioConfiguration() -> RTCAudioSessionConfiguration { + let configuration = RTCAudioSessionConfiguration.webRTC() + configuration.category = AVAudioSession.Category.playAndRecord.rawValue + configuration.mode = AVAudioSession.Mode.voiceChat.rawValue + configuration.categoryOptions = [.defaultToSpeaker, .allowBluetoothHFP] + return configuration + } + + static func requestMicrophone() async -> Bool { + if #available(iOS 17.0, *) { + switch AVAudioApplication.shared.recordPermission { + case .granted: return true + case .denied: return false + default: return await AVAudioApplication.requestRecordPermission() + } + } + let session = AVAudioSession.sharedInstance() + switch session.recordPermission { + case .granted: return true + case .denied: return false + default: + return await withCheckedContinuation { continuation in + session.requestRecordPermission { continuation.resume(returning: $0) } + } + } + } + + private func request(_ action: CXCallAction) async throws { + let transaction = CXTransaction(action: action) + try await withCheckedThrowingContinuation { + (continuation: CheckedContinuation) in + callController.request(transaction) { error in + if let error { + continuation.resume(throwing: error) + } else { + continuation.resume() + } + } + } + } + + // MARK: CXProviderDelegate (delivered on the main queue) + + nonisolated func providerDidReset(_ provider: CXProvider) { + MainActor.assumeIsolated { self.endedRemotely("connectionLost") } + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXStartCallAction) { + // The category before CallKit activates the session. + try? AVAudioSession.sharedInstance().setCategory( + .playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP]) + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXEndCallAction) { + let uuid = action.callUUID + MainActor.assumeIsolated { + // The system's end button (or ours, after `end` already closed it). + if self.callId == uuid, !self.closed { + self.closeMedia() + self.reset() + self.emit("hangup") + } + } + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) { + let uuid = action.callUUID + let muted = action.isMuted + MainActor.assumeIsolated { + guard self.callId == uuid else { return } + self.track?.isEnabled = !muted + self.emit("muted", ["muted": muted]) + } + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) { + action.fail() + } + + nonisolated func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) { + let rtc = RTCAudioSession.sharedInstance() + rtc.audioSessionDidActivate(audioSession) + rtc.lockForConfiguration() + try? rtc.setConfiguration(Self.audioConfiguration()) + rtc.unlockForConfiguration() + rtc.isAudioEnabled = true + MainActor.assumeIsolated { + if self.connected { self.emit("resumed") } + } + } + + nonisolated func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) { + let rtc = RTCAudioSession.sharedInstance() + rtc.audioSessionDidDeactivate(audioSession) + rtc.isAudioEnabled = false + MainActor.assumeIsolated { + if self.connected, !self.closed { + self.log.notice("audio session deactivated mid-call") + self.emit("interrupted") + } + } + } + + // MARK: RTCPeerConnectionDelegate + + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didChange newState: RTCPeerConnectionState + ) { + switch newState { + case .connected: + Task { @MainActor in self.peerConnected() } + case .failed: + Task { @MainActor in self.endedRemotely("connectionLost") } + case .disconnected: + // `disconnected` can recover; give it a few seconds. + Task { @MainActor in + try? await Task.sleep(nanoseconds: 5_000_000_000) + if let connection = self.connection, connection.connectionState != .connected { + self.endedRemotely("connectionLost") + } + } + default: + break + } + } + + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState + ) {} + nonisolated func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) + {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream + ) {} + nonisolated func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState + ) {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState + ) {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate + ) {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate] + ) {} + nonisolated func peerConnection( + _ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel + ) {} + + // MARK: RTCDataChannelDelegate + + nonisolated func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) { + guard dataChannel.readyState == .closed else { return } + Task { @MainActor in self.endedRemotely("remoteClosed") } + } + + /// Only the event type matters (`session.closed`); nothing from the + /// channel is kept. + nonisolated func dataChannel( + _ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer + ) { + guard !buffer.isBinary, + let event = try? JSONSerialization.jsonObject(with: buffer.data) as? [String: Any], + event["type"] as? String == "session.closed" + else { return } + Task { @MainActor in self.endedRemotely("remoteClosed") } + } +} diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 91129724034..4c0a90de445 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -46,6 +46,7 @@ import os.log private var nativeProfileTextEditorCoordinator: NativeProfileTextEditorCoordinator? private var nativeMessageActionSurfaceSupportChannel: FlutterMethodChannel? private var huddleMediaPlugin: HuddleMediaPlugin? + private var agentCallPlugin: AgentCallPlugin? override func application( _ application: UIApplication, @@ -65,6 +66,8 @@ import os.log let messenger = engineBridge.applicationRegistrar.messenger() huddleMediaPlugin = HuddleMediaPlugin(messenger: messenger) + // 1:1 agent calls: the CallKit provider exists from launch, not the first call. + agentCallPlugin = MainActor.assumeIsolated { AgentCallPlugin(messenger: messenger) } if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "BuzzIosNavigationBar") { registrar.register(IosNavigationBarFactory(messenger: messenger, parent: registrar.viewController), withId: "buzz/ios_navigation_bar") } diff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plist index 5dfde907785..8c658f8eb54 100644 --- a/mobile/ios/Runner/Info.plist +++ b/mobile/ios/Runner/Info.plist @@ -52,7 +52,7 @@ NSCameraUsageDescription Buzz uses the camera to take profile photos and animated avatars, attach photos to messages, and scan QR codes for device pairing. NSMicrophoneUsageDescription - Buzz needs microphone access so you can speak in Huddles and record voice notes. + Buzz needs microphone access so you can speak in Huddles, record voice notes and call your agents. NSPhotoLibraryUsageDescription Buzz uses your photo library to select profile photos and images to attach to messages. NSPhotoLibraryAddUsageDescription @@ -84,6 +84,11 @@ + UIBackgroundModes + + audio + voip + UIApplicationSupportsIndirectInputEvents UILaunchStoryboardName diff --git a/mobile/lib/features/agent_call/agent_call_api.dart b/mobile/lib/features/agent_call/agent_call_api.dart new file mode 100644 index 00000000000..33b8ec72da8 --- /dev/null +++ b/mobile/lib/features/agent_call/agent_call_api.dart @@ -0,0 +1,252 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:uuid/uuid.dart'; + +import '../../shared/guest_access/guest_access_client.dart'; +import '../../shared/relay/relay.dart'; +import 'agent_call_feed.dart'; + +/// The agent host's call routes for this app (`/api/buzz-voice/ios`), +/// every request NIP-98 signed by the signed-in user (exact URL with query, +/// method, and the SHA-256 of the exact body bytes) with `X-Buzz-Community`. +/// The host starts a call only from the caller's private 1:1 DM with the +/// agent and serves each call to its caller only. +const agentCallMount = '/api/buzz-voice/ios'; + +/// The feed long-poll waits up to 20 s on the host. +const _requestTimeout = Duration(seconds: 35); + +class AgentCallApiException implements Exception { + const AgentCallApiException(this.status, this.code); + + final int? status; + final String? code; + + @override + String toString() => 'AgentCallApiException($status, $code)'; +} + +class AgentCallStart { + const AgentCallStart({ + required this.callId, + required this.sdpAnswer, + required this.executeUntil, + }); + + final String callId; + final String sdpAnswer; + final DateTime? executeUntil; +} + +enum AgentCallStopOutcome { stopped, nothingToStop } + +String newAgentCallIdempotencyKey() => const Uuid().v4(); + +/// The call routes' origin: the guest route's origin (same host). +String? agentCallOrigin(GuestAccessRoute route) { + final uri = Uri.tryParse(route.baseUrl); + if (uri == null || uri.host.isEmpty) return null; + return uri.origin; +} + +class AgentCallApi { + AgentCallApi({ + required this.origin, + required this.communityId, + required this.nsec, + http.Client? httpClient, + }) : _client = httpClient ?? http.Client(); + + final String origin; + final String communityId; + final String nsec; + final http.Client _client; + + void close() => _client.close(); + + Future _send(String method, String path, [Object? body]) async { + final url = '$origin$agentCallMount/$path'; + final bytes = body == null ? const [] : utf8.encode(jsonEncode(body)); + final request = http.Request(method, Uri.parse(url)) + ..followRedirects = false + ..headers['Accept'] = 'application/json' + ..headers['X-Buzz-Community'] = communityId + ..headers['Authorization'] = buildNip98AuthHeader( + method: method, + url: url, + bodyBytes: bytes, + nsec: nsec, + ); + if (body != null) { + request.headers['Content-Type'] = 'application/json'; + request.bodyBytes = bytes; + } + http.Response response; + try { + final streamed = await _client.send(request).timeout(_requestTimeout); + response = await http.Response.fromStream( + streamed, + ).timeout(_requestTimeout); + } on TimeoutException { + throw const AgentCallApiException(null, 'voice_route_timeout'); + } on http.ClientException { + throw const AgentCallApiException(null, 'network'); + } + Object? decoded; + if (response.bodyBytes.isNotEmpty) { + try { + decoded = jsonDecode(utf8.decode(response.bodyBytes)); + } on FormatException { + decoded = null; + } + } + if (response.statusCode < 200 || response.statusCode >= 300) { + final code = decoded is Map && decoded['error'] is String + ? decoded['error'] as String + : null; + throw AgentCallApiException(response.statusCode, code); + } + return decoded; + } + + String _call(String callId) => 'calls/${Uri.encodeComponent(callId)}'; + + Future start({ + required String agentPubkey, + required String channelId, + required String sdpOffer, + required String clientTapAt, + required String systemCallUI, + }) async { + final body = await _send('POST', 'calls', { + 'agentPubkey': agentPubkey, + 'channelId': channelId, + 'sdpOffer': sdpOffer, + 'clientTapAt': clientTapAt, + 'clientDiagnostics': {'systemCallUI': systemCallUI}, + }); + if (body is! Map || + body['callId'] is! String || + body['sdpAnswer'] is! String) { + throw const AgentCallApiException(null, 'response_invalid'); + } + final until = body['executeUntil']; + return AgentCallStart( + callId: body['callId'] as String, + sdpAnswer: body['sdpAnswer'] as String, + executeUntil: until is String ? DateTime.tryParse(until) : null, + ); + } + + Future end(String callId, String reason) async { + await _send('POST', '${_call(callId)}/end', {'reason': reason}); + } + + Future stopWork(String callId) async { + try { + await _send('POST', '${_call(callId)}/stop', { + 'idempotencyKey': newAgentCallIdempotencyKey(), + }); + return AgentCallStopOutcome.stopped; + } on AgentCallApiException catch (error) { + if (error.code == 'voice_nothing_to_stop') { + return AgentCallStopOutcome.nothingToStop; + } + rethrow; + } + } + + /// Feed v2 long-poll: the whole snapshot, or null when unchanged after + /// waiting (the second value is then the unchanged `rev`). + Future<(AgentCallFeed?, String?)> feed( + String callId, { + String? rev, + int waitSeconds = 20, + }) async { + final query = { + 'rev': ?rev, + 'wait': '${waitSeconds.clamp(0, 20)}', + }; + final body = await _send( + 'GET', + '${_call(callId)}/feed?${Uri(queryParameters: query).query}', + ); + if (body is! Map) { + throw const AgentCallApiException(null, 'response_invalid'); + } + if (body['unchanged'] == true) { + return (null, body['rev'] is String ? body['rev'] as String : rev); + } + final feed = AgentCallFeed.tryParse(body); + if (feed == null) { + throw const AgentCallApiException(null, 'response_invalid'); + } + return (feed, feed.rev); + } + + Future answerQuestion({ + required String callId, + required String humanAskId, + required String? questionId, + required int optionIndex, + }) async { + await _send( + 'POST', + '${_call(callId)}/human-asks/${Uri.encodeComponent(humanAskId)}/answer', + { + 'questionId': ?questionId, + 'optionIndex': optionIndex, + 'idempotencyKey': newAgentCallIdempotencyKey(), + }, + ); + } + + Future cancelAsk(String callId, String askKey) async { + await _send('POST', '${_call(callId)}/asks/cancel', { + 'askKey': askKey, + 'idempotencyKey': newAgentCallIdempotencyKey(), + }); + } + + Future archiveAsk(String callId, String askKey) async { + await _send('POST', '${_call(callId)}/asks/state', { + 'askKey': askKey, + 'action': 'archive', + 'idempotencyKey': newAgentCallIdempotencyKey(), + }); + } +} + +/// A plain sentence for a failed request (codes only, never content). +String describeAgentCallError(Object error) { + final code = error is AgentCallApiException ? error.code : null; + final status = error is AgentCallApiException ? error.status : null; + switch (code) { + case 'voice_call_in_progress': + return "You're already on a call. Hang up there first."; + case 'voice_buzz_dm_required': + return 'Calls work only in your private DM with this agent.'; + case 'voice_buzz_dm_unverified': + return "Couldn't confirm this DM with the relay. Try again."; + case 'caller_not_allowed': + return "Your account isn't linked for calls with this agent."; + case 'agent_not_found': + return "This agent can't take calls."; + case 'voice_disabled': + return 'Calls are turned off for this agent.'; + case 'voice_conversation_unavailable': + return "This agent can't open a conversation with you yet."; + case 'rate_limited': + case 'voice_daily_limit': + return "You've reached the call limit for now. Try again later."; + case 'voice_route_timeout': + case 'network': + return "Couldn't reach the call service. Check your connection."; + case 'nip98_expired': + return "The call request expired. Check your phone's clock."; + } + if (status == 401) return "Couldn't sign the call request. Try again."; + return 'Calls are unavailable right now. Try again.'; +} diff --git a/mobile/lib/features/agent_call/agent_call_controller.dart b/mobile/lib/features/agent_call/agent_call_controller.dart new file mode 100644 index 00000000000..a66ec39a5dd --- /dev/null +++ b/mobile/lib/features/agent_call/agent_call_controller.dart @@ -0,0 +1,482 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/community/community_provider.dart'; +import '../../shared/guest_access/guest_access_client.dart'; +import '../../shared/huddle/huddle.dart'; +import '../../shared/relay/relay.dart'; +import 'agent_call_api.dart'; +import 'agent_call_feed.dart'; +import 'agent_call_media.dart'; + +/// The app's one 1:1 agent call (the host allows one per person): the same +/// voice core and call screen contract as the host's own phone apps. Media +/// is native (`AgentCallMedia`); the host answers the offer only from the +/// caller's private DM with the agent. The call screen follows the host's +/// feed long-poll (wait 20 s, backing off 1 s → 15 s), and after hang-up +/// until the recap is written (at most 90 s). +/// +/// Hang-up ends the call only; the agent's work goes on and its answers +/// land in the DM. Stop stops the work. + +enum AgentCallPhase { idle, connecting, live, ending, ended, error } + +enum AgentCallStopStatus { idle, stopping, stopped, nothingToStop, failed } + +@immutable +class AgentCallState { + const AgentCallState({ + this.phase = AgentCallPhase.idle, + this.agentPubkey, + this.agentName, + this.channelId, + this.callId, + this.connectedAt, + this.muted = false, + this.stop = AgentCallStopStatus.idle, + this.error, + this.endReason, + this.feed, + }); + + final AgentCallPhase phase; + final String? agentPubkey; + final String? agentName; + final String? channelId; + final String? callId; + final DateTime? connectedAt; + final bool muted; + final AgentCallStopStatus stop; + final String? error; + final String? endReason; + final AgentCallFeed? feed; + + bool get isBusy => + phase == AgentCallPhase.connecting || + phase == AgentCallPhase.live || + phase == AgentCallPhase.ending; + + AgentCallState copyWith({ + AgentCallPhase? phase, + String? callId, + DateTime? connectedAt, + bool? muted, + AgentCallStopStatus? stop, + String? error, + String? endReason, + AgentCallFeed? feed, + }) => AgentCallState( + phase: phase ?? this.phase, + agentPubkey: agentPubkey, + agentName: agentName, + channelId: channelId, + callId: callId ?? this.callId, + connectedAt: connectedAt ?? this.connectedAt, + muted: muted ?? this.muted, + stop: stop ?? this.stop, + error: error ?? this.error, + endReason: endReason ?? this.endReason, + feed: feed ?? this.feed, + ); +} + +/// The native media seam (overridden in tests). +final agentCallMediaProvider = Provider( + (ref) => MethodChannelAgentCallMedia(), +); + +/// The host's call routes for the active community and signed-in key. +final agentCallApiProvider = Provider((ref) { + final route = ref.watch(guestAccessRouteProvider); + final nsec = ref.watch(relayConfigProvider.select((config) => config.nsec)); + if (route == null || nsec == null || nsec.isEmpty) return null; + final origin = agentCallOrigin(route); + if (origin == null) return null; + final api = AgentCallApi( + origin: origin, + communityId: route.communityId, + nsec: nsec, + ); + ref.onDispose(api.close); + return api; +}); + +/// Whether a huddle holds the audio now (a call waits for it to end). +final agentCallHuddleBusyProvider = Provider( + (ref) => ref.watch(huddleSessionProvider).isInSession, +); + +final agentCallProvider = NotifierProvider( + AgentCallNotifier.new, +); + +@visibleForTesting +Duration agentCallFeedRetryDelay(int failures) => Duration( + milliseconds: math.min( + 15000, + 1000 * math.pow(2, math.max(0, failures - 1)).toInt(), + ), +); + +const _endedDismiss = Duration(seconds: 4); +const _stopStatusReset = Duration(seconds: 4); +const _feedAfterEnd = Duration(seconds: 90); +const _resumeTimeout = Duration(seconds: 8); + +class AgentCallNotifier extends Notifier { + int _attempt = 0; + int _feedToken = 0; + AgentCallApi? _api; + StreamSubscription? _events; + final List _timers = []; + Timer? _resumeTimer; + + @override + AgentCallState build() { + final media = ref.watch(agentCallMediaProvider); + _events = media.events.listen(_onMediaEvent); + final unregister = ref + .read(communityTransitionProvider) + .register(() async => reset()); + ref.onDispose(() { + unregister(); + _events?.cancel(); + _clearTimers(); + }); + return const AgentCallState(); + } + + AgentCallMedia get _media => ref.read(agentCallMediaProvider); + + void _later(Duration delay, void Function() callback) { + late final Timer timer; + timer = Timer(delay, () { + _timers.remove(timer); + callback(); + }); + _timers.add(timer); + } + + void _clearTimers() { + for (final timer in _timers) { + timer.cancel(); + } + _timers.clear(); + _resumeTimer?.cancel(); + _resumeTimer = null; + } + + /// Starts a call from the caller's 1:1 DM with the agent. + Future start({ + required String agentPubkey, + required String channelId, + required String agentName, + }) async { + if (state.isBusy) return; + _clearTimers(); + _feedToken++; + final attempt = ++_attempt; + final tapAt = DateTime.now().toUtc().toIso8601String(); + state = AgentCallState( + phase: AgentCallPhase.connecting, + agentPubkey: agentPubkey, + agentName: agentName, + channelId: channelId, + ); + if (ref.read(agentCallHuddleBusyProvider)) { + _fail('Leave the huddle first, then call.'); + return; + } + final api = ref.read(agentCallApiProvider); + if (api == null) { + _fail("Calls aren't available for this community."); + return; + } + _api = api; + + AgentCallOffer offer; + try { + offer = await _media.begin(agentName: agentName); + } on AgentCallMediaException catch (error) { + if (attempt == _attempt) _fail(_describeMediaError(error.code)); + return; + } + if (attempt != _attempt) { + unawaited(_media.end()); + return; + } + + AgentCallStart started; + try { + started = await api.start( + agentPubkey: agentPubkey, + channelId: channelId, + sdpOffer: offer.sdp, + clientTapAt: tapAt, + systemCallUI: offer.systemCallUI, + ); + } catch (error) { + if (attempt == _attempt) { + unawaited(_media.end()); + _fail(describeAgentCallError(error)); + } + return; + } + if (attempt != _attempt) { + // Hung up while the host was answering: end the call it opened. + unawaited(_quietEnd(api, started.callId, 'hangup')); + return; + } + state = state.copyWith(callId: started.callId); + _followFeed(api, started.callId); + + try { + await _media.accept(started.sdpAnswer); + } on AgentCallMediaException { + if (attempt == _attempt) { + unawaited(_quietEnd(api, started.callId, 'media_failed')); + unawaited(_media.end()); + _fail("The call connected but audio couldn't start. Try again."); + } + return; + } + final until = started.executeUntil; + if (until != null) { + _later(until.difference(DateTime.now()), () { + if (attempt == _attempt && state.isBusy) { + unawaited(_finish('time_limit')); + } + }); + } + } + + void _onMediaEvent(AgentCallMediaEventData data) { + switch (data.event) { + case AgentCallMediaEvent.connected: + if (state.phase == AgentCallPhase.connecting) { + state = state.copyWith( + phase: AgentCallPhase.live, + connectedAt: DateTime.now(), + ); + } + case AgentCallMediaEvent.remoteClosed: + unawaited(_finish('remote', mediaClosed: true)); + case AgentCallMediaEvent.connectionLost: + if (state.phase == AgentCallPhase.connecting) { + final api = _api; + final callId = state.callId; + if (api != null && callId != null) { + unawaited(_quietEnd(api, callId, 'media_failed')); + } + _fail( + "Audio couldn't connect. A firewall or VPN may be blocking calls.", + ); + } else { + unawaited(_finish('connection_lost', mediaClosed: true)); + } + case AgentCallMediaEvent.hangup: + unawaited(_finish('hangup', mediaClosed: true)); + case AgentCallMediaEvent.muted: + if (state.isBusy && data.muted != null) { + state = state.copyWith(muted: data.muted); + } + case AgentCallMediaEvent.interrupted: + if (state.phase != AgentCallPhase.live) return; + _resumeTimer?.cancel(); + final attempt = _attempt; + _resumeTimer = Timer(_resumeTimeout, () { + if (attempt == _attempt && state.phase == AgentCallPhase.live) { + unawaited(_finish('media_failed')); + } + }); + case AgentCallMediaEvent.resumed: + _resumeTimer?.cancel(); + _resumeTimer = null; + } + } + + void _followFeed(AgentCallApi api, String callId) { + final token = ++_feedToken; + unawaited(_runFeed(api, token, callId)); + } + + Future _runFeed(AgentCallApi api, int token, String callId) async { + String? rev; + var failures = 0; + DateTime? until; + while (token == _feedToken) { + final ended = !state.isBusy; + if (ended) { + final feed = state.feed; + if (feed != null && !feed.wantsMore) return; + until ??= DateTime.now().add(_feedAfterEnd); + if (DateTime.now().isAfter(until)) return; + } + try { + final (feed, nextRev) = await api.feed( + callId, + rev: rev, + waitSeconds: ended ? 5 : 20, + ); + failures = 0; + if (token != _feedToken) return; + rev = nextRev ?? rev; + if (feed != null && feed.callId == callId) { + state = state.copyWith(feed: feed); + } + } on AgentCallApiException catch (error) { + if (token != _feedToken) return; + if (error.status == 404 || error.status == 403 || error.status == 401) { + return; + } + failures++; + await Future.delayed(agentCallFeedRetryDelay(failures)); + } catch (_) { + if (token != _feedToken) return; + failures++; + await Future.delayed(agentCallFeedRetryDelay(failures)); + } + } + } + + void toggleMute() { + if (!state.isBusy) return; + final muted = !state.muted; + state = state.copyWith(muted: muted); + unawaited(_media.setMuted(muted)); + } + + /// Stops the agent's current work; the call goes on. + Future stopAgentWork() async { + final api = _api; + final callId = state.callId; + if (api == null || callId == null) return; + if (state.stop == AgentCallStopStatus.stopping) return; + final attempt = _attempt; + state = state.copyWith(stop: AgentCallStopStatus.stopping); + AgentCallStopStatus next; + try { + next = switch (await api.stopWork(callId)) { + AgentCallStopOutcome.stopped => AgentCallStopStatus.stopped, + AgentCallStopOutcome.nothingToStop => AgentCallStopStatus.nothingToStop, + }; + } catch (_) { + next = AgentCallStopStatus.failed; + } + if (attempt != _attempt) return; + state = state.copyWith(stop: next); + _later(_stopStatusReset, () { + if (attempt == _attempt && state.stop == next) { + state = state.copyWith(stop: AgentCallStopStatus.idle); + } + }); + } + + /// Hangs up. The agent keeps working; its answers land in the DM. + Future hangUp() => _finish('hangup'); + + Future answerQuestion({ + required String humanAskId, + required String? questionId, + required int optionIndex, + }) async { + final api = _api; + final callId = state.callId; + if (api == null || callId == null) return; + await api.answerQuestion( + callId: callId, + humanAskId: humanAskId, + questionId: questionId, + optionIndex: optionIndex, + ); + } + + Future cancelAsk(String askKey) async { + final api = _api; + final callId = state.callId; + if (api == null || callId == null) return; + await api.cancelAsk(callId, askKey); + } + + Future archiveAsk(String askKey) async { + final api = _api; + final callId = state.callId; + if (api == null || callId == null) return; + await api.archiveAsk(callId, askKey); + } + + Future _finish(String reason, {bool mediaClosed = false}) async { + if (!state.isBusy) return; + final callId = state.callId; + final api = _api; + final attempt = ++_attempt; + _clearTimers(); + if (!mediaClosed) unawaited(_media.end()); + state = state.copyWith(phase: AgentCallPhase.ending, endReason: reason); + if (api != null && callId != null) await _quietEnd(api, callId, reason); + if (attempt != _attempt) return; + state = state.copyWith(phase: AgentCallPhase.ended); + // A call with something on its screen keeps it (the recap) until + // closed; an empty one goes away. + _later(_endedDismiss, () { + if (attempt == _attempt && + state.phase == AgentCallPhase.ended && + (state.feed?.asks.isEmpty ?? true)) { + dismiss(); + } + }); + } + + Future _quietEnd(AgentCallApi api, String callId, String reason) async { + try { + await api.end(callId, reason); + } catch (_) { + // The host's sweep ends a call nobody holds. + } + } + + void _fail(String message) { + _attempt++; + _feedToken++; + _clearTimers(); + state = state.copyWith(phase: AgentCallPhase.error, error: message); + } + + /// Closes the error or "Call ended" screen. + void dismiss() { + if (state.isBusy) return; + _attempt++; + _feedToken++; + _clearTimers(); + state = const AgentCallState(); + } + + /// A community or account switch: hang up and clear the screen. + void reset() { + final api = _api; + final callId = state.callId; + if (state.isBusy) { + unawaited(_media.end()); + if (api != null && callId != null) { + unawaited(_quietEnd(api, callId, 'community_changed')); + } + } + _attempt++; + _feedToken++; + _clearTimers(); + _api = null; + state = const AgentCallState(); + } + + String _describeMediaError(String code) => switch (code) { + 'mic_denied' => + 'Microphone access is off for Buzz. Allow it in Settings, then call again.', + 'call_in_progress' => "You're already on a call.", + 'audio_unavailable' => "The phone's audio is busy. Try again.", + 'unsupported' => "Calls aren't available on this device.", + _ => "The call couldn't be set up. Try again.", + }; +} diff --git a/mobile/lib/features/agent_call/agent_call_feed.dart b/mobile/lib/features/agent_call/agent_call_feed.dart new file mode 100644 index 00000000000..d24c0e1ee4d --- /dev/null +++ b/mobile/lib/features/agent_call/agent_call_feed.dart @@ -0,0 +1,249 @@ +/// The agent host's call screen feed (contract v1 plus the additive v2 +/// fields): the whole current state of the caller's own call, keyed by ask. +/// Status is the host's ledger, never inferred here; every v2 field is +/// optional. +library; + +String? _string(Object? value) => value is String ? value : null; + +String? _nested(Object? value, String key) => + value is Map ? _string(value[key]) : null; + +List> _maps(Object? value) => value is List + ? value.whereType>().toList(growable: false) + : const []; + +const _terminal = {'answered', 'not_answered', 'failed'}; + +class AgentCallLink { + const AgentCallLink({required this.label, required this.url}); + + final String label; + final String url; +} + +/// Only https links are opened from the call screen. +String? safeHttpsUrl(String? url) { + if (url == null) return null; + final uri = Uri.tryParse(url); + return uri != null && uri.scheme == 'https' && uri.host.isNotEmpty + ? uri.toString() + : null; +} + +class AgentCallAsk { + const AgentCallAsk({ + required this.askKey, + required this.kind, + required this.text, + required this.status, + required this.statusReason, + required this.title, + required this.nowLine, + required this.resultText, + required this.links, + required this.archivedAt, + required this.pinnedAt, + required this.cancelledAt, + required this.canCancel, + }); + + final String askKey; + final String kind; + final String text; + final String status; + final String? statusReason; + final String? title; + final String? nowLine; + final String? resultText; + final List links; + final String? archivedAt; + final String? pinnedAt; + final String? cancelledAt; + final bool? canCancel; + + bool get isTerminal => _terminal.contains(status); + + static AgentCallAsk? tryParse(Map json) { + final key = _string(json['askKey']) ?? _string(json['utteranceId']); + final status = _string(json['status']); + if (key == null || status == null) return null; + final actions = json['actions']; + return AgentCallAsk( + askKey: key, + kind: _string(json['kind']) ?? 'ask', + text: _string(json['text']) ?? '', + status: status, + statusReason: _string(json['statusReason']), + title: _nested(json['title'], 'text'), + nowLine: + _nested(json['nowLine'], 'text') ?? _nested(json['progress'], 'text'), + resultText: _nested(json['result'], 'text'), + links: [ + for (final link in _maps(json['links'])) + if (safeHttpsUrl(_string(link['url'])) case final url?) + AgentCallLink(label: _string(link['title']) ?? url, url: url), + ], + archivedAt: _string(json['archivedAt']), + pinnedAt: _string(json['pinnedAt']), + cancelledAt: _string(json['cancelledAt']), + canCancel: actions is Map && actions['cancel'] is bool + ? actions['cancel'] as bool + : null, + ); + } + + /// A short title: the host's title, else the caller's first words. + String get displayTitle { + final host = title?.trim(); + if (host != null && host.isNotEmpty) return host; + final words = text.trim().split(RegExp(r'\s+')); + final short = words.take(8).join(' '); + return words.length > 8 ? '$short…' : short; + } + + String get statusLabel { + if (cancelledAt != null) return 'Cancelled'; + return switch (status) { + 'answered' => 'Done', + 'not_answered' => 'Not done', + 'failed' => 'Failed', + _ => 'Working', + }; + } + + /// The live line while working; null once terminal. + String? get liveLine => isTerminal ? null : nowLine; +} + +class AgentCallQuestion { + const AgentCallQuestion({ + required this.id, + required this.question, + required this.options, + }); + + final String? id; + final String question; + final List<(int, String)> options; +} + +class AgentCallHumanAsk { + const AgentCallHumanAsk({ + required this.humanAskId, + required this.state, + required this.questions, + }); + + final String humanAskId; + final String state; + final List questions; + + bool get isOpen => state == 'open' && questions.isNotEmpty; + + static AgentCallHumanAsk? tryParse(Object? value) { + if (value is! Map) return null; + final id = _string(value['humanAskId']); + if (id == null) return null; + return AgentCallHumanAsk( + humanAskId: id, + state: _string(value['state']) ?? 'closed', + questions: [ + for (final question in _maps(value['questions'])) + if (_string(question['question']) case final text?) + AgentCallQuestion( + id: _string(question['id']), + question: text, + options: [ + for (final option in _maps(question['options'])) + if (option['index'] is int && + _string(option['label']) != null) + (option['index'] as int, option['label'] as String), + ], + ), + ], + ); + } +} + +class AgentCallFeed { + const AgentCallFeed({ + required this.callId, + required this.rev, + required this.isLive, + required this.contract, + required this.destinationLabel, + required this.asks, + required this.humanAsk, + required this.recapWritten, + required this.recapSummary, + required this.recapLinks, + }); + + final String callId; + final String rev; + final bool isLive; + final int contract; + final String? destinationLabel; + final List asks; + final AgentCallHumanAsk? humanAsk; + + /// Whether the post-call recap exists (`summary` may still be null while + /// it is being written). + final bool recapWritten; + final String? recapSummary; + final List recapLinks; + + bool get isV2 => contract >= 2; + + static AgentCallFeed? tryParse(Map json) { + final callId = _string(json['callId']); + final rev = _string(json['rev']); + final asks = json['asks']; + if (callId == null || rev == null || asks is! List) return null; + final recap = json['recap']; + return AgentCallFeed( + callId: callId, + rev: rev, + isLive: json['state'] == 'live', + contract: json['contract'] is int ? json['contract'] as int : 1, + destinationLabel: _nested(json['destination'], 'label'), + asks: [for (final ask in _maps(asks)) ?AgentCallAsk.tryParse(ask)], + humanAsk: AgentCallHumanAsk.tryParse(json['humanAsk']), + recapWritten: recap is Map, + recapSummary: _nested(recap, 'summary'), + recapLinks: recap is Map + ? [ + for (final link in _maps(recap['links'])) + if (safeHttpsUrl(_string(link['url'])) case final url?) + AgentCallLink(label: _string(link['label']) ?? url, url: url), + ] + : const [], + ); + } + + /// Answers fold under their question; archived asks are listed apart; + /// pinned asks first (newest pin first), then oldest first. + List get shownAsks { + final shown = asks + .where((ask) => ask.kind == 'ask' && ask.archivedAt == null) + .toList(); + final pinned = shown.where((ask) => ask.pinnedAt != null).toList() + ..sort((a, b) => b.pinnedAt!.compareTo(a.pinnedAt!)); + return [...pinned, ...shown.where((ask) => ask.pinnedAt == null)]; + } + + int get archivedCount => + asks.where((ask) => ask.kind == 'ask' && ask.archivedAt != null).length; + + bool get anyWorking => + asks.any((ask) => ask.kind == 'ask' && !ask.isTerminal); + + AgentCallHumanAsk? get openQuestion => + humanAsk != null && humanAsk!.isOpen ? humanAsk : null; + + /// Whether to keep following after hang-up: v2 until the recap summary + /// is written. + bool get wantsMore => + isLive || (isV2 && (!recapWritten || recapSummary == null)); +} diff --git a/mobile/lib/features/agent_call/agent_call_media.dart b/mobile/lib/features/agent_call/agent_call_media.dart new file mode 100644 index 00000000000..8f0d5722296 --- /dev/null +++ b/mobile/lib/features/agent_call/agent_call_media.dart @@ -0,0 +1,156 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; + +const agentCallMethodChannelName = 'buzz/agent_call'; + +/// What the native side reports during a call. +enum AgentCallMediaEvent { + /// Audio connected. + connected, + + /// The voice session closed from the far side. + remoteClosed, + + /// The connection failed or did not recover. + connectionLost, + + /// The system's end button (CallKit) hung up. + hangup, + + /// The system's mute button changed (see [AgentCallMediaEventData.muted]). + muted, + + /// Another call or app took the audio; it may come back. + interrupted, + + /// The audio came back. + resumed, +} + +class AgentCallMediaEventData { + const AgentCallMediaEventData(this.event, {this.muted}); + + final AgentCallMediaEvent event; + final bool? muted; +} + +class AgentCallOffer { + const AgentCallOffer({required this.sdp, required this.systemCallUI}); + + final String sdp; + + /// `callkit`, or `in_app` when CallKit refused and the app runs the audio. + final String systemCallUI; +} + +class AgentCallMediaException implements Exception { + const AgentCallMediaException(this.code); + + final String code; + + @override + String toString() => 'AgentCallMediaException($code)'; +} + +/// The phone's media for a 1:1 agent call: microphone, the WebRTC offer and +/// answer, mute, and the system call (CallKit). Native in `AgentCallPlugin`. +abstract interface class AgentCallMedia { + Stream get events; + + /// Asks for the microphone, starts the system call and returns the offer. + Future begin({required String agentName}); + + Future accept(String sdpAnswer); + + Future setMuted(bool muted); + + /// Closes the media and ends the system call. + Future end(); +} + +final class MethodChannelAgentCallMedia implements AgentCallMedia { + MethodChannelAgentCallMedia({MethodChannel? channel}) + : _channel = channel ?? const MethodChannel(agentCallMethodChannelName) { + _channel.setMethodCallHandler(_handle); + } + + final MethodChannel _channel; + final _events = StreamController.broadcast(); + + @override + Stream get events => _events.stream; + + Future _handle(MethodCall call) async { + if (call.method != 'event') return null; + final arguments = call.arguments; + if (arguments is! Map) return null; + final event = switch (arguments['type']) { + 'connected' => AgentCallMediaEvent.connected, + 'remoteClosed' => AgentCallMediaEvent.remoteClosed, + 'connectionLost' => AgentCallMediaEvent.connectionLost, + 'hangup' => AgentCallMediaEvent.hangup, + 'muted' => AgentCallMediaEvent.muted, + 'interrupted' => AgentCallMediaEvent.interrupted, + 'resumed' => AgentCallMediaEvent.resumed, + _ => null, + }; + if (event == null) return null; + final muted = arguments['muted']; + _events.add( + AgentCallMediaEventData(event, muted: muted is bool ? muted : null), + ); + return null; + } + + @override + Future begin({required String agentName}) async { + try { + final result = await _channel.invokeMapMethod('begin', { + 'agentName': agentName, + }); + final sdp = result?['sdp']; + if (sdp is! String || sdp.isEmpty) { + throw const AgentCallMediaException('media_failed'); + } + final ui = result?['systemCallUI']; + return AgentCallOffer( + sdp: sdp, + systemCallUI: ui is String ? ui : 'callkit', + ); + } on PlatformException catch (error) { + throw AgentCallMediaException(error.code); + } on MissingPluginException { + throw const AgentCallMediaException('unsupported'); + } + } + + @override + Future accept(String sdpAnswer) async { + try { + await _channel.invokeMethod('accept', {'sdp': sdpAnswer}); + } on PlatformException catch (error) { + throw AgentCallMediaException(error.code); + } + } + + @override + Future setMuted(bool muted) async { + try { + await _channel.invokeMethod('setMuted', {'muted': muted}); + } on PlatformException { + // The track state is best effort; the screen still shows the choice. + } + } + + @override + Future end() async { + try { + await _channel.invokeMethod('end'); + } on PlatformException { + // Already ended. + } on MissingPluginException { + // No native side (tests, other platforms). + } + } +} diff --git a/mobile/lib/features/agent_call/agent_call_screen.dart b/mobile/lib/features/agent_call/agent_call_screen.dart new file mode 100644 index 00000000000..c4511246af8 --- /dev/null +++ b/mobile/lib/features/agent_call/agent_call_screen.dart @@ -0,0 +1,473 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../shared/theme/buzz_icons.dart'; +import '../../shared/theme/theme.dart'; +import '../../shared/widgets/ios_navigation_bar.dart'; +import 'agent_call_api.dart'; +import 'agent_call_controller.dart'; +import 'agent_call_feed.dart'; + +/// Starts (or returns to) the call with the agent of a 1:1 DM and shows the +/// call screen. The host checks that this is the caller's own private DM +/// with the agent before it answers. +Future openAgentCall( + BuildContext context, + WidgetRef ref, { + required String agentPubkey, + required String channelId, + required String agentName, +}) async { + final call = ref.read(agentCallProvider); + final notifier = ref.read(agentCallProvider.notifier); + if (!call.isBusy) { + if (call.phase == AgentCallPhase.ended || + call.phase == AgentCallPhase.error) { + notifier.dismiss(); + } + unawaited( + notifier.start( + agentPubkey: agentPubkey, + channelId: channelId, + agentName: agentName, + ), + ); + } + await Navigator.of(context).push( + MaterialPageRoute( + fullscreenDialog: true, + builder: (_) => const AgentCallScreen(), + ), + ); +} + +IosNavigationAction agentCallNavigationAction( + BuildContext context, + WidgetRef ref, { + required String agentPubkey, + required String channelId, + required String agentName, +}) => IosNavigationAction( + label: 'Call $agentName', + symbol: 'phone', + onPressed: () => unawaited( + openAgentCall( + context, + ref, + agentPubkey: agentPubkey, + channelId: channelId, + agentName: agentName, + ), + ), +); + +/// The "Call" button in a 1:1 agent DM header. +class AgentCallButton extends ConsumerWidget { + const AgentCallButton({ + super.key, + required this.agentPubkey, + required this.channelId, + required this.agentName, + }); + + final String agentPubkey; + final String channelId; + final String agentName; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final call = ref.watch(agentCallProvider); + final onThisCall = call.isBusy && call.agentPubkey == agentPubkey; + final label = onThisCall ? 'Back to the call' : 'Call $agentName'; + return IconButton( + key: const ValueKey('agent-call-button'), + color: onThisCall ? context.appColors.success : context.colors.primary, + tooltip: label, + onPressed: () => unawaited( + openAgentCall( + context, + ref, + agentPubkey: agentPubkey, + channelId: channelId, + agentName: agentName, + ), + ), + icon: Icon(Icons.call_outlined, size: 22, semanticLabel: label), + ); + } +} + +String _statusLine(AgentCallState call, int seconds) => switch (call.phase) { + AgentCallPhase.connecting => 'Calling…', + AgentCallPhase.live => + '${seconds ~/ 60}:${(seconds % 60).toString().padLeft(2, '0')}', + AgentCallPhase.ending => 'Hanging up…', + AgentCallPhase.ended => switch (call.endReason) { + 'time_limit' => 'Call ended (time limit)', + 'connection_lost' || 'media_failed' => 'Call ended (connection lost)', + _ => 'Call ended', + }, + AgentCallPhase.error => "Couldn't call", + AgentCallPhase.idle => '', +}; + +/// The call screen: who, how long, mute, hang up, stop the agent's work, +/// the call's asks with the open question's options, and after hang-up the +/// recap. Closing the screen during a call keeps the call going. +class AgentCallScreen extends HookConsumerWidget { + const AgentCallScreen({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final call = ref.watch(agentCallProvider); + final notifier = ref.read(agentCallProvider.notifier); + final tick = useState(0); + useEffect(() { + if (call.phase != AgentCallPhase.live) return null; + final timer = Timer.periodic( + const Duration(seconds: 1), + (_) => tick.value++, + ); + return timer.cancel; + }, [call.phase]); + useEffect(() { + if (call.phase == AgentCallPhase.idle) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (context.mounted) Navigator.of(context).maybePop(); + }); + } + return null; + }, [call.phase]); + final seconds = call.connectedAt == null + ? 0 + : DateTime.now().difference(call.connectedAt!).inSeconds; + final feed = call.feed; + final live = call.phase == AgentCallPhase.live; + final busy = call.isBusy; + + return Scaffold( + appBar: AppBar( + leading: IconButton( + tooltip: busy ? 'Minimize' : 'Close', + icon: Icon(busy ? Icons.expand_more : Icons.close), + onPressed: () { + if (!busy) notifier.dismiss(); + Navigator.of(context).maybePop(); + }, + ), + title: Column( + children: [ + Text(call.agentName ?? 'Agent'), + Semantics( + liveRegion: true, + child: Text( + _statusLine(call, seconds), + style: context.textTheme.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ], + ), + centerTitle: true, + ), + body: SafeArea( + child: ListView( + padding: const EdgeInsets.all(Grid.gutter), + children: [ + if (call.phase == AgentCallPhase.error) + Text(call.error ?? "The call couldn't start.") + else ...[ + if (feed?.openQuestion case final question?) + _QuestionCard(question: question), + if (feed != null) + for (final ask in feed.shownAsks) + _AskTile(ask: ask, live: live, v2: feed.isV2), + if ((feed?.shownAsks.isEmpty ?? true) && live) + Text( + 'Talk to ${call.agentName ?? 'the agent'}. What you ask shows up here.', + style: context.textTheme.bodyMedium?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + if ((feed?.archivedCount ?? 0) > 0) + Padding( + padding: const EdgeInsets.only(top: Grid.xxs), + child: Text('Archived (${feed!.archivedCount})'), + ), + if (call.phase == AgentCallPhase.ended && feed != null) + _Recap(feed: feed), + if (feed?.destinationLabel case final label?) + Padding( + padding: const EdgeInsets.only(top: Grid.xs), + child: Text( + 'Answers go to $label.', + style: context.textTheme.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + ), + ], + ], + ), + ), + bottomNavigationBar: busy + ? SafeArea( + child: Padding( + padding: const EdgeInsets.all(Grid.xs), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + IconButton.filledTonal( + tooltip: call.muted ? 'Unmute' : 'Mute', + isSelected: call.muted, + onPressed: live ? notifier.toggleMute : null, + icon: Icon(call.muted ? BuzzIcons.micOff : BuzzIcons.mic), + ), + if (live && (feed?.anyWorking ?? false)) + _StopButton(status: call.stop), + IconButton.filled( + tooltip: 'Hang up (the agent keeps working)', + style: IconButton.styleFrom( + backgroundColor: context.colors.error, + foregroundColor: context.colors.onError, + ), + onPressed: () => unawaited(notifier.hangUp()), + icon: const Icon(BuzzIcons.phoneOff), + ), + ], + ), + ), + ) + : null, + ); + } +} + +class _StopButton extends ConsumerWidget { + const _StopButton({required this.status}); + + final AgentCallStopStatus status; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final label = switch (status) { + AgentCallStopStatus.stopping => 'Stopping…', + AgentCallStopStatus.stopped => 'Stopped', + AgentCallStopStatus.nothingToStop => 'Nothing to stop', + AgentCallStopStatus.failed => "Couldn't stop", + AgentCallStopStatus.idle => 'Stop the agent', + }; + return TextButton.icon( + onPressed: status == AgentCallStopStatus.stopping + ? null + : () => + unawaited(ref.read(agentCallProvider.notifier).stopAgentWork()), + icon: const Icon(Icons.stop_circle_outlined), + label: Text(label), + ); + } +} + +Future _run(BuildContext context, Future Function() action) async { + try { + await action(); + } catch (error) { + if (!context.mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(describeAgentCallError(error)))); + } +} + +class _QuestionCard extends HookConsumerWidget { + const _QuestionCard({required this.question}); + + final AgentCallHumanAsk question; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final sending = useState(false); + final notifier = ref.read(agentCallProvider.notifier); + return Card( + margin: const EdgeInsets.only(bottom: Grid.twelve), + child: Padding( + padding: const EdgeInsets.all(Grid.twelve), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final item in question.questions) ...[ + Text(item.question, style: context.textTheme.bodyLarge), + const SizedBox(height: Grid.xxs), + Wrap( + spacing: Grid.xxs, + runSpacing: Grid.half, + children: [ + for (final (index, label) in item.options) + FilledButton.tonal( + onPressed: sending.value + ? null + : () async { + sending.value = true; + await _run( + context, + () => notifier.answerQuestion( + humanAskId: question.humanAskId, + questionId: item.id, + optionIndex: index, + ), + ); + if (context.mounted) sending.value = false; + }, + child: Text(label), + ), + ], + ), + ], + ], + ), + ), + ); + } +} + +class _AskTile extends ConsumerWidget { + const _AskTile({required this.ask, required this.live, required this.v2}); + + final AgentCallAsk ask; + final bool live; + + /// Per-ask controls (cancel, archive) are feed v2 routes. + final bool v2; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final notifier = ref.read(agentCallProvider.notifier); + final liveLine = ask.liveLine; + final canCancel = + v2 && + live && + ask.cancelledAt == null && + (ask.canCancel ?? !ask.isTerminal); + final result = ask.resultText?.trim() ?? ''; + return Card( + margin: const EdgeInsets.only(bottom: Grid.xxs), + child: Padding( + padding: const EdgeInsets.all(Grid.twelve), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Text( + ask.displayTitle, + style: context.textTheme.titleSmall, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + if (canCancel) + IconButton( + tooltip: 'Cancel this ask', + icon: const Icon(Icons.close, size: 20), + onPressed: () => + _run(context, () => notifier.cancelAsk(ask.askKey)), + ), + if (v2) + IconButton( + tooltip: 'Archive (the work goes on)', + icon: const Icon(Icons.archive_outlined, size: 20), + onPressed: () => + _run(context, () => notifier.archiveAsk(ask.askKey)), + ), + ], + ), + Text( + liveLine == null + ? ask.statusLabel + : '${ask.statusLabel} · $liveLine', + style: context.textTheme.bodySmall?.copyWith( + color: context.colors.onSurfaceVariant, + ), + ), + if (result.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: Grid.half), + child: Text( + result, + maxLines: 6, + overflow: TextOverflow.ellipsis, + ), + ) + else if (ask.statusReason case final reason?) + if (ask.status == 'not_answered' || ask.status == 'failed') + Padding( + padding: const EdgeInsets.only(top: Grid.half), + child: Text(reason), + ), + _Links(links: ask.links), + ], + ), + ), + ); + } +} + +class _Recap extends StatelessWidget { + const _Recap({required this.feed}); + + final AgentCallFeed feed; + + @override + Widget build(BuildContext context) { + if (!feed.isV2) return const SizedBox.shrink(); + final summary = feed.recapSummary; + return Padding( + padding: const EdgeInsets.only(top: Grid.xs), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Recap', style: context.textTheme.titleSmall), + const SizedBox(height: Grid.half), + Text(summary ?? 'Writing the recap…'), + _Links(links: feed.recapLinks), + ], + ), + ); + } +} + +class _Links extends StatelessWidget { + const _Links({required this.links}); + + final List links; + + @override + Widget build(BuildContext context) { + if (links.isEmpty) return const SizedBox.shrink(); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final link in links.take(10)) + TextButton( + onPressed: () { + final uri = Uri.tryParse(link.url); + if (uri != null) { + unawaited(launchUrl(uri, mode: LaunchMode.externalApplication)); + } + }, + child: Text( + link.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ); + } +} diff --git a/mobile/lib/features/channels/channel_detail_page.dart b/mobile/lib/features/channels/channel_detail_page.dart index 420cd2c1aeb..8a9d1531d5d 100644 --- a/mobile/lib/features/channels/channel_detail_page.dart +++ b/mobile/lib/features/channels/channel_detail_page.dart @@ -1,5 +1,6 @@ import 'agent_dm/agent_dm_scope.dart'; import 'agent_dm/agent_dm_sessions_button.dart'; +import '../agent_call/agent_call_screen.dart'; import '../../shared/agent_commands/agent_prewarm.dart'; import 'agent_reply_handoff.dart'; import 'huddle_timeline.dart'; @@ -753,6 +754,14 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { channel: resolvedChannel, agentPubkey: sessionsAgent, ), + if (dmAgent != null) + agentCallNavigationAction( + context, + ref, + agentPubkey: dmAgent, + channelId: resolvedChannel.id, + agentName: dmHeader?.label ?? resolvedChannel.name, + ), ], iconColor: context.colors.primary, titleContentHeight: appBarTitleContentHeight, @@ -778,6 +787,12 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget { channel: resolvedChannel, agentPubkey: sessionsAgent, ), + if (dmAgent != null) + AgentCallButton( + agentPubkey: dmAgent, + channelId: resolvedChannel.id, + agentName: dmHeader?.label ?? resolvedChannel.name, + ), ], ), body: Stack( diff --git a/mobile/test/features/agent_call/agent_call_test.dart b/mobile/test/features/agent_call/agent_call_test.dart new file mode 100644 index 00000000000..7a1f391d7bc --- /dev/null +++ b/mobile/test/features/agent_call/agent_call_test.dart @@ -0,0 +1,320 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:buzz/features/agent_call/agent_call_api.dart'; +import 'package:buzz/features/agent_call/agent_call_controller.dart'; +import 'package:buzz/features/agent_call/agent_call_feed.dart'; +import 'package:buzz/features/agent_call/agent_call_media.dart'; +import 'package:buzz/shared/guest_access/guest_access_client.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:nostr/nostr.dart' as nostr; + +const _call = '0192a6b0-0000-7000-8000-0000000000ac'; +const _channel = '0192a6b0-0000-7000-8000-0000000000af'; +final _agent = 'b' * 64; + +Map _feed({String state = 'live', List? asks}) => { + 'callId': _call, + 'rev': 'r1', + 'state': state, + 'agent': {'id': 'a', 'name': 'Alfred'}, + 'destination': {'kind': 'buzz_dm', 'label': 'your Buzz chat with Alfred'}, + 'asks': asks ?? const [], + 'humanAsk': null, + 'endedAt': null, +}; + +class _FakeMedia implements AgentCallMedia { + final events$ = StreamController.broadcast(); + final calls = []; + String? answer; + + @override + Stream get events => events$.stream; + + @override + Future begin({required String agentName}) async { + calls.add('begin:$agentName'); + return const AgentCallOffer(sdp: 'v=0 offer', systemCallUI: 'callkit'); + } + + @override + Future accept(String sdpAnswer) async { + answer = sdpAnswer; + } + + @override + Future setMuted(bool muted) async => calls.add('muted:$muted'); + + @override + Future end() async => calls.add('end'); +} + +void main() { + group('AgentCallApi', () { + test('starts from the DM, signed over the exact body', () async { + final keys = nostr.Keys.generate(); + http.Request? sent; + final api = AgentCallApi( + origin: 'https://api.example.com', + communityId: 'chat.example.com', + nsec: keys.nsec, + httpClient: MockClient((request) async { + sent = request; + return http.Response( + jsonEncode({ + 'callId': _call, + 'sdpAnswer': 'v=0 answer', + 'executeUntil': null, + }), + 201, + ); + }), + ); + final started = await api.start( + agentPubkey: _agent, + channelId: _channel, + sdpOffer: 'v=0 offer', + clientTapAt: '2026-10-23T12:00:00.000Z', + systemCallUI: 'callkit', + ); + expect(started.callId, _call); + expect( + sent!.url.toString(), + 'https://api.example.com/api/buzz-voice/ios/calls', + ); + expect(sent!.headers['X-Buzz-Community'], 'chat.example.com'); + final body = jsonDecode(sent!.body) as Map; + expect(body['agentPubkey'], _agent); + expect(body['channelId'], _channel); + expect(body['clientDiagnostics'], {'systemCallUI': 'callkit'}); + final event = + jsonDecode( + utf8.decode( + base64.decode( + sent!.headers['Authorization']!.substring('Nostr '.length), + ), + ), + ) + as Map; + final tags = (event['tags'] as List).cast>(); + expect( + tags.firstWhere((tag) => tag.first == 'payload')[1], + sha256.convert(sent!.bodyBytes).toString(), + ); + expect( + tags.firstWhere((tag) => tag.first == 'u')[1], + 'https://api.example.com/api/buzz-voice/ios/calls', + ); + }); + + test('host refusals become plain sentences', () async { + final api = AgentCallApi( + origin: 'https://api.example.com', + communityId: 'chat.example.com', + nsec: nostr.Keys.generate().nsec, + httpClient: MockClient( + (_) async => http.Response('{"error":"voice_buzz_dm_required"}', 409), + ), + ); + await expectLater( + api.start( + agentPubkey: _agent, + channelId: _channel, + sdpOffer: 'v', + clientTapAt: 'x', + systemCallUI: 'callkit', + ), + throwsA( + isA() + .having((e) => e.status, 'status', 409) + .having((e) => e.code, 'code', 'voice_buzz_dm_required'), + ), + ); + expect( + describeAgentCallError( + const AgentCallApiException(409, 'voice_buzz_dm_required'), + ), + contains('private DM'), + ); + }); + + test('the origin is the guest route host', () { + expect( + agentCallOrigin( + const GuestAccessRoute( + baseUrl: 'https://api.example.com/api/buzz-guest/v1', + communityId: 'chat.example.com', + ), + ), + 'https://api.example.com', + ); + }); + }); + + group('AgentCallFeed', () { + test('orders pinned asks first and keeps archived apart', () { + Map ask( + String key, { + String? pinnedAt, + String? archivedAt, + }) => { + 'utteranceId': key, + 'kind': 'ask', + 'text': 'do $key', + 'status': 'submitted', + 'pinnedAt': pinnedAt, + 'archivedAt': archivedAt, + 'links': const [], + }; + final feed = AgentCallFeed.tryParse( + _feed( + asks: [ + ask('a'), + ask('b', pinnedAt: '2026-10-23T12:01:00Z'), + ask('c', archivedAt: '2026-10-23T12:02:00Z'), + ask('d', pinnedAt: '2026-10-23T12:03:00Z'), + ], + ), + )!; + expect(feed.shownAsks.map((ask) => ask.askKey), ['d', 'b', 'a']); + expect(feed.archivedCount, 1); + expect(feed.anyWorking, isTrue); + }); + + test('opens only https links and waits for the recap after the call', () { + final ended = AgentCallFeed.tryParse({ + ..._feed( + state: 'ended', + asks: [ + { + 'utteranceId': 'a', + 'kind': 'ask', + 'text': 'x', + 'status': 'answered', + 'links': [ + {'url': 'https://example.com/deck', 'title': 'Deck'}, + {'url': 'javascript:alert(1)', 'title': 'Bad'}, + ], + }, + ], + ), + 'contract': 2, + 'recap': {'summary': null}, + })!; + expect(ended.asks.single.links.map((link) => link.url), [ + 'https://example.com/deck', + ]); + expect(ended.wantsMore, isTrue); + final written = AgentCallFeed.tryParse({ + ..._feed(state: 'ended'), + 'contract': 2, + 'recap': {'summary': '- Sent'}, + })!; + expect(written.wantsMore, isFalse); + }); + }); + + group('AgentCallNotifier', () { + late _FakeMedia media; + late List requests; + late ProviderContainer container; + + setUp(() { + media = _FakeMedia(); + requests = []; + final client = MockClient((request) async { + requests.add(request); + if (request.url.path.endsWith('/calls')) { + return http.Response( + jsonEncode({ + 'callId': _call, + 'sdpAnswer': 'v=0 answer', + 'executeUntil': null, + }), + 201, + ); + } + if (request.url.path.endsWith('/feed')) { + if (request.url.queryParameters['rev'] == 'r1') { + // A long-poll with nothing new. + await Future.delayed(const Duration(milliseconds: 50)); + return http.Response('{"rev":"r1","unchanged":true}', 200); + } + return http.Response(jsonEncode(_feed()), 200); + } + return http.Response('{}', 200); + }); + container = ProviderContainer( + overrides: [ + agentCallMediaProvider.overrideWithValue(media), + agentCallHuddleBusyProvider.overrideWithValue(false), + agentCallApiProvider.overrideWithValue( + AgentCallApi( + origin: 'https://api.example.com', + communityId: 'chat.example.com', + nsec: nostr.Keys.generate().nsec, + httpClient: client, + ), + ), + ], + ); + }); + + tearDown(() => container.dispose()); + + test( + 'a call connects, follows the feed and hangs up without stopping work', + () async { + final notifier = container.read(agentCallProvider.notifier); + await notifier.start( + agentPubkey: _agent, + channelId: _channel, + agentName: 'Alfred', + ); + expect(media.calls, ['begin:Alfred']); + expect(media.answer, 'v=0 answer'); + media.events$.add( + const AgentCallMediaEventData(AgentCallMediaEvent.connected), + ); + await Future.delayed(const Duration(milliseconds: 10)); + expect(container.read(agentCallProvider).phase, AgentCallPhase.live); + expect(container.read(agentCallProvider).feed?.callId, _call); + + await notifier.hangUp(); + final state = container.read(agentCallProvider); + expect(state.phase, AgentCallPhase.ended); + expect(media.calls, contains('end')); + final paths = requests.map((request) => request.url.path).toList(); + expect(paths, contains('/api/buzz-voice/ios/calls/$_call/end')); + expect(paths.where((path) => path.endsWith('/stop')), isEmpty); + notifier.dismiss(); + }, + ); + + test('a huddle in progress keeps the call from starting', () async { + final busy = ProviderContainer( + overrides: [ + agentCallMediaProvider.overrideWithValue(media), + agentCallHuddleBusyProvider.overrideWithValue(true), + ], + ); + addTearDown(busy.dispose); + await busy + .read(agentCallProvider.notifier) + .start(agentPubkey: _agent, channelId: _channel, agentName: 'Alfred'); + expect(busy.read(agentCallProvider).phase, AgentCallPhase.error); + expect(media.calls, isEmpty); + }); + + test('feed retries back off from 1 s to 15 s', () { + expect(agentCallFeedRetryDelay(1), const Duration(seconds: 1)); + expect(agentCallFeedRetryDelay(3), const Duration(seconds: 4)); + expect(agentCallFeedRetryDelay(9), const Duration(seconds: 15)); + }); + }); +} From 368e89276c4aa35a02514f2d069044f083d97286 Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Fri, 23 Oct 2026 08:40:37 -0700 Subject: [PATCH 4/7] fix(agent-call): one audio owner, signed-URL integrity, timeouts and caps Review fixes for 1:1 agent calls on desktop and iOS. - One audio owner per platform. Desktop: a call refuses while a huddle is active or starting (probe from the audio-owning HuddleProvider, then the native huddle state, before and after the mic opens); startHuddle/joinHuddle refuse while a call is busy (the huddle is refused, the call is never ended for it). iOS: the call holds agentCallAudioBusyProvider; HuddleSessionNotifier.join and MobileHuddleController._start refuse on it; the call re-checks the huddle after the native call is up; HuddleMediaPlugin never prepares, reactivates or deactivates the AVAudioSession while a call holds it. - Desktop native request: parse the URL once, check its normalised path, sign and send that same URL; ask ids reject escapes of dot, slash and backslash; answers capped by declared length and while read; the voice URL override and the HTTP-loopback allowance are debug-only. - Connect timeout (20 s) ends a still-connecting call as media_failed and closes the mic, on both platforms. - Desktop: a superseded mic request stops only its own stream; a call hung up while the offer is made never reaches the host. - iOS: peer and data-channel events act only for the current peer connection; CallKit name trimmed and capped; response cap shared with the hosted API client; in-call banner without CallKit; the Call button shows on iOS only. - Feed links show their host; no desktop Call button for agents managed on this device. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- .../src-tauri/src/commands/guest_access.rs | 14 +- .../src/extensions/agent_voice/mod.rs | 141 +++++++++--- .../lib/agentCallController.test.mjs | 135 +++++++++++- .../agent-call/lib/agentCallController.ts | 163 +++++++++++++- .../agent-call/ui/AgentCallButton.tsx | 13 +- .../features/agent-call/ui/AgentCallDock.tsx | 15 +- desktop/src/features/huddle/HuddleContext.tsx | 20 ++ docs/kiingo-fork-inventory.json | 12 +- mobile/ios/Runner/AgentCallPlugin.swift | 51 ++++- mobile/ios/Runner/HuddleMediaPlugin.swift | 19 +- .../features/agent_call/agent_call_api.dart | 35 ++- .../agent_call/agent_call_controller.dart | 59 ++++- .../agent_call/agent_call_screen.dart | 36 ++- .../channels/mobile_huddle_controller.dart | 4 + .../guest_access/guest_access_client.dart | 6 +- .../lib/shared/huddle/agent_call_audio.dart | 22 ++ mobile/lib/shared/huddle/huddle.dart | 1 + mobile/lib/shared/huddle/huddle_session.dart | 13 ++ .../features/agent_call/agent_call_test.dart | 206 +++++++++++++++++- 19 files changed, 891 insertions(+), 74 deletions(-) create mode 100644 mobile/lib/shared/huddle/agent_call_audio.dart diff --git a/desktop/src-tauri/src/commands/guest_access.rs b/desktop/src-tauri/src/commands/guest_access.rs index f09ece6fc14..5fca29e29b7 100644 --- a/desktop/src-tauri/src/commands/guest_access.rs +++ b/desktop/src-tauri/src/commands/guest_access.rs @@ -60,17 +60,21 @@ pub(crate) fn community_id_for_relay(relay_url: &str) -> String { .unwrap_or_default() } -/// HTTPS, or HTTP on loopback for local development (same rule as buzz-acp). +/// HTTPS, or HTTP on loopback in debug builds for local development (same +/// rule as buzz-acp). Release builds accept HTTPS only. pub(crate) fn acceptable_base_url(url: &str) -> bool { let Ok(parsed) = url::Url::parse(url) else { return false; }; match parsed.scheme() { "https" => true, - "http" => matches!( - parsed.host_str(), - Some("localhost") | Some("127.0.0.1") | Some("[::1]") | Some("::1") - ), + "http" => { + cfg!(debug_assertions) + && matches!( + parsed.host_str(), + Some("localhost") | Some("127.0.0.1") | Some("[::1]") | Some("::1") + ) + } _ => false, } } diff --git a/desktop/src-tauri/src/extensions/agent_voice/mod.rs b/desktop/src-tauri/src/extensions/agent_voice/mod.rs index d89e155f428..d4c6f5fa6cc 100644 --- a/desktop/src-tauri/src/extensions/agent_voice/mod.rs +++ b/desktop/src-tauri/src/extensions/agent_voice/mod.rs @@ -4,14 +4,17 @@ //! phone apps), not a huddle: audio runs WebRTC between this webview and the //! host's realtime voice provider, and the host answers the SDP offer. This //! module carries the host's call routes (`/api/buzz-voice/desktop/…`, -//! the origin taken from the guest route URL, or +//! the origin taken from the guest route URL, or in debug builds only //! `BUZZ_DESKTOP_AGENT_VOICE_URL`): //! //! - every request is NIP-98 (kind 27235, exact URL with query, method and //! the SHA-256 of the exact body bytes) signed by the signed-in user, with //! `X-Buzz-Community`, so the key never reaches the webview; //! - only the call routes are reachable (start, view, feed long-poll, end, -//! stop, answers and the per-ask routes, preferences), nothing else; +//! stop, answers and the per-ask routes, preferences), nothing else; the +//! request URL is parsed once, its normalised path checked, and that same +//! URL is signed and sent; +//! - answers are capped at 2 MiB (declared length first, then while read); //! - the answer is returned as `{ status, body }` for every HTTP status, so //! the webview can show the host's error codes; transport failures are //! errors. @@ -48,13 +51,39 @@ fn is_uuid(value: &str) -> bool { }) } +/// A human-ask id path segment: `[A-Za-z0-9._:-]` and percent escapes of +/// printable characters other than `.`, `/` and `\` (so no escape can turn +/// into traversal once the host decodes it), never only dots. fn is_ask_id(value: &str) -> bool { - !value.is_empty() - && value.len() <= 190 - && !value.bytes().all(|b| b == b'.') - && value - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b':' | b'-' | b'%')) + if value.is_empty() || value.len() > 190 || value.bytes().all(|b| b == b'.') { + return false; + } + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + let byte = bytes[index]; + if byte == b'%' { + let Some(hex) = value.get(index + 1..index + 3) else { + return false; + }; + if !hex.bytes().all(|h| h.is_ascii_hexdigit()) { + return false; + } + let Ok(decoded) = u8::from_str_radix(hex, 16) else { + return false; + }; + if !decoded.is_ascii_graphic() || matches!(decoded, b'.' | b'/' | b'\\') { + return false; + } + index += 3; + continue; + } + if !(byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')) { + return false; + } + index += 1; + } + true } /// The call route `path` (relative to the mount) if it is one this command @@ -114,8 +143,27 @@ fn voice_origin(override_url: Option, guest_route: Option) -> Op (origin != "null").then_some(origin) } -fn request_url(origin: &str, path: &str) -> String { - format!("{}{MOUNT}/{path}", origin.trim_end_matches('/')) +/// The one URL that is both signed and sent: parsed once, and only if its +/// normalised path and query are exactly the allowed route under the mount. +fn request_url(origin: &str, path: &str) -> Option { + let raw = format!("{}{MOUNT}/{path}", origin.trim_end_matches('/')); + let url = url::Url::parse(&raw).ok()?; + let (route, query) = match path.split_once('?') { + Some((route, query)) => (route, Some(query)), + None => (path, None), + }; + (url.path() == format!("{MOUNT}/{route}") && url.query() == query && url.fragment().is_none()) + .then_some(url) +} + +/// `BUZZ_DESKTOP_AGENT_VOICE_URL` points development builds at another host; +/// release builds always use the guest route's origin. +fn voice_url_override() -> Option { + if cfg!(debug_assertions) { + std::env::var("BUZZ_DESKTOP_AGENT_VOICE_URL").ok() + } else { + None + } } /// One signed request to the host's call routes as the signed-in user. @@ -140,18 +188,20 @@ pub async fn agent_voice_request( if method == "GET" && body.is_some() { return Err(error(None, "body_not_allowed")); } - let origin = voice_origin( - std::env::var("BUZZ_DESKTOP_AGENT_VOICE_URL").ok(), - guest_route_url(), - ) - .ok_or_else(|| error(None, "voice_route_unavailable"))?; + let origin = voice_origin(voice_url_override(), guest_route_url()) + .ok_or_else(|| error(None, "voice_route_unavailable"))?; let community_id = community_id_for_relay(&relay_ws_url_with_override(&state)); if community_id.is_empty() { return Err(error(None, "community_invalid")); } let keys = state.signing_keys()?; - let url = request_url(&origin, &path); - let authorization = nip98_header(&keys, &method, &url, body.as_deref().map(str::as_bytes))?; + let url = request_url(&origin, &path).ok_or_else(|| error(None, "path_not_allowed"))?; + let authorization = nip98_header( + &keys, + &method, + url.as_str(), + body.as_deref().map(str::as_bytes), + )?; let client = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .timeout(REQUEST_TIMEOUT) @@ -160,7 +210,7 @@ pub async fn agent_voice_request( let http_method = reqwest::Method::from_bytes(method.as_bytes()) .map_err(|_| error(None, "method_invalid"))?; let mut request = client - .request(http_method, &url) + .request(http_method, url) .header("Accept", "application/json") .header("Authorization", authorization) .header("X-Buzz-Community", community_id); @@ -182,13 +232,24 @@ pub async fn agent_voice_request( ) })?; let status = response.status().as_u16(); - let bytes = response - .bytes() - .await - .map_err(|_| error(Some(status), "response_unreadable"))?; - if bytes.len() > MAX_RESPONSE_BYTES { + if response + .content_length() + .is_some_and(|length| length > MAX_RESPONSE_BYTES as u64) + { return Err(error(Some(status), "response_too_large")); } + let mut response = response; + let mut bytes = Vec::new(); + while let Some(chunk) = response + .chunk() + .await + .map_err(|_| error(Some(status), "response_unreadable"))? + { + if bytes.len() + chunk.len() > MAX_RESPONSE_BYTES { + return Err(error(Some(status), "response_too_large")); + } + bytes.extend_from_slice(&chunk); + } let body = if bytes.is_empty() { Value::Null } else { @@ -216,6 +277,16 @@ mod tests { assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/q:1-a/answer")).is_some()); assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/q%3A1/answer")).is_some()); assert!(allowed_path("POST", &format!("calls/{CALL}/human-asks/../answer")).is_none()); + // Escapes that decode to traversal or a separator, and bad escapes. + for ask in [ + "%2e%2e", "%2E%2e", "a%2fb", "a%2Fb", "a%5cb", "a%5C", "%2e", "a%", "a%4", "a%+1", + "a%00", + ] { + assert!( + allowed_path("POST", &format!("calls/{CALL}/human-asks/{ask}/answer")).is_none(), + "{ask}" + ); + } assert!(allowed_path("PUT", "preferences").is_some()); // Anything else, another method, a query off the feed, or traversal. assert!(allowed_path("GET", "calls").is_none()); @@ -254,15 +325,33 @@ mod tests { request_url( "https://api.example.com", &format!("calls/{CALL}/feed?rev=a") - ), - format!("https://api.example.com/api/buzz-voice/desktop/calls/{CALL}/feed?rev=a") + ) + .map(String::from), + Some(format!( + "https://api.example.com/api/buzz-voice/desktop/calls/{CALL}/feed?rev=a" + )) + ); + } + + #[test] + fn the_signed_url_is_the_sent_url_or_nothing() { + let origin = "https://api.example.com"; + // A dot-segment the URL parser would normalise never gets signed. + assert!(request_url(origin, &format!("calls/{CALL}/human-asks/%2e%2e/answer")).is_none()); + assert!(request_url(origin, &format!("calls/{CALL}/human-asks/./answer")).is_none()); + assert!(request_url(origin, &format!("calls/{CALL}/end#x")).is_none()); + let url = + request_url(origin, &format!("calls/{CALL}/human-asks/q%3A1/answer")).expect("allowed"); + assert_eq!( + url.as_str(), + format!("{origin}/api/buzz-voice/desktop/calls/{CALL}/human-asks/q%3A1/answer") ); } #[test] fn a_body_is_bound_by_its_payload_hash() { let keys = nostr::Keys::parse(&"1".repeat(64)).expect("keys"); - let url = request_url("https://api.example.com", "calls"); + let url = String::from(request_url("https://api.example.com", "calls").expect("url")); let header = nip98_header(&keys, "POST", &url, Some(br#"{"sdpOffer":"v=0"}"#)).expect("header"); let encoded = header.strip_prefix("Nostr ").expect("scheme"); diff --git a/desktop/src/features/agent-call/lib/agentCallController.test.mjs b/desktop/src/features/agent-call/lib/agentCallController.test.mjs index b78aa35b5d9..cd05032b9cd 100644 --- a/desktop/src/features/agent-call/lib/agentCallController.test.mjs +++ b/desktop/src/features/agent-call/lib/agentCallController.test.mjs @@ -2,13 +2,26 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { AgentCallApiError } from "./agentCallApi.ts"; -import { AgentCallController, feedRetryDelay } from "./agentCallController.ts"; +import { + AgentCallController, + assertNoAgentCallForHuddle, + feedRetryDelay, +} from "./agentCallController.ts"; const CALL = "0192a6b0-0000-7000-8000-0000000000ac"; const AGENT = "b".repeat(64); const CHANNEL = "0192a6b0-0000-7000-8000-0000000000af"; const tick = () => new Promise((resolve) => setImmediate(resolve)); +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +function deferred() { + let resolve; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} function fakeMedia() { const track = { @@ -60,11 +73,13 @@ function fakePeer() { function harness(overrides = {}) { const media = fakeMedia(); - const peer = fakePeer(); + const peer = overrides.peer ?? fakePeer(); const log = { starts: [], ends: [], feeds: [] }; const feedAnswers = overrides.feedAnswers ?? []; const controller = new AgentCallController({ isSupported: () => true, + isHuddleActive: overrides.isHuddleActive ?? (async () => false), + connectTimeoutMs: overrides.connectTimeoutMs ?? 20_000, getUserMedia: overrides.getUserMedia ?? (async () => media.stream), createPeerConnection: () => peer, createAudioElement: () => ({ @@ -192,3 +207,119 @@ test("feed retries back off from 1 s to 15 s", () => { assert.equal(feedRetryDelay(4), 8_000); assert.equal(feedRetryDelay(9), 15_000); }); + +test("a call is refused while a huddle owns the mic", async () => { + let asked = false; + const h = harness({ + isHuddleActive: async () => true, + getUserMedia: async () => { + asked = true; + return fakeMedia().stream; + }, + }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + assert.equal(h.controller.getState().phase, "error"); + assert.equal(h.controller.getState().error?.kind, "huddle_active"); + assert.equal(asked, false); + assert.equal(h.log.starts.length, 0); +}); + +test("a huddle that starts while the mic opens refuses the call", async () => { + let checks = 0; + const h = harness({ + // Idle before the mic opens, active once it has. + isHuddleActive: async () => ++checks > 1, + }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + assert.equal(checks, 2); + assert.equal(h.controller.getState().error?.kind, "huddle_active"); + assert.equal(h.media.track.stopped, true); + assert.equal(h.log.starts.length, 0); +}); + +test("a huddle is refused while a call is busy, allowed once it ends", async () => { + const h = harness(); + assert.doesNotThrow(() => assertNoAgentCallForHuddle("start", h.controller)); + await h.controller.start({ + agentPubkey: AGENT, + channelId: CHANNEL, + agentName: "Alfred", + }); + assert.throws( + () => assertNoAgentCallForHuddle("join", h.controller), + /End your call with Alfred before you join a huddle/, + ); + await h.controller.hangUp(); + assert.doesNotThrow(() => assertNoAgentCallForHuddle("start", h.controller)); +}); + +test("a superseded mic request stops only its own stream", async () => { + const first = fakeMedia(); + const second = fakeMedia(); + const pending = deferred(); + let calls = 0; + const h = harness({ + getUserMedia: async () => (++calls === 1 ? pending.promise : second.stream), + }); + const firstStart = h.controller.start({ + agentPubkey: AGENT, + channelId: CHANNEL, + }); + await tick(); + h.controller.reset(); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + pending.resolve(first.stream); + await firstStart; + assert.equal(first.track.stopped, true); + assert.equal(second.track.stopped, false); + assert.equal(h.controller.getState().phase, "connecting"); + assert.equal(h.log.starts.length, 1); + h.controller.reset(); +}); + +test("a hang-up while the offer is made never reaches the host", async () => { + const peer = fakePeer(); + const offer = deferred(); + peer.createOffer = () => offer.promise; + const h = harness({ peer }); + const starting = h.controller.start({ + agentPubkey: AGENT, + channelId: CHANNEL, + }); + await tick(); + assert.equal(h.controller.getState().phase, "connecting"); + h.controller.reset(); + offer.resolve({ type: "offer", sdp: "v=0 offer" }); + await starting; + assert.equal(h.log.starts.length, 0); + assert.equal(peer.closed, true); +}); + +test("a call still connecting after the timeout ends as media_failed", async () => { + const h = harness({ connectTimeoutMs: 5 }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + assert.equal(h.controller.getState().phase, "connecting"); + await sleep(20); + assert.equal(h.controller.getState().phase, "error"); + assert.equal(h.controller.getState().error?.kind, "connection_failed"); + assert.deepEqual(h.log.ends, [{ callId: CALL, reason: "media_failed" }]); + assert.equal(h.media.track.stopped, true); + assert.equal(h.peer.closed, true); +}); + +test("a timed-out call the host answers late is ended as media_failed", async () => { + const answer = deferred(); + const h = harness({ + connectTimeoutMs: 5, + startCall: () => answer.promise, + }); + const starting = h.controller.start({ + agentPubkey: AGENT, + channelId: CHANNEL, + }); + await sleep(20); + assert.equal(h.controller.getState().phase, "error"); + answer.resolve({ callId: CALL, sdpAnswer: "v=0 answer", executeUntil: null }); + await starting; + assert.deepEqual(h.log.ends, [{ callId: CALL, reason: "media_failed" }]); +}); diff --git a/desktop/src/features/agent-call/lib/agentCallController.ts b/desktop/src/features/agent-call/lib/agentCallController.ts index af7b11a6deb..3a7d9576039 100644 --- a/desktop/src/features/agent-call/lib/agentCallController.ts +++ b/desktop/src/features/agent-call/lib/agentCallController.ts @@ -1,3 +1,5 @@ +import { invokeTauri } from "@/shared/api/tauri"; + import { type StartAgentCallResponse, describeAgentCallError, @@ -31,6 +33,12 @@ import { * * Hang-up ends the call only. It never cancels the agent's work; its answers * land in the DM. Stop does that, through the host's stop control. + * + * One audio owner: a call never runs beside a huddle. A call refuses to start + * while a huddle is active or starting (checked before and again after the + * mic opens), and a huddle refuses to start or join while a call is busy + * (`assertNoAgentCallForHuddle`). Otherwise huddle members would be heard as + * the caller's asks and the agent's voice would play into the room. */ export type AgentCallPhase = @@ -47,6 +55,7 @@ export type AgentCallClientErrorKind = | "mic_denied" | "mic_unavailable" | "unsupported" + | "huddle_active" | "connection_failed"; export type AgentCallEndReason = @@ -105,6 +114,10 @@ const STOP_STATUS_RESET_MS = 4_000; /** The feed long-poll's wait, and how long it is followed after hang-up. */ const FEED_WAIT_S = 20; const FEED_AFTER_END_MS = 90_000; +/** How long a call may stay connecting before it ends as `media_failed`. */ +const CONNECT_TIMEOUT_MS = 20_000; +const HUDDLE_ACTIVE_MESSAGE = + "You're in a huddle. Leave it to call your agent."; export function feedRetryDelay(failures: number): number { return Math.min(15_000, 1_000 * 2 ** Math.max(0, failures - 1)); @@ -119,9 +132,38 @@ type Transport = { stopWork: typeof stopAgentCallWork; getFeed: typeof getAgentCallFeed; isSupported: () => boolean; + /** Whether a huddle holds (or is taking) the mic in this app. */ + isHuddleActive: () => Promise; + connectTimeoutMs: number; now: () => number; }; +let huddleAudioProbe: (() => boolean) | null = null; + +/** + * The huddle provider that owns the app's audio session registers how to tell + * whether a huddle is active or starting. Returns the unregister function. + */ +export function registerHuddleAudioProbe(probe: () => boolean): () => void { + huddleAudioProbe = probe; + return () => { + if (huddleAudioProbe === probe) huddleAudioProbe = null; + }; +} + +/** The registered probe, then the native huddle state (any window's huddle). */ +async function webviewHuddleActive(): Promise { + if (huddleAudioProbe?.()) return true; + try { + const state = await invokeTauri<{ phase?: string } | null>( + "get_huddle_state", + ); + return Boolean(state?.phase && state.phase !== "idle"); + } catch { + return false; + } +} + /** Whether this webview can place a call at all (WebRTC and a mic API). */ export function isAgentCallSupported(): boolean { return ( @@ -149,9 +191,17 @@ const webviewTransport = (): Transport => ({ stopWork: stopAgentCallWork, getFeed: getAgentCallFeed, isSupported: isAgentCallSupported, + isHuddleActive: webviewHuddleActive, + connectTimeoutMs: CONNECT_TIMEOUT_MS, now: () => Date.now(), }); +function stopTracks(stream: MediaStream) { + for (const track of stream.getTracks()) { + track.stop(); + } +} + function describeMicError(error: unknown): { kind: AgentCallClientErrorKind; message: string; @@ -196,9 +246,13 @@ export class AgentCallController { private audio: HTMLAudioElement | null = null; private timers = new Set>(); private disconnectTimer: ReturnType | null = null; + /** The attempt the connect timeout ended, so its late answer ends as such. */ + private timedOutAttempt = 0; + private connectTimer: ReturnType | null = null; constructor(transport?: Partial) { this.transport = { + connectTimeoutMs: CONNECT_TIMEOUT_MS, ...(typeof window !== "undefined" ? webviewTransport() : {}), ...transport, } as Transport; @@ -269,9 +323,13 @@ export class AgentCallController { // Unlock playback inside the gesture; the stream is attached later. this.audio = this.transport.createAudioElement(); void this.audio.play().catch(() => undefined); + if (await this.abandonForHuddle(attempt)) { + return; + } + let stream: MediaStream; try { - this.stream = await this.transport.getUserMedia({ + stream = await this.transport.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, @@ -286,17 +344,28 @@ export class AgentCallController { return; } if (attempt !== this.attempt) { - this.releaseMedia(); + // Superseded while the mic opened: close only this attempt's stream. + stopTracks(stream); + return; + } + this.stream = stream; + // A huddle may have started while the mic permission was pending. + if (await this.abandonForHuddle(attempt)) { return; } this.set({ phase: "connecting" }); + this.connectTimer = this.later( + () => this.onConnectTimeout(attempt), + this.transport.connectTimeoutMs, + ); + let peer: RTCPeerConnection | null = null; let offerSdp: string; try { - const peer = this.transport.createPeerConnection(); + peer = this.transport.createPeerConnection(); this.peer = peer; - for (const track of this.stream.getAudioTracks()) { - peer.addTrack(track, this.stream); + for (const track of stream.getAudioTracks()) { + peer.addTrack(track, stream); } peer.ontrack = (event) => { if (!this.audio) { @@ -329,6 +398,17 @@ export class AgentCallController { } return; } + if (attempt !== this.attempt) { + // Hung up while the offer was made: never ask the host to answer it. + if (this.peer !== peer) { + try { + peer.close(); + } catch { + // Already closed. + } + } + return; + } let response: StartAgentCallResponse; try { @@ -348,9 +428,12 @@ export class AgentCallController { return; } if (attempt !== this.attempt) { - // Hung up while the host was answering: end the call it opened. + // Hung up (or timed out) while the host was answering: end the call it + // opened. + const reason = + this.timedOutAttempt === attempt ? "media_failed" : "hangup"; void this.transport - .endCall(response.callId, "hangup") + .endCall(response.callId, reason) .catch(() => undefined); return; } @@ -377,6 +460,46 @@ export class AgentCallController { this.scheduleLimit(attempt, response.executeUntil); }; + /** + * Refuses the call while a huddle owns the mic. Also true when the attempt + * was superseded meanwhile, so the caller stops either way. + */ + private async abandonForHuddle(attempt: number): Promise { + let active: boolean; + try { + active = await this.transport.isHuddleActive(); + } catch { + active = false; + } + if (attempt !== this.attempt) { + return true; + } + if (active) { + this.fail({ kind: "huddle_active", message: HUDDLE_ACTIVE_MESSAGE }); + } + return active; + } + + /** Still connecting after the timeout: end as `media_failed`, close the mic. */ + private onConnectTimeout(attempt: number) { + if (attempt !== this.attempt || this.state.phase !== "connecting") { + return; + } + const callId = this.state.callId; + if (callId) { + void this.transport + .endCall(callId, "media_failed") + .catch(() => undefined); + } else { + this.timedOutAttempt = attempt; + } + this.fail({ + kind: "connection_failed", + message: + "The call couldn't connect. Check your connection and try again.", + }); + } + private scheduleLimit(attempt: number, executeUntil: string | null) { const until = executeUntil ? Date.parse(executeUntil) : Number.NaN; if (!Number.isFinite(until)) { @@ -404,6 +527,11 @@ export class AgentCallController { this.disconnectTimer = null; } if (this.state.phase === "connecting") { + if (this.connectTimer) { + clearTimeout(this.connectTimer); + this.timers.delete(this.connectTimer); + this.connectTimer = null; + } this.set({ phase: "live", connectedAt: this.transport.now() }); } return; @@ -644,8 +772,8 @@ export class AgentCallController { } private releaseMedia() { - for (const track of this.stream?.getTracks() ?? []) { - track.stop(); + if (this.stream) { + stopTracks(this.stream); } this.stream = null; if (this.channel) { @@ -679,6 +807,23 @@ export class AgentCallController { export const agentCallController = new AgentCallController(); +/** + * Huddle start/join guard: a huddle never starts beside a busy agent call + * (the huddle is refused; the call is never ended for it). + */ +export function assertNoAgentCallForHuddle( + action: "start" | "join", + controller: AgentCallController = agentCallController, +) { + if (!controller.isBusy) { + return; + } + const name = controller.getState().agentName; + throw new Error( + `End your call with ${name ?? "your agent"} before you ${action} a huddle.`, + ); +} + /** Community switch seam (`resetCommunityState`). */ export function resetAgentCall() { agentCallController.reset(); diff --git a/desktop/src/features/agent-call/ui/AgentCallButton.tsx b/desktop/src/features/agent-call/ui/AgentCallButton.tsx index e32ac2962cb..5c0b04bc4f4 100644 --- a/desktop/src/features/agent-call/ui/AgentCallButton.tsx +++ b/desktop/src/features/agent-call/ui/AgentCallButton.tsx @@ -1,5 +1,6 @@ import { Phone } from "lucide-react"; +import { useManagedAgentsQuery } from "@/features/agents/hooks"; import { useKnownAgentPubkeys } from "@/features/agents/useKnownAgentPubkeys"; import type { Channel } from "@/shared/api/types"; import { normalizePubkey } from "@/shared/lib/pubkey"; @@ -12,6 +13,10 @@ import { useAgentCall } from "./useAgentCall"; * "Call " in a 1:1 agent DM header: a proper voice call with the * agent (its host's voice core), not a huddle. The host checks that this is * the caller's own private DM with the agent before it answers. + * + * Only hosted agents take calls: an agent this app runs locally (a managed + * agent on this device) has no voice host, so it gets no Call button. The + * host stays the authority for everything else and refuses with a reason. */ export function AgentCallButton({ agentName, @@ -25,10 +30,16 @@ export function AgentCallButton({ isAgentHint: boolean; }) { const knownAgents = useKnownAgentPubkeys(); + const managedAgents = useManagedAgentsQuery().data; const call = useAgentCall(); const key = normalizePubkey(agentPubkey); const isAgent = isAgentHint || knownAgents.has(key); - if (channel.channelType !== "dm" || !isAgent) return null; + const runsOnThisDevice = (managedAgents ?? []).some( + (agent) => normalizePubkey(agent.pubkey) === key, + ); + if (channel.channelType !== "dm" || !isAgent || runsOnThisDevice) { + return null; + } const busy = call.phase === "requesting_mic" || diff --git a/desktop/src/features/agent-call/ui/AgentCallDock.tsx b/desktop/src/features/agent-call/ui/AgentCallDock.tsx index cfaa3299ede..846c3978796 100644 --- a/desktop/src/features/agent-call/ui/AgentCallDock.tsx +++ b/desktop/src/features/agent-call/ui/AgentCallDock.tsx @@ -382,6 +382,15 @@ function Recap({ feed }: { feed: AgentCallFeed }) { ); } +/** The link's host, shown beside its label so a label can't disguise it. */ +function linkHost(url: string): string { + try { + return new URL(url).host; + } catch { + return ""; + } +} + function LinkList({ links }: { links: { label: string; url: string }[] }) { const safe = links .map((link) => ({ label: link.label, url: safeHttpsUrl(link.url) })) @@ -398,9 +407,13 @@ function LinkList({ links }: { links: { label: string; url: string }[] }) { toast.error("Failed to open link"); }); }} + title={link.url} type="button" > - {link.label} + {link.label}{" "} + + ({linkHost(link.url)}) + ))} diff --git a/desktop/src/features/huddle/HuddleContext.tsx b/desktop/src/features/huddle/HuddleContext.tsx index 8e6ccbbd890..d071917b360 100644 --- a/desktop/src/features/huddle/HuddleContext.tsx +++ b/desktop/src/features/huddle/HuddleContext.tsx @@ -17,6 +17,10 @@ import type { HuddleContextValue, HuddleLevelsValue, } from "./HuddleContext.types"; +import { + assertNoAgentCallForHuddle, + registerHuddleAudioProbe, +} from "@/features/agent-call/lib/agentCallController"; /** * Huddle lifecycle (React context): @@ -117,6 +121,20 @@ export function HuddleProvider({ const [ephemeralChannelId, setEphemeralChannelId] = React.useState< string | null >(null); + const ephemeralChannelIdRef = React.useRef(ephemeralChannelId); + ephemeralChannelIdRef.current = ephemeralChannelId; + // One audio owner: an agent call refuses to start while this huddle is + // active or starting (see `assertNoAgentCallForHuddle` for the reverse). + React.useEffect(() => { + if (!ownsAudioSession) return; + return registerHuddleAudioProbe( + () => + busyRef.current || + rustActiveRef.current || + micConnectedRef.current || + ephemeralChannelIdRef.current !== null, + ); + }, [ownsAudioSession]); /** Self pubkey — fetched once, used to filter out own messages from TTS */ const selfPubkeyRef = React.useRef(null); const { activeSpeakers, resetSpeakerActivity, speakerLevels } = @@ -629,6 +647,7 @@ export function HuddleProvider({ channelName?: string, ) => { if (busyRef.current) return; + assertNoAgentCallForHuddle("start"); busyRef.current = true; tokenRef.current += 1; @@ -709,6 +728,7 @@ export function HuddleProvider({ huddleThreadEventId?: string, ) => { if (busyRef.current) return; + assertNoAgentCallForHuddle("join"); busyRef.current = true; tokenRef.current += 1; const myToken = tokenRef.current; diff --git a/docs/kiingo-fork-inventory.json b/docs/kiingo-fork-inventory.json index 8d1c784a342..dc9aba50a59 100644 --- a/docs/kiingo-fork-inventory.json +++ b/docs/kiingo-fork-inventory.json @@ -1778,7 +1778,7 @@ { "classification": "retain-generic", "owner": "Buzz messaging maintainers", - "purpose": "Desktop 1:1 agent calls from an agent DM: a proper voice call with the agent through its host's voice core (WebRTC between the webview and the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call button beside the sessions picker in a 1:1 agent DM header (known agents only) starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent (never channels, group DMs or guests). Every request goes through one native command, agent_voice_request, that signs NIP-98 (kind 27235, exact URL with query, method, SHA-256 payload of the exact body) as the signed-in user with X-Buzz-Community, reaches only the host's call routes under /api/buzz-voice/desktop (allowlisted paths, https only, 35 s timeout, size caps, no redirects) and returns {status, body}. The call controller is a port of the host's web call controller: mic with echo cancellation, an oai-events data channel, the time limit, a 5 s disconnect grace, mute, stop the agent's work, hang-up that never cancels work, and the host's call screen feed long-polled (wait 20 s, 1 s to 15 s backoff) for asks, the open question's option taps, per-ask cancel and archive (feed v2) and the post-call recap (followed at most 90 s after hang-up). The dock is mounted once in AppShell; a community switch hangs up and clears it (resetCommunityState()). Hooks: one module plus re-export in extensions/mod.rs, one use item and one command registration in lib.rs, one element and import in ChannelScreenHeader.tsx, one element and import in AppShell.tsx, one reset line and import in useCommunityInit.ts, and the microphone usage string in Info.plist.", + "purpose": "Desktop 1:1 agent calls from an agent DM: a proper voice call with the agent through its host's voice core (WebRTC between the webview and the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call button beside the sessions picker in a 1:1 agent DM header (known agents only) starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent (never channels, group DMs or guests). Every request goes through one native command, agent_voice_request, that signs NIP-98 (kind 27235, exact URL with query, method, SHA-256 payload of the exact body) as the signed-in user with X-Buzz-Community, reaches only the host's call routes under /api/buzz-voice/desktop (allowlisted paths, https only, 35 s timeout, size caps, no redirects) and returns {status, body}. The call controller is a port of the host's web call controller: mic with echo cancellation, an oai-events data channel, the time limit, a 5 s disconnect grace, mute, stop the agent's work, hang-up that never cancels work, and the host's call screen feed long-polled (wait 20 s, 1 s to 15 s backoff) for asks, the open question's option taps, per-ask cancel and archive (feed v2) and the post-call recap (followed at most 90 s after hang-up). The dock is mounted once in AppShell; a community switch hangs up and clears it (resetCommunityState()). Hooks: one module plus re-export in extensions/mod.rs, one use item and one command registration in lib.rs, one element and import in ChannelScreenHeader.tsx, one element and import in AppShell.tsx, one reset line and import in useCommunityInit.ts, and the microphone usage string in Info.plist. One audio owner: a call refuses while a huddle is active or starting (a probe registered by the audio-owning HuddleProvider, then the native huddle state, checked before and after the mic opens), and HuddleContext.tsx refuses huddle start and join while a call is busy (one import, one probe registration effect, one guard line in each of startHuddle and joinHuddle). Calls still connecting after 20 s end as media_failed. The native command parses the request URL once, checks its normalised path, and signs and sends that same URL; ask ids reject escapes of dot, slash and backslash; answers are capped at 2 MiB by declared length and while read; BUZZ_DESKTOP_AGENT_VOICE_URL and the shared HTTP-loopback allowance in guest_access.rs apply to debug builds only. No Call button for agents managed on this device.", "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", "paths": [ @@ -1792,24 +1792,30 @@ "desktop/src/features/agent-call/lib/agentCallFeed.ts", "desktop/src/features/agent-call/ui/AgentCallButton.tsx", "desktop/src/features/agent-call/ui/AgentCallDock.tsx", - "desktop/src/features/agent-call/ui/useAgentCall.ts" + "desktop/src/features/agent-call/ui/useAgentCall.ts", + "desktop/src/features/huddle/HuddleContext.tsx" ] }, { "classification": "retain-generic", "owner": "Buzz mobile maintainers", - "purpose": "iOS 1:1 agent calls from an agent DM, matching the desktop call: a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call action beside the sessions action in a 1:1 agent DM header (native navigation action and Flutter button) opens the call screen and starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. Requests go to /api/buzz-voice/ios, NIP-98 signed by the signed-in user over the exact URL, method and body bytes, with X-Buzz-Community. AgentCallPlugin (method channel buzz/agent_call) owns the media: the stasel/WebRTC 154.0.0 binary package pinned exactly (revision 0c0ad84d, binary checksum a2bcdda9...), an outgoing CallKit call created from a provider built at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app audio fallback when CallKit refuses, and interruption, route-change and media-services-reset handling; UIBackgroundModes audio and voip keep the call alive on the lock screen. The Dart controller follows the host's call screen feed by long-poll (asks, the open question's option taps, per-ask cancel and archive, the recap), refuses while a huddle holds the audio, and hangs up on a community switch. Hooks: one plugin property and construction in AppDelegate.swift, the plugin file, the WebRTC package reference and product in project.pbxproj and Package.resolved, the background modes and microphone string in Info.plist, and one native action plus one button in channel_detail_page.dart.", + "purpose": "iOS 1:1 agent calls from an agent DM, matching the desktop call: a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call action beside the sessions action in a 1:1 agent DM header (native navigation action and Flutter button) opens the call screen and starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. Requests go to /api/buzz-voice/ios, NIP-98 signed by the signed-in user over the exact URL, method and body bytes, with X-Buzz-Community. AgentCallPlugin (method channel buzz/agent_call) owns the media: the stasel/WebRTC 154.0.0 binary package pinned exactly (revision 0c0ad84d, binary checksum a2bcdda9...), an outgoing CallKit call created from a provider built at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app audio fallback when CallKit refuses, and interruption, route-change and media-services-reset handling; UIBackgroundModes audio and voip keep the call alive on the lock screen. The Dart controller follows the host's call screen feed by long-poll (asks, the open question's option taps, per-ask cancel and archive, the recap), refuses while a huddle holds the audio, and hangs up on a community switch. Hooks: one plugin property and construction in AppDelegate.swift, the plugin file, the WebRTC package reference and product in project.pbxproj and Package.resolved, the background modes and microphone string in Info.plist, and one native action plus one button in channel_detail_page.dart (the button shows on iOS only). One audio owner: while a call is busy it holds agentCallAudioBusyProvider (shared/huddle/agent_call_audio.dart, exported from huddle.dart), which HuddleSessionNotifier.join (huddle_session.dart, one guard) and MobileHuddleController._start (mobile_huddle_controller.dart, one guard before announcing) refuse on; the call refuses while a huddle is in session, at the tap and again after the native call is up. Natively, VoiceAudioSessionOwner (AgentCallPlugin.swift) marks the call's hold on the AVAudioSession and HuddleMediaPlugin.swift never prepares, reactivates or deactivates the session while it is set (four guards). Peer events act only for the current peer connection; calls still connecting 20 s after the native call is up end as media_failed; answers are capped at the hosted API's 2 MiB (guestAccessMaxResponseBytes); the CallKit name is trimmed and capped at 60 characters; an in-call banner explains a call running without CallKit; feed links show their host.", "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", "paths": [ "mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved", "mobile/ios/Runner/AgentCallPlugin.swift", + "mobile/ios/Runner/HuddleMediaPlugin.swift", "mobile/ios/Runner/Info.plist", "mobile/lib/features/agent_call/agent_call_api.dart", "mobile/lib/features/agent_call/agent_call_controller.dart", "mobile/lib/features/agent_call/agent_call_feed.dart", "mobile/lib/features/agent_call/agent_call_media.dart", "mobile/lib/features/agent_call/agent_call_screen.dart", + "mobile/lib/features/channels/mobile_huddle_controller.dart", + "mobile/lib/shared/huddle/agent_call_audio.dart", + "mobile/lib/shared/huddle/huddle.dart", + "mobile/lib/shared/huddle/huddle_session.dart", "mobile/test/features/agent_call/agent_call_test.dart" ] }, diff --git a/mobile/ios/Runner/AgentCallPlugin.swift b/mobile/ios/Runner/AgentCallPlugin.swift index 1488a5b79d6..0dcb4bf11be 100644 --- a/mobile/ios/Runner/AgentCallPlugin.swift +++ b/mobile/ios/Runner/AgentCallPlugin.swift @@ -5,6 +5,13 @@ import UIKit import os @preconcurrency import WebRTC +/// Which feature holds the shared `AVAudioSession` (main thread only). An +/// agent call holds it from `begin` until its media is torn down; while it +/// does, huddle media never configures, reactivates or deactivates it. +enum VoiceAudioSessionOwner { + nonisolated(unsafe) static var agentCallActive = false +} + /// Native media for 1:1 agent calls from an agent DM (`buzz/agent_call`). /// /// A proper voice call with the agent through its host's voice core, not a @@ -77,7 +84,7 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele let arguments = call.arguments as? [String: Any] ?? [:] switch call.method { case "begin": - let name = (arguments["agentName"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? "Agent" + let name = Self.callerName(arguments["agentName"] as? String) Task { @MainActor in await self.begin(agentName: name, result: result) } case "accept": guard let sdp = arguments["sdp"] as? String, !sdp.isEmpty else { @@ -98,6 +105,17 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele } } + /// The agent's name as CallKit shows it: trimmed, control characters + /// dropped, at most 60 characters, "Agent" when nothing is left. + static func callerName(_ raw: String?) -> String { + let cleaned = String( + String.UnicodeScalarView( + (raw ?? "").unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }) + ).trimmingCharacters(in: .whitespacesAndNewlines) + let name = String(cleaned.prefix(60)).trimmingCharacters(in: .whitespacesAndNewlines) + return name.isEmpty ? "Agent" : name + } + private func emit(_ type: String, _ extra: [String: Any] = [:]) { var payload = extra payload["type"] = type @@ -119,6 +137,7 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele callId = id closed = false connected = false + VoiceAudioSessionOwner.agentCallActive = true let handle = CXHandle(type: .generic, value: agentName) let action = CXStartCallAction(call: id, handle: handle) action.isVideo = false @@ -223,6 +242,7 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele inApp = false connected = false closed = true + VoiceAudioSessionOwner.agentCallActive = false } private func endInAppAudio() { @@ -477,18 +497,27 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele nonisolated func peerConnection( _ peerConnection: RTCPeerConnection, didChange newState: RTCPeerConnectionState ) { + // Every event acts only for the call's current peer connection, never a + // closed earlier one (a stale timer must not end a newer call). switch newState { case .connected: - Task { @MainActor in self.peerConnected() } + Task { @MainActor in + guard peerConnection === self.connection else { return } + self.peerConnected() + } case .failed: - Task { @MainActor in self.endedRemotely("connectionLost") } + Task { @MainActor in + guard peerConnection === self.connection else { return } + self.endedRemotely("connectionLost") + } case .disconnected: // `disconnected` can recover; give it a few seconds. Task { @MainActor in try? await Task.sleep(nanoseconds: 5_000_000_000) - if let connection = self.connection, connection.connectionState != .connected { - self.endedRemotely("connectionLost") - } + guard peerConnection === self.connection, + peerConnection.connectionState != .connected + else { return } + self.endedRemotely("connectionLost") } default: break @@ -524,7 +553,10 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele nonisolated func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) { guard dataChannel.readyState == .closed else { return } - Task { @MainActor in self.endedRemotely("remoteClosed") } + Task { @MainActor in + guard dataChannel === self.dataChannel else { return } + self.endedRemotely("remoteClosed") + } } /// Only the event type matters (`session.closed`); nothing from the @@ -536,6 +568,9 @@ final class AgentCallPlugin: NSObject, CXProviderDelegate, RTCPeerConnectionDele let event = try? JSONSerialization.jsonObject(with: buffer.data) as? [String: Any], event["type"] as? String == "session.closed" else { return } - Task { @MainActor in self.endedRemotely("remoteClosed") } + Task { @MainActor in + guard dataChannel === self.dataChannel else { return } + self.endedRemotely("remoteClosed") + } } } diff --git a/mobile/ios/Runner/HuddleMediaPlugin.swift b/mobile/ios/Runner/HuddleMediaPlugin.swift index 5421f176d33..7e534c7bd22 100644 --- a/mobile/ios/Runner/HuddleMediaPlugin.swift +++ b/mobile/ios/Runner/HuddleMediaPlugin.swift @@ -49,7 +49,7 @@ final class HuddleMediaPlugin { if let mediaServicesResetObserver { NotificationCenter.default.removeObserver(mediaServicesResetObserver) } - if audioSessionPrepared { + if audioSessionPrepared, !VoiceAudioSessionOwner.agentCallActive { try? audioSession.overrideOutputAudioPort(.none) try? audioSession.setActive( false, @@ -163,6 +163,17 @@ final class HuddleMediaPlugin { ) return } + // An agent call holds the audio session: never take it over. + guard !VoiceAudioSessionOwner.agentCallActive else { + result( + FlutterError( + code: "audio_busy", + message: "End your agent call before joining a Huddle.", + details: nil + ) + ) + return + } guard audioSession.recordPermission == .granted else { result( FlutterError( @@ -418,7 +429,7 @@ final class HuddleMediaPlugin { } private func handleInterruption(_ notification: Notification) { - guard audioSessionPrepared, + guard audioSessionPrepared, !VoiceAudioSessionOwner.agentCallActive, let rawType = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? NSNumber, let type = AVAudioSession.InterruptionType(rawValue: rawType.uintValue) @@ -466,7 +477,9 @@ final class HuddleMediaPlugin { private func stop(result: @escaping FlutterResult) { audioEngine?.stop() audioEngine = nil - guard audioSessionPrepared else { + guard audioSessionPrepared, !VoiceAudioSessionOwner.agentCallActive else { + // Never deactivate the session an agent call holds. + audioSessionPrepared = false speakerEnabled = false result(nil) return diff --git a/mobile/lib/features/agent_call/agent_call_api.dart b/mobile/lib/features/agent_call/agent_call_api.dart index 33b8ec72da8..6ee25af88a3 100644 --- a/mobile/lib/features/agent_call/agent_call_api.dart +++ b/mobile/lib/features/agent_call/agent_call_api.dart @@ -1,5 +1,6 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:typed_data'; import 'package:http/http.dart' as http; import 'package:uuid/uuid.dart'; @@ -83,34 +84,52 @@ class AgentCallApi { request.headers['Content-Type'] = 'application/json'; request.bodyBytes = bytes; } - http.Response response; + int status; + Uint8List responseBytes; try { final streamed = await _client.send(request).timeout(_requestTimeout); - response = await http.Response.fromStream( - streamed, - ).timeout(_requestTimeout); + status = streamed.statusCode; + responseBytes = await _readCapped(streamed).timeout(_requestTimeout); } on TimeoutException { throw const AgentCallApiException(null, 'voice_route_timeout'); } on http.ClientException { throw const AgentCallApiException(null, 'network'); } Object? decoded; - if (response.bodyBytes.isNotEmpty) { + if (responseBytes.isNotEmpty) { try { - decoded = jsonDecode(utf8.decode(response.bodyBytes)); + decoded = jsonDecode(utf8.decode(responseBytes)); } on FormatException { decoded = null; } } - if (response.statusCode < 200 || response.statusCode >= 300) { + if (status < 200 || status >= 300) { final code = decoded is Map && decoded['error'] is String ? decoded['error'] as String : null; - throw AgentCallApiException(response.statusCode, code); + throw AgentCallApiException(status, code); } return decoded; } + /// The answer's bytes, at most [guestAccessMaxResponseBytes]: a larger + /// declared length is refused before reading, and reading stops past it. + static Future _readCapped(http.StreamedResponse response) async { + final status = response.statusCode; + final declared = response.contentLength; + if (declared != null && declared > guestAccessMaxResponseBytes) { + throw AgentCallApiException(status, 'response_too_large'); + } + final bytes = BytesBuilder(copy: false); + await for (final chunk in response.stream) { + if (bytes.length + chunk.length > guestAccessMaxResponseBytes) { + throw AgentCallApiException(status, 'response_too_large'); + } + bytes.add(chunk); + } + return bytes.takeBytes(); + } + String _call(String callId) => 'calls/${Uri.encodeComponent(callId)}'; Future start({ diff --git a/mobile/lib/features/agent_call/agent_call_controller.dart b/mobile/lib/features/agent_call/agent_call_controller.dart index a66ec39a5dd..b7e48d68ea2 100644 --- a/mobile/lib/features/agent_call/agent_call_controller.dart +++ b/mobile/lib/features/agent_call/agent_call_controller.dart @@ -21,6 +21,10 @@ import 'agent_call_media.dart'; /// /// Hang-up ends the call only; the agent's work goes on and its answers /// land in the DM. Stop stops the work. +/// +/// One audio owner: the call refuses while a Huddle is in session (checked +/// at the tap and again once the native call is up), and while it is busy it +/// holds `agentCallAudioBusyProvider`, which refuses Huddle starts and joins. enum AgentCallPhase { idle, connecting, live, ending, ended, error } @@ -40,6 +44,7 @@ class AgentCallState { this.error, this.endReason, this.feed, + this.systemCallUI, }); final AgentCallPhase phase; @@ -54,6 +59,10 @@ class AgentCallState { final String? endReason; final AgentCallFeed? feed; + /// `callkit`, or `in_app` when CallKit refused and the call runs without + /// the system call screen. + final String? systemCallUI; + bool get isBusy => phase == AgentCallPhase.connecting || phase == AgentCallPhase.live || @@ -68,6 +77,7 @@ class AgentCallState { String? error, String? endReason, AgentCallFeed? feed, + String? systemCallUI, }) => AgentCallState( phase: phase ?? this.phase, agentPubkey: agentPubkey, @@ -80,6 +90,7 @@ class AgentCallState { error: error ?? this.error, endReason: endReason ?? this.endReason, feed: feed ?? this.feed, + systemCallUI: systemCallUI ?? this.systemCallUI, ); } @@ -109,6 +120,12 @@ final agentCallHuddleBusyProvider = Provider( (ref) => ref.watch(huddleSessionProvider).isInSession, ); +/// How long a call may stay connecting once the native call is up before it +/// ends as `media_failed` (overridden in tests). +final agentCallConnectTimeoutProvider = Provider( + (ref) => const Duration(seconds: 20), +); + final agentCallProvider = NotifierProvider( AgentCallNotifier.new, ); @@ -125,6 +142,7 @@ const _endedDismiss = Duration(seconds: 4); const _stopStatusReset = Duration(seconds: 4); const _feedAfterEnd = Duration(seconds: 90); const _resumeTimeout = Duration(seconds: 8); +const _huddleRefusal = 'Leave the huddle first, then call.'; class AgentCallNotifier extends Notifier { int _attempt = 0; @@ -134,10 +152,15 @@ class AgentCallNotifier extends Notifier { final List _timers = []; Timer? _resumeTimer; + /// The attempt the connect timeout ended, so its late answer ends as such. + int _timedOutAttempt = 0; + @override AgentCallState build() { final media = ref.watch(agentCallMediaProvider); _events = media.events.listen(_onMediaEvent); + final audio = ref.read(agentCallAudioBusyProvider.notifier); + listenSelf((_, next) => audio.update(next.isBusy)); final unregister = ref .read(communityTransitionProvider) .register(() async => reset()); @@ -187,7 +210,7 @@ class AgentCallNotifier extends Notifier { channelId: channelId, ); if (ref.read(agentCallHuddleBusyProvider)) { - _fail('Leave the huddle first, then call.'); + _fail(_huddleRefusal); return; } final api = ref.read(agentCallApiProvider); @@ -208,6 +231,17 @@ class AgentCallNotifier extends Notifier { unawaited(_media.end()); return; } + // A Huddle may have joined while the microphone prompt was up. + if (ref.read(agentCallHuddleBusyProvider)) { + unawaited(_media.end()); + _fail(_huddleRefusal); + return; + } + state = state.copyWith(systemCallUI: offer.systemCallUI); + _later( + ref.read(agentCallConnectTimeoutProvider), + () => _onConnectTimeout(attempt), + ); AgentCallStart started; try { @@ -226,8 +260,10 @@ class AgentCallNotifier extends Notifier { return; } if (attempt != _attempt) { - // Hung up while the host was answering: end the call it opened. - unawaited(_quietEnd(api, started.callId, 'hangup')); + // Hung up (or timed out) while the host was answering: end the call it + // opened. + final reason = _timedOutAttempt == attempt ? 'media_failed' : 'hangup'; + unawaited(_quietEnd(api, started.callId, reason)); return; } state = state.copyWith(callId: started.callId); @@ -253,6 +289,23 @@ class AgentCallNotifier extends Notifier { } } + /// Still connecting after the timeout: end as `media_failed` and close + /// the microphone. + void _onConnectTimeout(int attempt) { + if (attempt != _attempt || state.phase != AgentCallPhase.connecting) { + return; + } + final api = _api; + final callId = state.callId; + if (api != null && callId != null) { + unawaited(_quietEnd(api, callId, 'media_failed')); + } else { + _timedOutAttempt = attempt; + } + unawaited(_media.end()); + _fail("The call couldn't connect. Check your connection and try again."); + } + void _onMediaEvent(AgentCallMediaEventData data) { switch (data.event) { case AgentCallMediaEvent.connected: diff --git a/mobile/lib/features/agent_call/agent_call_screen.dart b/mobile/lib/features/agent_call/agent_call_screen.dart index c4511246af8..57dfa6ffa9e 100644 --- a/mobile/lib/features/agent_call/agent_call_screen.dart +++ b/mobile/lib/features/agent_call/agent_call_screen.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -65,7 +66,8 @@ IosNavigationAction agentCallNavigationAction( ), ); -/// The "Call" button in a 1:1 agent DM header. +/// The "Call" button in a 1:1 agent DM header. Calls run on iOS only (the +/// native media is iOS), so elsewhere there is no button. class AgentCallButton extends ConsumerWidget { const AgentCallButton({ super.key, @@ -80,6 +82,9 @@ class AgentCallButton extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { + if (defaultTargetPlatform != TargetPlatform.iOS) { + return const SizedBox.shrink(); + } final call = ref.watch(agentCallProvider); final onThisCall = call.isBusy && call.agentPubkey == agentPubkey; final label = onThisCall ? 'Back to the call' : 'Call $agentName'; @@ -182,6 +187,7 @@ class AgentCallScreen extends HookConsumerWidget { if (call.phase == AgentCallPhase.error) Text(call.error ?? "The call couldn't start.") else ...[ + if (busy && call.systemCallUI == 'in_app') const _InAppBanner(), if (feed?.openQuestion case final question?) _QuestionCard(question: question), if (feed != null) @@ -442,6 +448,32 @@ class _Recap extends StatelessWidget { } } +/// CallKit refused this call, so it runs without the system call screen. +class _InAppBanner extends StatelessWidget { + const _InAppBanner(); + + @override + Widget build(BuildContext context) { + return Container( + key: const ValueKey('agent-call-in-app-banner'), + margin: const EdgeInsets.only(bottom: Grid.xs), + padding: const EdgeInsets.all(Grid.xs), + decoration: BoxDecoration( + color: context.colors.surfaceContainerHighest, + borderRadius: BorderRadius.circular(Radii.md), + ), + child: Text( + "This call isn't on the iPhone's call screen. Mute and hang up here, " + 'and keep Buzz open.', + style: context.textTheme.bodySmall, + ), + ); + } +} + +/// The link's host, shown beside its label so a label can't disguise it. +String _linkHost(String url) => Uri.tryParse(url)?.host ?? ''; + class _Links extends StatelessWidget { const _Links({required this.links}); @@ -462,7 +494,7 @@ class _Links extends StatelessWidget { } }, child: Text( - link.label, + '${link.label} (${_linkHost(link.url)})', maxLines: 1, overflow: TextOverflow.ellipsis, ), diff --git a/mobile/lib/features/channels/mobile_huddle_controller.dart b/mobile/lib/features/channels/mobile_huddle_controller.dart index 4cb856f3811..f10a7695d69 100644 --- a/mobile/lib/features/channels/mobile_huddle_controller.dart +++ b/mobile/lib/features/channels/mobile_huddle_controller.dart @@ -142,6 +142,10 @@ final class MobileHuddleController extends Notifier { Future _start({required String parentChannelId}) async { if (state) return; + // Refuse before announcing a Huddle that could not take the audio. + if (ref.read(agentCallAudioBusyProvider)) { + throw StateError(agentCallHuddleRefusal); + } final generation = ++_generation; final admissionEpoch = ++_admissionEpoch; state = true; diff --git a/mobile/lib/shared/guest_access/guest_access_client.dart b/mobile/lib/shared/guest_access/guest_access_client.dart index 88eb1fd8bad..c7739e9d9d4 100644 --- a/mobile/lib/shared/guest_access/guest_access_client.dart +++ b/mobile/lib/shared/guest_access/guest_access_client.dart @@ -27,7 +27,9 @@ const guestRouteRelayUrl = String.fromEnvironment( ); const _requestTimeout = Duration(seconds: 20); -const _maxResponseBytes = 2 * 1024 * 1024; + +/// The largest answer read from the hosted API (shared with agent calls). +const guestAccessMaxResponseBytes = 2 * 1024 * 1024; /// A route error: the contract's `error` code plus the HTTP status, if any. class GuestAccessException implements Exception { @@ -182,7 +184,7 @@ class GuestAccessClient { streamed, ).timeout(_requestTimeout); final status = response.statusCode; - if (response.bodyBytes.length > _maxResponseBytes) { + if (response.bodyBytes.length > guestAccessMaxResponseBytes) { throw GuestAccessException('response_too_large', status: status); } Object? decoded; diff --git a/mobile/lib/shared/huddle/agent_call_audio.dart b/mobile/lib/shared/huddle/agent_call_audio.dart new file mode 100644 index 00000000000..c0c6226ff66 --- /dev/null +++ b/mobile/lib/shared/huddle/agent_call_audio.dart @@ -0,0 +1,22 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +/// One audio owner: true while a 1:1 agent call holds the phone's audio (set +/// by the call). A Huddle never starts or joins beside it, or Huddle members +/// would be heard as the caller's asks and the agent's voice would play into +/// the room. The call refuses to start while a Huddle is in session. +final agentCallAudioBusyProvider = NotifierProvider( + AgentCallAudioBusy.new, +); + +final class AgentCallAudioBusy extends Notifier { + @override + bool build() => false; + + void update(bool busy) { + if (state != busy) state = busy; + } +} + +/// What a refused Huddle start or join says. +const agentCallHuddleRefusal = + 'End your agent call before starting or joining a Huddle.'; diff --git a/mobile/lib/shared/huddle/huddle.dart b/mobile/lib/shared/huddle/huddle.dart index a9972dcd59b..11d66433d5d 100644 --- a/mobile/lib/shared/huddle/huddle.dart +++ b/mobile/lib/shared/huddle/huddle.dart @@ -1,3 +1,4 @@ +export 'agent_call_audio.dart'; export 'huddle_auth.dart'; export 'huddle_media.dart'; export 'huddle_session.dart'; diff --git a/mobile/lib/shared/huddle/huddle_session.dart b/mobile/lib/shared/huddle/huddle_session.dart index e08d28c5d16..5d51d4e19f3 100644 --- a/mobile/lib/shared/huddle/huddle_session.dart +++ b/mobile/lib/shared/huddle/huddle_session.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../features/age_gate/age_signal_provider.dart'; +import 'agent_call_audio.dart'; import 'huddle_auth.dart'; import 'huddle_media.dart'; import 'huddle_transport.dart'; @@ -220,6 +221,18 @@ final class HuddleSessionNotifier extends Notifier { if (_ageRestricted) { throw StateError('Huddle unavailable while age-restricted'); } + if (ref.read(agentCallAudioBusyProvider)) { + // An agent call holds the audio: refuse, never take it over. + if (!state.isInSession) { + state = HuddleSessionState( + phase: HuddleSessionPhase.failed, + parentChannelId: parameters.parentChannelId, + ephemeralChannelId: parameters.ephemeralChannelId, + error: agentCallHuddleRefusal, + ); + } + return; + } if (state.isInSession) { if (state.ephemeralChannelId == parameters.ephemeralChannelId) return; state = state.copyWith( diff --git a/mobile/test/features/agent_call/agent_call_test.dart b/mobile/test/features/agent_call/agent_call_test.dart index 7a1f391d7bc..1decdbc4294 100644 --- a/mobile/test/features/agent_call/agent_call_test.dart +++ b/mobile/test/features/agent_call/agent_call_test.dart @@ -5,10 +5,15 @@ import 'package:buzz/features/agent_call/agent_call_api.dart'; import 'package:buzz/features/agent_call/agent_call_controller.dart'; import 'package:buzz/features/agent_call/agent_call_feed.dart'; import 'package:buzz/features/agent_call/agent_call_media.dart'; +import 'package:buzz/features/agent_call/agent_call_screen.dart'; import 'package:buzz/shared/guest_access/guest_access_client.dart'; +import 'package:buzz/shared/huddle/huddle.dart'; import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:hooks_riverpod/misc.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:nostr/nostr.dart' as nostr; @@ -28,17 +33,31 @@ Map _feed({String state = 'live', List? asks}) => { 'endedAt': null, }; +/// A Huddle's in-session flag the call reads (flipped by a test). +final _huddleInSession = NotifierProvider<_Flag, bool>(_Flag.new); + +final class _Flag extends Notifier { + @override + bool build() => false; + + void raise() => state = true; +} + class _FakeMedia implements AgentCallMedia { final events$ = StreamController.broadcast(); final calls = []; String? answer; + /// Runs inside `begin`, as if while the microphone prompt was up. + void Function()? onBegin; + @override Stream get events => events$.stream; @override Future begin({required String agentName}) async { calls.add('begin:$agentName'); + onBegin?.call(); return const AgentCallOffer(sdp: 'v=0 offer', systemCallUI: 'callkit'); } @@ -223,11 +242,31 @@ void main() { late _FakeMedia media; late List requests; late ProviderContainer container; + late http.Client client; + + ProviderContainer build(List overrides) { + final built = ProviderContainer( + overrides: [ + agentCallMediaProvider.overrideWithValue(media), + agentCallApiProvider.overrideWithValue( + AgentCallApi( + origin: 'https://api.example.com', + communityId: 'chat.example.com', + nsec: nostr.Keys.generate().nsec, + httpClient: client, + ), + ), + ...overrides, + ], + ); + addTearDown(built.dispose); + return built; + } setUp(() { media = _FakeMedia(); requests = []; - final client = MockClient((request) async { + client = MockClient((request) async { requests.add(request); if (request.url.path.endsWith('/calls')) { return http.Response( @@ -311,10 +350,175 @@ void main() { expect(media.calls, isEmpty); }); + test('a Huddle that joins while the call is set up refuses it', () async { + final busy = build([ + agentCallHuddleBusyProvider.overrideWith( + (ref) => ref.watch(_huddleInSession), + ), + ]); + media.onBegin = () => busy.read(_huddleInSession.notifier).raise(); + await busy + .read(agentCallProvider.notifier) + .start(agentPubkey: _agent, channelId: _channel, agentName: 'Alfred'); + expect(busy.read(agentCallProvider).phase, AgentCallPhase.error); + expect(media.calls, ['begin:Alfred', 'end']); + expect(requests, isEmpty); + expect(busy.read(agentCallAudioBusyProvider), isFalse); + }); + + test('a busy call refuses Huddle joins until it ends', () async { + var huddleMedia = 0; + final both = build([ + agentCallHuddleBusyProvider.overrideWithValue(false), + huddleMediaFactoryProvider.overrideWithValue(() { + huddleMedia++; + throw StateError('no Huddle media in this test'); + }), + ]); + final notifier = both.read(agentCallProvider.notifier); + await notifier.start( + agentPubkey: _agent, + channelId: _channel, + agentName: 'Alfred', + ); + expect(both.read(agentCallAudioBusyProvider), isTrue); + + await both + .read(huddleSessionProvider.notifier) + .join( + HuddleConnectionParameters( + relayWebSocketUrl: 'wss://buzz.example', + nsec: + '09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506', + parentChannelId: '11111111-2222-4333-8444-555555555555', + ephemeralChannelId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + ), + ); + final huddle = both.read(huddleSessionProvider); + expect(huddle.phase, HuddleSessionPhase.failed); + expect(huddle.error, agentCallHuddleRefusal); + expect(huddleMedia, 0); + expect(both.read(agentCallProvider).isBusy, isTrue); + + await notifier.hangUp(); + expect(both.read(agentCallAudioBusyProvider), isFalse); + notifier.dismiss(); + }); + + test( + 'a call still connecting after the timeout ends as media_failed', + () async { + final timed = build([ + agentCallHuddleBusyProvider.overrideWithValue(false), + agentCallConnectTimeoutProvider.overrideWithValue( + const Duration(milliseconds: 20), + ), + ]); + await timed + .read(agentCallProvider.notifier) + .start( + agentPubkey: _agent, + channelId: _channel, + agentName: 'Alfred', + ); + expect(timed.read(agentCallProvider).phase, AgentCallPhase.connecting); + await Future.delayed(const Duration(milliseconds: 80)); + expect(timed.read(agentCallProvider).phase, AgentCallPhase.error); + expect(media.calls, contains('end')); + final end = requests.firstWhere( + (request) => request.url.path.endsWith('/end'), + ); + expect(jsonDecode(end.body), {'reason': 'media_failed'}); + expect(timed.read(agentCallAudioBusyProvider), isFalse); + }, + ); + test('feed retries back off from 1 s to 15 s', () { expect(agentCallFeedRetryDelay(1), const Duration(seconds: 1)); expect(agentCallFeedRetryDelay(3), const Duration(seconds: 4)); expect(agentCallFeedRetryDelay(9), const Duration(seconds: 15)); }); }); + + group('AgentCallApi response cap', () { + AgentCallApi api(http.Client client) => AgentCallApi( + origin: 'https://api.example.com', + communityId: 'chat.example.com', + nsec: nostr.Keys.generate().nsec, + httpClient: client, + ); + + test('a declared oversize answer is refused before reading', () async { + final client = MockClient.streaming( + (_, _) async => http.StreamedResponse( + const Stream.empty(), + 200, + contentLength: guestAccessMaxResponseBytes + 1, + ), + ); + await expectLater( + api(client).end(_call, 'hangup'), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'response_too_large', + ), + ), + ); + }); + + test('an undeclared oversize answer stops being read at the cap', () async { + final chunk = List.filled(512 * 1024, 32); + final client = MockClient.streaming( + (_, _) async => http.StreamedResponse( + Stream.fromIterable(List.filled(5, chunk)), + 200, + ), + ); + await expectLater( + api(client).end(_call, 'hangup'), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'response_too_large', + ), + ), + ); + }); + }); + + group('AgentCallButton', () { + Future pump(WidgetTester tester) => tester.pumpWidget( + ProviderScope( + overrides: [agentCallMediaProvider.overrideWithValue(_FakeMedia())], + child: MaterialApp( + home: Scaffold( + body: AgentCallButton( + agentPubkey: _agent, + channelId: _channel, + agentName: 'Alfred', + ), + ), + ), + ), + ); + + testWidgets('shows on iOS', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await pump(tester); + expect(find.byKey(const ValueKey('agent-call-button')), findsOneWidget); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('is hidden on Android', (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await pump(tester); + expect(find.byKey(const ValueKey('agent-call-button')), findsNothing); + debugDefaultTargetPlatformOverride = null; + }); + }); } From 6fc9e1865f771668a46ae9cb13d8eedcddfe8f10 Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Fri, 23 Oct 2026 08:52:30 -0700 Subject: [PATCH 5/7] test(desktop): loopback HTTP base URLs are debug-only base_urls_must_be_https_or_loopback_http now expects loopback HTTP to be accepted exactly when debug assertions are on, so it holds in release test runs too. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- desktop/src-tauri/src/commands/guest_access.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/desktop/src-tauri/src/commands/guest_access.rs b/desktop/src-tauri/src/commands/guest_access.rs index 5fca29e29b7..39a7c1094bc 100644 --- a/desktop/src-tauri/src/commands/guest_access.rs +++ b/desktop/src-tauri/src/commands/guest_access.rs @@ -287,7 +287,11 @@ mod tests { assert!(acceptable_base_url( "https://api.example.com/api/buzz-guest/v1" )); - assert!(acceptable_base_url("http://127.0.0.1:8080/v1")); + // Loopback HTTP is for development builds only. + assert_eq!( + acceptable_base_url("http://127.0.0.1:8080/v1"), + cfg!(debug_assertions) + ); assert!(!acceptable_base_url("http://api.example.com/v1")); assert!(!acceptable_base_url("ftp://api.example.com")); } From 55fcb8a795b0d3433e06810c5d60210ae2ffb979 Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Fri, 23 Oct 2026 09:13:46 -0700 Subject: [PATCH 6/7] fix(agent-call): fail closed on unknown huddle state; wait for huddle starts Review follow-ups for 1:1 agent calls. - Desktop: when the native huddle state can't be read, the call refuses with a clear reason instead of assuming no huddle. - iOS: a call also refuses while a huddle start is under way (huddleStartingProvider, mirrored from MobileHuddleController), so a huddle is never announced and then rolled back for a call. - Desktop: the Call button waits for the local agent inventory, so it never flashes for an agent managed on this device. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- .../lib/agentCallController.test.mjs | 19 +++++++++++ .../agent-call/lib/agentCallController.ts | 33 ++++++++++++------- .../agent-call/ui/AgentCallButton.tsx | 12 ++++--- docs/kiingo-fork-inventory.json | 4 +-- .../agent_call/agent_call_controller.dart | 7 ++-- .../channels/mobile_huddle_controller.dart | 3 ++ .../lib/shared/huddle/agent_call_audio.dart | 14 ++++++-- .../features/agent_call/agent_call_test.dart | 11 +++++++ 8 files changed, 80 insertions(+), 23 deletions(-) diff --git a/desktop/src/features/agent-call/lib/agentCallController.test.mjs b/desktop/src/features/agent-call/lib/agentCallController.test.mjs index cd05032b9cd..877e7dfc4bd 100644 --- a/desktop/src/features/agent-call/lib/agentCallController.test.mjs +++ b/desktop/src/features/agent-call/lib/agentCallController.test.mjs @@ -224,6 +224,25 @@ test("a call is refused while a huddle owns the mic", async () => { assert.equal(h.log.starts.length, 0); }); +test("an unreadable huddle state refuses the call (fails closed)", async () => { + let asked = false; + const h = harness({ + isHuddleActive: async () => { + throw new Error("ipc_failed"); + }, + getUserMedia: async () => { + asked = true; + return fakeMedia().stream; + }, + }); + await h.controller.start({ agentPubkey: AGENT, channelId: CHANNEL }); + assert.equal(h.controller.getState().phase, "error"); + assert.equal(h.controller.getState().error?.kind, "huddle_active"); + assert.match(h.controller.getState().error?.message ?? "", /couldn't check/); + assert.equal(asked, false); + assert.equal(h.log.starts.length, 0); +}); + test("a huddle that starts while the mic opens refuses the call", async () => { let checks = 0; const h = harness({ diff --git a/desktop/src/features/agent-call/lib/agentCallController.ts b/desktop/src/features/agent-call/lib/agentCallController.ts index 3a7d9576039..8f14aa6fb56 100644 --- a/desktop/src/features/agent-call/lib/agentCallController.ts +++ b/desktop/src/features/agent-call/lib/agentCallController.ts @@ -118,6 +118,8 @@ const FEED_AFTER_END_MS = 90_000; const CONNECT_TIMEOUT_MS = 20_000; const HUDDLE_ACTIVE_MESSAGE = "You're in a huddle. Leave it to call your agent."; +const HUDDLE_UNKNOWN_MESSAGE = + "Buzz couldn't check whether a huddle is using the microphone, so the call didn't start. Try again."; export function feedRetryDelay(failures: number): number { return Math.min(15_000, 1_000 * 2 ** Math.max(0, failures - 1)); @@ -151,17 +153,19 @@ export function registerHuddleAudioProbe(probe: () => boolean): () => void { }; } -/** The registered probe, then the native huddle state (any window's huddle). */ +/** + * The registered probe, then the native huddle state (any window's huddle). + * Throws when the native state can't be read; the call then refuses. + */ async function webviewHuddleActive(): Promise { if (huddleAudioProbe?.()) return true; - try { - const state = await invokeTauri<{ phase?: string } | null>( - "get_huddle_state", - ); - return Boolean(state?.phase && state.phase !== "idle"); - } catch { - return false; + const state = await invokeTauri<{ phase?: unknown } | null>( + "get_huddle_state", + ); + if (typeof state?.phase !== "string") { + throw new Error("huddle_state_unreadable"); } + return state.phase !== "idle"; } /** Whether this webview can place a call at all (WebRTC and a mic API). */ @@ -461,19 +465,24 @@ export class AgentCallController { }; /** - * Refuses the call while a huddle owns the mic. Also true when the attempt - * was superseded meanwhile, so the caller stops either way. + * Refuses the call while a huddle owns the mic, and fails closed when the + * huddle state can't be read. Also true when the attempt was superseded + * meanwhile, so the caller stops either way. */ private async abandonForHuddle(attempt: number): Promise { - let active: boolean; + let active: boolean | null; try { active = await this.transport.isHuddleActive(); } catch { - active = false; + active = null; } if (attempt !== this.attempt) { return true; } + if (active === null) { + this.fail({ kind: "huddle_active", message: HUDDLE_UNKNOWN_MESSAGE }); + return true; + } if (active) { this.fail({ kind: "huddle_active", message: HUDDLE_ACTIVE_MESSAGE }); } diff --git a/desktop/src/features/agent-call/ui/AgentCallButton.tsx b/desktop/src/features/agent-call/ui/AgentCallButton.tsx index 5c0b04bc4f4..f64e179d4e7 100644 --- a/desktop/src/features/agent-call/ui/AgentCallButton.tsx +++ b/desktop/src/features/agent-call/ui/AgentCallButton.tsx @@ -30,13 +30,17 @@ export function AgentCallButton({ isAgentHint: boolean; }) { const knownAgents = useKnownAgentPubkeys(); - const managedAgents = useManagedAgentsQuery().data; + const managedAgents = useManagedAgentsQuery(); const call = useAgentCall(); const key = normalizePubkey(agentPubkey); const isAgent = isAgentHint || knownAgents.has(key); - const runsOnThisDevice = (managedAgents ?? []).some( - (agent) => normalizePubkey(agent.pubkey) === key, - ); + // Wait for the local inventory so the button never flashes for a local + // agent; a failed inventory read still shows it (the host decides). + const runsOnThisDevice = + managedAgents.isPending || + (managedAgents.data ?? []).some( + (agent) => normalizePubkey(agent.pubkey) === key, + ); if (channel.channelType !== "dm" || !isAgent || runsOnThisDevice) { return null; } diff --git a/docs/kiingo-fork-inventory.json b/docs/kiingo-fork-inventory.json index dc9aba50a59..216f9ff75b7 100644 --- a/docs/kiingo-fork-inventory.json +++ b/docs/kiingo-fork-inventory.json @@ -1778,7 +1778,7 @@ { "classification": "retain-generic", "owner": "Buzz messaging maintainers", - "purpose": "Desktop 1:1 agent calls from an agent DM: a proper voice call with the agent through its host's voice core (WebRTC between the webview and the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call button beside the sessions picker in a 1:1 agent DM header (known agents only) starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent (never channels, group DMs or guests). Every request goes through one native command, agent_voice_request, that signs NIP-98 (kind 27235, exact URL with query, method, SHA-256 payload of the exact body) as the signed-in user with X-Buzz-Community, reaches only the host's call routes under /api/buzz-voice/desktop (allowlisted paths, https only, 35 s timeout, size caps, no redirects) and returns {status, body}. The call controller is a port of the host's web call controller: mic with echo cancellation, an oai-events data channel, the time limit, a 5 s disconnect grace, mute, stop the agent's work, hang-up that never cancels work, and the host's call screen feed long-polled (wait 20 s, 1 s to 15 s backoff) for asks, the open question's option taps, per-ask cancel and archive (feed v2) and the post-call recap (followed at most 90 s after hang-up). The dock is mounted once in AppShell; a community switch hangs up and clears it (resetCommunityState()). Hooks: one module plus re-export in extensions/mod.rs, one use item and one command registration in lib.rs, one element and import in ChannelScreenHeader.tsx, one element and import in AppShell.tsx, one reset line and import in useCommunityInit.ts, and the microphone usage string in Info.plist. One audio owner: a call refuses while a huddle is active or starting (a probe registered by the audio-owning HuddleProvider, then the native huddle state, checked before and after the mic opens), and HuddleContext.tsx refuses huddle start and join while a call is busy (one import, one probe registration effect, one guard line in each of startHuddle and joinHuddle). Calls still connecting after 20 s end as media_failed. The native command parses the request URL once, checks its normalised path, and signs and sends that same URL; ask ids reject escapes of dot, slash and backslash; answers are capped at 2 MiB by declared length and while read; BUZZ_DESKTOP_AGENT_VOICE_URL and the shared HTTP-loopback allowance in guest_access.rs apply to debug builds only. No Call button for agents managed on this device.", + "purpose": "Desktop 1:1 agent calls from an agent DM: a proper voice call with the agent through its host's voice core (WebRTC between the webview and the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call button beside the sessions picker in a 1:1 agent DM header (known agents only) starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent (never channels, group DMs or guests). Every request goes through one native command, agent_voice_request, that signs NIP-98 (kind 27235, exact URL with query, method, SHA-256 payload of the exact body) as the signed-in user with X-Buzz-Community, reaches only the host's call routes under /api/buzz-voice/desktop (allowlisted paths, https only, 35 s timeout, size caps, no redirects) and returns {status, body}. The call controller is a port of the host's web call controller: mic with echo cancellation, an oai-events data channel, the time limit, a 5 s disconnect grace, mute, stop the agent's work, hang-up that never cancels work, and the host's call screen feed long-polled (wait 20 s, 1 s to 15 s backoff) for asks, the open question's option taps, per-ask cancel and archive (feed v2) and the post-call recap (followed at most 90 s after hang-up). The dock is mounted once in AppShell; a community switch hangs up and clears it (resetCommunityState()). Hooks: one module plus re-export in extensions/mod.rs, one use item and one command registration in lib.rs, one element and import in ChannelScreenHeader.tsx, one element and import in AppShell.tsx, one reset line and import in useCommunityInit.ts, and the microphone usage string in Info.plist. One audio owner: a call refuses while a huddle is active or starting (a probe registered by the audio-owning HuddleProvider, then the native huddle state, checked before and after the mic opens), and HuddleContext.tsx refuses huddle start and join while a call is busy (one import, one probe registration effect, one guard line in each of startHuddle and joinHuddle). Calls still connecting after 20 s end as media_failed. The native command parses the request URL once, checks its normalised path, and signs and sends that same URL; ask ids reject escapes of dot, slash and backslash; answers are capped at 2 MiB by declared length and while read; BUZZ_DESKTOP_AGENT_VOICE_URL and the shared HTTP-loopback allowance in guest_access.rs apply to debug builds only. A call also refuses (fails closed) when the huddle state can't be read. No Call button for agents managed on this device, and none until the local inventory has loaded.", "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", "paths": [ @@ -1799,7 +1799,7 @@ { "classification": "retain-generic", "owner": "Buzz mobile maintainers", - "purpose": "iOS 1:1 agent calls from an agent DM, matching the desktop call: a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call action beside the sessions action in a 1:1 agent DM header (native navigation action and Flutter button) opens the call screen and starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. Requests go to /api/buzz-voice/ios, NIP-98 signed by the signed-in user over the exact URL, method and body bytes, with X-Buzz-Community. AgentCallPlugin (method channel buzz/agent_call) owns the media: the stasel/WebRTC 154.0.0 binary package pinned exactly (revision 0c0ad84d, binary checksum a2bcdda9...), an outgoing CallKit call created from a provider built at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app audio fallback when CallKit refuses, and interruption, route-change and media-services-reset handling; UIBackgroundModes audio and voip keep the call alive on the lock screen. The Dart controller follows the host's call screen feed by long-poll (asks, the open question's option taps, per-ask cancel and archive, the recap), refuses while a huddle holds the audio, and hangs up on a community switch. Hooks: one plugin property and construction in AppDelegate.swift, the plugin file, the WebRTC package reference and product in project.pbxproj and Package.resolved, the background modes and microphone string in Info.plist, and one native action plus one button in channel_detail_page.dart (the button shows on iOS only). One audio owner: while a call is busy it holds agentCallAudioBusyProvider (shared/huddle/agent_call_audio.dart, exported from huddle.dart), which HuddleSessionNotifier.join (huddle_session.dart, one guard) and MobileHuddleController._start (mobile_huddle_controller.dart, one guard before announcing) refuse on; the call refuses while a huddle is in session, at the tap and again after the native call is up. Natively, VoiceAudioSessionOwner (AgentCallPlugin.swift) marks the call's hold on the AVAudioSession and HuddleMediaPlugin.swift never prepares, reactivates or deactivates the session while it is set (four guards). Peer events act only for the current peer connection; calls still connecting 20 s after the native call is up end as media_failed; answers are capped at the hosted API's 2 MiB (guestAccessMaxResponseBytes); the CallKit name is trimmed and capped at 60 characters; an in-call banner explains a call running without CallKit; feed links show their host.", + "purpose": "iOS 1:1 agent calls from an agent DM, matching the desktop call: a proper voice call with the agent through its host's voice core (WebRTC to the host's realtime voice provider, the host answering the SDP offer), not a huddle. A Call action beside the sessions action in a 1:1 agent DM header (native navigation action and Flutter button) opens the call screen and starts the call with the agent key and the DM channel id; the host answers only after proving the signer is the verified requester of that private 1:1 DM with the agent. Requests go to /api/buzz-voice/ios, NIP-98 signed by the signed-in user over the exact URL, method and body bytes, with X-Buzz-Community. AgentCallPlugin (method channel buzz/agent_call) owns the media: the stasel/WebRTC 154.0.0 binary package pinned exactly (revision 0c0ad84d, binary checksum a2bcdda9...), an outgoing CallKit call created from a provider built at engine start (kept out of Recents, system mute and end), WebRTC in manual-audio mode activated by CallKit (playAndRecord, voiceChat), an in-app audio fallback when CallKit refuses, and interruption, route-change and media-services-reset handling; UIBackgroundModes audio and voip keep the call alive on the lock screen. The Dart controller follows the host's call screen feed by long-poll (asks, the open question's option taps, per-ask cancel and archive, the recap), refuses while a huddle holds the audio, and hangs up on a community switch. Hooks: one plugin property and construction in AppDelegate.swift, the plugin file, the WebRTC package reference and product in project.pbxproj and Package.resolved, the background modes and microphone string in Info.plist, and one native action plus one button in channel_detail_page.dart (the button shows on iOS only). One audio owner: while a call is busy it holds agentCallAudioBusyProvider (shared/huddle/agent_call_audio.dart, exported from huddle.dart), which HuddleSessionNotifier.join (huddle_session.dart, one guard) and MobileHuddleController._start (mobile_huddle_controller.dart, one guard before announcing, plus a listenSelf that mirrors its start-in-progress state to huddleStartingProvider) refuse on; the call refuses while a huddle is in session or starting, at the tap and again after the native call is up. Natively, VoiceAudioSessionOwner (AgentCallPlugin.swift) marks the call's hold on the AVAudioSession and HuddleMediaPlugin.swift never prepares, reactivates or deactivates the session while it is set (four guards). Peer events act only for the current peer connection; calls still connecting 20 s after the native call is up end as media_failed; answers are capped at the hosted API's 2 MiB (guestAccessMaxResponseBytes); the CallKit name is trimmed and capped at 60 characters; an in-call banner explains a call running without CallKit; feed links show their host.", "upstreamStatus": "Generic mechanism configured by the build-time guest route URL; not yet proposed upstream.", "removalCondition": "Remove when block/buzz offers agent voice calls or the host stops serving the call routes.", "paths": [ diff --git a/mobile/lib/features/agent_call/agent_call_controller.dart b/mobile/lib/features/agent_call/agent_call_controller.dart index b7e48d68ea2..f157f27c104 100644 --- a/mobile/lib/features/agent_call/agent_call_controller.dart +++ b/mobile/lib/features/agent_call/agent_call_controller.dart @@ -115,9 +115,12 @@ final agentCallApiProvider = Provider((ref) { return api; }); -/// Whether a huddle holds the audio now (a call waits for it to end). +/// Whether a huddle holds the audio now, or a huddle start is under way (a +/// call waits for it to end). final agentCallHuddleBusyProvider = Provider( - (ref) => ref.watch(huddleSessionProvider).isInSession, + (ref) => + ref.watch(huddleSessionProvider).isInSession || + ref.watch(huddleStartingProvider), ); /// How long a call may stay connecting once the native call is up before it diff --git a/mobile/lib/features/channels/mobile_huddle_controller.dart b/mobile/lib/features/channels/mobile_huddle_controller.dart index f10a7695d69..72b53356dd2 100644 --- a/mobile/lib/features/channels/mobile_huddle_controller.dart +++ b/mobile/lib/features/channels/mobile_huddle_controller.dart @@ -103,6 +103,9 @@ final class MobileHuddleController extends Notifier { @override bool build() { + // This controller's state is "a start is under way"; agent calls read it. + final starting = ref.read(huddleStartingProvider.notifier); + listenSelf((_, next) => starting.update(next)); final unregisterBeforePause = ref .read(relaySessionProvider.notifier) .registerBeforePause(_leaveForBackground); diff --git a/mobile/lib/shared/huddle/agent_call_audio.dart b/mobile/lib/shared/huddle/agent_call_audio.dart index c0c6226ff66..e78b69f5084 100644 --- a/mobile/lib/shared/huddle/agent_call_audio.dart +++ b/mobile/lib/shared/huddle/agent_call_audio.dart @@ -4,11 +4,19 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; /// by the call). A Huddle never starts or joins beside it, or Huddle members /// would be heard as the caller's asks and the agent's voice would play into /// the room. The call refuses to start while a Huddle is in session. -final agentCallAudioBusyProvider = NotifierProvider( - AgentCallAudioBusy.new, +final agentCallAudioBusyProvider = NotifierProvider( + AudioOwnerFlag.new, ); -final class AgentCallAudioBusy extends Notifier { +/// True while a Huddle start is under way (from before it is announced until +/// it joins or rolls back), set by the Huddle controller. A call refuses +/// then too, so a Huddle is never announced and then rolled back for it. +final huddleStartingProvider = NotifierProvider( + AudioOwnerFlag.new, +); + +/// One side's claim on the phone's audio. +final class AudioOwnerFlag extends Notifier { @override bool build() => false; diff --git a/mobile/test/features/agent_call/agent_call_test.dart b/mobile/test/features/agent_call/agent_call_test.dart index 1decdbc4294..b2ecc93f2b9 100644 --- a/mobile/test/features/agent_call/agent_call_test.dart +++ b/mobile/test/features/agent_call/agent_call_test.dart @@ -350,6 +350,17 @@ void main() { expect(media.calls, isEmpty); }); + test('a Huddle start under way keeps the call from starting', () async { + final starting = build([]); + starting.read(huddleStartingProvider.notifier).update(true); + await starting + .read(agentCallProvider.notifier) + .start(agentPubkey: _agent, channelId: _channel, agentName: 'Alfred'); + expect(starting.read(agentCallProvider).phase, AgentCallPhase.error); + expect(media.calls, isEmpty); + expect(requests, isEmpty); + }); + test('a Huddle that joins while the call is set up refuses it', () async { final busy = build([ agentCallHuddleBusyProvider.overrideWith( From 26868ffce9815b417c34c8a74472b02380a38175 Mon Sep 17 00:00:00 2001 From: Ross Hartmann Date: Fri, 23 Oct 2026 09:17:24 -0700 Subject: [PATCH 7/7] fix(mobile): a Huddle join clears an in-flight start's starting flag MobileHuddleController.join supersedes an in-flight start by bumping the generation, so the start's finally skipped its reset and the controller (and huddleStartingProvider, which agent calls read) stayed "starting" until the next leave, end, background or community switch. join now clears it like the other superseding paths. Widget test covers a join during an in-flight start. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Ross Hartmann --- .../channels/mobile_huddle_controller.dart | 3 ++ .../channels/channel_detail_page_test.dart | 47 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/mobile/lib/features/channels/mobile_huddle_controller.dart b/mobile/lib/features/channels/mobile_huddle_controller.dart index 72b53356dd2..8c2a0150210 100644 --- a/mobile/lib/features/channels/mobile_huddle_controller.dart +++ b/mobile/lib/features/channels/mobile_huddle_controller.dart @@ -217,6 +217,9 @@ final class MobileHuddleController extends Notifier { required String startedEventId, }) async { ++_generation; + // A join supersedes an in-flight start, whose finally then skips the + // reset: clear "starting" here so calls and new starts aren't refused. + state = false; final admissionEpoch = ++_admissionEpoch; _latestAdmissionTargetBackingChannelId = ephemeralChannelId; final currentPubkey = ref.read(currentPubkeyProvider); diff --git a/mobile/test/features/channels/channel_detail_page_test.dart b/mobile/test/features/channels/channel_detail_page_test.dart index b32deed9be0..cde6d5bdf81 100644 --- a/mobile/test/features/channels/channel_detail_page_test.dart +++ b/mobile/test/features/channels/channel_detail_page_test.dart @@ -8819,6 +8819,53 @@ void main() { }, ); + testWidgets('a join during an in-flight Huddle start clears starting', ( + tester, + ) async { + final createGate = Completer(); + final relaySession = _ReconnectingRelaySession( + huddleCreatePublishGate: createGate.future, + ); + + await tester.pumpWidget( + _buildTestable( + messages: const [], + users: const {'self': UserProfile(pubkey: 'self')}, + relayConfigNotifier: _HuddleRelayConfigNotifier(), + relaySessionNotifier: relaySession, + huddleCurrentPubkey: 'self', + huddleMediaFactory: _HuddleTestMedia.new, + huddleTransportFactory: (_) => _HuddleTestTransport(), + createChannelActions: (ref) => _FakeChannelActions(ref), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(const ValueKey('channel-huddle-button'))); + await relaySession.huddleCreatePublishStarted.future; + final container = ProviderScope.containerOf( + tester.element(find.byType(MobileHuddleShell)), + ); + expect(container.read(huddleStartingProvider), isTrue); + + final join = container + .read(mobileHuddleControllerProvider.notifier) + .join( + parentChannelId: _channelId, + ephemeralChannelId: _huddleChannelId, + startedBy: 'desktop', + startedEventId: 'superseding-join', + ); + expect(container.read(huddleStartingProvider), isFalse); + + createGate.complete(); + await join.catchError((_) {}); + await tester.pump(const Duration(seconds: 1)); + expect(container.read(huddleStartingProvider), isFalse); + await container.read(mobileHuddleControllerProvider.notifier).leave(); + await tester.pump(const Duration(seconds: 1)); + }); + testWidgets( 'community transition leaves a newer call after background cleanup', (tester) async {