From 534cffcfd3c4d504091c762202ca9813e9dcac12 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:35:39 -0500 Subject: [PATCH 1/8] fix(mcp): ask before a batch that replaces the whole site, as edit_site does apply_commands and the edit_* tools now share one rule for which commands remove content, so site.replace in a batch waits for approval when Agent Connect is set to ask. --- backend/app/mcp_domains.py | 6 ++++- backend/app/mcp_server.py | 6 ++--- backend/tests/test_agent_asks.py | 44 ++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_agent_asks.py diff --git a/backend/app/mcp_domains.py b/backend/app/mcp_domains.py index 2f6714bd..7664b5f8 100644 --- a/backend/app/mcp_domains.py +++ b/backend/app/mcp_domains.py @@ -113,12 +113,16 @@ } +def removing(command) -> bool: + return str(command).endswith(('.remove', '.delete')) or command == 'site.replace' + + def domain_tools(): tools = [] for name, title, intro, commands in DOMAINS: lines = '\n'.join(f'- {command} {COMMAND_DOCS[command]}' for command in commands) description = f'{intro} One command per call, applied as one undo step.\n{lines}' - removes = any(command.endswith('.remove') or command == 'site.replace' for command in commands) + removes = any(removing(command) for command in commands) tools.append({ 'name': name, 'title': title, diff --git a/backend/app/mcp_server.py b/backend/app/mcp_server.py index 8296dddb..8f7e4ced 100644 --- a/backend/app/mcp_server.py +++ b/backend/app/mcp_server.py @@ -14,7 +14,7 @@ from .config import ORIGINS, PORT, VERSION from .engine import EngineError from .mcp_catalog import TOOLS as BASE_TOOLS -from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, tokens, tree +from .mcp_domains import COMMAND_DOCS, DOMAIN_BY_NAME, DOMAIN_TOOLS, INSTRUCTIONS, PROMPTS, compact, removing, tokens, tree from .providers.catalog import PROVIDER_BY_NAME, PROVIDER_TOOLS from .providers.service import dispatch_tool as provider_dispatch from .service import studio @@ -75,9 +75,9 @@ async def call_tool(context, params): errors = list(Draft202012Validator(BY_NAME[params.name]['inputSchema']).iter_errors(arguments)) if errors: raise EngineError(errors[0].message[:400], 422) - removes = params.name == 'apply_commands' and any(str(item.get('command', '')).endswith(('.remove', '.delete')) for item in arguments.get('commands', []) if isinstance(item, dict)) + removes = params.name == 'apply_commands' and any(removing(item.get('command', '')) for item in arguments.get('commands', []) if isinstance(item, dict)) if params.name in DOMAIN_BY_NAME: # domain tools: judge the one command, not the tool's worst case - removes = arguments['command'].endswith('.remove') or arguments['command'] == 'site.replace' + removes = removing(arguments['command']) if params.name == 'motion_track': # judged per call like the domain tools: only a null track deletes removes = arguments['track'] is None if params.name == 'library_import_site': # only an import that replaces matching routes swaps content away diff --git a/backend/tests/test_agent_asks.py b/backend/tests/test_agent_asks.py new file mode 100644 index 00000000..f1e3208e --- /dev/null +++ b/backend/tests/test_agent_asks.py @@ -0,0 +1,44 @@ +import pytest + +from test_f2_f3_mcp import call + + +@pytest.fixture() +def agents_asking(client): + assert client.post("/api/agents", json={"enabled": True}).status_code == 200 + previous = client.post("/api/approvals/settings", json={}).json()["agentDestructive"] + client.post("/api/approvals/settings", json={"agentDestructive": True}) + yield + client.post("/api/approvals/settings", json={"agentDestructive": previous}) + client.post("/api/agents", json={"enabled": False}) + + +@pytest.fixture() +def asked(monkeypatch): + from app.engine import EngineError + from app.service import studio + + seen = [] + + async def refuse(kind, subject, *args, **kwargs): + seen.append(subject["tool"]) + raise EngineError("Declined.", 403) + + monkeypatch.setattr(studio.approvals, "wait", refuse) + return seen + + +def test_replacing_the_whole_site_through_apply_commands_asks_first_like_edit_site(client, agents_asking, asked): + state = client.get("/api/state").json() + before = state["site"] + replacement = {**before, "name": "Replaced by a batch"} + result = call(client, "apply_commands", {"commands": [{"command": "site.replace", "params": {"site": replacement}}]}) + assert result.get("isError") and asked == ["apply_commands"] + assert client.get("/api/state").json()["site"]["name"] == before["name"] + result = call(client, "edit_site", {"command": "site.replace", "params": {"site": replacement}}) + assert result.get("isError") and asked == ["apply_commands", "edit_site"] + + +def test_an_ordinary_batch_does_not_ask(client, agents_asking, asked): + result = call(client, "apply_commands", {"commands": [{"command": "token.set", "params": {"name": "asks-none", "value": "#123456"}}]}) + assert not result.get("isError") and asked == [] From bad8d061a948201823daa1f41129767b6454c022 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:36:07 -0500 Subject: [PATCH 2/8] fix(mcp): send_to_formpublisher runs the hand-off in the engine itself The tool called the engine's own hand-off route over HTTP without the window key, which that route requires, so it was always refused. It now runs the same hand-off directly. --- backend/app/authoring_tools.py | 26 ++------------------------ backend/tests/test_agent_asks.py | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/backend/app/authoring_tools.py b/backend/app/authoring_tools.py index 195ca47b..996cbb0e 100644 --- a/backend/app/authoring_tools.py +++ b/backend/app/authoring_tools.py @@ -5,14 +5,10 @@ Annotations follow the MCP meaning: readOnlyHint false for anything that changes the site; destructiveHint only where a call deletes or overwrites what a person may have made (removals, a preset applied over existing values); idempotentHint where repeating the same call leaves the same result.""" -import asyncio import base64 import binascii import json -import urllib.error -import urllib.request -from .config import AUTH_TOKEN, PORT from .engine import EngineError from .mcp_catalog import REVISION, tool from .mcp_domains import compact @@ -122,25 +118,6 @@ def matches(item): return result -def _send(locale): - url = f'http://127.0.0.1:{PORT}/api/handoff/formpublisher' + (f'?locale={urllib.request.quote(locale)}' if locale else '') - headers = {'X-FormWeb-Channel': 'agent', 'Content-Type': 'application/json'} - if AUTH_TOKEN: - headers['Authorization'] = 'Bearer ' + AUTH_TOKEN - request = urllib.request.Request(url, data=b'{}', headers=headers, method='POST') - try: - with urllib.request.urlopen(request, timeout=60) as response: - return json.loads(response.read()) - except urllib.error.HTTPError as error: - try: - detail = json.loads(error.read()).get('detail', error.reason) - except ValueError: - detail = error.reason - raise EngineError(str(detail), error.code) - except (urllib.error.URLError, OSError) as error: - raise EngineError(f'Could not reach the FormWeb hand-off route: {error}', 502) - - async def dispatch(name, arguments): from . import library, library_routes from .code_components import build_component @@ -213,8 +190,9 @@ async def dispatch(name, arguments): hosts = [child for page in result.get('pages') or [] for child in site['nodes'].get(roots.get(page, ''), {}).get('children', [])] return {**made, **(await _bring_in(hosts))} if name == 'send_to_formpublisher': + from .handoff import send_to_formpublisher studio.access.authorize('read') - return await asyncio.to_thread(_send, arguments.get('locale')) + return await send_to_formpublisher(arguments.get('locale')) if name == 'copy_element': from .fragment_routes import fragment_of if arguments.get('clip') is True and arguments.get('embed_assets') is not True: diff --git a/backend/tests/test_agent_asks.py b/backend/tests/test_agent_asks.py index f1e3208e..ffa27e19 100644 --- a/backend/tests/test_agent_asks.py +++ b/backend/tests/test_agent_asks.py @@ -1,6 +1,6 @@ import pytest -from test_f2_f3_mcp import call +from test_f2_f3_mcp import agents_on, call, payload # noqa: F401 @pytest.fixture() @@ -42,3 +42,19 @@ def test_replacing_the_whole_site_through_apply_commands_asks_first_like_edit_si def test_an_ordinary_batch_does_not_ask(client, agents_asking, asked): result = call(client, "apply_commands", {"commands": [{"command": "token.set", "params": {"name": "asks-none", "value": "#123456"}}]}) assert not result.get("isError") and asked == [] + + +def test_the_formpublisher_tool_delivers_without_the_window_key(client, agents_on, monkeypatch): + from app import handoff + + sent = [] + + def receive(url, data, headers): + sent.append(headers["Content-Type"]) + return {"site": "site-1", "revision": "rev-1"} + + monkeypatch.setattr(handoff, "_post", receive) + result = call(client, "send_to_formpublisher", {}) + assert not result.get("isError"), result + assert payload(result)["delivered"] == "live" and payload(result)["site"] == "site-1" + assert sent == ["application/zip"] From f7d7dbc3e619fe88d590f64d4cc13f4fd7ae8f17 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:36:54 -0500 Subject: [PATCH 3/8] fix(agents): write only client files whose launcher exists The installed app has no formweb launcher in its folder, so Write in Agent Connect now refuses there instead of adding entries that cannot start, including the account-wide Antigravity file. On Windows the Codex project file starts formweb.bat directly instead of a Unix shell. --- backend/app/clients.py | 20 ++++++++++++++++---- backend/tests/test_agent_client_files.py | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 backend/tests/test_agent_client_files.py diff --git a/backend/app/clients.py b/backend/app/clients.py index b9fa27b6..78ff467b 100644 --- a/backend/app/clients.py +++ b/backend/app/clients.py @@ -5,14 +5,15 @@ reads one file for the whole account, ~/.gemini/config/mcp_config.json: its card adds the one entry named formweb there when the person asks, keeps every other entry and key, and leaves alone an entry of that name it did not write. The Claude Code card's Open button does not depend on its file: it starts Claude through POST /api/terminal/open with -FormWeb's own MCP config. +FormWeb's own MCP config. On Windows the Codex file names formweb.bat in this folder. The installed app ships no +launcher, so there it writes none of these files. """ import json import os from pathlib import Path from . import claude_code -from .config import ROOT +from .config import FROZEN, ROOT from .engine import EngineError CLIENTS = { @@ -40,6 +41,15 @@ } +INSTALLED = 'The installed app does not include the formweb launcher these files start, so nothing was written. Open in Agent Connect starts each program with FormWeb\'s tools.' + + +def content(client_id, system=None): + if client_id == 'codex' and (system or os.name) == 'nt': + return f'[mcp_servers.formweb]\ncommand = {json.dumps(str(ROOT / "formweb.bat"))}\nargs = ["mcp"]\nstartup_timeout_sec = 30\ntool_timeout_sec = 120\n' + return CLIENTS[client_id]['content'] + + ANTIGRAVITY = {'name': 'Antigravity', 'path': '~/.gemini/config/mcp_config.json', 'cli': 'agy', 'start': 'agy'} ANTIGRAVITY_ENTRY = 'formweb' OLDER_FILE = '~/.gemini/antigravity-cli/mcp_config.json' @@ -94,7 +104,7 @@ def card(client_id): spec = CLIENTS[client_id] path = ROOT / spec['path'] current = path.read_text(encoding='utf-8') if path.is_file() else None - status = 'missing' if current is None else 'ready' if current == spec['content'] else 'changed' + status = 'missing' if current is None else 'ready' if current == content(client_id) else 'changed' found = claude_code.located('claude' if client_id == 'claude-code' else client_id).path is not None return {'id': client_id, 'name': spec['name'], 'file': spec['path'], 'status': status, 'cliFound': found, 'cli': spec['cli'], 'start': spec['start'], 'launch': '/api/terminal/open' if client_id == 'claude-code' else None} @@ -104,6 +114,8 @@ def cards(): def write(client_id): + if FROZEN: + raise EngineError(INSTALLED, 409) if client_id == 'antigravity': return antigravity_write() if client_id not in CLIENTS: @@ -113,5 +125,5 @@ def write(client_id): if not path.is_relative_to(ROOT.resolve()): raise EngineError('Client file must stay inside the FormWeb folder.', 400) path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(spec['content'], encoding='utf-8') + path.write_text(content(client_id), encoding='utf-8') return card(client_id) diff --git a/backend/tests/test_agent_client_files.py b/backend/tests/test_agent_client_files.py new file mode 100644 index 00000000..d21afd8d --- /dev/null +++ b/backend/tests/test_agent_client_files.py @@ -0,0 +1,23 @@ +import pytest + + +@pytest.mark.parametrize("client_id", ["claude-code", "codex", "cursor", "antigravity"]) +def test_the_installed_app_writes_no_client_file_that_starts_a_launcher_it_does_not_ship(client, monkeypatch, tmp_path, client_id): + from app import clients + + monkeypatch.setattr(clients, "FROZEN", True) + monkeypatch.setattr(clients, "ROOT", tmp_path) + answer = client.post(f"/api/agents/clients/{client_id}", json={}) + assert answer.status_code == 409 and "installed app" in answer.json()["detail"] + assert list(tmp_path.iterdir()) == [] and not clients.antigravity_file().exists() + + +def test_the_codex_file_on_windows_starts_the_windows_launcher_without_a_unix_shell(monkeypatch, tmp_path): + import tomllib + + from app import clients + + monkeypatch.setattr(clients, "ROOT", tmp_path / "Form Web") + entry = tomllib.loads(clients.content("codex", "nt"))["mcp_servers"]["formweb"] + assert entry["command"] == str(tmp_path / "Form Web" / "formweb.bat") and entry["args"] == ["mcp"] + assert clients.content("codex", "posix") == clients.CLIENTS["codex"]["content"] From 424556ce010f08b1cd0996d89117fabe2d83cf5a Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:37:08 -0500 Subject: [PATCH 4/8] fix(config): the installed app accepts only its own window's origin by default The editor's development ports are allowed only when running from the source folder. FORMWEB_ORIGINS still overrides the list. --- backend/app/config.py | 10 +++++++++- backend/tests/test_agent_client_files.py | 7 +++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/backend/app/config.py b/backend/app/config.py index 6176cece..5e8d2c7f 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -18,7 +18,15 @@ DATA_DIR = Path(os.getenv('FORMWEB_DATA_DIR', str(ROOT / 'Data' if FROZEN else ROOT / 'backend/data'))).resolve() FRONTEND_DIST = Path(os.getenv('FORMWEB_FRONTEND_DIST', str(BUNDLE / 'frontend_dist' if FROZEN else ROOT / 'frontend/dist'))).resolve() AUTH_TOKEN = os.getenv('FORMWEB_AUTH_TOKEN', '') -ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', f'http://localhost:5240,http://127.0.0.1:5240,http://localhost:5241,http://127.0.0.1:5241,http://localhost:{PORT},http://127.0.0.1:{PORT}').split(',') if x.strip()) +DEV_PORTS = (5240, 5241) + + +def default_origins(frozen: bool, port: int) -> tuple[str, ...]: + ports = (port,) if frozen else (*DEV_PORTS, port) + return tuple(f'http://{host}:{item}' for item in ports for host in ('localhost', '127.0.0.1')) + + +ORIGINS = tuple(x.strip() for x in os.getenv('FORMWEB_ORIGINS', ','.join(default_origins(FROZEN, PORT))).split(',') if x.strip()) PUBLIC_BASE = f'http://127.0.0.1:{PORT}' CLIP_SECONDS_DEFAULT = 15 * 60 diff --git a/backend/tests/test_agent_client_files.py b/backend/tests/test_agent_client_files.py index d21afd8d..05ad3cee 100644 --- a/backend/tests/test_agent_client_files.py +++ b/backend/tests/test_agent_client_files.py @@ -21,3 +21,10 @@ def test_the_codex_file_on_windows_starts_the_windows_launcher_without_a_unix_sh entry = tomllib.loads(clients.content("codex", "nt"))["mcp_servers"]["formweb"] assert entry["command"] == str(tmp_path / "Form Web" / "formweb.bat") and entry["args"] == ["mcp"] assert clients.content("codex", "posix") == clients.CLIENTS["codex"]["content"] + + +def test_the_installed_app_accepts_only_its_own_window_origin_by_default(): + from app import config + + assert config.default_origins(True, 8241) == ("http://localhost:8241", "http://127.0.0.1:8241") + assert "http://localhost:5240" in config.default_origins(False, 8240) and "http://127.0.0.1:8240" in config.default_origins(False, 8240) From f59d07f38551a53f489d549be4291abc15d4776d Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 09:38:13 -0500 Subject: [PATCH 5/8] fix(agents): start npm-installed agent programs on Windows without cmd.exe An npm .cmd shim is resolved to node and its script, which then run directly. Any other .cmd or .bat start is refused when a word holds a control character, % or a cmd.exe character outside quotes, so prompts reach the program as given. --- backend/app/claude_code.py | 8 ++- backend/app/windows_start.py | 83 +++++++++++++++++++++++++++++ backend/tests/test_windows_start.py | 82 ++++++++++++++++++++++++++++ 3 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 backend/app/windows_start.py create mode 100644 backend/tests/test_windows_start.py diff --git a/backend/app/claude_code.py b/backend/app/claude_code.py index ea8a47be..3f6cdfe5 100644 --- a/backend/app/claude_code.py +++ b/backend/app/claude_code.py @@ -8,9 +8,11 @@ import json import os import secrets +import shutil +from dataclasses import replace from pathlib import Path -from . import agent_lookup +from . import agent_lookup, windows_start from .config import DATA_DIR, PORT from .engine import EngineError @@ -76,6 +78,8 @@ def workdir(): def located(kind, fresh=False): found = agent_lookup.find(kind, setting=None, override_vars=OVERRIDES.get(kind, ()), shell_timeout=10.0, fresh=fresh) + if found.path and not windows_start.startable(found.path): + return replace(found, state='broken', error=windows_start.REFUSED) return agent_lookup.check(found, child_env(path=found.path), 15.0, fresh) @@ -132,7 +136,7 @@ def _base(binary, prompt, resume, headless, config): def _wrap(argv): - return agent_lookup.start_argv(argv) + return windows_start.start_words(argv, node=lambda: shutil.which('node', path=child_env(path=argv[0]).get('PATH'))) def argv(prompt, resume, config): diff --git a/backend/app/windows_start.py b/backend/app/windows_start.py new file mode 100644 index 00000000..418ac9ed --- /dev/null +++ b/backend/app/windows_start.py @@ -0,0 +1,83 @@ +"""How FormWeb starts an agent program on Windows. A program installed by npm is a .cmd file that only starts node with +its script, so FormWeb starts node with that script itself and no command interpreter reads the words. Any other .cmd or +.bat is run by cmd.exe, which reads the whole line: such a start is refused when a word holds a control character or %, +or one of cmd's own characters outside quotes, so every word reaches the program as it was given.""" +import re +import shutil +import subprocess +from pathlib import Path + +from . import agent_lookup +from .engine import EngineError + +BATCH = ('.cmd', '.bat') +CONTROL = re.compile(r'[\x00-\x1f\x7f]') +SPECIAL = frozenset('&|<>^()!') +SHIM = re.compile(r'"%dp0%\\([^"%\r\n]+)"\s+%\*') +REFUSED = 'This program is started through cmd.exe on Windows, which would read part of what was given as its own syntax, so it was not started. Remove line breaks, % and the characters & | < > ^ ( ) ! outside quoted text, or give the path to a program that is not a .cmd or .bat file.' + + +def _node(folder: Path, node) -> str | None: + beside = folder / 'node.exe' + if beside.is_file(): + return str(beside) + return node() if node else shutil.which('node') + + +def shim_target(path, node=None) -> list[str] | None: + """[node, script] for an npm .cmd shim whose script is inside the shim's folder, else None.""" + shim = Path(path) + if shim.suffix.lower() != '.cmd': + return None + try: + hit = SHIM.search(shim.read_text(encoding='utf-8', errors='replace')[:16384]) + except OSError: + return None + parts = [part for part in re.split(r'[\\/]', hit.group(1)) if part] if hit else [] + if not parts or any(part in ('.', '..') or ':' in part for part in parts): + return None + script = shim.parent.joinpath(*parts) + program = _node(shim.parent, node) if script.is_file() else None + return [program, str(script)] if program else None + + +def _plain_outside_quotes(line: str) -> bool: + quoted = False + for char in line: + if char == '"': + quoted = not quoted + elif not quoted and char in SPECIAL: + return False + return True + + +def cmd_safe(words) -> bool: + line = subprocess.list2cmdline([str(word) for word in words]) + if CONTROL.search(line) or '%' in line: + return False + views = [line] + if line.startswith('"'): + last = line.rfind('"') + views.append(line[1:last] + line[last + 1:]) + return all(_plain_outside_quotes(view) for view in views) + + +def _batch(words, platform) -> bool: + return agent_lookup.windows(platform) and str(words[0]).lower().endswith(BATCH) + + +def start_words(cmd, platform=None, node=None) -> list[str]: + words = [str(word) for word in cmd] + if not _batch(words, platform): + return agent_lookup.start_argv(words, platform=platform) + direct = shim_target(words[0], node) + if direct: + return [*direct, *words[1:]] + if not cmd_safe(words): + raise EngineError(REFUSED, 400) + return agent_lookup.start_argv(words, platform=platform) + + +def startable(path, platform=None) -> bool: + """Whether the finder's own check (path --version) can run this program safely.""" + return not _batch([path], platform) or cmd_safe([path, '--version']) diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py new file mode 100644 index 00000000..bb0e3af9 --- /dev/null +++ b/backend/tests/test_windows_start.py @@ -0,0 +1,82 @@ +import pytest + +SHIM = ( + '@ECHO off\r\nGOTO start\r\n:find_dp0\r\nSET dp0=%~dp0\r\nEXIT /b\r\n:start\r\nSETLOCAL\r\nCALL :find_dp0\r\n\r\n' + 'IF EXIST "%dp0%\\node.exe" (\r\n SET "_prog=%dp0%\\node.exe"\r\n) ELSE (\r\n SET "_prog=node"\r\n SET PATHEXT=%PATHEXT:;.JS;=;%\r\n)\r\n\r\n' + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\@scope\\tool\\cli.js" %*\r\n' +) + + +@pytest.fixture() +def npm_folder(tmp_path): + folder = tmp_path / "npm" + (folder / "node_modules" / "@scope" / "tool").mkdir(parents=True) + (folder / "node_modules" / "@scope" / "tool" / "cli.js").write_text("") + (folder / "tool.cmd").write_text(SHIM) + return folder + + +def test_an_npm_shim_is_started_through_node_without_the_command_interpreter(npm_folder): + from app import windows_start + + (npm_folder / "node.exe").write_text("") + words = windows_start.start_words([str(npm_folder / "tool.cmd"), "--", "a prompt with 50% & \"quotes\"\nand a second line"], platform="win32") + assert words == [str(npm_folder / "node.exe"), str(npm_folder / "node_modules" / "@scope" / "tool" / "cli.js"), "--", "a prompt with 50% & \"quotes\"\nand a second line"] + + +def test_a_shim_without_node_beside_it_uses_node_from_the_path(npm_folder, tmp_path): + from app import windows_start + + elsewhere = tmp_path / "node-home" + elsewhere.mkdir() + words = windows_start.start_words([str(npm_folder / "tool.cmd"), "--version"], platform="win32", node=lambda: str(elsewhere / "node.exe")) + assert words[0] == str(elsewhere / "node.exe") and words[2:] == ["--version"] + + +def test_a_shim_naming_a_script_outside_its_folder_is_not_followed(npm_folder): + from app import windows_start + + (npm_folder / "tool.cmd").write_text(SHIM.replace("node_modules\\@scope\\tool\\cli.js", "..\\other\\cli.js")) + assert windows_start.shim_target(npm_folder / "tool.cmd", lambda: "node.exe") is None + + +@pytest.mark.parametrize("word", ["line\nbreak", "tab\there", "bell\x07", "del\x7f", "50%", "%PATH%", "a&b", "a|b", "a>b", "a Date: Sun, 29 Nov 2026 10:19:25 -0500 Subject: [PATCH 6/8] fix(agents): follow npm shims only to node.exe or a native program on Windows A shim whose node is itself a batch file, or whose script runs under another program, now goes through the same checks as any other .cmd start. A program path ending in dots, spaces or a data stream name is recognised as the batch file Windows would run. --- backend/app/windows_start.py | 33 +++++++++++++++++++------ backend/tests/test_windows_start.py | 38 +++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/backend/app/windows_start.py b/backend/app/windows_start.py index 418ac9ed..0df08387 100644 --- a/backend/app/windows_start.py +++ b/backend/app/windows_start.py @@ -13,7 +13,10 @@ BATCH = ('.cmd', '.bat') CONTROL = re.compile(r'[\x00-\x1f\x7f]') SPECIAL = frozenset('&|<>^()!') -SHIM = re.compile(r'"%dp0%\\([^"%\r\n]+)"\s+%\*') +SHIM = re.compile(r'("%_prog%"\s+)?"%dp0%\\([^"%\r\n]+)"\s+%\*') +PROG = re.compile(r'SET\s+"_prog=%dp0%\\([^"%\r\n]+)"', re.IGNORECASE) +NATIVE = ('.exe', '.com') +STREAM = re.compile(r'(::\$data)?[ .]*$', re.IGNORECASE) REFUSED = 'This program is started through cmd.exe on Windows, which would read part of what was given as its own syntax, so it was not started. Remove line breaks, % and the characters & | < > ^ ( ) ! outside quoted text, or give the path to a program that is not a .cmd or .bat file.' @@ -21,23 +24,37 @@ def _node(folder: Path, node) -> str | None: beside = folder / 'node.exe' if beside.is_file(): return str(beside) - return node() if node else shutil.which('node') + found = node() if node else shutil.which('node') + return found if found and _suffix(found) in NATIVE else None + + +def _suffix(path) -> str: + return Path(STREAM.sub('', str(path))).suffix.lower() def shim_target(path, node=None) -> list[str] | None: - """[node, script] for an npm .cmd shim whose script is inside the shim's folder, else None.""" + """What an npm .cmd shim starts, when its target is inside the shim's folder: [node, script] for a node script, + [program] for a native program, else None. Node is used only as node.exe, never through another batch file.""" shim = Path(path) - if shim.suffix.lower() != '.cmd': + if _suffix(shim) != '.cmd': return None try: - hit = SHIM.search(shim.read_text(encoding='utf-8', errors='replace')[:16384]) + text = shim.read_text(encoding='utf-8', errors='replace')[:16384] except OSError: return None - parts = [part for part in re.split(r'[\\/]', hit.group(1)) if part] if hit else [] + hit = SHIM.search(text) + parts = [part for part in re.split(r'[\\/]', hit.group(2)) if part] if hit else [] if not parts or any(part in ('.', '..') or ':' in part for part in parts): return None script = shim.parent.joinpath(*parts) - program = _node(shim.parent, node) if script.is_file() else None + if not script.is_file(): + return None + if not hit.group(1): + return [str(script)] if _suffix(script) in NATIVE else None + prog = PROG.search(text) + if not prog or prog.group(1).lower() != 'node.exe': + return None + program = _node(shim.parent, node) return [program, str(script)] if program else None @@ -63,7 +80,7 @@ def cmd_safe(words) -> bool: def _batch(words, platform) -> bool: - return agent_lookup.windows(platform) and str(words[0]).lower().endswith(BATCH) + return agent_lookup.windows(platform) and _suffix(words[0]) in BATCH def start_words(cmd, platform=None, node=None) -> list[str]: diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index bb0e3af9..eec736ed 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -80,3 +80,41 @@ def test_other_systems_and_programs_start_as_before(tmp_path): words = ["/opt/tool", "--", "50% & more\nlines"] assert windows_start.start_words(words, platform="darwin") == agent_lookup.start_argv(words, platform="darwin") assert windows_start.start_words(["C:\\tools\\tool.exe", "50% & more"], platform="win32") == ["C:\\tools\\tool.exe", "50% & more"] + + +def test_a_shim_whose_node_is_itself_a_batch_file_goes_through_the_checks(npm_folder): + from app import windows_start + from app.engine import EngineError + + shim = str(npm_folder / "tool.cmd") + assert windows_start.shim_target(shim, lambda: str(npm_folder / "nodist" / "node.cmd")) is None + with pytest.raises(EngineError): + windows_start.start_words([shim, "a&b"], platform="win32", node=lambda: str(npm_folder / "nodist" / "node.cmd")) + + +def test_a_shim_for_a_native_program_starts_that_program(tmp_path): + from app import windows_start + + folder = tmp_path / "npm" + (folder / "node_modules" / "tool" / "bin").mkdir(parents=True) + (folder / "node_modules" / "tool" / "bin" / "tool.exe").write_text("") + (folder / "tool.cmd").write_text('@ECHO off\r\n"%dp0%\\node_modules\\tool\\bin\\tool.exe" %*\r\n') + words = windows_start.start_words([str(folder / "tool.cmd"), "50% & more"], platform="win32") + assert words == [str(folder / "node_modules" / "tool" / "bin" / "tool.exe"), "50% & more"] + + +def test_a_shim_that_runs_its_script_with_another_program_is_not_followed(npm_folder): + from app import windows_start + + (npm_folder / "tool.cmd").write_text(SHIM.replace("node.exe", "sh.exe").replace('"_prog=node"', '"_prog=sh"')) + assert windows_start.shim_target(npm_folder / "tool.cmd", lambda: "node.exe") is None + + +@pytest.mark.parametrize("name", ["tool.cmd.", "tool.CMD ", "tool.bat::$DATA", "TOOL.BAT"]) +def test_batch_files_are_known_by_the_name_windows_would_run(tmp_path, name): + from app import windows_start + from app.engine import EngineError + + with pytest.raises(EngineError): + windows_start.start_words([str(tmp_path / name), "a&b"], platform="win32") + assert windows_start.startable(str(tmp_path / "R&D" / name), platform="win32") is False From d1c49822c87ced075f63b4d09982397171908329 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 10:19:25 -0500 Subject: [PATCH 7/8] fix(agents): write the Windows Codex launcher path as plain UTF-8 TOML A folder name with characters outside the Basic Multilingual Plane no longer produces a config Codex cannot read. --- backend/app/clients.py | 2 +- backend/tests/test_agent_client_files.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/backend/app/clients.py b/backend/app/clients.py index 78ff467b..1abd2aad 100644 --- a/backend/app/clients.py +++ b/backend/app/clients.py @@ -46,7 +46,7 @@ def content(client_id, system=None): if client_id == 'codex' and (system or os.name) == 'nt': - return f'[mcp_servers.formweb]\ncommand = {json.dumps(str(ROOT / "formweb.bat"))}\nargs = ["mcp"]\nstartup_timeout_sec = 30\ntool_timeout_sec = 120\n' + return f'[mcp_servers.formweb]\ncommand = {json.dumps(str(ROOT / "formweb.bat"), ensure_ascii=False)}\nargs = ["mcp"]\nstartup_timeout_sec = 30\ntool_timeout_sec = 120\n' return CLIENTS[client_id]['content'] diff --git a/backend/tests/test_agent_client_files.py b/backend/tests/test_agent_client_files.py index 05ad3cee..804ed289 100644 --- a/backend/tests/test_agent_client_files.py +++ b/backend/tests/test_agent_client_files.py @@ -28,3 +28,13 @@ def test_the_installed_app_accepts_only_its_own_window_origin_by_default(): assert config.default_origins(True, 8241) == ("http://localhost:8241", "http://127.0.0.1:8241") assert "http://localhost:5240" in config.default_origins(False, 8240) and "http://127.0.0.1:8240" in config.default_origins(False, 8240) + + +def test_the_codex_file_on_windows_keeps_any_folder_name_readable(monkeypatch, tmp_path): + import tomllib + + from app import clients + + folder = tmp_path / "Sites \U0001f3a8 \"draft\" \\ café" + monkeypatch.setattr(clients, "ROOT", folder) + assert tomllib.loads(clients.content("codex", "nt"))["mcp_servers"]["formweb"]["command"] == str(folder / "formweb.bat") From 9eaed65640e5026fb75c611a11e72d6db9badf09 Mon Sep 17 00:00:00 2001 From: gbarnai Date: Sun, 29 Nov 2026 11:46:27 -0500 Subject: [PATCH 8/8] fix(agents): refuse every cmd.exe syntax character in batch-file starts on Windows A .cmd or .bat start that still goes through cmd.exe is refused when any word holds a control character or one of & | < > ^ ( ) ! % ", quoted or not, and when a program path that needs quotes is followed by a word that needs quotes. The message points to standard input or a file for long text. npm shims keep starting node or their native program directly. --- backend/app/windows_start.py | 43 +++++++++++----------- backend/tests/test_windows_start.py | 55 ++++++++++++++++++++++++++--- 2 files changed, 73 insertions(+), 25 deletions(-) diff --git a/backend/app/windows_start.py b/backend/app/windows_start.py index 0df08387..2e49c540 100644 --- a/backend/app/windows_start.py +++ b/backend/app/windows_start.py @@ -1,10 +1,10 @@ """How FormWeb starts an agent program on Windows. A program installed by npm is a .cmd file that only starts node with its script, so FormWeb starts node with that script itself and no command interpreter reads the words. Any other .cmd or -.bat is run by cmd.exe, which reads the whole line: such a start is refused when a word holds a control character or %, -or one of cmd's own characters outside quotes, so every word reaches the program as it was given.""" +.bat is run by cmd.exe, which reads the whole line again and treats some characters as its own syntax even inside quotes. +Such a start is refused when any word holds a control character or one of & | < > ^ ( ) ! % ", and when a program path +that needs quotes is followed by a word that needs quotes, so every word reaches the program as it was given.""" import re import shutil -import subprocess from pathlib import Path from . import agent_lookup @@ -12,12 +12,15 @@ BATCH = ('.cmd', '.bat') CONTROL = re.compile(r'[\x00-\x1f\x7f]') -SPECIAL = frozenset('&|<>^()!') +RESERVED = frozenset('&|<>^()!%"') SHIM = re.compile(r'("%_prog%"\s+)?"%dp0%\\([^"%\r\n]+)"\s+%\*') PROG = re.compile(r'SET\s+"_prog=%dp0%\\([^"%\r\n]+)"', re.IGNORECASE) NATIVE = ('.exe', '.com') STREAM = re.compile(r'(::\$data)?[ .]*$', re.IGNORECASE) -REFUSED = 'This program is started through cmd.exe on Windows, which would read part of what was given as its own syntax, so it was not started. Remove line breaks, % and the characters & | < > ^ ( ) ! outside quoted text, or give the path to a program that is not a .cmd or .bat file.' +REFUSED = ('This program is started through cmd.exe on Windows, which reads some characters as its own syntax even inside quotes, ' + 'so it was not started. A word given to it may not hold line breaks or other control characters, or any of ' + '& | < > ^ ( ) ! % ", and a program path with spaces or @ may not be followed by a word with spaces. Pass long text ' + 'through standard input or a file if the program supports it, or give the path to a program that is not a .cmd or .bat file.') def _node(folder: Path, node) -> str | None: @@ -58,25 +61,25 @@ def shim_target(path, node=None) -> list[str] | None: return [program, str(script)] if program else None -def _plain_outside_quotes(line: str) -> bool: - quoted = False - for char in line: - if char == '"': - quoted = not quoted - elif not quoted and char in SPECIAL: - return False - return True +def _plain(word: str) -> bool: + return not CONTROL.search(word) and not RESERVED.intersection(word) + + +def _needs_quotes(word: str) -> bool: + return word == '' or ' ' in word def cmd_safe(words) -> bool: - line = subprocess.list2cmdline([str(word) for word in words]) - if CONTROL.search(line) or '%' in line: + """Whether cmd.exe /c would pass every word to the batch file unchanged. No word may hold a control character or a + reserved character, quoted or not. A quoted program path keeps its quotes only when it is the line's one quoted + word and holds no @, so a path that needs quotes may not be followed by another word that needs them.""" + words = [str(word) for word in words] + if not words or not all(_plain(word) for word in words): return False - views = [line] - if line.startswith('"'): - last = line.rfind('"') - views.append(line[1:last] + line[last + 1:]) - return all(_plain_outside_quotes(view) for view in views) + program, rest = words[0], words[1:] + if _needs_quotes(program): + return '@' not in program and not any(_needs_quotes(word) for word in rest) + return True def _batch(words, platform) -> bool: diff --git a/backend/tests/test_windows_start.py b/backend/tests/test_windows_start.py index eec736ed..f130fa28 100644 --- a/backend/tests/test_windows_start.py +++ b/backend/tests/test_windows_start.py @@ -40,19 +40,27 @@ def test_a_shim_naming_a_script_outside_its_folder_is_not_followed(npm_folder): assert windows_start.shim_target(npm_folder / "tool.cmd", lambda: "node.exe") is None -@pytest.mark.parametrize("word", ["line\nbreak", "tab\there", "bell\x07", "del\x7f", "50%", "%PATH%", "a&b", "a|b", "a>b", "ab", "a