Skip to content

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

feat(live): end a Live call when the person clearly asks to hang up (#4312)

Aditya Umale471be4373a32
diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.ts
index d377e66c71..4e5a7617e4 100644
--- a/server/live-call-controller.test.ts
+++ b/server/live-call-controller.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { LiveCallState } from "../shared/wire.ts";
import {
- ATTACH_TIMEOUT_MS, CLOSE_TIMEOUT_MS, CONSENT_SETTLE_MS, DELEGATION_SETTLE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
+ ATTACH_TIMEOUT_MS, CLOSE_TIMEOUT_MS, CONSENT_SETTLE_MS, DELEGATION_SETTLE_MS, GOODBYE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
} from "./live-call-controller.ts";
import { LIVE_COPY } from "../shared/live-approval.ts";
@@ -474,6 +474,107 @@ describe("LiveCallController relay", () => {
});
});
+ describe("a spoken request to hang up", () => {
+ const closes = (t: ReturnType<typeof setup>) => t.socket().sent.filter((e) => e.type === "session.close");
+
+ it("says goodbye, then ends the call the way the End button does", async () => {
+ const t = await live();
+ hear(t, "okay, thanks, you can hang up now.", 100);
+ await delegate(t, "del_1", 400);
+ expect(t.deps.send).not.toHaveBeenCalled();
+ expect(t.socket().appends("instructions").at(-1)).toMatchObject({ delegation_id: "del_1", content: LIVE_COPY.goodbye });
+ expect(closes(t)).toHaveLength(0);
+ hear(t, "wait", 1_000);
+ await delegate(t, "del_2", 1_200);
+ expect(t.deps.send).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(GOODBYE_MS);
+ expect(closes(t)).toHaveLength(1);
+ t.socket().receive({ type: "session.closed", reason: "close_requested" });
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "hung-up" });
+ expect(t.controller.current()).toBeNull();
+ });
+
+ it("says nothing about a request that fails to send after the goodbye", async () => {
+ let fail: (error: Error) => void = () => {};
+ const t = await live({ send: vi.fn(() => new Promise<never>((_resolve, reject) => { fail = reject; })) });
+ hear(t, "check my mail", 100);
+ await delegate(t, "del_1", 400);
+ hear(t, "hang up", 1_000);
+ await delegate(t, "del_2", 1_200);
+ fail(new Error("offline"));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.socket().appends("commentary")).toHaveLength(0);
+ });
+
+ it("never says an answer is missing when the bot stops during the goodbye", async () => {
+ const t = await live();
+ hear(t, "check my mail", 100);
+ await delegate(t, "del_1", 400);
+ t.setActivity("working");
+ await vi.advanceTimersByTimeAsync(0);
+ hear(t, "hang up", 2_000);
+ await delegate(t, "del_2", 2_200);
+ t.setActivity("idle");
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.socket().appends("commentary").map((e) => e.content)).not.toContain(LIVE_COPY.noAnswer);
+ });
+
+ it("keeps the call for anything that is not a clear request to hang up", async () => {
+ for (const text of ["don't hang up", "how do I end the call?", "hang up the poster in my room", "end the call with Sam on my calendar", "bye"]) {
+ const t = await live();
+ hear(t, text, 100);
+ await delegate(t, "del_1", 400);
+ expect(vi.mocked(t.deps.send).mock.calls.map(([input]) => input.text), text).toEqual([text]);
+ await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
+ expect(closes(t), text).toHaveLength(0);
+ expect(t.controller.current()?.status, text).toBe("live");
+ }
+ });
+
+ it("never hangs up on the voice's own words heard back through a speaker", async () => {
+ const t = await live();
+ t.socket().receive({ type: "session.output_transcript.delta", delta: "Should I hang up?", start_ms: 1_000, end_ms: 2_000 });
+ hear(t, "hang up", 1_200, 1_400);
+ await delegate(t, "del_1", 1_500);
+ await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
+ expect(closes(t)).toHaveLength(0);
+ expect(t.socket().appends("instructions").some((e) => e.content === LIVE_COPY.goodbye)).toBe(false);
+ });
+
+ it("keeps the call when the words before \"hang up\" were heard over the voice", async () => {
+ const t = await live();
+ t.socket().receive({ type: "session.output_transcript.delta", delta: "Here is what I found.", start_ms: 1_000, end_ms: 2_000 });
+ hear(t, "don't", 1_200, 1_400);
+ hear(t, "hang up", 2_100, 2_300);
+ await delegate(t, "del_1", 2_500);
+ await vi.advanceTimersByTimeAsync(GOODBYE_MS + CLOSE_TIMEOUT_MS);
+ expect(closes(t)).toHaveLength(0);
+ expect(t.socket().appends("instructions").some((e) => e.content === LIVE_COPY.goodbye)).toBe(false);
+ });
+
+ it("speaks no more of the bot's answers once the goodbye starts", async () => {
+ const t = await live();
+ hear(t, "check my mail", 100);
+ await delegate(t, "del_1", 300);
+ hear(t, "okay, thanks, you can hang up now.", 1_000);
+ await delegate(t, "del_2", 1_200);
+ t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: LIVE_COPY.goodbye });
+ expect(t.socket().appends("commentary")).toHaveLength(0);
+ });
+
+ it("keeps the real end reason when the call drops during the goodbye", async () => {
+ const t = await live();
+ hear(t, "hang up", 100);
+ await delegate(t, "del_1", 400);
+ t.socket().drop();
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost" });
+ await vi.advanceTimersByTimeAsync(GOODBYE_MS);
+ expect(closes(t)).toHaveLength(0);
+ });
+ });
+
it("sends the words since the last request to the bot, as the call's starter", async () => {
const t = await live();
const callId = t.controller.current()!.callId;
@@ -894,6 +995,32 @@ describe("LiveCallController relay", () => {
expect(t.socket().appends("instructions").at(-1)).toMatchObject({ content: LIVE_COPY.notClear });
});
+ it("says nothing about a failed save once the person asked to hang up", async () => {
+ let finish: (result: { ok: false; error: string }) => void = () => {};
+ const t = await live({ respond: vi.fn(() => new Promise<{ ok: false; error: string }>((resolve) => { finish = resolve; })) });
+ t.message(approval());
+ await vi.advanceTimersByTimeAsync(0);
+ hear(t, "yes go ahead", 5_000);
+ await delegate(t, "del_2", 5_200);
+ expect(t.deps.respond).toHaveBeenCalled();
+ hear(t, "hang up", 6_000);
+ await delegate(t, "del_3", 6_200);
+ finish({ ok: false, error: "disk full" });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(t.socket().appends("commentary").map((e) => e.content)).not.toContain(LIVE_COPY.saveFailed("disk full"));
+ });
+
+ it("grants nothing heard after the person asked to hang up", async () => {
+ const t = await live();
+ t.message(approval());
+ await vi.advanceTimersByTimeAsync(0);
+ hear(t, "hang up", 5_000);
+ await delegate(t, "del_2", 5_200);
+ hear(t, "yes", 5_400);
+ await vi.advanceTimersByTimeAsync(CONSENT_SETTLE_MS + 1);
+ expect(t.deps.respond).not.toHaveBeenCalled();
+ });
+
it("accepts a yes heard in a quiet moment, without a delegation", async () => {
const t = await live();
t.message(approval());
diff --git a/server/live-call-controller.ts b/server/live-call-controller.ts
index 63adf6763e..6460da5e1d 100644
--- a/server/live-call-controller.ts
+++ b/server/live-call-controller.ts
@@ -7,7 +7,7 @@ import {
import { clampAppend, commentaryChunks, LiveTranscript } from "../shared/live-call.ts";
import { signInWaits } from "../shared/sign-in-request.ts";
import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason } from "../shared/wire.ts";
-import { LIVE_NEEDS_KEY, liveCallSummaryLine, LiveSessionError, liveVoice } from "./live-call.ts";
+import { LIVE_NEEDS_KEY, liveCallSummaryLine, LiveSessionError, liveVoice, spokenHangUp } from "./live-call.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { Message, StoreChange } from "./store.ts";
@@ -18,6 +18,8 @@ export const ATTACH_TIMEOUT_MS = 10_000;
export const CLOSE_TIMEOUT_MS = 5_000;
export const IDLE_CHECK_MS = 15_000;
export const STATUS_INTERVAL_MS = 30_000;
+/** Time for the voice to say goodbye before a call the person asked to end is closed. */
+export const GOODBYE_MS = 4_000;
const SOCKET_OPEN = 1;
const MAX_ERRORS = 5;
const MAX_REVOKED_DEVICES = 200;
@@ -116,6 +118,8 @@ interface Call {
drainBatch: string[] | null;
spokenAnswers: Set<string>;
pendingEnd: LiveEndReason | null;
+ /** The person asked to hang up; the voice is saying goodbye before the call closes. */
+ goodbye: boolean;
timers: Set<Timer>;
consentTimer: Timer | null;
idleTimer: ReturnType<typeof setInterval> | null;
@@ -253,6 +257,7 @@ export class LiveCallController {
drainBatch: null,
spokenAnswers: new Set(),
pendingEnd: null,
+ goodbye: false,
timers: new Set(),
consentTimer: null,
idleTimer: null,
@@ -460,9 +465,16 @@ export class LiveCallController {
private async delegate(call: Call, id: string, offsetMs: number): Promise<void> {
- if (call.state.status !== "live") return;
+ if (call.state.status !== "live" || call.goodbye) return;
const heard = call.transcript.takeRequestParts(offsetMs);
const said = heard.text;
+ // Only the person's own words, never what the voice said back, and all of them: "don't" may be lost in the echo.
+ if (spokenHangUp(heard.withoutEcho) && spokenHangUp(said)) {
+ call.goodbye = true;
+ this.append(call, "instructions", LIVE_COPY.goodbye, id);
+ this.later(call, () => this.hangUp(call, "hung-up"), GOODBYE_MS);
+ return;
+ }
if (call.approval && !call.approval.submitted) {
await this.decide(call, heard.withoutEcho, id, said);
return;
@@ -474,7 +486,7 @@ export class LiveCallController {
call.stats.answers += 1;
const answer = heard.withoutEcho || said;
const result = await this.respond(call, { auth: call.auth, threadId: call.state.threadId, requestId: question.requestId, behavior: "answer", message: answer, callId: call.state.callId }, id);
- if (!result) return;
+ if (!result || call.goodbye) return;
if (result.ok) {
this.append(call, "thinking", LIVE_COPY.answerPassed, id);
} else if (call.question === question) {
@@ -510,12 +522,13 @@ export class LiveCallController {
}
const detail = error instanceof Error ? error.message.trim().slice(0, 200) : "";
this.recordError(call, "send-failed");
+ if (call.goodbye) return;
this.append(call, "commentary", `The request could not be sent to ${call.botName}${detail ? `: ${detail}` : "."}`, id);
}
}
private async decide(call: Call, said: string, delegationId: string | null, heard: string = said): Promise<void> {
- if (call.state.status !== "live") return;
+ if (call.state.status !== "live" || call.goodbye) return;
const open = call.approval;
if (!open || open.submitted) return;
const decision = spokenConsent(said, "live");
@@ -536,7 +549,7 @@ export class LiveCallController {
behavior: decision,
message: decision === "deny" ? LIVE_COPY.deniedMessage : undefined,
}, delegationId);
- if (!result) return;
+ if (!result || call.goodbye) return;
if (!result.ok && call.approval === open) {
open.submitted = false;
this.append(call, "commentary", LIVE_COPY.saveFailed(result.error.trim().slice(0, 200)), delegationId);
@@ -573,7 +586,7 @@ export class LiveCallController {
if (activity === "working") this.touch(call);
if (activity === "working" && (was === "idle" || call.workStartedAt === null)) this.beginWork(call);
if (activity === "idle") call.workStartedAt = null;
- if (was === "idle" || activity !== "idle") return;
+ if (was === "idle" || activity !== "idle" || call.goodbye) return;
this.forgetUnqueued(call);
if (call.approval || call.question || call.queuedIds.size) return;
if (!call.pendingCall.size && !call.claimNextTerminal) return;
@@ -602,6 +615,7 @@ export class LiveCallController {
}
return;
}
+ if (call.goodbye) return;
if (message.kind === "options") {
this.onCard(call, message);
return;
diff --git a/server/live-call.test.ts b/server/live-call.test.ts
index 21d3cf5374..19ab703351 100644
--- a/server/live-call.test.ts
+++ b/server/live-call.test.ts
@@ -13,6 +13,7 @@ import {
liveInstructions,
liveSessionsUrl,
MAX_SDP_BYTES,
+ spokenHangUp,
} from "./live-call.ts";
import { CLOUD_HOME_PLACE } from "./system-prompt.ts";
@@ -243,3 +244,20 @@ describe("liveErrorMessage", () => {
expect(liveErrorMessage(400)).toMatch(/call settings/);
});
});
+
+describe("spokenHangUp", () => {
+ it("accepts only a whole, clear request to end the call", () => {
+ for (const text of ["hang up", "Hang up.", "please hang up", "you can hang up now", "okay, bye, hang up", "thanks, you can end the call now",
+ "end the call", "End call please", "can you hang up?", "go ahead and end this call", "let's end the call. Bye!", "um, hang up the call", "that\u2019s all, let\u2019s end the call"]) {
+ expect(spokenHangUp(text), text).toBe(true);
+ }
+ for (const text of ["", "bye", "goodbye", "thanks", "don't hang up", "please don't end the call", "no, hang up", "how do I end the call?",
+ "hang up the poster", "hang up on him", "end the call with Sam", "what's the weather, then hang up", "end it", "should I hang up?"]) {
+ expect(spokenHangUp(text), text).toBe(false);
+ }
+ });
+
+ it("tells the voice to delegate a hang-up request and never to end a call on its own", () => {
+ expect(liveInstructions({ name: "Rigel" })).toContain("- The user clearly asks you to hang up or end the call. Never end or offer to end the call on your own.");
+ });
+});
diff --git a/server/live-call.ts b/server/live-call.ts
index de3e8f2afc..4ab32b1922 100644
--- a/server/live-call.ts
+++ b/server/live-call.ts
@@ -89,6 +89,7 @@ export function liveInstructions(bot: LiveBot, { cloudHome = false }: { cloudHom
"- The user asks something about you that this conversation does not already answer, for example which AI model you run on.",
"- The user answers a question you asked, including yes or no to a permission request.",
"- A correction or a new detail changes work already requested.",
+ "- The user clearly asks you to hang up or end the call. Never end or offer to end the call on your own.",
"Do not delegate to the backend when:",
"- You can answer from this conversation or from a result that is still current.",
"- The user only greets you, thanks you, or asks you to repeat something you already said.",
@@ -102,6 +103,17 @@ export function liveInstructions(bot: LiveBot, { cloudHome = false }: { cloudHom
].join("\n");
}
+// Words that may open or close a hang-up request ("okay, bye, hang up now").
+const HANG_UP_LEAD = /^(?:(?:um+|uh+|er+|so|well|ok|okay|alright|all right|great|thanks|thank you|bye|goodbye|that's all|that is all)(?:[\s,.!?-]+|$))+/i;
+// The whole utterance must be the request: "don't hang up", "how do I end the call?" or
+// "hang up the poster" never match, and neither does anything a page, file or bot said.
+const HANG_UP = /^(?:(?:please|you can|you may|go ahead and|can you|could you|would you|will you|let's|let us)[\s,]+)*(?:hang\s+up(?:\s+(?:the|this)\s+(?:call|phone))?|end\s+(?:(?:the|this|our)\s+)?call)(?:[\s,.!]+(?:now|please|thanks|thank you|bye|goodbye))*[\s.!?]*$/i;
+
+/** True only when the person's own words on a Live call are a clear request to hang up. */
+export function spokenHangUp(text: string): boolean {
+ return HANG_UP.test(text.trim().replace(/[\u2018\u2019]/g, "'").replace(HANG_UP_LEAD, ""));
+}
+
export function liveInitialInput(history: LiveHistoryMessage[]) {
const picked: LiveHistoryMessage[] = [];
let total = 0;
diff --git a/shared/live-approval.ts b/shared/live-approval.ts
index ecbe9bb731..2163e0a8ea 100644
--- a/shared/live-approval.ts
+++ b/shared/live-approval.ts
@@ -141,5 +141,6 @@ export const LIVE_COPY = {
lastStep ? `; last step: ${lastStep}, ${duration(lastStepAgoMs)} ago` : ""}).`,
signedOut: "The call has ended because the sign-in that started it has ended. Sign in again to start a new call.",
unpaired: "The call has ended because the phone that started it was unpaired from this computer.",
+ goodbye: "The user asked to end the call. Say a short goodbye in one sentence and nothing else; the call ends right after.",
permissionRequest: (prompt: string) => `You need the user's permission. Say it in your own words: ${prompt} Ask for a clear yes or no, then delegate their answer.`,
};