Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(live): address review of the Fish Audio Live call

Nathaniel1176b064150d
diff --git a/server/live-fish.test.ts b/server/live-fish.test.ts
index ca22c2d7f9..2fa6b36708 100644
--- a/server/live-fish.test.ts
+++ b/server/live-fish.test.ts
@@ -146,6 +146,17 @@ describe("the relay of a Fish call", () => {
]);
});
+ it("takes a batch the client posts again only from the events it has not had", () => {
+ const { relay, messages } = opened();
+ relay.receive([{ type: "connected" }, { type: "delegate", id: "d1", atMs: 1 }], 0);
+ relay.receive([{ type: "connected" }, { type: "delegate", id: "d1", atMs: 1 }, { type: "spoke", startMs: 2, endMs: 3 }], 0);
+ relay.receive([{ type: "spoke", startMs: 2, endMs: 3 }], 2);
+ expect(messages).toEqual([
+ { type: "session.delegation.created", delegation: { id: "d1", target: "client" }, offset_ms: 1 },
+ { type: "session.output_transcript.delta", start_ms: 2, end_ms: 3 },
+ ]);
+ });
+
it("maps only known endings to a reason", () => {
const { relay, messages } = opened();
relay.receive([{ type: "ended", reason: "user_hangup" }, { type: "ended", reason: "conversation_timeout" }]);
diff --git a/server/live-fish.ts b/server/live-fish.ts
index 55cbb6b4f3..324ca7b3dd 100644
--- a/server/live-fish.ts
+++ b/server/live-fish.ts
@@ -26,7 +26,6 @@ export function fishLiveBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
return /^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(override) ? override : FISH_BASE;
}
-/** null without a usable agent id. */
export function fishLiveEndpoint(agentId: string | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {
const id = agentId?.trim() ?? "";
return AGENT_ID.test(id) ? { provider: "fish", apiBase: `${fishLiveBaseUrl(env)}/v1/agent`, model: id } : null;
@@ -172,6 +171,7 @@ export class FishRelay implements LiveSocket {
private queue: LiveFishRelayCommand[] = [];
private waiter: (() => void) | null = null;
private ended: Promise<unknown> | null = null;
+ private received = 0;
constructor(input: { sessionId: string; token: string; endSession: () => Promise<unknown>; forget: () => void }) {
this.sessionId = input.sessionId;
@@ -215,8 +215,11 @@ export class FishRelay implements LiveSocket {
}
/** The client's reports, in order. Before the client has joined only `connected`, `ended` and `error` count. */
- receive(events: LiveFishRelayEvent[]): void {
- for (const event of events) {
+ receive(events: LiveFishRelayEvent[], from = this.received): void {
+ // A batch the client retries after a lost answer starts at events already taken; those are skipped.
+ const fresh = events.slice(Math.max(0, this.received - from));
+ this.received = Math.max(this.received, from + events.length);
+ for (const event of fresh) {
if (this.readyState === SOCKET.closed) return;
if (event.type === "connected") {
if (this.readyState !== SOCKET.connecting) continue;
@@ -286,7 +289,6 @@ export class FishRelay implements LiveSocket {
}
}
-/** The relays of running fish calls, by Fish session id. */
export class FishRelays {
private readonly relays = new Map<string, FishRelay>();
@@ -301,7 +303,6 @@ export class FishRelays {
return { relay, token };
}
- /** The controller's attach: the relay `open` made for this session. */
socket(sessionId: string): FishRelay {
const relay = this.relays.get(sessionId);
if (!relay) throw new Error("no relay for that session");
diff --git a/server/routes/live.test.ts b/server/routes/live.test.ts
index 3cc54fda23..7fab696ed4 100644
--- a/server/routes/live.test.ts
+++ b/server/routes/live.test.ts
@@ -250,7 +250,7 @@ describe("a Fish Audio call", () => {
const { d, relay } = relayDeps();
const events = [{ type: "connected" }, { type: "heard", text: "hi", startMs: 1, endMs: 2 }, { type: "delegate", id: "call_1", atMs: 3 }];
expect(await request(d, "POST", "/api/live/relay", body({ events, wait: true }))).toEqual({ status: 200, body: { commands: [{ type: "close" }], closed: false } });
- expect(relay.receive).toHaveBeenCalledWith(events);
+ expect(relay.receive).toHaveBeenCalledWith(events, undefined);
expect(relay.poll).toHaveBeenCalledWith(0);
});
diff --git a/server/routes/live.ts b/server/routes/live.ts
index 1156bae299..e648b6c2f4 100644
--- a/server/routes/live.ts
+++ b/server/routes/live.ts
@@ -13,7 +13,7 @@ export interface LiveRouteDeps {
settings(): LiveSettings;
saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; fishAgentId?: string; voice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;
/** A running Fish Audio call's relay, only for the token its start answered with. */
- fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[]): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
+ fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[], from?: number): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
}
const id = z.string().regex(/^[\w-]{1,120}$/);
@@ -38,6 +38,7 @@ const relayBody = z.object({
sessionId: z.string().min(1).max(200),
token: z.string().min(1).max(200),
events: z.array(relayEvent).max(20).optional(),
+ from: z.number().int().min(0).max(1_000_000).optional(),
wait: z.boolean().optional(),
}).strict();
// Strict, so `key` is refused rather than ignored: the key is saved only through the credential store or PUT /api/config.
@@ -105,7 +106,7 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
if (!parsed.success) return json(res, 400, { error: "The call update was not valid." });
const relay = deps.fishRelay(parsed.data.sessionId, parsed.data.token);
if (!relay) return json(res, 404, { error: "That call is not running." });
- if (parsed.data.events?.length) relay.receive(parsed.data.events);
+ if (parsed.data.events?.length) relay.receive(parsed.data.events, parsed.data.from);
return json(res, 200, await relay.poll(parsed.data.wait && !parsed.data.events?.length ? RELAY_POLL_MS : 0));
}
diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsx
index 0067d6a4fc..6ef0edf1e4 100644
--- a/src/components/LiveCallSettings.tsx
+++ b/src/components/LiveCallSettings.tsx
@@ -127,7 +127,8 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
{live.keySource !== "live" && !azure && !fish && (
<div className="-mt-2 text-[12px] text-ink-tertiary">{t(live.keySource === "openai" ? "call.live.keyFromApiKeys" : "call.live.needsKey")} <KeysLink id="openai" purpose="liveCalls" /></div>
)}
- {changingKey && <LiveKeySetup compact onSaved={() => setChangingKey(false)} />}
+ {/* Keyed by provider: a key typed for one provider is never saved for another. */}
+ {changingKey && <LiveKeySetup key={state.config?.live?.provider ?? "openai"} compact onSaved={() => setChangingKey(false)} />}
<div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} {t(copy.cost)}</div>
{error && <div className="text-[12px] text-danger">{error}</div>}
</div>
diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsx
index 37a8969568..e6f82fcd59 100644
--- a/src/components/LiveKeyNeeded.tsx
+++ b/src/components/LiveKeyNeeded.tsx
@@ -25,7 +25,7 @@ export function LiveKeyNeeded() {
</div>
<LiveProviderSettings />
{(azure || fish) && <DismissWhenReady ready={live?.configured === true} />}
- {keyForm && <LiveKeySetup compact onSaved={() => {}} />}
+ {keyForm && <LiveKeySetup key={state.config?.live?.provider ?? "openai"} compact onSaved={() => {}} />}
{!azure && !fish && <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(openKeySettings("openai", "liveCalls")); }}>{t("call.live.openApiKeys")}</button>}
<p className="text-[12px] leading-[1.45] text-ink-tertiary">{!keyForm && `${liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} `}{t(copy.cost)}</p>
</section>;
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 4e978737f1..c6706d0dc9 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { Archive, Cloud, Gauge, CloudDownload, Coins, Download, FlaskConical, KeyRound, LockKeyhole, Monitor, Palette, ScrollText, Search, Settings, Sparkles, TabletSmartphone, Terminal, User, Users, X, Building2, Zap, BookOpen, ImagePlus } from "lucide-react";
-import { useStore, type AppSettingsSection } from "@/state/store";
+import { useStore, type AppSettingsSection, type ConfigStatus } from "@/state/store";
import { skillsLibraryEnabled } from "@/lib/feature-flags";
import { type LocaleKey } from "@/locales";
import { t } from "@/lib/i18n";
@@ -165,23 +165,23 @@ export function revealSettingsBlock(
if (block) scrollWithin(scroller, block);
}
-function simplePageMatches(page: SimpleSettingsPage, query: string): boolean {
+function simplePageMatches(page: SimpleSettingsPage, query: string, config?: ConfigStatus | null): boolean {
if (!query) return true;
if ([t(page.labelKey), ...page.keywords ?? []].some((part) => part.toLowerCase().includes(query))) return true;
return page.sections.some((id) => {
const entry = SECTIONS.find((candidate) => candidate.id === id);
- return entry ? sectionMatches(entry, query) : false;
+ return entry ? sectionMatches(entry, query, config) : false;
});
}
-export function sectionMatches(section: (typeof SECTIONS)[number], query: string): boolean {
+export function sectionMatches(section: (typeof SECTIONS)[number], query: string, config?: ConfigStatus | null): boolean {
if (!query) return true;
- if (section.id === "connections" && KEY_CATALOG.some((entry) => keyMatches(entry, query))) return true;
+ if (section.id === "connections" && KEY_CATALOG.some((entry) => keyMatches(entry, query, config))) return true;
return [t(section.labelKey), ...section.keywords].some((part) => part.toLowerCase().includes(query));
}
-export function keySearchResults(query: string): KeyEntry[] {
- return query ? KEY_CATALOG.filter((entry) => keyMatches(entry, query)).slice(0, 8) : [];
+export function keySearchResults(query: string, config?: ConfigStatus | null): KeyEntry[] {
+ return query ? KEY_CATALOG.filter((entry) => keyMatches(entry, query, config)).slice(0, 8) : [];
}
export const openKeyResult = (entry: KeyEntry) => entry.uses ? openKeySettings(entry.uses, entry.id) : openKeySettings(entry.id);
@@ -224,11 +224,11 @@ function SettingsDialog() {
.filter((entry) => entry.id !== "botAccess" || (Boolean(state.config?.team) && ownerOrAdmin === true))
.filter((entry) => !(state.config?.team && ownerOrAdmin === false && TEAM_ADMIN_SECTIONS.includes(entry.id)));
const availableSections = baseSections.filter((entry) => entry.id !== "skills" || skillsLibraryEnabled(state.config));
- const visibleSections = availableSections.filter((entry) => sectionMatches(entry, q));
+ const visibleSections = availableSections.filter((entry) => sectionMatches(entry, q, state.config));
const simpleAvailable = new Set<AppSettingsSection>([...availableSections.map((entry) => entry.id), ...(remoteActive ? [] : ["updates" as const])]);
const simplePages = advanced ? [] : simpleSettingsPages(simpleAvailable, section);
- const visiblePages = simplePages.filter((page) => simplePageMatches(page, q));
+ const visiblePages = simplePages.filter((page) => simplePageMatches(page, q, state.config));
const currentPage = simplePages.find((page) => page.sections.includes(section));
const sectionLabelKey = advanced
@@ -258,7 +258,7 @@ function SettingsDialog() {
const [reveal, setReveal] = useState<string | null>(null);
const advancedMatches = advanced || SIMPLE_ONLY || !q ? [] : SIMPLE_ADVANCED_ONLY.filter((key) => t(key).toLowerCase().includes(q));
const moreSections = availableSections.filter((entry) => SIMPLE_HIDDEN_SECTIONS.includes(entry.id));
- const keyResults = remoteActive || !availableSections.some((entry) => entry.id === "connections") ? [] : keySearchResults(q);
+ const keyResults = remoteActive || !availableSections.some((entry) => entry.id === "connections") ? [] : keySearchResults(q, state.config);
const keyResultButtons = (className: string) => keyResults.map((entry) => (
<button key={entry.id} type="button" data-settings-key-result={entry.id} className={className}
onClick={() => { setQuery(""); setSubPage(null); dispatch(openKeyResult(entry)); }}>
@@ -506,7 +506,7 @@ function SettingsDialog() {
const resultClass = "flex min-h-8 shrink-0 cursor-pointer items-center rounded-lg px-[9px] py-1.5 text-left text-[13px] leading-[18px] text-ink transition-colors hover:bg-ink/[0.06] motion-reduce:transition-none";
const goTo = (id: AppSettingsSection) => { setSubPage(null); openSection(id); };
const moreMatches = !q ? [] : [
- ...moreSections.filter((entry) => sectionMatches(entry, q)).map((entry) => ({ key: entry.id, labelKey: entry.labelKey, open: () => goTo(entry.id) })),
+ ...moreSections.filter((entry) => sectionMatches(entry, q, state.config)).map((entry) => ({ key: entry.id, labelKey: entry.labelKey, open: () => goTo(entry.id) })),
...(simpleAvailable.has("general") ? SIMPLE_MORE_LIMITS : []).filter((key) => t(key).toLowerCase().includes(q))
.map((key) => ({ key, labelKey: key, open: () => { openMore(); setReveal("limits"); } })),
];
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
index 47d4b40122..a1c29eee38 100644
--- a/src/components/keys/KeysPage.tsx
+++ b/src/components/keys/KeysPage.tsx
@@ -151,7 +151,7 @@ export function KeysPage() {
// With Azure or Fish Audio chosen, Live calls do not use the OpenAI key that row points at.
const azureLive = state.config?.live?.provider === "azure" || state.config?.live?.provider === "fish";
- const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q) && !(azureLive && entry.id === "liveCalls"));
+ const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q, state.config) && !(azureLive && entry.id === "liveCalls"));
const sections = KEY_SECTIONS.flatMap((section) => {
const own = rows.filter((entry) => entry.section === section.id);
return own.length > 0 ? [{ id: section.id, rows: own }] : [];
diff --git a/src/components/keys/key-catalog.test.ts b/src/components/keys/key-catalog.test.ts
index 37fd9c5535..cd34a97764 100644
--- a/src/components/keys/key-catalog.test.ts
+++ b/src/components/keys/key-catalog.test.ts
@@ -110,6 +110,14 @@ describe("searching the keys", () => {
expect(found("gemini")).toEqual(["openaiCompat", "geminiTts", "imageGemini"]);
expect(found("no such key anywhere")).toEqual([]);
});
+
+ it("matches the Live key row by the provider Live calls use", () => {
+ const shown = (query: string, provider: "fish" | "azure") =>
+ KEY_CATALOG.filter((entry) => keyMatches(entry, query, { live: { provider } } as never)).map((entry) => entry.id);
+ expect(shown("fish", "fish")).toEqual(expect.arrayContaining(["fishAudio", "liveKey"]));
+ expect(shown("azure", "azure")).toContain("liveKey");
+ expect(found("fish")).not.toContain("liveKey");
+ });
});
describe("a key pasted into the wrong row", () => {
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index 9471fa5dd6..b527924c1e 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -238,10 +238,12 @@ export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefi
return entry.target?.saved(config) ?? entry.status?.(config) ?? { configured: false };
}
-export function keyMatches(entry: KeyEntry, query: string): boolean {
+/** With `config`, the row is matched as shown: the Live key row by the provider Live calls use. */
+export function keyMatches(entry: KeyEntry, query: string, config?: ConfigStatus | null): boolean {
const q = query.trim().toLowerCase();
if (!q) return true;
- return [t(entry.labelKey), t(entry.purposeKey), t(keySection(entry).titleKey), entry.name, ...entry.words].some((part) => part.toLowerCase().includes(q));
+ const shown = config ? shownKeyEntry(entry.id, config) : entry;
+ return [t(shown.labelKey), t(shown.purposeKey), t(keySection(shown).titleKey), shown.name, ...shown.words].some((part) => part.toLowerCase().includes(q));
}
export function looksLikeOtherKey(entry: KeyEntry, value: string): KeyEntry | null {
diff --git a/src/lib/live-call-fish.test.ts b/src/lib/live-call-fish.test.ts
index 6fe6f6fab9..ef850f8865 100644
--- a/src/lib/live-call-fish.test.ts
+++ b/src/lib/live-call-fish.test.ts
@@ -19,7 +19,6 @@ class FakeSession {
tool(callId: string) { return this.options.clientTools[FISH_DELEGATE_TOOL]!({}, { callId }); }
}
-/** A relay that records what the call posts and hands each waiting poll the next queued batch. */
function fakeRelay() {
const posted: Array<Record<string, unknown>> = [];
const batches: Array<{ commands: LiveFishRelayCommand[]; closed: boolean }> = [];
@@ -178,6 +177,47 @@ describe("a Fish Audio call's relay", () => {
expect(made!.end).toHaveBeenCalledTimes(1);
expect(relay.posted).toEqual([]);
});
+
+ it("posts a batch again after a failed post, numbered so the relay takes none of it twice", async () => {
+ const relay = fakeRelay();
+ const deliver = relay.request.getMockImplementation()!;
+ let failNext = true;
+ relay.request.mockImplementation(async (path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ if (body.events && failNext) {
+ failNext = false;
+ relay.posted.push(body);
+ throw new Error("offline");
+ }
+ return deliver(path, init);
+ });
+ vi.useFakeTimers({ toFake: ["setTimeout"] });
+ const { session } = await joined(relay);
+ session.on.onConnect({ sessionId: "sess_1" });
+ const batches = () => relay.posted.filter((body) => body.events);
+ await vi.waitFor(() => expect(batches()).toHaveLength(1));
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(batches().map((body) => [body.from, body.events])).toEqual([[0, [{ type: "connected" }]], [0, [{ type: "connected" }]]]);
+ session.on.onError({ code: "late" });
+ await vi.waitFor(() => expect(batches()).toHaveLength(3));
+ expect(batches()[2]).toMatchObject({ from: 1, events: [{ type: "error", code: "late" }] });
+ });
+
+ it("ends the call on Fish when the harness stays unreachable", async () => {
+ const relay = fakeRelay();
+ relay.request.mockImplementation(async (_path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ relay.posted.push(body);
+ if (body.wait) throw new Error("offline");
+ return { commands: [], closed: false };
+ });
+ vi.useFakeTimers({ toFake: ["setTimeout"] });
+ const { session, hooks } = await joined(relay);
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(session.end).toHaveBeenCalledTimes(1);
+ expect(hooks.ended).toHaveBeenCalledWith("relay_unavailable");
+ expect(relay.posted.filter((body) => body.wait)).toHaveLength(5);
+ });
});
describe("a Fish Audio Live call on screen", () => {
@@ -202,7 +242,7 @@ describe("a Fish Audio Live call on screen", () => {
resetLiveMedia();
configureLiveMedia({ request: request as never, startFish: startFish as never, getUserMedia: getUserMedia as never, createPeer: vi.fn() as never });
});
- afterEach(() => { resetLiveMedia(); vi.unstubAllGlobals(); });
+ afterEach(() => { resetLiveMedia(); vi.unstubAllGlobals(); vi.useRealTimers(); });
it("asks the harness for a Fish session without an offer, and leaves the microphone to Fish's SDK", async () => {
await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
@@ -235,6 +275,30 @@ describe("a Fish Audio Live call on screen", () => {
expect(liveMedia().phase).toBe("idle");
});
+ it("ends the harness's call when Fish drops the session", async () => {
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ session!.on.onConnect({ sessionId: "sess_1" });
+ session!.on.onDisconnect({ reason: "connection_lost" });
+ expect(request).toHaveBeenCalledWith("/api/live/call/end", expect.objectContaining({ body: JSON.stringify({ callId: "c1" }) }));
+ });
+
+ it("does not drop the call while Fish's SDK waits on the microphone prompt", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout"] });
+ let grant: (() => void) | null = null;
+ startFish.mockImplementationOnce((options: FishSessionOptions) => new Promise((resolve) => {
+ grant = () => resolve(session = new FakeSession(options));
+ }));
+ const starting = startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ await vi.waitFor(() => expect(grant).not.toBeNull());
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(liveMedia().phase).toBe("starting");
+ grant!();
+ await starting;
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(liveMedia().phase).toBe("failed");
+ expect(request).toHaveBeenCalledWith("/api/live/call/end", expect.anything());
+ });
+
it("explains a microphone Fish was refused, and retries as a Fish call", async () => {
startFish.mockRejectedValueOnce(Object.assign(new Error("denied"), { code: "mic_permission_denied" }));
configureLiveMedia({ request: request as never, startFish: startFish as never, pageMicrophone: async () => "allowed" });
diff --git a/src/lib/live-call-fish.ts b/src/lib/live-call-fish.ts
index e610acbb94..684ce304da 100644
--- a/src/lib/live-call-fish.ts
+++ b/src/lib/live-call-fish.ts
@@ -68,6 +68,8 @@ export class FishCall {
private session: FishAgentSession | null = null;
private closed = false;
private outbox: LiveFishRelayEvent[] = [];
+ /** How many events the relay has taken; a retried batch carries its first one's number, so none is applied twice. */
+ private delivered = 0;
private flushing: Promise<void> | null = null;
private readonly segmentStarts = new Map<string, number>();
private speakingSince: number | null = null;
@@ -178,11 +180,14 @@ export class FishCall {
private async flush(): Promise<void> {
await Promise.resolve();
while (this.outbox.length && !this.closed) {
- const events = this.outbox.splice(0, MAX_EVENTS_PER_POST);
+ const events = this.outbox.slice(0, MAX_EVENTS_PER_POST);
try {
- this.apply(await this.post({ events }));
+ const answer = await this.post({ events, from: this.delivered });
+ this.delivered += events.length;
+ this.outbox.splice(0, events.length);
+ this.apply(answer);
} catch {
- return;
+ await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
}
}
}
@@ -196,13 +201,18 @@ export class FishCall {
this.apply(answer);
if (answer.closed) return;
} catch {
- if (++failures >= MAX_POLL_FAILURES) return;
- await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
+ // Unreachable, the harness can neither answer nor end the call, so it is not left running on Fish.
+ if (++failures >= MAX_POLL_FAILURES) {
+ this.close();
+ this.hooks.ended("relay_unavailable");
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, RETRY_MS * failures));
}
}
}
- private post(body: { events?: LiveFishRelayEvent[]; wait?: boolean }): Promise<RelayAnswer> {
+ private post(body: { events?: LiveFishRelayEvent[]; from?: number; wait?: boolean }): Promise<RelayAnswer> {
return this.hooks.request<RelayAnswer>("/api/live/relay", {
method: "POST",
body: JSON.stringify({ sessionId: this.transport.session.session_id, token: this.transport.relayToken, ...body }),
diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.ts
index 032b0f0e1e..c6144610dc 100644
--- a/src/lib/live-call-media.ts
+++ b/src/lib/live-call-media.ts
@@ -301,16 +301,23 @@ async function startFishCall(target: { botId: string; threadId: string }, mine:
if (mine === generation) set({ caption: text.slice(-CAPTION_CHARS), heard: "" });
},
ended: () => {
- if (mine === generation) onSessionClosed();
+ if (mine !== generation) return;
+ // Closing the call drops its queued `ended` report, so the server hears of it here.
+ if (state.callId) void endOnServer(state.callId);
+ onSessionClosed();
},
now: () => Date.now(),
}, deps.startFish);
fishCall = call;
- connectTimer = setTimeout(() => {
- if (mine === generation) void dropped(t("call.live.droppedNoAudio"));
- }, MEDIA_CONNECT_TIMEOUT_MS);
+ // Started only now: the SDK's start includes the microphone prompt, which may take the person a while.
await call.start();
- if (mine === generation && state.muted) call.setMuted(true);
+ if (mine !== generation) return;
+ if (state.muted) call.setMuted(true);
+ if (!fishConnected) {
+ connectTimer = setTimeout(() => {
+ if (mine === generation) void dropped(t("call.live.droppedNoAudio"));
+ }, MEDIA_CONNECT_TIMEOUT_MS);
+ }
}
export async function hangUpLiveCall(): Promise<void> {