@mthines/reaper-mcp 0.100.1 → 0.101.0

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.
package/main.js CHANGED
@@ -3052,7 +3052,7 @@ import { z as z14 } from "zod/v4";
3052
3052
  function registerMediaTools(server) {
3053
3053
  server.tool(
3054
3054
  "list_media_items",
3055
- "List all media items on a track with position, length, name, volume, mute state, and whether it is MIDI or audio",
3055
+ "List all media items on a track with position, length, name, volume (the item gain), takeVolume (the active take gain), totalGainDb (what the item plays: item + take), mute state, and whether it is MIDI or audio",
3056
3056
  {
3057
3057
  trackIndex: z14.coerce.number().min(0).describe("0-based track index")
3058
3058
  },
@@ -3066,7 +3066,7 @@ function registerMediaTools(server) {
3066
3066
  );
3067
3067
  server.tool(
3068
3068
  "get_media_item_properties",
3069
- "Get detailed properties of a media item: position, length, volume, fades, play rate, take info, source file",
3069
+ "Get detailed properties of a media item: position, length, volume (item gain, dB), takeVolume / takePolarityInverted / takePan (the active take), totalGainDb (item + take, what the item plays), fades, play rate, pitch, take count, source file, lock",
3070
3070
  {
3071
3071
  trackIndex: z14.coerce.number().min(0).describe("0-based track index"),
3072
3072
  itemIndex: z14.coerce.number().min(0).describe("0-based item index on the track")
@@ -3081,7 +3081,7 @@ function registerMediaTools(server) {
3081
3081
  );
3082
3082
  server.tool(
3083
3083
  "set_media_item_properties",
3084
- "Set media item properties: position (seconds), length (seconds), volume (dB), mute, fade in/out lengths, play rate",
3084
+ "Set media item properties: position (seconds), length (seconds), volume (item gain, dB), takeVolume (active take gain, dB), takePan, takePolarityInverted, pitch (semitones), preservePitch, mute, fade in/out lengths, play rate, locked, loopSource. The item plays item volume + take volume (see totalGainDb in get_media_item_properties). Take fields are checked before anything is written.",
3085
3085
  {
3086
3086
  trackIndex: z14.coerce.number().min(0).describe("0-based track index"),
3087
3087
  itemIndex: z14.coerce.number().min(0).describe("0-based item index on the track"),
@@ -3091,20 +3091,17 @@ function registerMediaTools(server) {
3091
3091
  mute: z14.coerce.number().min(0).max(1).optional().describe("Mute state (0=unmuted, 1=muted)"),
3092
3092
  fadeInLength: z14.coerce.number().min(0).optional().describe("Fade-in length in seconds"),
3093
3093
  fadeOutLength: z14.coerce.number().min(0).optional().describe("Fade-out length in seconds"),
3094
- playRate: z14.coerce.number().min(0.1).max(10).optional().describe("Playback rate (1.0=normal, 0.5=half, 2.0=double)")
3094
+ playRate: z14.coerce.number().min(0.1).max(10).optional().describe("Playback rate (1.0=normal, 0.5=half, 2.0=double)"),
3095
+ takeVolume: z14.coerce.number().min(-150).max(60).optional().describe("Active take gain in dB (0 = unity); separate from item volume, the item plays both. -150 = silence. Keeps the take polarity unless takePolarityInverted is given"),
3096
+ takePan: z14.coerce.number().min(-1).max(1).optional().describe("Active take pan (-1 left, 0 centre, 1 right)"),
3097
+ takePolarityInverted: z14.coerce.number().min(0).max(1).optional().describe("Flip the active take polarity (1 = inverted, 0 = normal)"),
3098
+ pitch: z14.coerce.number().min(-48).max(48).optional().describe("Active take pitch in semitones"),
3099
+ preservePitch: z14.coerce.number().min(0).max(1).optional().describe("Keep the pitch when the play rate changes (1 = on, 0 = off)"),
3100
+ locked: z14.coerce.number().min(0).max(1).optional().describe("Lock the item against edits (1 = locked, 0 = unlocked)"),
3101
+ loopSource: z14.coerce.number().min(0).max(1).optional().describe("Loop the source to fill the item (1 = on, 0 = off)")
3095
3102
  },
3096
- async ({ trackIndex: trackIndex5, itemIndex: itemIndex2, position, length, volume, mute, fadeInLength, fadeOutLength, playRate }) => {
3097
- const res = await sendCommand("set_media_item_properties", {
3098
- trackIndex: trackIndex5,
3099
- itemIndex: itemIndex2,
3100
- position,
3101
- length,
3102
- volume,
3103
- mute,
3104
- fadeInLength,
3105
- fadeOutLength,
3106
- playRate
3107
- });
3103
+ async (args) => {
3104
+ const res = await sendCommand("set_media_item_properties", args);
3108
3105
  if (!res.success) {
3109
3106
  return { content: [{ type: "text", text: `Error: ${res.error}` }], isError: true };
3110
3107
  }
@@ -3124,7 +3121,14 @@ function registerMediaTools(server) {
3124
3121
  mute: z14.coerce.number().min(0).max(1).optional().describe("Mute state (0=unmuted, 1=muted)"),
3125
3122
  fadeInLength: z14.coerce.number().min(0).optional().describe("Fade-in length in seconds"),
3126
3123
  fadeOutLength: z14.coerce.number().min(0).optional().describe("Fade-out length in seconds"),
3127
- playRate: z14.coerce.number().min(0.1).max(10).optional().describe("Playback rate (1.0=normal)")
3124
+ playRate: z14.coerce.number().min(0.1).max(10).optional().describe("Playback rate (1.0=normal)"),
3125
+ takeVolume: z14.coerce.number().min(-150).max(60).optional().describe("Active take gain in dB (0 = unity); separate from item volume, the item plays both. -150 = silence. Keeps the take polarity unless takePolarityInverted is given"),
3126
+ takePan: z14.coerce.number().min(-1).max(1).optional().describe("Active take pan (-1 left, 0 centre, 1 right)"),
3127
+ takePolarityInverted: z14.coerce.number().min(0).max(1).optional().describe("Flip the active take polarity (1 = inverted, 0 = normal)"),
3128
+ pitch: z14.coerce.number().min(-48).max(48).optional().describe("Active take pitch in semitones"),
3129
+ preservePitch: z14.coerce.number().min(0).max(1).optional().describe("Keep the pitch when the play rate changes (1 = on, 0 = off)"),
3130
+ locked: z14.coerce.number().min(0).max(1).optional().describe("Lock the item against edits (1 = locked, 0 = unlocked)"),
3131
+ loopSource: z14.coerce.number().min(0).max(1).optional().describe("Loop the source to fill the item (1 = on, 0 = off)")
3128
3132
  })).describe("Array of item property updates to apply")
3129
3133
  },
3130
3134
  async ({ items }) => {
@@ -5362,6 +5366,23 @@ var MIN_PYTHON_MINOR = 10;
5362
5366
  function getPythonBin() {
5363
5367
  return process.env["PYTHON_BIN"] ?? "python3";
5364
5368
  }
5369
+ var WINDOWS_PYTHON_CANDIDATES = ["python3", "python", "py"];
5370
+ async function resolvePythonBin(isWindows = platform2() === "win32") {
5371
+ const configured = getPythonBin();
5372
+ if (process.env["PYTHON_BIN"] || !isWindows) return configured;
5373
+ let tooOld = null;
5374
+ for (const candidate of WINDOWS_PYTHON_CANDIDATES) {
5375
+ try {
5376
+ await checkPython(candidate);
5377
+ return candidate;
5378
+ } catch (err) {
5379
+ if (!tooOld && err instanceof Error && err.message.startsWith(`Python ${MIN_PYTHON_MAJOR}.${MIN_PYTHON_MINOR}+ required`)) {
5380
+ tooOld = candidate;
5381
+ }
5382
+ }
5383
+ }
5384
+ return tooOld ?? configured;
5385
+ }
5365
5386
  function parsePythonVersion(output) {
5366
5387
  const match = output.match(/Python\s+(\d+)\.(\d+)\.(\d+)/i);
5367
5388
  if (!match) return null;
@@ -5407,9 +5428,12 @@ function resolveRequirementsTxt(baseDir) {
5407
5428
  const sidecarDir = resolveAssetDir(baseDir, "sidecar");
5408
5429
  return join5(sidecarDir, "requirements.txt");
5409
5430
  }
5431
+ function pipUpgradeCommand() {
5432
+ return `"${join5(SIDECAR_VENV_PATH, VENV_BIN, VENV_PYTHON_NAME)}" -m pip install --upgrade pip`;
5433
+ }
5410
5434
  async function installDeps(requirementsPath) {
5411
5435
  const pip = join5(SIDECAR_VENV_PATH, VENV_BIN, VENV_PIP_NAME);
5412
- await exec(`"${pip}" install --upgrade pip`);
5436
+ await exec(pipUpgradeCommand());
5413
5437
  const { stdout, stderr } = await exec(`"${pip}" install -r "${requirementsPath}"`);
5414
5438
  if (stdout) process.stdout.write(stdout);
5415
5439
  if (stderr) process.stderr.write(stderr);
@@ -5697,7 +5721,7 @@ Installing sidecar scripts to: ${SIDECAR_DIR}`);
5697
5721
  console.log("\nRun `reaper-mcp doctor` to verify.\n");
5698
5722
  }
5699
5723
  async function installCore() {
5700
- const pythonBin = getPythonBin();
5724
+ const pythonBin = await resolvePythonBin();
5701
5725
  console.log(`
5702
5726
  Checking Python interpreter: ${pythonBin}`);
5703
5727
  let version = "";
@@ -5962,7 +5986,10 @@ var SidecarClientImpl = class {
5962
5986
  } catch {
5963
5987
  }
5964
5988
  const child = spawn(VENV_PYTHON, [SIDECAR_SCRIPT_PATH], {
5965
- stdio: ["pipe", "pipe", "pipe"]
5989
+ stdio: ["pipe", "pipe", "pipe"],
5990
+ // Requests and responses are UTF-8; on Windows Python would otherwise use cp1252 and garble
5991
+ // non-ASCII paths. PYTHONUTF8 also covers any process the sidecar starts.
5992
+ env: { ...process.env, PYTHONUTF8: "1", PYTHONIOENCODING: "utf-8" }
5966
5993
  });
5967
5994
  if (child.stdout) {
5968
5995
  child.stdout.setEncoding("utf8");
@@ -11984,7 +12011,7 @@ async function doctor() {
11984
12011
  let pythonOk = false;
11985
12012
  let pythonDetail = "Not found";
11986
12013
  try {
11987
- const pythonBin = process.env["PYTHON_BIN"] ?? "python3";
12014
+ const pythonBin = await resolvePythonBin();
11988
12015
  const { stdout, stderr } = await execAsync(`"${pythonBin}" --version`);
11989
12016
  const versionStr = (stdout + stderr).trim();
11990
12017
  const match = versionStr.match(/Python\s+(\d+)\.(\d+)/i);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mthines/reaper-mcp",
3
- "version": "0.100.1",
3
+ "version": "0.101.0",
4
4
  "type": "module",
5
5
  "description": "MCP server for controlling REAPER DAW — real-time mixing, FX control, and frequency analysis for AI agents",
6
6
  "license": "MIT",
@@ -2915,7 +2915,7 @@ function handlers.list_media_items(params)
2915
2915
  end
2916
2916
 
2917
2917
  local vol_raw = reaper.GetMediaItemInfo_Value(item, "D_VOL")
2918
- items[#items + 1] = {
2918
+ local entry = {
2919
2919
  itemIndex = i,
2920
2920
  position = reaper.GetMediaItemInfo_Value(item, "D_POSITION"),
2921
2921
  length = reaper.GetMediaItemInfo_Value(item, "D_LENGTH"),
@@ -2928,6 +2928,12 @@ function handlers.list_media_items(params)
2928
2928
  isMidi = is_midi,
2929
2929
  takeName = take_name,
2930
2930
  }
2931
+ -- `volume` is the item's own gain; the take has one too, and the item plays both
2932
+ if items_lib_ok then
2933
+ local lv = items_lib.item_levels(reaper, item)
2934
+ entry.takeVolume, entry.totalGainDb = lv.takeVolume, lv.totalGainDb
2935
+ end
2936
+ items[#items + 1] = entry
2931
2937
  end
2932
2938
 
2933
2939
  return { trackIndex = track_idx, items = items, total = #items }
@@ -2961,6 +2967,10 @@ function handlers.get_media_item_properties(params)
2961
2967
 
2962
2968
  local vol_raw = reaper.GetMediaItemInfo_Value(item, "D_VOL")
2963
2969
 
2970
+ -- `volume` is the item's own gain; the active take has its own gain, pan and
2971
+ -- polarity, and the item plays item gain + take gain (totalGainDb)
2972
+ local lv = items_lib_ok and items_lib.item_levels(reaper, item) or {}
2973
+
2964
2974
  return {
2965
2975
  trackIndex = params.trackIndex,
2966
2976
  itemIndex = params.itemIndex,
@@ -2969,6 +2979,13 @@ function handlers.get_media_item_properties(params)
2969
2979
  name = take_name,
2970
2980
  volume = to_db(vol_raw),
2971
2981
  volumeRaw = vol_raw,
2982
+ takeVolume = lv.takeVolume,
2983
+ takePolarityInverted = lv.takePolarityInverted,
2984
+ takePan = lv.takePan,
2985
+ preservePitch = lv.preservePitch,
2986
+ totalGainDb = lv.totalGainDb,
2987
+ takeCount = lv.takeCount,
2988
+ activeTakeIndex = lv.activeTakeIndex,
2972
2989
  muted = reaper.GetMediaItemInfo_Value(item, "B_MUTE") ~= 0,
2973
2990
  fadeInLength = reaper.GetMediaItemInfo_Value(item, "D_FADEINLEN"),
2974
2991
  fadeOutLength = reaper.GetMediaItemInfo_Value(item, "D_FADEOUTLEN"),
@@ -2989,7 +3006,21 @@ function handlers.set_media_item_properties(params)
2989
3006
  local track, item, err = get_media_item(params)
2990
3007
  if err then return nil, err end
2991
3008
 
3009
+ -- take gain/pan/polarity, pitch, lock, loop (mcp_items_lib.lua): checked before anything is written
3010
+ local wants_lib = false
3011
+ for _, k in ipairs({ "takeVolume", "takePan", "takePolarityInverted", "pitch", "preservePitch", "locked", "loopSource" }) do
3012
+ if params[k] ~= nil then wants_lib = true end
3013
+ end
3014
+ if wants_lib then
3015
+ if not items_lib_ok then
3016
+ return nil, "mcp_items_lib.lua is not installed next to mcp_bridge.lua — run `reaper-mcp setup` and restart the bridge"
3017
+ end
3018
+ local bad = items_lib.check_item_props(params, reaper.GetActiveTake(item) ~= nil)
3019
+ if bad then return nil, bad end
3020
+ end
3021
+
2992
3022
  reaper.Undo_BeginBlock()
3023
+ if wants_lib then items_lib.apply_item_props(reaper, item, params) end
2993
3024
 
2994
3025
  if params.position ~= nil then
2995
3026
  reaper.SetMediaItemInfo_Value(item, "D_POSITION", params.position)
@@ -3049,6 +3080,22 @@ function handlers.set_media_items_properties(params)
3049
3080
  errors[#errors + 1] = "Item " .. item_idx .. " not found on track " .. track_idx
3050
3081
  else
3051
3082
  local item = reaper.GetTrackMediaItem(track, item_idx)
3083
+ -- take gain/pan/polarity, pitch, lock, loop (mcp_items_lib.lua): a bad value skips this item
3084
+ local wants_lib, bad = false, nil
3085
+ for _, k in ipairs({ "takeVolume", "takePan", "takePolarityInverted", "pitch", "preservePitch", "locked", "loopSource" }) do
3086
+ if item_params[k] ~= nil then wants_lib = true end
3087
+ end
3088
+ if wants_lib then
3089
+ if items_lib_ok then
3090
+ bad = items_lib.check_item_props(item_params, reaper.GetActiveTake(item) ~= nil)
3091
+ else
3092
+ bad = "mcp_items_lib.lua is not installed next to mcp_bridge.lua — run `reaper-mcp setup` and restart the bridge"
3093
+ end
3094
+ end
3095
+ if bad then
3096
+ errors[#errors + 1] = "Item " .. item_idx .. " on track " .. track_idx .. ": " .. bad
3097
+ else
3098
+ if wants_lib then items_lib.apply_item_props(reaper, item, item_params) end
3052
3099
  if item_params.position ~= nil then
3053
3100
  reaper.SetMediaItemInfo_Value(item, "D_POSITION", item_params.position)
3054
3101
  end
@@ -3074,6 +3121,7 @@ function handlers.set_media_items_properties(params)
3074
3121
  end
3075
3122
  end
3076
3123
  edited = edited + 1
3124
+ end
3077
3125
  end
3078
3126
  end
3079
3127
  end
@@ -874,4 +874,95 @@ end
874
874
  function M.list_fx_chains(api, _, ctx) return list_files(api, ctx, "FXChains", M.FX_CHAIN_EXT) end
875
875
  function M.list_track_templates(api, _, ctx) return list_files(api, ctx, "TrackTemplates", M.TEMPLATE_EXT) end
876
876
 
877
+ -- -----------------------------------------------------------------------------
878
+ -- Item and take gain, pan, pitch (read in get/list_media_items, written by
879
+ -- set_media_item(s)_properties)
880
+ --
881
+ -- What an item plays is item gain (D_VOL on the item) times the active take's
882
+ -- gain (D_VOL on the take), so a level read from the item alone can be 20 dB
883
+ -- off. A negative take D_VOL is a polarity flip: its level is the magnitude.
884
+ -- -----------------------------------------------------------------------------
885
+
886
+ M.MIN_DB = -150.0
887
+ local MAX_TAKE_DB = 60.0
888
+ local MAX_PITCH = 48.0
889
+
890
+ local function lin_to_db(v)
891
+ v = math.abs(v or 1)
892
+ if v <= 0 then return M.MIN_DB end
893
+ return math.floor(20 * math.log(v, 10) * 1000 + 0.5) / 1000
894
+ end
895
+
896
+ local function db_to_lin(db)
897
+ if db <= M.MIN_DB then return 0 end
898
+ return 10 ^ (db / 20)
899
+ end
900
+
901
+ -- Item and active-take levels for one item; also the take count and active take.
902
+ -- Safe on an item without takes (empty take fields are left out).
903
+ function M.item_levels(api, item)
904
+ local item_db = lin_to_db(api.GetMediaItemInfo_Value(item, "D_VOL"))
905
+ local out = { itemVolume = item_db, takeCount = api.CountTakes(item) }
906
+ local take = api.GetActiveTake(item)
907
+ if not take then
908
+ out.totalGainDb = item_db
909
+ return out
910
+ end
911
+ local tv = api.GetMediaItemTakeInfo_Value(take, "D_VOL")
912
+ out.takeVolume = lin_to_db(tv)
913
+ out.takePolarityInverted = tv < 0
914
+ out.takePan = api.GetMediaItemTakeInfo_Value(take, "D_PAN")
915
+ out.preservePitch = api.GetMediaItemTakeInfo_Value(take, "B_PPITCH") ~= 0
916
+ out.totalGainDb = math.floor((item_db + out.takeVolume) * 1000 + 0.5) / 1000
917
+ for i = 0, out.takeCount - 1 do
918
+ if api.GetTake(item, i) == take then out.activeTakeIndex = i end
919
+ end
920
+ return out
921
+ end
922
+
923
+ -- Check the item/take fields of one set request without writing anything.
924
+ -- Returns nil when fine, else the reason. `has_take` says the item has an
925
+ -- active take (take fields on an item without one are refused).
926
+ function M.check_item_props(p, has_take)
927
+ local function num(name, lo, hi)
928
+ local v = p[name]
929
+ if v == nil then return nil end
930
+ local n = tonumber(v)
931
+ if not n then return name .. " must be a number" end
932
+ if n < lo or n > hi then return name .. " must be between " .. lo .. " and " .. hi end
933
+ end
934
+ local bad = num("takeVolume", M.MIN_DB, MAX_TAKE_DB) or num("takePan", -1, 1)
935
+ or num("pitch", -MAX_PITCH, MAX_PITCH)
936
+ if bad then return bad end
937
+ if not has_take and (p.takeVolume ~= nil or p.takePan ~= nil or p.takePolarityInverted ~= nil
938
+ or p.pitch ~= nil or p.preservePitch ~= nil) then
939
+ return "item has no active take: takeVolume, takePan, takePolarityInverted, pitch and preservePitch need one"
940
+ end
941
+ end
942
+
943
+ local function truthy(v) return v == true or v == 1 or v == "1" or v == "true" end
944
+
945
+ -- Write the item/take fields (already checked by check_item_props). Changing
946
+ -- takeVolume keeps the take's polarity unless takePolarityInverted is given.
947
+ function M.apply_item_props(api, item, p)
948
+ local take = api.GetActiveTake(item)
949
+ if take then
950
+ if p.takeVolume ~= nil or p.takePolarityInverted ~= nil then
951
+ local cur = api.GetMediaItemTakeInfo_Value(take, "D_VOL")
952
+ local inverted = cur < 0
953
+ if p.takePolarityInverted ~= nil then inverted = truthy(p.takePolarityInverted) end
954
+ local mag = math.abs(cur)
955
+ if p.takeVolume ~= nil then mag = db_to_lin(tonumber(p.takeVolume)) end
956
+ api.SetMediaItemTakeInfo_Value(take, "D_VOL", inverted and -mag or mag)
957
+ end
958
+ if p.takePan ~= nil then api.SetMediaItemTakeInfo_Value(take, "D_PAN", tonumber(p.takePan)) end
959
+ if p.pitch ~= nil then api.SetMediaItemTakeInfo_Value(take, "D_PITCH", tonumber(p.pitch)) end
960
+ if p.preservePitch ~= nil then
961
+ api.SetMediaItemTakeInfo_Value(take, "B_PPITCH", truthy(p.preservePitch) and 1 or 0)
962
+ end
963
+ end
964
+ if p.locked ~= nil then api.SetMediaItemInfo_Value(item, "C_LOCK", truthy(p.locked) and 1 or 0) end
965
+ if p.loopSource ~= nil then api.SetMediaItemInfo_Value(item, "B_LOOPSRC", truthy(p.loopSource) and 1 or 0) end
966
+ end
967
+
877
968
  return M
@@ -73,8 +73,16 @@ local function temp_dir(reaper, env)
73
73
  dir = reaper.GetTempPath()
74
74
  else
75
75
  local t = env.os.tmpname()
76
- dir = t:match("^(.+)[/\\][^/\\]+$") or "/tmp"
76
+ dir = t:match("^(.+)[/\\][^/\\]+$")
77
77
  env.os.remove(t)
78
+ -- Windows' os.tmpname() is a bare name like "\\s3k4." with no folder in it
79
+ if not dir and env.os.getenv then
80
+ for _, var in ipairs({ "TEMP", "TMP" }) do
81
+ local v = env.os.getenv(var)
82
+ if v and v ~= "" then dir = v; break end
83
+ end
84
+ end
85
+ dir = dir or "/tmp"
78
86
  end
79
87
  if dir:sub(-1) ~= "/" and dir:sub(-1) ~= "\\" then dir = dir .. "/" end
80
88
  return dir
package/sidecar/server.py CHANGED
@@ -615,9 +615,19 @@ def dispatch(raw: str) -> str:
615
615
  # Main loop
616
616
  # ---------------------------------------------------------------------------
617
617
 
618
+ def configure_stdio() -> None:
619
+ """Speak UTF-8 on stdin/stdout whatever the locale says.
620
+
621
+ The Node side writes and reads UTF-8. On Windows Python defaults to the locale
622
+ encoding (cp1252), which turns a path like "å" into two wrong characters.
623
+ stdout is line-buffered so responses are delivered immediately.
624
+ """
625
+ sys.stdin.reconfigure(encoding="utf-8")
626
+ sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
627
+
628
+
618
629
  def main() -> None:
619
- # Disable output buffering so responses are delivered immediately
620
- sys.stdout = os.fdopen(sys.stdout.fileno(), "w", buffering=1)
630
+ configure_stdio()
621
631
 
622
632
  # Log startup to stderr (visible in MCP server logs)
623
633
  print(f"[reaper-mcp-sidecar] Starting — Python {sys.version}", file=sys.stderr, flush=True)
@@ -475,3 +475,26 @@ def test_separate_method_says_how_to_install_when_demucs_is_missing(tmp_path, mo
475
475
  _write_sine(path, -12)
476
476
  resp = _call("separate", {"path": str(path), "outDir": str(tmp_path / "out")})
477
477
  assert "setup-sidecar --with-separation" in resp["error"]["message"]
478
+
479
+
480
+ def test_configure_stdio_decodes_utf8_even_under_a_cp1252_locale():
481
+ """Windows defaults stdio to cp1252, which turns a UTF-8 "\u00e5" into two characters."""
482
+ import os
483
+ import subprocess
484
+ import sys
485
+
486
+ sidecar_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
487
+ code = (
488
+ "import sys; sys.path.insert(0, sys.argv[1]); import server; server.configure_stdio(); "
489
+ "line = sys.stdin.readline().strip(); "
490
+ "print(sys.stdin.encoding, sys.stdout.encoding, line == 'Bj\\u00e5rn')"
491
+ )
492
+ env = {**os.environ, "PYTHONIOENCODING": "cp1252", "PYTHONUTF8": "0"}
493
+ out = subprocess.run(
494
+ [sys.executable, "-c", code, sidecar_dir],
495
+ input="Bj\u00e5rn\n".encode("utf-8"),
496
+ capture_output=True,
497
+ env=env,
498
+ check=True,
499
+ )
500
+ assert out.stdout.decode("utf-8").split() == ["utf-8", "utf-8", "True"]