Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(voice-runtime): quote the user's latest words instead of guessing their language

muterCc23e279278ba
diff --git a/apps/teamhub/internal/taskexecution/attempt_reconcile.go b/apps/teamhub/internal/taskexecution/attempt_reconcile.go
index 50c2fd4d..b5548b0a 100644
--- a/apps/teamhub/internal/taskexecution/attempt_reconcile.go
+++ b/apps/teamhub/internal/taskexecution/attempt_reconcile.go
@@ -274,17 +274,6 @@ func taskDoneReminder(taskID string) string {
"ordinary message what the user should add or check, if anything."
}
-// ReportReply is the Agent's own words in an idle Task report, without the
-// first line that tells the Meta what to do with them. Any other report is
-// returned whole.
-func ReportReply(report string) string {
- header, reply, found := strings.Cut(report, "\n")
- if found && strings.HasPrefix(header, "Task ") && strings.Contains(header, ") is idle. If it is done, deliver it") {
- return reply
- }
- return report
-}
-
func failTaskAttempt(
ctx context.Context,
queries *store.Queries,
diff --git a/apps/teamhub/internal/taskexecution/attempt_reconcile_test.go b/apps/teamhub/internal/taskexecution/attempt_reconcile_test.go
index 5cb12801..f905e155 100644
--- a/apps/teamhub/internal/taskexecution/attempt_reconcile_test.go
+++ b/apps/teamhub/internal/taskexecution/attempt_reconcile_test.go
@@ -113,18 +113,3 @@ func TestInspectCurrentAttemptRunsKeepsTheReportedRunAndError(t *testing.T) {
t.Fatalf("activation failure=%+v err=%v", result, err)
}
}
-
-func TestReportReplyDropsOnlyTheMetaReminder(t *testing.T) {
- idle := "Task Find ticket prices (workitem_1) is idle. " + taskDoneReminder("workitem_1") + "\nAdult tickets are 190.\nBook ahead."
- if got := ReportReply(idle); got != "Adult tickets are 190.\nBook ahead." {
- t.Fatalf("idle report: %q", got)
- }
- failed := "Task Find ticket prices (workitem_1) failed: the site was down"
- if got := ReportReply(failed); got != failed {
- t.Fatalf("failed report: %q", got)
- }
- plain := "Task one\nsecond line"
- if got := ReportReply(plain); got != plain {
- t.Fatalf("other text: %q", got)
- }
-}
diff --git a/apps/teamhub/internal/voice/voice_live_tasks.go b/apps/teamhub/internal/voice/voice_live_tasks.go
index e157900e..dad32300 100644
--- a/apps/teamhub/internal/voice/voice_live_tasks.go
+++ b/apps/teamhub/internal/voice/voice_live_tasks.go
@@ -54,7 +54,7 @@ func (s *Service) voiceLiveTaskViews(ctx context.Context, session voicelive.Sess
// The live voice coordinates the task: it gets the AlterEgo's own
// words, without what a Meta is reminded to do with them.
records[index].Report = &voicelive.TaskReport{
- ID: row.ReportID, Body: taskexecution.ReportReply(row.ReportBody), Delivered: row.ReportDelivered,
+ ID: row.ReportID, Body: row.ReportBody, Delivered: row.ReportDelivered,
}
}
if row.RunID != "" {
diff --git a/apps/voice-runtime/src/realtime.ts b/apps/voice-runtime/src/realtime.ts
index e6293fea..1a86f5bf 100644
--- a/apps/voice-runtime/src/realtime.ts
+++ b/apps/voice-runtime/src/realtime.ts
@@ -32,7 +32,7 @@ export function historyPairs(
* language these instructions, tools and results happen to be written in.
*/
const languageRule =
- "LANGUAGE: Speak only the language of the user's latest words. When they speak Chinese, even with a few English words in it, every word you say is Chinese, except names of people, companies, products and apps: say an English word the user or a result used by its Chinese equivalent (the Chinese for deadline, follow-up, job offer, meeting, update, draft, onboarding), restate any message, email or reminder you are about to send in Chinese, translate English results, meeting names and titles into Chinese, and read numbers, dates and versions the Chinese way. When they speak English, answer in English, with no Chinese word in it. Titles and text you write into a document, email or note are in the user's language too, unless they ask for another. The language of these instructions, the tools and the results never decides the language you speak, and your reasoning is never spoken.";
+ "LANGUAGE: Speak only the language of the user's latest words. When they speak Chinese, even with a few English words in it, every word you say is Chinese, except names of people, companies, products and apps: say an English word the user or a result used by its Chinese equivalent (the Chinese for deadline, follow-up, job offer, meeting, update, draft, onboarding), restate any message, email or reminder you are about to send in Chinese, translate English results, meeting names and titles into Chinese, and read numbers, dates and versions the Chinese way. When they speak English, answer in English, with no word of another language in it. Titles and text you write into a document, email or note are in the user's language too, unless they ask for another. The language of these instructions, the tools and the results never decides the language you speak, and your reasoning is never spoken.";
/** Said first and last, right after the language: how long one answer is. */
const lengthRule =
diff --git a/apps/voice-runtime/src/xai-live.test.ts b/apps/voice-runtime/src/xai-live.test.ts
index 4b8eaf63..fe78d172 100644
--- a/apps/voice-runtime/src/xai-live.test.ts
+++ b/apps/voice-runtime/src/xai-live.test.ts
@@ -4,22 +4,10 @@ import { WebSocketServer, type WebSocket } from "ws";
import { afterEach, describe, expect, it } from "vitest";
import type { LiveEvent } from "./live-session.js";
-import {
- cutOffNote,
- spokenLanguage,
- withLanguage,
- XaiLiveSession,
-} from "./xai-live.js";
-
-/** Han text built from code points, so the source holds no Chinese. */
-const han = (count: number) =>
- String.fromCodePoint(
- ...Array.from({ length: count }, (_, index) => 0x4e00 + index),
- );
-/** A Chinese request with English names in it, as the live input reads. */
-const chineseRequest = `${han(5)}Chrome${han(6)}OpenAI${han(3)}`;
-/** Japanese: kana mixed with Han. */
-const japaneseRequest = `${han(2)}${String.fromCodePoint(0x306e, 0x30cb, 0x30e5)}${han(2)}`;
+import { cutOffNote, withLanguage, XaiLiveSession } from "./xai-live.js";
+
+/** A request in a language the code names nowhere. */
+const spanishRequest = "abre Bing y busca noticias de OpenAI";
type Sent = Record<string, unknown>;
const servers: WebSocketServer[] = [];
@@ -391,7 +379,7 @@ describe("XaiLiveSession", () => {
{
type: "conversation.item.input_audio_transcription.completed",
item_id: "i1",
- transcript: chineseRequest,
+ transcript: spanishRequest,
status: "completed",
},
{ type: "response.created", response: { id: "r1" } },
@@ -407,7 +395,9 @@ describe("XaiLiveSession", () => {
await waitForSent(provider.sent, 2);
const item = provider.sent.at(-1)?.item as { output: string };
expect(item.output.startsWith('{"status":"created"}')).toBe(true);
- expect(item.output).toContain("The user speaks Chinese");
+ expect(item.output).toContain(
+ `Reply in the language of the user's latest words (“${spanishRequest}”)`,
+ );
await session.close();
});
@@ -919,16 +909,12 @@ describe("XaiLiveSession", () => {
});
});
-describe("spokenLanguage", () => {
- it("reads Chinese with English names in it as Chinese", () => {
- expect(spokenLanguage(chineseRequest)).toBe("Chinese");
- expect(spokenLanguage("Please use my local browser")).toBe("English");
- expect(spokenLanguage("OK")).toBeUndefined();
- expect(spokenLanguage(japaneseRequest)).toBeUndefined();
- });
-
- it("leaves a result alone when the language is unknown", () => {
+describe("withLanguage", () => {
+ it("quotes the user's latest words and leaves a result alone without them", () => {
expect(withLanguage("ok")).toBe("ok");
- expect(withLanguage("ok", "English")).toContain("entirely in English");
+ expect(withLanguage("ok", " ")).toBe("ok");
+ const long = withLanguage("ok", "word ".repeat(100));
+ expect(long.startsWith("ok\n\nReply in the language")).toBe(true);
+ expect(long).toContain("…”)");
});
});
diff --git a/apps/voice-runtime/src/xai-live.ts b/apps/voice-runtime/src/xai-live.ts
index fcab66d1..6c217698 100644
--- a/apps/voice-runtime/src/xai-live.ts
+++ b/apps/voice-runtime/src/xai-live.ts
@@ -102,31 +102,26 @@ function audioConfig(transport: "binary" | "json", speed?: number) {
};
}
-export type SpokenLanguage = "Chinese" | "English";
-
-/**
- * The language of a user transcript: Chinese once Han characters outnumber
- * the Latin words mixed into it (Chrome, OpenAI), English when it is Latin
- * words only. Japanese kana or too little text decide nothing.
- */
-export function spokenLanguage(text: string): SpokenLanguage | undefined {
- if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) return undefined;
- const han = text.match(/\p{Script=Han}/gu)?.length ?? 0;
- const latinWords = text.match(/[A-Za-z]+/g)?.length ?? 0;
- if (han > 0 && han >= latinWords) return "Chinese";
- if (han === 0 && latinWords >= 2) return "English";
- return undefined;
-}
+/** How much of the user's latest words a tool result quotes back. */
+const latestWordsLimit = 160;
/**
* Grok answers right after a tool result, whose English JSON and the English
* tool descriptions pulled Chinese replies into English mid-sentence (a Chinese
- * “it is written” followed by “titled …, open beside the chat”).
- * The reminder sits where the reply starts.
+ * “it is written” followed by “titled …, open beside the chat”). The reminder
+ * sits where the reply starts and quotes the user's latest words, so the model
+ * sees which language to keep without any language being named here.
*/
-export function withLanguage(output: string, language?: SpokenLanguage) {
- if (!language) return output;
- return `${output}\n\nThe user speaks ${language}: say your reply entirely in ${language}, every word except names of people, companies, products and apps, whatever language this result is in.`;
+export function withLanguage(output: string, latestWords?: string) {
+ const words = latestWords?.trim();
+ if (!words) return output;
+ const quoted =
+ words.length > latestWordsLimit
+ ? `${words.slice(0, latestWordsLimit)}…`
+ : words;
+ return `${output}
+
+Reply in the language of the user's latest words (“${quoted}”), every word except names of people, companies, products and apps, whatever language this result is in.`;
}
const maximumQueuedEvents = 2_048;
@@ -259,8 +254,8 @@ export class XaiLiveSession implements LiveSession {
private readonly completedInputs = new Set<string>();
private readonly inputTexts = new Map<string, string>();
private lastInputId?: string;
- /** The language of the user's latest words, for tool results. */
- private userLanguage?: SpokenLanguage;
+ /** The user's latest words, quoted back with tool results. */
+ private latestWords?: string;
private constructor(
private readonly socket: WebSocket,
@@ -557,7 +552,7 @@ export class XaiLiveSession implements LiveSession {
item: {
type: "function_call_output",
call_id: result.callId,
- output: withLanguage(result.output, this.userLanguage),
+ output: withLanguage(result.output, this.latestWords),
},
});
}
@@ -621,8 +616,7 @@ export class XaiLiveSession implements LiveSession {
const itemId = text("item_id");
if (this.completedInputs.has(itemId)) return;
this.inputTexts.set(itemId, text("transcript"));
- this.userLanguage =
- spokenLanguage(text("transcript")) ?? this.userLanguage;
+ this.latestWords = text("transcript") || this.latestWords;
// The transcript is cumulative, as the worker's partial is.
return this.push({
type: "transcript_delta",
@@ -633,8 +627,7 @@ export class XaiLiveSession implements LiveSession {
case "conversation.item.input_audio_transcription.completed": {
const itemId = text("item_id");
this.inputTexts.set(itemId, text("transcript"));
- this.userLanguage =
- spokenLanguage(text("transcript")) ?? this.userLanguage;
+ this.latestWords = text("transcript") || this.latestWords;
// Interim segments also arrive as "completed" while still in progress.
if (event.status === "completed") this.completeInput(itemId);
return;