aimux 0.3.76__tar.gz → 0.3.78__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. {aimux-0.3.76 → aimux-0.3.78}/PKG-INFO +1 -1
  2. {aimux-0.3.76 → aimux-0.3.78}/pyproject.toml +1 -1
  3. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/__init__.py +1 -1
  4. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/mcp_server.py +96 -9
  5. {aimux-0.3.76 → aimux-0.3.78}/tests/real/conftest.py +12 -4
  6. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_view_image.py +8 -5
  7. {aimux-0.3.76 → aimux-0.3.78}/tests/test_mcp_server.py +104 -11
  8. {aimux-0.3.76 → aimux-0.3.78}/.gitignore +0 -0
  9. {aimux-0.3.76 → aimux-0.3.78}/LICENSE +0 -0
  10. {aimux-0.3.76 → aimux-0.3.78}/README.md +0 -0
  11. {aimux-0.3.76 → aimux-0.3.78}/SKILL.md +0 -0
  12. {aimux-0.3.76 → aimux-0.3.78}/design.md +0 -0
  13. {aimux-0.3.76 → aimux-0.3.78}/docs/bridge-protocol.md +0 -0
  14. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/__main__.py +0 -0
  15. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/aimux.conf +0 -0
  16. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/bridge.py +0 -0
  17. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/bridge_client.py +0 -0
  18. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/bridge_server.py +0 -0
  19. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/bridge_windows.py +0 -0
  20. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/cli.py +0 -0
  21. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/constants.py +0 -0
  22. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/gui_help_document.py +0 -0
  23. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/gui_helper.py +0 -0
  24. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/local_alignment.py +0 -0
  25. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/logging_setup.py +0 -0
  26. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/output.py +0 -0
  27. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/port_forward.py +0 -0
  28. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/port_tunnel.py +0 -0
  29. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/session.py +0 -0
  30. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/skills/mobius-gui-operation/SKILL.md +0 -0
  31. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/ssh.py +0 -0
  32. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/tmux.py +0 -0
  33. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/transfer.py +0 -0
  34. {aimux-0.3.76 → aimux-0.3.78}/src/aimux/wait.py +0 -0
  35. {aimux-0.3.76 → aimux-0.3.78}/tests/.gitkeep +0 -0
  36. {aimux-0.3.76 → aimux-0.3.78}/tests/conftest.py +0 -0
  37. {aimux-0.3.76 → aimux-0.3.78}/tests/manual_localhost_8824_remote.md +0 -0
  38. {aimux-0.3.76 → aimux-0.3.78}/tests/real/Dockerfile +0 -0
  39. {aimux-0.3.76 → aimux-0.3.78}/tests/real/run.sh +0 -0
  40. {aimux-0.3.76 → aimux-0.3.78}/tests/real/smoke_bridge.sh +0 -0
  41. {aimux-0.3.76 → aimux-0.3.78}/tests/real/smoke_local.sh +0 -0
  42. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_apply_patch.py +0 -0
  43. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_download.py +0 -0
  44. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_exec.py +0 -0
  45. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_ping.py +0 -0
  46. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_stream.py +0 -0
  47. {aimux-0.3.76 → aimux-0.3.78}/tests/real/test_real_write_stdin.py +0 -0
  48. {aimux-0.3.76 → aimux-0.3.78}/tests/real/verify_windows_exec.py +0 -0
  49. {aimux-0.3.76 → aimux-0.3.78}/tests/remote_test.md +0 -0
  50. {aimux-0.3.76 → aimux-0.3.78}/tests/test_apply_patch_description.py +0 -0
  51. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_cli.py +0 -0
  52. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_data_plane.py +0 -0
  53. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_files.py +0 -0
  54. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_health_version.py +0 -0
  55. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_keepalive.py +0 -0
  56. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_reconnect.py +0 -0
  57. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_restart_cli.py +0 -0
  58. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_runtime.py +0 -0
  59. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_shutdown.py +0 -0
  60. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_upload_slices.py +0 -0
  61. {aimux-0.3.76 → aimux-0.3.78}/tests/test_bridge_watchdog.py +0 -0
  62. {aimux-0.3.76 → aimux-0.3.78}/tests/test_cli_read_patch.py +0 -0
  63. {aimux-0.3.76 → aimux-0.3.78}/tests/test_cli_remote.py +0 -0
  64. {aimux-0.3.76 → aimux-0.3.78}/tests/test_file_ops.py +0 -0
  65. {aimux-0.3.76 → aimux-0.3.78}/tests/test_file_transfer.py +0 -0
  66. {aimux-0.3.76 → aimux-0.3.78}/tests/test_gui_helper.py +0 -0
  67. {aimux-0.3.76 → aimux-0.3.78}/tests/test_local_alignment.py +0 -0
  68. {aimux-0.3.76 → aimux-0.3.78}/tests/test_mcp_download.py +0 -0
  69. {aimux-0.3.76 → aimux-0.3.78}/tests/test_port_forward.py +0 -0
  70. {aimux-0.3.76 → aimux-0.3.78}/tests/test_port_tunnel.py +0 -0
  71. {aimux-0.3.76 → aimux-0.3.78}/tests/test_remote_server_integration.py +0 -0
  72. {aimux-0.3.76 → aimux-0.3.78}/tests/test_ssh_remote.py +0 -0
  73. {aimux-0.3.76 → aimux-0.3.78}/tests/test_tmux.py +0 -0
  74. {aimux-0.3.76 → aimux-0.3.78}/tests/window_board.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aimux
3
- Version: 0.3.76
3
+ Version: 0.3.78
4
4
  Summary: AI-agent-friendly tmux wrapper: unified local + remote sessions, single-pane sessions, safe primitives.
5
5
  Author: aimux
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "aimux"
7
- version = "0.3.76"
7
+ version = "0.3.78"
8
8
  description = "AI-agent-friendly tmux wrapper: unified local + remote sessions, single-pane sessions, safe primitives."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,2 +1,2 @@
1
1
  """aimux — AI-agent-friendly tmux wrapper."""
2
- __version__ = "0.3.76"
2
+ __version__ = "0.3.78"
@@ -489,10 +489,23 @@ def _remote_is_windows(profile: str) -> bool:
489
489
 
490
490
 
491
491
  def _decode_text(data: bytes) -> str:
492
- """Decode remote file bytes, tolerating what Windows shells actually write."""
492
+ """Decode remote file bytes, tolerating what Windows shells actually write.
493
+
494
+ cmd writes its output in the console code page (cp936 on a Chinese system,
495
+ cp1252 elsewhere). Decoding those bytes as UTF-8 with "replace" produced the
496
+ "�" soup users saw, so fall back to the code pages before giving up.
497
+ """
493
498
  if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
494
499
  return data.decode("utf-16", "replace")
495
- return data.decode("utf-8-sig", "replace") # utf-8-sig drops a BOM
500
+ try:
501
+ return data.decode("utf-8-sig") # utf-8-sig drops a BOM
502
+ except UnicodeDecodeError:
503
+ for encoding in ("cp936", "cp1252"):
504
+ try:
505
+ return data.decode(encoding)
506
+ except (UnicodeDecodeError, LookupError):
507
+ continue
508
+ return data.decode("utf-8-sig", "replace")
496
509
 
497
510
 
498
511
  def _exec_temp_base() -> str:
@@ -551,7 +564,11 @@ def _exec_plan(*, cmd: str, profile: str, shell_bin: str | None, windows: bool)
551
564
  f"{runner} {script} > {outfile} 2>&1; echo $? > {codefile}")
552
565
 
553
566
  if family == "cmd":
554
- body = f"@echo off\r\n{cmd}\r\necho %errorlevel% > \"{_win_path(codefile)}\"\r\n"
567
+ # UTF-8 console so the script body (UTF-8 on disk) and the program
568
+ # output are both read/written as UTF-8 instead of the system code page,
569
+ # which is what turned Chinese text into mojibake.
570
+ body = (f"@echo off\r\nchcp 65001 >nul\r\n{cmd}\r\n"
571
+ f"echo %errorlevel% > \"{_win_path(codefile)}\"\r\n")
555
572
  return _ExecPlan(script, outfile, codefile, body,
556
573
  f"\"{_win_path(script)}\" > \"{_win_path(outfile)}\" 2>&1")
557
574
 
@@ -773,10 +790,15 @@ def _remote_exec_command_tempfile(remote: str, profile: str, args: dict) -> dict
773
790
  _sessions[sid].update(tmp_script=plan.script, tmp_out=plan.out, tmp_code=plan.code)
774
791
  try:
775
792
  # 1) command verbatim -> temp script (no send_keys mangling).
793
+ # Windows PowerShell 5.1 reads a BOM-less .ps1 as ANSI, so non-ASCII
794
+ # text in the command would arrive as mojibake.
795
+ body_bytes = plan.body.encode("utf-8")
796
+ if plan.script.endswith(".ps1"):
797
+ body_bytes = b"\xef\xbb\xbf" + body_bytes
776
798
  c.file_write(
777
799
  remote=remote,
778
800
  path=plan.script,
779
- content_b64=base64.b64encode(plan.body.encode("utf-8")).decode("ascii"),
801
+ content_b64=base64.b64encode(body_bytes).decode("ascii"),
780
802
  timeout=60.0,
781
803
  )
782
804
  # 2) trivial launch line -> redirect output + exit code to files.
@@ -940,6 +962,42 @@ def _remote_write_stdin(remote: str, profile: str, args: dict) -> dict:
940
962
  # ---------------------------------------------------------------------------
941
963
 
942
964
 
965
+ # An image block is not counted against a client's text budget, but keep a
966
+ # ceiling so a huge file cannot stall the transport. Beyond it the bytes are
967
+ # spooled to a local file and reported by path instead of being inlined.
968
+ _IMAGE_INLINE_MAX_BYTES = 4 * 1024 * 1024
969
+
970
+
971
+ def _mcp_content(*blocks: dict) -> dict:
972
+ """A tool result made of MCP content blocks instead of one JSON blob."""
973
+ return {"__mcp_content__": list(blocks)}
974
+
975
+
976
+ def _image_spool_dir() -> Path:
977
+ directory = Path(tempfile.gettempdir()) / "aimux-images"
978
+ directory.mkdir(parents=True, exist_ok=True)
979
+ try:
980
+ os.chmod(directory, 0o700)
981
+ except OSError:
982
+ pass
983
+ return directory
984
+
985
+
986
+ def _sniff_image_mime(raw: bytes) -> str | None:
987
+ """Identify the format from the bytes: an extension can lie, magic cannot."""
988
+ if raw.startswith(b"\x89PNG\r\n\x1a\n"):
989
+ return "png"
990
+ if raw.startswith(b"\xff\xd8\xff"):
991
+ return "jpeg"
992
+ if raw[:6] in (b"GIF87a", b"GIF89a"):
993
+ return "gif"
994
+ if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
995
+ return "webp"
996
+ if raw[:2] == b"BM":
997
+ return "bmp"
998
+ return None
999
+
1000
+
943
1001
  def _remote_view_image(remote: str, profile: str, args: dict) -> dict:
944
1002
  path = args.get("path")
945
1003
  if not isinstance(path, str) or not path:
@@ -950,10 +1008,29 @@ def _remote_view_image(remote: str, profile: str, args: dict) -> dict:
950
1008
  res = _client().file_read(remote=remote, path=path, timeout=180.0)
951
1009
  raw = _file_bytes(res)
952
1010
  ext = os.path.splitext(path)[1].lstrip(".").lower()
953
- mime = {"jpg": "jpeg", "jpeg": "jpeg", "png": "png", "gif": "gif",
954
- "webp": "webp", "bmp": "bmp"}.get(ext, ext or "octet-stream")
1011
+ mime = _sniff_image_mime(raw)
1012
+ if mime is None:
1013
+ raise ValueError(
1014
+ f"{path} is not a recognised image (got {len(raw)} bytes, extension {ext or 'none'}); "
1015
+ "supported: png, jpeg, gif, webp, bmp — convert the file first")
1016
+ name = os.path.basename(path) or "image"
1017
+ meta = f"{name} · {len(raw)} bytes · image/{mime} · detail={detail}"
1018
+ if len(raw) > _IMAGE_INLINE_MAX_BYTES:
1019
+ # Inlining this would blow any client's result limit. A real file is
1020
+ # something the caller can open; a base64 .txt never was.
1021
+ directory = _image_spool_dir()
1022
+ stem = os.path.splitext(re.sub(r"[^A-Za-z0-9_.-]", "_", name))[0][:80] or "image"
1023
+ target = directory / f"{stem}-{os.getpid()}.{mime}"
1024
+ target.write_bytes(raw)
1025
+ return _mcp_content({"type": "text", "text": (
1026
+ f"{meta} · too large to inline (limit {_IMAGE_INLINE_MAX_BYTES} bytes); "
1027
+ f"saved to {target}. Open that path with your image reader, or capture a "
1028
+ f"smaller region and call again.")})
955
1029
  b64 = base64.b64encode(raw).decode("ascii")
956
- return {"detail": detail, "image_url": f"data:image/{mime};base64,{b64}"}
1030
+ return _mcp_content(
1031
+ {"type": "image", "data": b64, "mimeType": f"image/{mime}"},
1032
+ {"type": "text", "text": meta},
1033
+ )
957
1034
 
958
1035
 
959
1036
  # ---------------------------------------------------------------------------
@@ -1486,7 +1563,10 @@ CLASSIC_TOOLS = [
1486
1563
  },
1487
1564
  {
1488
1565
  "name": "remote_view_image",
1489
- "description": "Read an image file from the remote machine and return it as a data URL for visual inspection.",
1566
+ "description": "Read an image from the remote machine and return it as native image content, "
1567
+ "so the model sees the pixels rather than base64 text. Images above "
1568
+ f"{_IMAGE_INLINE_MAX_BYTES // (1024 * 1024)} MB are written to a local file and reported "
1569
+ "by path instead of being inlined. Accepted formats: png, jpeg, gif, webp, bmp.",
1490
1570
  "inputSchema": {
1491
1571
  "type": "object",
1492
1572
  "properties": {
@@ -2362,7 +2442,14 @@ def _dispatch(remote: str, profile: str, req: dict) -> None:
2362
2442
  return
2363
2443
  try:
2364
2444
  res = func(remote, profile, args)
2365
- _result(req_id, {"content": [{"type": "text", "text": json.dumps(res, ensure_ascii=False)}]})
2445
+ # Most tools answer with a JSON document; image-returning tools
2446
+ # hand back MCP content blocks so the client renders the pixels
2447
+ # instead of showing the model a wall of base64.
2448
+ blocks = res.get("__mcp_content__") if isinstance(res, dict) else None
2449
+ if blocks is not None:
2450
+ _result(req_id, {"content": blocks})
2451
+ else:
2452
+ _result(req_id, {"content": [{"type": "text", "text": json.dumps(res, ensure_ascii=False)}]})
2366
2453
  except Exception as e: # tool execution error → MCP-level error result
2367
2454
  _result(req_id, {"isError": True, "content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}]})
2368
2455
  return
@@ -260,14 +260,22 @@ class McpClient:
260
260
  raise RuntimeError(f"MCP error calling {tool}: {r['error']}")
261
261
  result = r["result"]
262
262
  content = result.get("content") or []
263
- text = content[0]["text"] if content else ""
263
+ text = next((b.get("text", "") for b in content if b.get("type") == "text"), "")
264
+ images = [b for b in content if b.get("type") == "image"]
264
265
  if result.get("isError"):
265
266
  raise RuntimeError(f"{tool} returned isError: {text}")
266
- # Tool handlers return json.dumps(res) as the content text.
267
+ # Tool handlers return json.dumps(res) as the content text; image tools
268
+ # return an image block plus a human-readable summary instead.
267
269
  try:
268
- return json.loads(text)
270
+ payload = json.loads(text)
269
271
  except json.JSONDecodeError:
270
- return {"_raw": text}
272
+ payload = {"_raw": text}
273
+ if images:
274
+ image = images[0]
275
+ payload["image_url"] = f"data:{image['mimeType']};base64,{image['data']}"
276
+ payload["mimeType"] = image["mimeType"]
277
+ payload["text"] = text
278
+ return payload
271
279
 
272
280
  def close(self) -> None:
273
281
  try:
@@ -25,10 +25,11 @@ def test_view_image_png(mcp, tmp_path):
25
25
  p = tmp_path / "red.png"
26
26
  p.write_bytes(PNG_1x1_RED)
27
27
  res = mcp.call("remote_view_image", path=str(p))
28
- assert res["detail"] == "high"
28
+ # The tool answers with an MCP image block, so the model sees pixels.
29
29
  url = res["image_url"]
30
30
  assert url.startswith("data:image/png;base64,")
31
31
  assert base64.b64decode(url.split(",", 1)[1]) == PNG_1x1_RED
32
+ assert "detail=high" in res["text"]
32
33
 
33
34
 
34
35
  def test_view_image_jpeg(mcp, tmp_path):
@@ -42,15 +43,17 @@ def test_view_image_detail_original(mcp, tmp_path):
42
43
  p = tmp_path / "x.png"
43
44
  p.write_bytes(PNG_1x1_RED)
44
45
  res = mcp.call("remote_view_image", path=str(p), detail="original")
45
- assert res["detail"] == "original"
46
+ assert res["mimeType"] == "image/png"
47
+ assert "detail=original" in res["text"]
46
48
 
47
49
 
48
50
  def test_view_image_unknown_ext_fallthrough(mcp, tmp_path):
49
51
  p = tmp_path / "blob.xyz"
50
52
  p.write_bytes(b"\x00\x01\x02\x03")
51
- res = mcp.call("remote_view_image", path=str(p))
52
- # Unknown extension → mime equals the ext ("xyz"); data URL carries it.
53
- assert res["image_url"].startswith("data:image/xyz;base64,"), res["image_url"]
53
+ # The bytes are not an image and the extension is no help: refuse instead
54
+ # of claiming a data URL nothing can decode.
55
+ with pytest.raises(RuntimeError, match="not a recognised image"):
56
+ mcp.call("remote_view_image", path=str(p))
54
57
 
55
58
 
56
59
  def test_view_image_empty_path_raises(mcp):
@@ -194,19 +194,76 @@ def test_parse_rejects_unknown_marker():
194
194
 
195
195
  # ---- tools ----
196
196
 
197
- def test_view_image(fake):
198
- fake.files["/x.png"] = b"\x89PNG\r\n fake image bytes"
197
+ def test_view_image_returns_native_image_content(fake):
198
+ fake.files["/x.png"] = b"\x89PNG\r\n\x1a\n fake image bytes"
199
199
  r = mcp_server._remote_view_image("r", "p", {"path": "/x.png"})
200
- assert r["detail"] == "high"
201
- assert r["image_url"].startswith("data:image/png;base64,")
202
- assert base64.b64decode(r["image_url"].split(",", 1)[1]) == fake.files["/x.png"]
200
+ blocks = r["__mcp_content__"]
201
+ # A data-URL string made the model read base64; the image block makes the
202
+ # client show the pixels.
203
+ assert blocks[0]["type"] == "image"
204
+ assert blocks[0]["mimeType"] == "image/png"
205
+ assert base64.b64decode(blocks[0]["data"]) == fake.files["/x.png"]
206
+ assert blocks[1]["type"] == "text"
207
+ assert "x.png" in blocks[1]["text"] and "detail=high" in blocks[1]["text"]
208
+
209
+
210
+ def test_view_image_sniffs_the_type_from_bytes(fake):
211
+ fake.files["/y.JPG"] = b"\xff\xd8\xff\xe0 jpeg bytes"
212
+ r = mcp_server._remote_view_image("r", "p", {"path": "/y.JPG", "detail": "original"})
213
+ blocks = r["__mcp_content__"]
214
+ assert blocks[0]["mimeType"] == "image/jpeg"
215
+ assert "detail=original" in blocks[1]["text"]
203
216
 
204
217
 
205
- def test_view_image_jpeg_and_detail(fake):
206
- fake.files["/y.JPG"] = b"jpeg bytes"
207
- r = mcp_server._remote_view_image("r", "p", {"path": "/y.JPG", "detail": "original"})
208
- assert r["detail"] == "original"
209
- assert r["image_url"].startswith("data:image/jpeg;base64,")
218
+ def test_view_image_rejects_a_non_image(fake):
219
+ fake.files["/notes.png"] = b"just text"
220
+ with pytest.raises(ValueError, match="not a recognised image"):
221
+ mcp_server._remote_view_image("r", "p", {"path": "/notes.png"})
222
+
223
+
224
+ def test_view_image_spools_oversized_images_to_a_real_file(monkeypatch, tmp_path, fake):
225
+ fake.files["/big.png"] = b"\x89PNG\r\n\x1a\n" + b"x" * 100
226
+ monkeypatch.setattr(mcp_server, "_IMAGE_INLINE_MAX_BYTES", 50)
227
+ monkeypatch.setattr(mcp_server, "_image_spool_dir", lambda: tmp_path)
228
+
229
+ r = mcp_server._remote_view_image("r", "p", {"path": "/big.png"})
230
+
231
+ blocks = r["__mcp_content__"]
232
+ assert len(blocks) == 1 and blocks[0]["type"] == "text"
233
+ saved = list(tmp_path.glob("*.png"))
234
+ # A real file the caller can open — not a .txt full of base64.
235
+ assert len(saved) == 1 and saved[0].read_bytes() == fake.files["/big.png"]
236
+ assert str(saved[0]) in blocks[0]["text"]
237
+
238
+
239
+ def test_dispatch_returns_image_blocks_for_view_image(monkeypatch, fake):
240
+ fake.files["/x.png"] = b"\x89PNG\r\n\x1a\nabc"
241
+ results: list[dict] = []
242
+ monkeypatch.setattr(mcp_server, "_send", lambda obj: results.append(obj))
243
+ monkeypatch.setattr(mcp_server, "_ACTIVE_TOOLSET", "classic")
244
+
245
+ mcp_server._dispatch("box", "cmd", {
246
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
247
+ "params": {"name": "remote_view_image", "arguments": {"path": "/x.png"}},
248
+ })
249
+
250
+ content = results[-1]["result"]["content"]
251
+ assert content[0]["type"] == "image" and content[0]["mimeType"] == "image/png"
252
+
253
+
254
+ def test_dispatch_keeps_json_text_for_ordinary_tools(monkeypatch, fake):
255
+ results: list[dict] = []
256
+ monkeypatch.setattr(mcp_server, "_send", lambda obj: results.append(obj))
257
+ monkeypatch.setattr(mcp_server, "_ACTIVE_TOOLSET", "classic")
258
+
259
+ mcp_server._dispatch("box", "cmd", {
260
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
261
+ "params": {"name": "remote_ping", "arguments": {}},
262
+ })
263
+
264
+ content = results[-1]["result"]["content"]
265
+ assert len(content) == 1 and content[0]["type"] == "text"
266
+ assert json.loads(content[0]["text"])["ok"] is True
210
267
 
211
268
 
212
269
  def test_ping(fake):
@@ -679,7 +736,9 @@ def test_exec_plan_posix_unchanged():
679
736
  def test_exec_plan_windows_cmd_writes_exit_code_inside_the_batch_file():
680
737
  plan = mcp_server._exec_plan(cmd="whoami", profile="cmd", shell_bin=None, windows=True)
681
738
  assert plan.script.startswith("~/AppData/Local/Temp/aimux_tmp/") and plan.script.endswith(".cmd")
682
- assert plan.body.startswith("@echo off\r\nwhoami\r\n")
739
+ # UTF-8 console first, so the command body and its output are not read as
740
+ # the system code page (cp936), which produced mojibake.
741
+ assert plan.body.startswith("@echo off\r\nchcp 65001 >nul\r\nwhoami\r\n")
683
742
  assert f'echo %errorlevel% > "{mcp_server._win_path(plan.code)}"' in plan.body
684
743
  assert plan.launch == f'"{mcp_server._win_path(plan.script)}" > "{mcp_server._win_path(plan.out)}" 2>&1'
685
744
 
@@ -755,6 +814,40 @@ def test_decode_text_tolerates_windows_shell_encodings():
755
814
  assert mcp_server._decode_text("保留".encode("utf-8")) == "保留"
756
815
 
757
816
 
817
+ def test_decode_text_falls_back_to_the_console_code_page():
818
+ # cmd writes cp936 on a Chinese Windows box; decoding it as UTF-8 with
819
+ # "replace" is what produced the "�" soup.
820
+ assert mcp_server._decode_text("保留".encode("cp936")) == "保留"
821
+ assert mcp_server._decode_text("café".encode("cp1252")) == "café"
822
+ assert mcp_server._decode_text(b"plain ascii") == "plain ascii"
823
+
824
+
825
+ def test_powershell_script_is_uploaded_with_a_utf8_bom(monkeypatch):
826
+ # Windows PowerShell 5.1 reads a BOM-less .ps1 as ANSI; Chinese in the
827
+ # command would arrive as mojibake.
828
+ written: dict = {}
829
+
830
+ class C:
831
+ def file_write(self, *, remote, path, content_b64, timeout=60.0):
832
+ written[path] = base64.b64decode(content_b64)
833
+ return {"ok": True}
834
+
835
+ def send_keys(self, **kw):
836
+ return {"ok": True}
837
+
838
+ monkeypatch.setattr(mcp_server, "_client", lambda: C())
839
+ monkeypatch.setattr(mcp_server, "_create_exec_session", lambda *a, **k: "sid")
840
+ monkeypatch.setattr(mcp_server, "_wait_exec_done",
841
+ lambda *a, **k: ("", 0, True, 0.1, False))
842
+ monkeypatch.setattr(mcp_server, "_sessions", {"sid": {"name": "s", "remote": "r"}})
843
+
844
+ mcp_server._remote_exec_command("r", "powershell", {"cmd": "Write-Output 保留", "yield_time_ms": 500})
845
+
846
+ script = next(path for path in written if path.endswith(".ps1"))
847
+ assert written[script].startswith(b"\xef\xbb\xbf")
848
+ assert "保留".encode("utf-8") in written[script]
849
+
850
+
758
851
  def test_read_code_file_ignores_noise_around_the_number(monkeypatch):
759
852
  class C:
760
853
  def __init__(self, data):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes