Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions src/kimi_cli/web/runner/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@
JSONRPCOutMessageAdapter = TypeAdapter[JSONRPCOutMessage](JSONRPCOutMessage)


def _decode_worker_output(data: bytes) -> str:
return data.decode("utf-8", errors="replace")


class SessionProcess:
"""Manages a single session's KimiCLI subprocess.

Expand Down Expand Up @@ -306,6 +310,7 @@ async def _read_loop(self) -> None:
stderr = await self._process.stderr.read()
if not stderr:
stderr = b"No stderr"
stderr_text = _decode_worker_output(stderr)
# Clear in-flight IDs before broadcasting so that
# is_busy is already False when the frontend reacts
# to the error and sends a new prompt.
Expand All @@ -315,24 +320,23 @@ async def _read_loop(self) -> None:
id=str(uuid4()),
error=JSONRPCErrorObject(
code=self._process.returncode or -1,
message=stderr.decode("utf-8"),
message=stderr_text,
),
).model_dump_json()
)
logger.warning(
f"Process exited with {self._process.returncode}: "
f"{stderr.decode('utf-8')}"
f"Process exited with {self._process.returncode}: {stderr_text}"
)
await self._emit_status(
"error",
reason="process_exit",
detail=stderr.decode("utf-8"),
detail=stderr_text,
)
break
else:
continue

await self._broadcast(line.decode("utf-8").rstrip("\n"))
await self._broadcast(_decode_worker_output(line).rstrip("\n"))

# Handle out message
try:
Comment on lines +339 to 342
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 json.loads(line) on raw bytes raises uncaught UnicodeDecodeError for non-UTF-8 stdout lines

On line 339, _decode_worker_output(line) safely handles non-UTF-8 bytes for the broadcast. However, on line 343, json.loads(line) still receives the original raw bytes. When those bytes contain invalid UTF-8 (e.g., \x97), json.loads raises UnicodeDecodeError (confirmed: it is NOT a subclass of json.JSONDecodeError). This exception escapes the inner except json.JSONDecodeError: handler at line 362 and propagates to the outer except Exception as e: at line 367, terminating the entire read loop and putting the session into error state. The intent of the inner handler is to gracefully skip unparseable lines, but this case slips through. The fix is to pass the already-decoded string to json.loads so that invalid-UTF-8 lines produce a json.JSONDecodeError (due to the replacement character making invalid JSON), which IS caught by the inner handler, allowing the loop to continue.

(Refers to lines 339-343)

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Expand Down
33 changes: 33 additions & 0 deletions tests/web/test_session_error_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,39 @@ async def tracking_broadcast(msg: str) -> None:
assert sp.status.state == "error"


@pytest.mark.asyncio
async def test_read_loop_eof_handles_non_utf8_stderr() -> None:
sp = SessionProcess(uuid4())
messages: list[str] = []

async def capture_broadcast(msg: str) -> None:
messages.append(msg)

sp._broadcast = capture_broadcast # type: ignore[assignment]

mock_stdout = asyncio.StreamReader()
mock_stdout.feed_eof()

mock_stderr = asyncio.StreamReader()
mock_stderr.feed_data(b"windows dash: \x97")
mock_stderr.feed_eof()

mock_process = MagicMock()
mock_process.stdout = mock_stdout
mock_process.stderr = mock_stderr
mock_process.returncode = 1

sp._process = mock_process
sp._expecting_exit = False

await sp._read_loop()

assert messages
assert "windows dash: �" in messages[0]
assert sp.status.reason == "process_exit"
assert sp.status.detail == "windows dash: �"


# ---------------------------------------------------------------------------
# Tests: error state allows recovery with new prompt
# ---------------------------------------------------------------------------
Expand Down
Loading