Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(cli): print reply text from lh gen text SSE responses (#20554)

YuTengjingfbd9a8d74b87
diff --git a/apps/cli/src/commands/generate.test.ts b/apps/cli/src/commands/generate.test.ts
index 8b98d379d9a..371b4269926 100644
--- a/apps/cli/src/commands/generate.test.ts
+++ b/apps/cli/src/commands/generate.test.ts
@@ -99,15 +99,67 @@ describe('generate command', () => {
}
describe('text', () => {
+ const jsonResponse = (body: unknown) =>
+ new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' } });
+
+ const sseResponse = (events: Array<{ data: unknown; event?: string }>, chunkSize = 7) => {
+ const raw = events
+ .map(({ data, event }) =>
+ [
+ 'id: chat_test',
+ event ? `event: ${event}` : undefined,
+ `data: ${typeof data === 'string' && data === '[DONE]' ? data : JSON.stringify(data)}`,
+ '',
+ '',
+ ]
+ .filter((line) => line !== undefined)
+ .join('\n'),
+ )
+ .join('');
+ const encoder = new TextEncoder();
+ // Split into small chunks so events straddle read() boundaries
+ const stream = new ReadableStream({
+ start(controller) {
+ for (let i = 0; i < raw.length; i += chunkSize) {
+ controller.enqueue(encoder.encode(raw.slice(i, i + chunkSize)));
+ }
+ controller.close();
+ },
+ });
+ return new Response(stream, { headers: { 'content-type': 'text/event-stream' } });
+ };
+
+ /** Gemini reply as emitted by `/webapi/chat/*` */
+ const geminiEvents = [
+ { data: { content: 'Hello there', partType: 'text' }, event: 'content_part' },
+ { data: { content: ', how are you?', partType: 'text' }, event: 'content_part' },
+ { data: 'STOP', event: 'stop' },
+ { data: { totalInputTokens: 6, totalOutputTokens: 7 }, event: 'usage' },
+ { data: { latency: 650, ttft: 607 }, event: 'speed' },
+ ];
+
+ /** OpenAI Responses reply as emitted by `/webapi/chat/*` */
+ const openaiEvents = [
+ { data: 'in_progress', event: 'data' },
+ { data: { type: 'response.in_progress' }, event: 'data' },
+ { data: 'encrypted-signature', event: 'reasoning_signature' },
+ { data: 'Hello', event: 'text' },
+ { data: ', world', event: 'text' },
+ { data: { type: 'response.completed' }, event: 'data' },
+ { data: { totalTokens: 272 }, event: 'usage' },
+ ];
+
+ const writtenText = () =>
+ stdoutSpy.mock.calls.map(([chunk]: [unknown]) => String(chunk)).join('');
+
it('should default to non-streaming and output plain text', async () => {
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue({
- json: vi.fn().mockResolvedValue({
- choices: [{ message: { content: 'Response text' } }],
- }),
- ok: true,
- }),
+ vi
+ .fn()
+ .mockResolvedValue(
+ jsonResponse({ choices: [{ message: { content: 'Response text' } }] }),
+ ),
);
const program = createProgram();
@@ -127,13 +179,7 @@ describe('generate command', () => {
model: 'gpt-4o-mini',
usage: { completion_tokens: 5, prompt_tokens: 10 },
};
- vi.stubGlobal(
- 'fetch',
- vi.fn().mockResolvedValue({
- json: vi.fn().mockResolvedValue(responseBody),
- ok: true,
- }),
- );
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(responseBody)));
const program = createProgram();
await program.parseAsync(['node', 'test', 'generate', 'text', 'Hello', '--json']);
@@ -141,19 +187,31 @@ describe('generate command', () => {
expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(responseBody, null, 2));
});
- it('should stream when --stream is explicitly passed', async () => {
- const encoder = new TextEncoder();
- const stream = new ReadableStream({
- start(controller) {
- controller.enqueue(
- encoder.encode('data: {"choices":[{"delta":{"content":"Hello"}}]}\n\n'),
- );
- controller.enqueue(encoder.encode('data: [DONE]\n\n'));
- controller.close();
- },
+ it('should collect SSE text when the server ignores non-streaming mode', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents)));
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hello']);
+
+ expect(writtenText()).toBe('Hello there, how are you?\n');
+ expect(log.error).not.toHaveBeenCalled();
+ });
+
+ it('should output collected SSE as JSON when --json is used without --stream', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents)));
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hello', '--json']);
+
+ expect(JSON.parse(consoleSpy.mock.calls[0][0] as string)).toEqual({
+ content: 'Hello there, how are you?',
+ finishReason: 'STOP',
+ usage: { totalInputTokens: 6, totalOutputTokens: 7 },
});
+ });
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ body: stream, ok: true }));
+ it('should stream Gemini content parts without printing the stop reason', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents)));
const program = createProgram();
await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
@@ -162,18 +220,118 @@ describe('generate command', () => {
const body = JSON.parse(fetchCall[1]!.body as string);
expect(body.stream).toBe(true);
- expect(stdoutSpy).toHaveBeenCalledWith('Hello');
+ expect(writtenText()).toBe('Hello there, how are you?\n');
+ });
+
+ it('should stream only text events from the LobeHub protocol', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(openaiEvents)));
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
+
+ expect(writtenText()).toBe('Hello, world\n');
+ });
+
+ it('should keep reasoning parts out of the reply text', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ sseResponse([
+ // Gemini thought parts, as emitted by the google stream transformer
+ {
+ data: {
+ content: 'Thinking...',
+ inReasoning: true,
+ partType: 'text',
+ thoughtSignature: 'sig',
+ },
+ event: 'reasoning_part',
+ },
+ { data: 'more thoughts', event: 'reasoning' },
+ { data: { content: 'Answer', partType: 'text' }, event: 'content_part' },
+ ]),
+ ),
+ );
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--json']);
+
+ expect(JSON.parse(consoleSpy.mock.calls[0][0] as string)).toMatchObject({
+ content: 'Answer',
+ reasoning: 'Thinking...more thoughts',
+ });
+ });
+
+ it('should warn when an image model replies without text', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ sseResponse([
+ { data: { content: 'iVBORw0KGgo=', partType: 'image' }, event: 'content_part' },
+ { data: 'STOP', event: 'stop' },
+ ]),
+ ),
+ );
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Draw a cat']);
+
+ expect(writtenText()).toBe('\n');
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('generate image'));
+ });
+
+ it('should stream plain OpenAI chat-completion chunks', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockResolvedValue(
+ sseResponse([
+ { data: { choices: [{ delta: { content: 'Hello' } }] } },
+ { data: '[DONE]' },
+ ]),
+ ),
+ );
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream']);
+
+ expect(writtenText()).toBe('Hello\n');
+ });
+
+ it('should print each SSE event as a JSON line with --stream --json', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(sseResponse(geminiEvents.slice(0, 3))));
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi', '--stream', '--json']);
+
+ expect(consoleSpy.mock.calls.map(([line]) => JSON.parse(line as string))).toEqual(
+ geminiEvents.slice(0, 3),
+ );
+ });
+
+ it('should exit when the SSE stream reports an error', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ sseResponse([
+ { data: 'Partial', event: 'text' },
+ { data: { message: 'quota exceeded' }, event: 'error' },
+ ]),
+ ),
+ );
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'generate', 'text', 'Hi']);
+
+ expect(log.error).toHaveBeenCalledWith(expect.stringContaining('quota exceeded'));
+ expect(exitSpy).toHaveBeenCalledWith(1);
});
it('should parse provider from model string', async () => {
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue({
- json: vi.fn().mockResolvedValue({
- choices: [{ message: { content: 'ok' } }],
- }),
- ok: true,
- }),
+ vi.fn().mockResolvedValue(jsonResponse({ choices: [{ message: { content: 'ok' } }] })),
);
const program = createProgram();
@@ -196,11 +354,7 @@ describe('generate command', () => {
it('should exit on error response', async () => {
vi.stubGlobal(
'fetch',
- vi.fn().mockResolvedValue({
- ok: false,
- status: 500,
- text: vi.fn().mockResolvedValue('Internal error'),
- }),
+ vi.fn().mockResolvedValue(new Response('Internal error', { status: 500 })),
);
const program = createProgram();
diff --git a/apps/cli/src/commands/generate/text.ts b/apps/cli/src/commands/generate/text.ts
index 673b5a76232..0d4457db84f 100644
--- a/apps/cli/src/commands/generate/text.ts
+++ b/apps/cli/src/commands/generate/text.ts
@@ -1,6 +1,7 @@
import type { Command } from 'commander';
import { getAuthInfo } from '../../api/http';
+import { CLI_PRIMARY_BIN } from '../../constants/identity';
import { log } from '../../utils/logger';
export function registerTextCommand(parent: Command) {
@@ -58,8 +59,8 @@ export function registerTextCommand(parent: Command) {
const payload: Record<string, any> = {
messages,
model,
- // For non-streaming, use responseMode 'json' to get a plain JSON response
- // instead of SSE (the backend converts non-stream to SSE by default)
+ // Ask for a plain JSON body when not streaming; runtimes that ignore
+ // responseMode still reply with SSE, handled below
responseMode: useStream ? 'stream' : 'json',
stream: useStream,
};
@@ -81,7 +82,11 @@ export function registerTextCommand(parent: Command) {
return;
}
- if (!useStream) {
+ // `/webapi/chat/*` answers with LobeHub's SSE protocol even for `stream: false`
+ // on most providers (`responseMode: 'json'` is only honored by some runtimes),
+ // so only treat the body as plain JSON when the server says it is.
+ const contentType = res.headers.get('content-type') || '';
+ if (contentType.includes('application/json')) {
const body = await res.json();
if (options.json) {
console.log(JSON.stringify(body, null, 2));
@@ -98,60 +103,205 @@ export function registerTextCommand(parent: Command) {
return;
}
- // Stream SSE response
if (!res.body) {
log.error('No response body received');
process.exit(1);
return;
}
- await streamSSEResponse(res.body, options.json);
+ if (useStream) {
+ await streamSSEResponse(res.body, options.json);
+ } else {
+ await collectSSEResponse(res.body, options.json);
+ }
},
);
}
-async function streamSSEResponse(body: ReadableStream<Uint8Array>, json?: boolean): Promise<void> {
+interface SSEEvent {
+ data: any;
+ /** SSE `event:` field; `undefined` for plain OpenAI-style streams */
+ event?: string;
+}
+
+/**
+ * Parse an SSE body into events. LobeHub's chat protocol tags every event with
+ * `event: <type>` (`text`, `content_part`, `reasoning`, `stop`, `usage`, `error`, ...),
+ * and the meaning of `data` depends on that type.
+ */
+async function* parseSSE(body: ReadableStream<Uint8Array>): AsyncGenerator<SSEEvent> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = '';
+ let event: string | undefined;
+ let dataLines: string[] = [];
+
+ const flush = (): SSEEvent | undefined => {
+ if (dataLines.length === 0) {
+ event = undefined;
+ return;
+ }
+ const raw = dataLines.join('\n');
+ const current = event;
+ event = undefined;
+ dataLines = [];
+
+ try {
+ return { data: JSON.parse(raw), event: current };
+ } catch {
+ return { data: raw, event: current };
+ }
+ };
try {
while (true) {
const { done, value } = await reader.read();
- if (done) break;
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
- buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
- buffer = lines.pop() || '';
+ buffer = done ? '' : lines.pop() || '';
- for (const line of lines) {
- if (!line.startsWith('data:')) continue;
- const data = line.slice(5).trim();
- if (data === '[DONE]') {
- if (!json) process.stdout.write('\n');
- return;
+ for (const rawLine of lines) {
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
+ if (line === '') {
+ const parsed = flush();
+ if (parsed) yield parsed;
+ } else if (line.startsWith('event:')) {
+ event = line.slice(6).trim();
+ } else if (line.startsWith('data:')) {
+ dataLines.push(line.slice(5).trimStart());
}
+ }
- try {
- const parsed = JSON.parse(data);
- if (json) {
- console.log(JSON.stringify(parsed));
- } else if (typeof parsed === 'string' && parsed !== 'stop') {
- // LobeHub SSE sends content as JSON strings: "Hello", "world"
- process.stdout.write(parsed);
- } else if (parsed?.choices?.[0]?.delta?.content) {
- // Standard OpenAI SSE format
- process.stdout.write(parsed.choices[0].delta.content);
- }
- } catch {
- // Not JSON, might be raw text chunk
- if (!json) process.stdout.write(data);
- }
+ if (done) {
+ const parsed = flush();
+ if (parsed) yield parsed;
+ return;
}
}
- // Final newline
- if (!json) process.stdout.write('\n');
} finally {
reader.releaseLock();
}
}
+
+type SSEPayload =
+ | { kind: 'done' }
+ | { kind: 'error'; data: unknown }
+ | { kind: 'image' }
+ | { kind: 'reasoning'; text: string }
+ | { kind: 'text'; text: string }
+ | { kind: 'other' };
+
+function classifySSEEvent({ data, event }: SSEEvent): SSEPayload {
+ if (data === '[DONE]') return { kind: 'done' };
+
+ switch (event) {
+ case 'text': {
+ return typeof data === 'string' ? { kind: 'text', text: data } : { kind: 'other' };
+ }
+ case 'reasoning': {
+ return typeof data === 'string' ? { kind: 'reasoning', text: data } : { kind: 'other' };
+ }
+ // Gemini emits multimodal parts instead of `text` / `reasoning` events:
+ // reply parts as `content_part`, thought parts as `reasoning_part`
+ case 'content_part': {
+ if (data?.partType === 'image') return { kind: 'image' };
+ if (data?.partType !== 'text' || typeof data.content !== 'string') return { kind: 'other' };
+ return { kind: 'text', text: data.content };
+ }
+ case 'reasoning_part': {
+ if (data?.partType !== 'text' || typeof data.content !== 'string') return { kind: 'other' };
+ return { kind: 'reasoning', text: data.content };
+ }
+ case 'base64_image': {
+ return { kind: 'image' };
+ }
+ case 'error': {
+ return { data, kind: 'error' };
+ }
+ case undefined: {
+ // Plain OpenAI chat-completion chunks without `event:` tags
+ const content = data?.choices?.[0]?.delta?.content;
+ return typeof content === 'string' ? { kind: 'text', text: content } : { kind: 'other' };
+ }
+ default: {
+ return { kind: 'other' };
+ }
+ }
+}
+
+/** Image models answer with image parts only, which would otherwise print nothing */
+function warnImageOnlyReply(imageCount: number): void {
+ log.warn(
+ `The model returned ${imageCount} image(s) and no text. Use \`${CLI_PRIMARY_BIN} generate image\` for image models.`,
+ );
+}
+
+function reportSSEError(data: unknown): void {
+ log.error(`Text generation failed: ${typeof data === 'string' ? data : JSON.stringify(data)}`);
+ process.exit(1);
+}
+
+async function streamSSEResponse(body: ReadableStream<Uint8Array>, json?: boolean): Promise<void> {
+ let hasText = false;
+ let imageCount = 0;
+
+ for await (const event of parseSSE(body)) {
+ const payload = classifySSEEvent(event);
+ if (payload.kind === 'done') break;
+
+ if (json) {
+ console.log(JSON.stringify(event));
+ if (payload.kind === 'error') process.exit(1);
+ continue;
+ }
+
+ if (payload.kind === 'error') {
+ process.stdout.write('\n');
+ reportSSEError(payload.data);
+ return;
+ }
+ if (payload.kind === 'text') {
+ hasText = true;
+ process.stdout.write(payload.text);
+ } else if (payload.kind === 'image') imageCount++;
+ }
+
+ if (json) return;
+ process.stdout.write('\n');
+ if (!hasText && imageCount > 0) warnImageOnlyReply(imageCount);
+}
+
+async function collectSSEResponse(body: ReadableStream<Uint8Array>, json?: boolean): Promise<void> {
+ let content = '';
+ let reasoning = '';
+ let finishReason: unknown;
+ let imageCount = 0;
+ let usage: unknown;
+
+ for await (const event of parseSSE(body)) {
+ const payload = classifySSEEvent(event);
+ if (payload.kind === 'done') break;
+
+ if (payload.kind === 'error') {
+ reportSSEError(payload.data);
+ return;
+ }
+ if (payload.kind === 'text') content += payload.text;
+ else if (payload.kind === 'reasoning') reasoning += payload.text;
+ else if (payload.kind === 'image') imageCount++;
+ else if (event.event === 'stop') finishReason = event.data;
+ else if (event.event === 'usage') usage = event.data;
+ }
+
+ if (json) {
+ console.log(
+ JSON.stringify({ content, finishReason, reasoning: reasoning || undefined, usage }, null, 2),
+ );
+ return;
+ }
+
+ process.stdout.write(content);
+ process.stdout.write('\n');
+ if (!content && imageCount > 0) warnImageOnlyReply(imageCount);
+}