Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

7.9 KB
Raw Blame
// REST client for the voice orb. Plain same-origin fetch (mirrors
// agenticIdeApi), `no-store` so a WebView cannot answer with yesterday's state.
import { fill, translate } from "@/i18n";
import { voiceModeEndpoint } from "./embeddedDesktop";

export interface VoiceCallAnswer {
  armed: boolean;
  /**
   * Why the host refused, when `armed` is false (`lib/voiceStartRefusal.ts`).
   * Absent on a host from before the field existed.
   */
  reason?: string;
}

export interface VoiceHangupAnswer {
  stopped: boolean;
}

/**
 * A failed voice request. `status` lets a caller tell "this host runs no
 * speech pipeline" (503) apart from a real failure; the message is what the
 * person reads.
 */
export type VoiceRequestError = Error & { status: number };

async function post<T>(path: string): Promise<T> {
  const res = await fetch(path, { method: "POST", cache: "no-store" });
  if (!res.ok) {
    let detail = "";
    try {
      detail = ((await res.json()) as { detail?: string }).detail ?? "";
    } catch {
      /* a non-JSON error body — the status line below still names the failure */
    }
    const message =
      res.status === 503
        ? translate("voice.not_running_here")
        : detail || fill(translate("voice.request_failed"), { status: res.status });
    throw Object.assign(new Error(message), { status: res.status }) as VoiceRequestError;
  }
  return (await res.json()) as T;
}

/** Start a voice conversation — the click-shaped wake word. */
export function requestVoiceCall(): Promise<VoiceCallAnswer> {
  return post<VoiceCallAnswer>("/api/voice/call");
}

/** End the running voice conversation — same contract as the hangup key. */
export function requestVoiceHangup(): Promise<VoiceHangupAnswer> {
  return post<VoiceHangupAnswer>("/api/voice/hangup");
}

/**
 * Whether the configured realtime transport needs a browser-supplied WebRTC
 * offer at all (`requires_webrtc_offer` from GET /api/settings/voice-mode).
 *
 * A capability, never a provider id (AP-21). `null` means the backend could not
 * be asked and is NOT the same as `false`: an unknown answer must keep every
 * genuine failure visible, because hiding a real blocker is the worse failure.
 */
export async function fetchRealtimeOfferRequirement(): Promise<boolean | null> {
  try {
    const res = await fetch(voiceModeEndpoint(), { cache: "no-store" });
    if (!res.ok) return null;
    const body = (await res.json()) as { requires_webrtc_offer?: unknown };
    return typeof body.requires_webrtc_offer === "boolean"
      ? body.requires_webrtc_offer
      : null;
  } catch (error) {
    // Deliberately degraded to "unknown" rather than swallowed: the caller
    // treats null as "cannot rule the requirement out" and still reports.
    console.info("Realtime offer requirement could not be read.", error);
    return null;
  }
}

export interface TtsVolumeState {
  volume: number;
}

export interface SpeakerOutputState {
  muted: boolean;
  volume: number;
  revision: number;
}

export async function fetchSpeakerMute(): Promise<SpeakerOutputState> {
  const res = await fetch("/api/settings/speaker-mute", { cache: "no-store" });
  if (!res.ok) throw new Error(`Speaker state request failed (${res.status}).`);
  return (await res.json()) as SpeakerOutputState;
}

export function toggleSpeakerMute(): Promise<SpeakerOutputState> {
  return post<SpeakerOutputState>("/api/settings/speaker-mute");
}

/** The master TTS volume — 0.0–1.0, the same value the settings slider shows. */
export async function fetchTtsVolume(): Promise<TtsVolumeState> {
  const res = await fetch("/api/settings/tts-volume", { cache: "no-store" });
  if (!res.ok) throw new Error(`Voice volume request failed (${res.status}).`);
  return (await res.json()) as TtsVolumeState;
}

/**
 * Set the master TTS volume. `persist: false` keeps the change session-only —
 * the voice bubble's speaker toggle must never write a mute into jarvis.toml
 * that would survive a restart the user has long forgotten about.
 */
export async function setTtsVolume(
  volume: number,
  persist: boolean,
): Promise<void> {
  const res = await fetch("/api/settings/tts-volume", {
    method: "PUT",
    cache: "no-store",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ volume, persist }),
  });
  if (!res.ok) {
    let detail = "";
    try {
      detail = ((await res.json()) as { detail?: string }).detail ?? "";
    } catch {
      /* a non-JSON error body — the status line below still names the failure */
    }
    throw new Error(detail || `Voice volume change failed (${res.status}).`);
  }
}

export interface VoiceRuntimeState {
  /** Is a speech pipeline running on this host at all? */
  available: boolean;
  /** The fine-grained state every voice surface renders, straight from the
   *  supervisor. `"idle"` whenever no session is running. */
  voiceState: string;
  /** No speech pipeline will ever run here (a VPS, `jarvis serve`), and
   *  /ws/audio accepts a call: the browser that presses Start holds it. */
  browserCall: boolean;
}

/**
 * The backend's own word on what voice is doing RIGHT NOW.
 *
 * `SystemStateChanged` is a one-shot event, so a window that missed one — a
 * dropped socket, a backend restart, a fresh mount — keeps whatever it heard
 * last with nothing to correct it. This is the REST mirror the surfaces
 * reconcile against (hooks/useVoiceStateResync).
 *
 * `null` means "could not be asked" and is NOT "idle": an unknown answer must
 * never overwrite a live state the events are keeping correct.
 */
export async function fetchVoiceRuntimeState(): Promise<VoiceRuntimeState | null> {
  try {
    const res = await fetch("/api/voice/state", { cache: "no-store" });
    if (!res.ok) return null;
    const body = (await res.json()) as {
      available?: unknown;
      state?: unknown;
      voice_state?: unknown;
      browser_call?: unknown;
    };
    const available = body.available === true;
    // An older backend without the field never offers a browser-held call.
    const browserCall = body.browser_call === true;
    if (typeof body.voice_state === "string") {
      return { available, voiceState: body.voice_state, browserCall };
    }
    // A backend from before the field existed still answers the coarse
    // question honestly: an idle pipeline IS "no session runs", which is the
    // whole correction this is read for. Anything else stays "unknown" so a
    // live call is never touched on a guess.
    if (typeof body.state === "string") {
      return {
        available,
        voiceState: body.state === "idle" ? "idle" : "unknown",
        browserCall,
      };
    }
    return null;
  } catch (error) {
    // Offline / headless / the route missing on an older backend: the caller
    // treats null as "no answer" and leaves the store exactly as it is.
    console.info("Voice runtime state could not be read.", error);
    return null;
  }
}


/** Read the active GPT-Live call without starting another connection. */
export async function fetchVoiceComposerSession(): Promise<string | null> {
  const response = await fetch("/api/live/composer", { cache: "no-store" });
  if (!response.ok) throw new Error("Voice input is unavailable.");
  const body = (await response.json()) as { session_id?: unknown };
  return typeof body.session_id === "string" ? body.session_id : null;
}

/** Submit into the existing live call. The request id is reused after an uncertain reply. */
export async function submitVoiceComposer(
  sessionId: string,
  text: string,
  attachments: import("./agentChatApi").ChatAttachment[],
  requestId: string,
): Promise<void> {
  const response = await fetch("/api/live/composer", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      session_id: sessionId,
      request_id: requestId,
      text,
      attachments,
    }),
  });
  if (!response.ok) {
    const body = await response.json().catch(() => null);
    throw new Error(typeof body?.detail === "string" ? body.detail : "Voice input was not accepted.");
  }
}