Repository navigation
Conversation
`mmx text chat --stream` ended its SSE loop on the first `done` read from
the response body, whether or not the server had sent `message_stop` or
`data: [DONE]`. A connection dropped mid-response therefore printed the
partial answer (or, with `--output json`, a complete-looking
`{"content": "..."}` object) and exited 0, so callers could not tell a
truncated response from a finished one.
ERRORS.md documents the intended behaviour for `mmx text chat`:
| Stream disconnected mid-response | `Stream disconnected before response completed.` |
Track the terminator and raise that error with the documented network
exit code (6) when the stream ends without one.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
Still current against main, full suite passes locally except the pre-existing installer timeout test. Same shape as #266 which NianJiuZst already reviewed, so it should be a quick one. |
|
Independently checked
For the last case, the complete message is received, but This is a pre-existing boundary, not a regression introduced by this PR. The unchanged original chat tests also pass (base 6/6, PR 7/7). Synthetic local HTTP only; no live provider, full-suite or response-cancellation qualification. Self-contained five-case testSave as import { describe, expect, it } from 'bun:test';
import { pathToFileURL } from 'node:url';
const arm = process.env.MMX_OWNER_ARM;
if (!arm) throw new Error('MMX_OWNER_ARM is required');
const { default: command } = await import(pathToFileURL(`${arm}/src/commands/text/chat.ts`).href);
const frames = [
{ type: 'message_start', message: { id: 'msg_local_fixture', type: 'message', role: 'assistant', content: [], model: 'synthetic', stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Hello' } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },
];
const delta = frames.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('');
const done = 'data: [DONE]\n\n';
const stop = 'event: message_stop\ndata: {"type":"message_stop"}\n\n';
async function runFixture(terminal: string, holdOpen: boolean) {
let requests = 0;
const server = Bun.serve({
hostname: '127.0.0.1',
port: 0,
fetch(req) {
requests++;
if (new URL(req.url).pathname !== '/anthropic/v1/messages') {
return new Response('Unexpected route', { status: 501 });
}
const body = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(delta + terminal));
if (!holdOpen) controller.close();
},
});
return new Response(body, { headers: { 'Content-Type': 'text/event-stream' } });
},
});
const originalLog = console.log;
let output = '';
let error: unknown;
console.log = (msg: unknown) => { output += `${String(msg)}\n`; };
try {
await command.execute({
apiKey: 'synthetic-local-test-key', region: 'global', baseUrl: `http://127.0.0.1:${server.port}`,
output: 'json', timeout: 0.5, verbose: false, quiet: true, noColor: true,
yes: false, dryRun: false, nonInteractive: true, async: false,
}, {
message: ['Synthetic local completion'], stream: true, quiet: true, verbose: false,
noColor: true, yes: false, dryRun: false, help: false, nonInteractive: true, async: false,
});
} catch (caught) {
error = caught;
} finally {
console.log = originalLog;
server.stop(true);
}
expect(requests).toBe(1);
return { output, error };
}
describe('HTTP SSE terminal observations', () => {
it('accepts DONE followed by EOF', async () => {
const result = await runFixture(done, false);
expect(result.error).toBeUndefined();
expect(JSON.parse(result.output)).toEqual({ content: 'Hello' });
});
it('accepts message_stop followed by EOF', async () => {
const result = await runFixture(stop, false);
expect(result.error).toBeUndefined();
expect(JSON.parse(result.output)).toEqual({ content: 'Hello' });
});
it('rejects EOF before either terminal without a success JSON object', async () => {
const result = await runFixture('', false);
expect(result.error).toBeInstanceOf(Error);
expect((result.error as Error).message).toBe('Stream disconnected before response completed.');
expect(result.output).toBe('');
});
it('accepts DONE without waiting for HTTP EOF', async () => {
const result = await runFixture(done, true);
expect(result.error).toBeUndefined();
expect(JSON.parse(result.output)).toEqual({ content: 'Hello' });
});
it('accepts message_stop without waiting for HTTP EOF', async () => {
const result = await runFixture(stop, true);
expect(result.error).toBeUndefined();
expect(JSON.parse(result.output)).toEqual({ content: 'Hello' });
});
}); |
Summary
mmx text chat --streamtreats a dropped connection as a finished response. Itprints the partial answer and exits
0, so a caller cannot distinguish atruncated reply from a complete one. With
--output jsonit is worse: thecommand emits a well-formed, complete-looking
{"content": "..."}object thatsilently contains only the bytes that arrived.
ERRORS.mdalready documents the intended behaviour under## Text Commands→mmx text chat:Stream disconnected before response completed.That string does not exist anywhere in
src/ortest/— the documented erroris never raised. This is a contract violation against the repo's own error
reference, not a new behaviour proposal.
Root cause
src/commands/text/chat.ts— the SSE consumer exits its loop on whatever endsthe generator, with no notion of a terminator:
parseSSE(src/client/stream.ts) returns normally when the body readerreports
done, which is exactly what a server or proxy closing the connectionearly produces.
message_stop— a member of theStreamEventunion insrc/types/api.ts— is never inspected, and neither is the absence of[DONE]. The success path then runs unchanged.Merged PR #227 (
fix: time out stalled streams) covers the stalled case (nobytes for N seconds) in
src/client/http.ts; a stream that closes cleanly butearly never trips that timeout.
Fix
One flag in
src/commands/text/chat.ts, set by either terminator the API uses,checked once after the loop:
Exit code 6 (
ExitCode.NETWORK), per the### Exit Codestable inERRORS.md("Network error") — a dropped stream is a transport failure, not a usage or
content error. Text already streamed to stdout is left as-is (a newline is
added so the shell prompt is not glued to the partial output); the JSON summary
is not printed, so no complete-looking object is produced for an incomplete
response.
Accepting
[DONE]as well asmessage_stopkeeps every existing streamingtest green — the repo's
sseResponsehelper appendsdata: [DONE].How tested
New regression test in
test/commands/text/chat.test.tsdriving the repo'sexisting
test/helpers/mock-server— no live API call, no API key.Reproduction (before the fix)
Mock route returns an SSE body with deltas and no terminator:
mmx text chat --message Hello --stream --output jsonprints:Exit code
0. Expected (perERRORS.md):Stream disconnected before response completed.with exit code 6.Test evidence — fails before, passes after
Without the source change (test only):
With the fix:
Full suite / typecheck / lint:
Environment: bun 1.3.13, macOS.
Duplicate check
Run via
gh api search/issues(all states) andgh api .../pulls/<n>/files:repo:MiniMax-AI/cli Stream disconnectedrepo:MiniMax-AI/cli message_stoprepo:MiniMax-AI/cli stream truncatedrepo:MiniMax-AI/cli SSEparseSSEtests, #197 surfaces music stream errorsrepo:MiniMax-AI/cli DONE streamrepo:MiniMax-AI/cli parseSSErepo:MiniMax-AI/cli text chat streamrepo:MiniMax-AI/cli in:title streamfix: time out stalled streams(merged,src/client/http.ts): an idle timeout, which a cleanly-closed early stream never tripsAll 13 open PRs checked file-by-file (#261, #230, #228, #226, #225, #223, #222,
#221, #219, #209, #207, #204, #186). Only #225 and #204 touch
src/commands/text/chat.ts; neither patch mentionsparseSSE,message_stop,[DONE]or disconnect handling, and neither touchesERRORS.md.Disclosure: prepared with AI assistance (Claude Code); I reviewed the change and take responsibility for it.
🤖 Generated with Claude Code
Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.