The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(api): correct message segmentation for multi-part auth responses
Steven Enamakele6c50af52be6
diff --git a/app/src/services/api/__tests__/authApi.test.ts b/app/src/services/api/__tests__/authApi.test.tsdeleted file mode 100644index a051597a90..0000000000--- a/app/src/services/api/__tests__/authApi.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest';--import { sendEmailMagicLink } from '../authApi';--describe('sendEmailMagicLink', () => {- afterEach(() => {- vi.restoreAllMocks();- vi.useRealTimers();- });-- it('posts the email and redirect URI to the backend', async () => {- const fetchSpy = vi- .spyOn(globalThis, 'fetch')- .mockResolvedValue(new Response('{}', { status: 200 }) as Response);-- await sendEmailMagicLink('[email protected]', 'openhuman://');-- const backendUrl = process.env.VITEST_MOCK_API_URL ?? 'http://localhost:5005';- expect(fetchSpy).toHaveBeenCalledWith(`${backendUrl}/auth/email/send-link`, {- method: 'POST',- headers: { 'Content-Type': 'application/json', 'x-web-version': '0.0.0-test' },- body: JSON.stringify({ email: '[email protected]', frontendRedirectUri: 'openhuman://' }),- signal: expect.any(AbortSignal),- });- });-- it('times out stalled requests and surfaces a retry message', async () => {- vi.useFakeTimers();-- vi.spyOn(globalThis, 'fetch').mockImplementation((_input, init) => {- const signal = init?.signal as AbortSignal | undefined;- return new Promise((_resolve, reject) => {- signal?.addEventListener('abort', () => {- reject(new DOMException('The operation was aborted.', 'AbortError'));- });- });- });-- const request = sendEmailMagicLink('[email protected]', 'openhuman://', 100);- const rejection = expect(request).rejects.toThrow('Request timed out. Please try again.');-- await vi.advanceTimersByTimeAsync(100);-- await rejection;- });-});diff --git a/app/src/services/api/authApi.ts b/app/src/services/api/authApi.tsdeleted file mode 100644index b6c9912d4e..0000000000--- a/app/src/services/api/authApi.ts+++ /dev/null@@ -1,54 +0,0 @@-import { getBackendUrl } from '../backendUrl';-import { getClientVersionHeaders } from '../clientVersionHeaders';-import { loginWithToken } from '../session/sessionOwner';--const EMAIL_MAGIC_LINK_TIMEOUT_MS = 15_000;--/**- * Send a magic-link email for email-based login.- * POST /auth/email/send-link- * @param email - The user's email address.- * @param frontendRedirectUri - Where the backend should redirect after verification- * (e.g. "openhuman://" for desktop, or the web app origin for web).- */-export async function sendEmailMagicLink(- email: string,- frontendRedirectUri: string,- timeoutMs = EMAIL_MAGIC_LINK_TIMEOUT_MS-): Promise<void> {- const backendUrl = await getBackendUrl();- const controller = new AbortController();- const timeoutId = window.setTimeout(() => controller.abort(), timeoutMs);-- try {- const versionHeaders = await getClientVersionHeaders();- const response = await fetch(`${backendUrl}/auth/email/send-link`, {- method: 'POST',- headers: { 'Content-Type': 'application/json', ...versionHeaders },- body: JSON.stringify({ email, frontendRedirectUri }),- signal: controller.signal,- });- if (!response.ok) {- const body = (await response.json().catch(() => ({}))) as { error?: string };- throw new Error(body.error ?? `Failed to send magic link (${response.status})`);- }- } catch (error) {- if (- (error instanceof DOMException && error.name === 'AbortError') ||- (error instanceof Error && error.name === 'AbortError')- ) {- throw new Error('Request timed out. Please try again.');- }- throw error;- } finally {- window.clearTimeout(timeoutId);- }-}--/**- * Consume a verified login token and install the resulting session through- * the session owner. Works for both Telegram and OAuth login tokens.- */-export async function loginWithLoginToken(loginToken: string): Promise<void> {- await loginWithToken(loginToken);-}diff --git a/app/src/utils/__tests__/messageSegmentation.test.ts b/app/src/utils/__tests__/messageSegmentation.test.tsdeleted file mode 100644index 5f9ae92d75..0000000000--- a/app/src/utils/__tests__/messageSegmentation.test.ts+++ /dev/null@@ -1,143 +0,0 @@-import { describe, expect, it } from 'vitest';--import { getSegmentDelay, segmentMessage } from '../messageSegmentation';--describe('segmentMessage', () => {- it('returns the original text as a single segment when text is short', () => {- const short = 'Hello there!';- expect(segmentMessage(short)).toEqual([short]);- });-- it('returns single segment for text under 80 chars', () => {- const text = 'This is a sentence that is almost long enough but not quite yet for splitting.';- expect(segmentMessage(text)).toHaveLength(1);- });-- it('splits on paragraph breaks', () => {- const text =- 'First paragraph with enough content to be meaningful and readable.\n\n' +- 'Second paragraph that also has meaningful content and is not too short.';- const segments = segmentMessage(text);- expect(segments.length).toBeGreaterThanOrEqual(2);- expect(segments[0]).toContain('First paragraph');- expect(segments[1]).toContain('Second paragraph');- });-- it('merges short paragraphs with the previous one', () => {- const text =- 'First paragraph with enough content to stand alone as a meaningful segment.\n\n' +- 'Short.\n\n' +- 'Third paragraph with enough content to be a standalone bubble in delivery.';- const segments = segmentMessage(text);- // "Short." should be merged with first or third- expect(segments.every(s => s.length >= 40)).toBe(true);- });-- it('merges a short first paragraph into the second paragraph', () => {- const text =- 'Ok.\n\n' +- 'This second paragraph is intentionally long enough to stand alone after merging.';- const segments = segmentMessage(text);-- expect(segments.length).toBe(1);- expect(segments[0].startsWith('Ok.\n\n')).toBe(true);- expect(segments[0].length).toBeGreaterThanOrEqual(40);- });-- it('forward-merges a short first paragraph yet keeps the remaining bubbles', () => {- // Three paragraphs where only the first is below MIN_SEGMENT_CHARS. This- // exercises the forward-merge branch in mergeTooShort while still returning- // multiple segments from the paragraph-split strategy (no leading stub).- const text =- 'Ok.\n\n' +- 'This second paragraph is intentionally long enough to stand alone as a bubble.\n\n' +- 'And a third paragraph that is also long enough to remain its own standalone bubble.';- const segments = segmentMessage(text);-- expect(segments).toHaveLength(2);- expect(segments[0].startsWith('Ok.\n\n')).toBe(true);- expect(segments.every(s => s.length >= 40)).toBe(true);- });-- it('splits on sentence boundaries when no paragraph breaks exist', () => {- const text =- 'This is the first sentence with some content. This is the second sentence with more content. ' +- 'This is the third sentence that adds even more words. And this is a final wrap-up sentence here.';- const segments = segmentMessage(text);- expect(segments.length).toBeGreaterThanOrEqual(2);- });-- it('never returns more than 5 segments', () => {- const manyParagraphs = Array.from(- { length: 10 },- (_, i) =>- `Paragraph ${i + 1} has enough words and content to be a real standalone bubble message.`- ).join('\n\n');- const segments = segmentMessage(manyParagraphs);- expect(segments.length).toBeLessThanOrEqual(5);- });-- it('handles text with only a single paragraph gracefully', () => {- const single =- 'This is a single paragraph that happens to be long enough to potentially split but has no newlines or clear sentence breaks ending in uppercase.';- const segments = segmentMessage(single);- expect(segments.length).toBeGreaterThanOrEqual(1);- expect(segments.every(s => s.length > 0)).toBe(true);- });-- it('does not return empty segments', () => {- const text =- 'Valid first paragraph content.\n\n\n\n\n\nValid second paragraph content that is long enough.';- const segments = segmentMessage(text);- expect(segments.every(s => s.trim().length > 0)).toBe(true);- });-});--describe('getSegmentDelay', () => {- it('returns a value between 500 and 1400 ms', () => {- const delays = [- getSegmentDelay(''),- getSegmentDelay('short'),- getSegmentDelay('x'.repeat(100)),- getSegmentDelay('x'.repeat(1000)),- ];- for (const d of delays) {- expect(d).toBeGreaterThanOrEqual(500);- expect(d).toBeLessThanOrEqual(1400);- }- });-- it('returns a larger delay for longer segments', () => {- const short = getSegmentDelay('Hi there!');- const long = getSegmentDelay(- 'This is a much longer segment that contains many more words and characters.'- );- expect(long).toBeGreaterThan(short);- });-});--describe('edge cases', () => {- it('handles text with only whitespace', () => {- expect(segmentMessage(' ')).toEqual(['']);- });-- it('handles exactly 80 characters — treated as short, returns single segment', () => {- const text = 'a'.repeat(80);- expect(segmentMessage(text)).toHaveLength(1);- });-- it('handles exactly 81 characters with a paragraph break — may split', () => {- const text = 'a'.repeat(40) + '\n\n' + 'b'.repeat(40);- const result = segmentMessage(text);- // Both paragraphs are >= MIN_SEGMENT_CHARS so should split- expect(result.length).toBeGreaterThanOrEqual(1);- });-- it('delay scales with length', () => {- const short = getSegmentDelay('hi');- const long = getSegmentDelay('a'.repeat(500));- expect(long).toBeGreaterThan(short);- expect(long).toBeLessThanOrEqual(1400);- expect(short).toBeGreaterThanOrEqual(500);- });-});diff --git a/app/src/utils/messageSegmentation.ts b/app/src/utils/messageSegmentation.tsdeleted file mode 100644index 4a91af14ff..0000000000--- a/app/src/utils/messageSegmentation.ts+++ /dev/null@@ -1,140 +0,0 @@-/**- * messageSegmentation — splits AI responses into natural chat bubbles.- *- * Gate: only called when local model is active. Cloud/API paths bypass this entirely.- */--const MIN_SEGMENT_CHARS = 40;-const MAX_SEGMENTS = 5;--/**- * Split `text` into an array of segments suitable for multi-bubble delivery.- *- * Priority order:- * 1. Paragraph breaks (\n\n) — highest-fidelity natural split.- * 2. Sentence-ending punctuation (. ! ?) followed by space + uppercase.- * 3. Fall back to the whole text as a single segment.- *- * Always returns at least one element. Returns the original text as `[text]`- * when it's too short or cannot be meaningfully split.- */-export function segmentMessage(text: string): string[] {- const trimmed = text.trim();-- // Don't bother segmenting short messages- if (trimmed.length < 80) return [trimmed];-- // --- Strategy 1: paragraph splits ---- const paragraphs = trimmed- .split(/\n\n+/)- .map(p => p.trim())- .filter(p => p.length > 0);-- if (paragraphs.length >= 2) {- const merged = mergeTooShort(paragraphs, '\n\n');- if (merged.length >= 2) return merged.slice(0, MAX_SEGMENTS);- }-- // --- Strategy 2: sentence splits ---- const sentences = splitSentences(trimmed);- if (sentences.length >= 2) {- const grouped = groupSentences(sentences);- if (grouped.length >= 2) return grouped.slice(0, MAX_SEGMENTS);- }-- // --- Fallback: single bubble ---- return [trimmed];-}--/**- * Estimate a natural inter-bubble delay in milliseconds.- * Scales loosely with the length of the segment just delivered.- * Bounded: min 500ms, max 1 400ms.- */-export function getSegmentDelay(segment: string): number {- const base = 500;- const perChar = 1.5;- return Math.min(base + segment.length * perChar, 1400);-}--// ─── helpers ─────────────────────────────────────────────────────────────────--/**- * Merge adjacent items that are shorter than MIN_SEGMENT_CHARS.- *- * Previously only short segments following a prior segment were merged (into- * the preceding one). A short *first* segment was left as-is because the- * `result.length > 0` guard prevented it from being absorbed. This caused the- * first chat bubble to show fewer than MIN_SEGMENT_CHARS characters while all- * subsequent short segments were correctly consolidated.- *- * Fix: after the normal backward-merge pass, check whether the first segment- * is still too short and, if so, forward-merge it into the second segment.- */-function mergeTooShort(parts: string[], joiner: string): string[] {- const result: string[] = [];- for (const part of parts) {- if (result.length > 0 && part.length < MIN_SEGMENT_CHARS) {- result[result.length - 1] += joiner + part;- } else {- result.push(part);- }- }-- // If the first segment is still shorter than the minimum, forward-merge it- // into the second segment (if one exists) so no leading stub bubble is shown.- if (result.length >= 2 && result[0].length < MIN_SEGMENT_CHARS) {- result[1] = result[0] + joiner + result[1];- result.shift();- }-- return result;-}--/**- * Split on sentence-ending punctuation (. ! ?) followed by a space and- * an uppercase letter. Uses a manual loop to avoid lookbehind assertions- * that may not be available in all WebKit versions.- */-function splitSentences(text: string): string[] {- const parts: string[] = [];- let current = '';-- for (let i = 0; i < text.length; i++) {- current += text[i];- const ch = text[i];- const next1 = text[i + 1];- const next2 = text[i + 2];-- if (- (ch === '.' || ch === '!' || ch === '?') &&- next1 === ' ' &&- next2 !== undefined &&- next2 >= 'A' &&- next2 <= 'Z'- ) {- parts.push(current.trim());- current = '';- i++; // skip the space- }- }-- if (current.trim().length > 0) parts.push(current.trim());- return parts.filter(p => p.length > 0);-}--/**- * Group individual sentences into at most MAX_SEGMENTS bubbles.- * Tries to aim for 2–3 bubbles for readability.- */-function groupSentences(sentences: string[]): string[] {- const targetCount = Math.min(3, Math.ceil(sentences.length / 2));- const groupSize = Math.ceil(sentences.length / targetCount);- const groups: string[] = [];-- for (let i = 0; i < sentences.length; i += groupSize) {- groups.push(sentences.slice(i, i + groupSize).join(' '));- }-- return groups.filter(g => g.length >= MIN_SEGMENT_CHARS);-}