From ef32b5be7eda0706612654c10d9d34cf964bcc18 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Sat, 3 Oct 2026 14:18:00 +0000 Subject: [PATCH 1/2] fix(sandbox): keep Qwen Code discovery from starting Playwright MCP Qwen Code 0.23.3 asks every MCP server for prompts/list and resources/list at the start of every turn, whatever the server advertised. The lazy Playwright MCP launcher from #4117 had no answer for them, so the discovery itself started mcp-server-playwright on every Qwen turn. The launcher now answers prompts/list, resources/list and resources/templates/list with the server's own -32601 Method not found while the recorded capabilities lack prompts or resources, and leaves them to the server when it advertises them. Also from the #4117 review: - the started server's protocol version is compared with the version the client was told, not the one it asked for; - PLAYWRIGHT_MCP_* settings in the environment start the server at once; - the manifest records the server file it was recorded from, and a server the session put ahead of it on PATH starts at once; - the container check sends Qwen Code's discovery and covers every argument set. Refs #4117 --- .../container-sandbox-runtime-test.ts | 48 ++++-- .../tests/manual/reference/automation.md | 2 +- services/sandbox-runtime/Dockerfile | 11 +- services/sandbox-runtime/README.md | 11 +- .../daemon/src/tale-playwright-mcp.test.ts | 156 +++++++++++++++++- services/sandbox-runtime/tale-playwright-mcp | 87 ++++++++-- 6 files changed, 270 insertions(+), 45 deletions(-) diff --git a/services/platform/tests/integration/container-sandbox-runtime-test.ts b/services/platform/tests/integration/container-sandbox-runtime-test.ts index 68267e3db3..012a30c17d 100644 --- a/services/platform/tests/integration/container-sandbox-runtime-test.ts +++ b/services/platform/tests/integration/container-sandbox-runtime-test.ts @@ -700,13 +700,15 @@ send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: ' console.log(''); console.log('--- playwright MCP starts only when a turn uses the browser ---'); // The launcher answers the start of a turn from the manifests the image build -// recorded for the platform's argument sets (playwright-mcp-args.json): the -// real server, a Node process holding ~100 MB, must not run until the first -// tool call, its tool list must be the server's own, and a tool call must -// reach a server started then. +// recorded for the platform's argument sets (playwright-mcp-args.json): for +// each set, the real server, a Node process holding ~100 MB, must not run +// until the first tool call, even after Qwen Code's discovery (the prompt and +// resource lists, asked whatever the server advertised), and the tool list and +// those lists must be answered as the server's own; a tool call must reach a +// server started then. { const nodeScript = `const { spawn, execFileSync } = require('child_process'); -const args = JSON.parse(require('fs').readFileSync('/opt/tale/playwright-mcp/args.json', 'utf8'))[0]; +const argSets = JSON.parse(require('fs').readFileSync('/opt/tale/playwright-mcp/args.json', 'utf8')); const serverRunning = () => { try { execFileSync('pgrep', ['-f', 'bin/mcp-server-playwright']); return true; } catch { return false; } }; @@ -732,19 +734,31 @@ function session(command, argv) { return { srv, ask, tell }; } const init = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'conformance', version: '1.0' } }; +const lists = ['prompts/list', 'resources/list', 'resources/templates/list']; +const ended = (srv) => new Promise((done) => { srv.on('exit', done); srv.kill(); }); (async () => { const deadline = setTimeout(() => { console.error('LAZY_TIMEOUT'); process.exit(1); }, 90000); - const lazy = session('tale-playwright-mcp', args); - await lazy.ask(1, 'initialize', init); - lazy.tell('notifications/initialized'); - const listed = await lazy.ask(2, 'tools/list'); - if (serverRunning()) { console.error('LAZY_SERVER_STARTED_EARLY'); process.exit(1); } - const direct = session('mcp-server-playwright', args); - await direct.ask(1, 'initialize', init); - direct.tell('notifications/initialized'); - const own = await direct.ask(2, 'tools/list'); - direct.srv.kill(); - if (JSON.stringify(listed.result) !== JSON.stringify(own.result)) { console.error('LAZY_TOOLS_DIFFER'); process.exit(1); } + let lazy; + let listed; + for (const [n, args] of argSets.entries()) { + const turn = session('tale-playwright-mcp', args); + await turn.ask(1, 'initialize', init); + turn.tell('notifications/initialized'); + const turnListed = await turn.ask(2, 'tools/list'); + const unlisted = []; + for (const [i, method] of lists.entries()) unlisted.push(await turn.ask(10 + i, method, {})); + if (serverRunning()) { console.error('LAZY_SERVER_STARTED_EARLY ' + n); process.exit(1); } + const direct = session('mcp-server-playwright', args); + await direct.ask(1, 'initialize', init); + direct.tell('notifications/initialized'); + const own = await direct.ask(2, 'tools/list'); + const ownUnlisted = []; + for (const [i, method] of lists.entries()) ownUnlisted.push(await direct.ask(10 + i, method, {})); + await ended(direct.srv); + if (JSON.stringify(turnListed.result) !== JSON.stringify(own.result)) { console.error('LAZY_TOOLS_DIFFER ' + n); process.exit(1); } + if (JSON.stringify(unlisted) !== JSON.stringify(ownUnlisted)) { console.error('LAZY_LISTS_DIFFER ' + n + ' ' + JSON.stringify(unlisted) + ' ' + JSON.stringify(ownUnlisted)); process.exit(1); } + if (n === 0) { lazy = turn; listed = turnListed; } else await ended(turn.srv); + } const called = await lazy.ask(3, 'tools/call', { name: 'browser_navigate', arguments: { url: 'about:blank' } }); if (called.error || (called.result && called.result.isError)) { console.error('LAZY_NAVIGATE_FAILED ' + JSON.stringify(called)); process.exit(1); } clearTimeout(deadline); @@ -781,7 +795,7 @@ const init = { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { na ); if (combined.includes('MCP_LAZY_OK')) { pass( - 'playwright MCP answers the start itself and starts the server on the first tool call', + 'playwright MCP answers the start itself (Qwen Code discovery included) for every argument set and starts the server on the first tool call', ); } else { fail(`playwright MCP lazy start failed (got: ${combined.slice(0, 400)})`); diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index c12f3010f9..3a462e5b20 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -189,7 +189,7 @@ Legend: βœ… fully automated Β· πŸ”Ά partially automated Β· β›” manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed Claude Code agent turn on a model that is not Claude names its exec in every request (`ANTHROPIC_CUSTOM_HEADERS: x-bf-eh-x-tale-cache-affinity: `, which the gateway forwards upstream as `X-Tale-Cache-Affinity`), keeping any header the harness already sends; a Claude model, an exec without an id and a bring-your-own credential send none | πŸ”Ά backend | `lib/harnesses/exec-builder.test.ts`; whether a multi-replica balancer keeps the turn on one replica is a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed harness turn that ends cleanly with nothing at all from its model (no text, no tool call, no output tokens: the empty 200 a serving cluster answers when it fails mid-prefill) settles failed with β€œThe model returned an empty answer, so the agent did nothing this turn.”: an automation `agent` node as a retryable `harness_error`, a task run on the retryable `empty_turn` path with its conversation handle kept, and a resumed task start is not taken for a dead handle. A turn that only called tools (the operator question included) or only reported output tokens (a reasoning-only turn, for one) is not empty; Claude Code's turn totals come from its result | πŸ”Ά backend | `backend/core/chat/external_turn_shared.test.ts`, `lib/harnesses/parsers/claude-stream-json.test.ts` (the pinned-CLI `empty-answer-turn`, `token-only-turn` and `thinking-only-turn` captures), `backend/core/automations/agent_host.empty_answer.test.ts`, `backend/core/tasks/agent_run_host.empty_answer.test.ts`; a live empty answer from a failing model server stays a deployment check | | [projects](../suites/projects.md) | Runtime image carries every managed harness (Qwen Code included); Codex runs as its native binary, without the npm launcher's Node process as its parent for the whole run | βœ… automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-driven: every `managed: true` harness's exec binary on the agent PATH; `codex` is the direct launcher and runs), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (returned SDK failures end as errors; resume restores the stored conversation) | -| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB): the launcher answers `initialize` β€” as the server would for every protocol version MCP has named, the server's latest for one it does not speak β€” `tools/list` and `ping` from manifests the image build records for the platform's argument sets, starts the server on the first other request, replaying the client's start under an id of its own, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | βœ… automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest, the start answered without it, the start replayed on the first tool call, a roots request round trip, an unknown version and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server: not running after `tools/list`, the same tool list as the server's, a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | +| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` β€” as the server would for every protocol version MCP has named, the server's latest for one it does not speak β€” `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own, logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | βœ… automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) | An exec's leftover processes are ended: what its command backgrounded (`cmd &`, `nohup`, a descendant in a session of its own) gets SIGTERM, then SIGKILL, when the command exits β€” or, while another exec of the session still runs, when the session's last running exec ends β€” and at once on a cancel or at the deadline (what an exited exec left waiting included, and the group SIGKILL while the exec's own process runs even when no process there shows the tag); leftovers that wait keep their output pipes; the exit is reported without waiting out the drain grace; each process is signalled once (the group as a whole, on its own only a tagged process that left it), and a group whose tagged processes all left is never signalled later; a dropped attach releases its subscriber and its active operation; a session stop passes SIGTERM on to every live exec and to what exited execs left waiting; a group known to be the exec's gets its signal before the process table is read, a scan answers with what it read after two seconds and skips a process whose read never came back, and runnerd ends itself by SIGKILL while such a read is out; a leftover that stayed in the exec's group without the tag is still reached through the group's recorded processes (pid and start time) once it waited, and by the SIGKILL after an exec that ended alone; a steer's restart cancels the old exec as a rotation (`?leftovers=keep`, passed on by the spawner): only its own group ends, what it left outside is held until an exec started after it ends (a later cancel of the old exec leaves it held; with no successor within ten minutes the hold lifts), and a Stop or a crash still ends everything; a cancelled Gemini, Qwen or Pi turn removes its staged settings and context file, and a second signal does not cut that cleanup short; every exec runs under the subreaper shim (`tale-exec-shim`), so a process that left the exec's group and session and replaced its environment is still found below it and ended, and a round whose every exec still has its shim reads `stat` alone; the shim's status pipe gives the command's group, its exit status (128 + N for signal N) or why it could not run, the shim's own exit standing in only when the pipe ended without one; a cancel that comes before the shim named the group signals the group once it does; a refused subreaper is logged once and the exec falls back to group and tag | βœ… automated | `services/sandbox-runtime/daemon/src/exec-manager.test.ts` (exec tag in the environment, background child ended at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a `setsid` descendant found by its tag on Linux, a dropped consumer settles its attach), `process-reaper.test.ts` (tag and process-group match, one signal per process, no stale group, one scan per round, init and runnerd never, a known group signalled before a hanging read, the scan deadline and the skipped stalled read, the stat-only group record, a recorded member's proof and a reused pid's none, a shim's descendants whatever their group, session or tag, a stat-only scan while every shim runs, the tag again once a shim has exited, an unreadable environment still walked through), `exec-shim.test.ts` (on Linux the shim built from its source: output and exit status, 128 + N for a signal, a spawn error, a `setsid env -i` escapee ended with its exec, while another exec runs and after a rotation, and out of reach without the shim, a cancel before the group is named; everywhere, stand-in shims for the status pipe: its exit over the shim's, a killed shim, a spawn error, a refused subreaper said once), `tests/integration/container-sandbox-runtime-test.ts` (the image's runnerd names its shim and ends an escapee), `daemon-exit.test.ts` (the SIGKILL exit while a read is out, under Node), `main.test.ts` (`?leftovers=keep` over HTTP on Linux), `harness-wrapper-cancel.test.ts` (each wrapper's staged files removed after one and after two signals); the rotation in `exec-manager.test.ts` (the group ended, the held server ended once the next exec ends, a hold outlasting an earlier exec and a late cancel, a `setsid` server on Linux) and the untagged in-group leftover after a deferral and after an exec that ended alone (Linux); `services/sandbox/src/server.test.ts` + `services/sandbox/src/session/session-routes.test.ts` (the flag reaches runnerd); `backend/core/node_only/sandbox/helpers/session_client.test.ts` (the query) and `backend/core/tasks/agent_run_host.reap.test.ts` (the restart lane rotates, a Stop and a crash cancel in full) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | βœ… automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; the control run without the setting still shows the rewrite) | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `TASK-F35` (the image half): runnerd links every built-in skill baked into the runtime image into each harness's native user-level skill directory (`.claude/skills`, `.agents/skills`, `.hermes/skills`), keeping a directory or live link of someone's own; before every exec it withdraws the link beside a same-named skill the workspace repository ships in `.claude/skills` or `.agents/skills`, and restores it once the repository drops it. Every managed harness names `visual-aspect-analyzer` in its first model request, and with a repository copy in both directories lists that copy (Hermes, which reads no project skills, keeps the baked one) | πŸ”Ά image + stub model | `services/sandbox-runtime/daemon/src/baked-skills.test.ts`, `exec-manager.test.ts` (the reconcile runs before each spawn), `tests/integration/container-sandbox-runtime-test.ts` (every registry harness has a directory; each managed harness's golden exec through runnerd against a request-recording stub; links withdrawn and restored); a live model reading and running the skill stays `TASK-F35` | diff --git a/services/sandbox-runtime/Dockerfile b/services/sandbox-runtime/Dockerfile index 25aa9ebfcc..f4f507f784 100644 --- a/services/sandbox-runtime/Dockerfile +++ b/services/sandbox-runtime/Dockerfile @@ -511,11 +511,12 @@ COPY services/sandbox-runtime/tale-git-credential /usr/local/bin/tale-git-creden # Playwright MCP launcher: appends --proxy-server/--proxy-bypass from the # container's HTTPS_PROXY/NO_PROXY (Chromium ignores the env vars), and answers -# the start of an agent turn (initialize, tools/list) from manifests of the -# real server's answers, recorded below for the argument sets the platform -# passes (playwright-mcp-args.json, held to exec-builder.ts by its test): the -# server, a Node process holding ~100 MB, starts only once the turn first uses -# the browser. The agent adapters use this as the MCP command. +# the start of an agent turn (initialize, tools/list, the prompt and resource +# lists) from manifests of the real server's answers, recorded below for the +# argument sets the platform passes (playwright-mcp-args.json, held to +# exec-builder.ts by its test): the server, a Node process holding ~100 MB, +# starts only once the turn first uses the browser. The agent adapters use +# this as the MCP command. COPY services/sandbox-runtime/tale-playwright-mcp /usr/local/bin/tale-playwright-mcp COPY services/sandbox-runtime/playwright-mcp-args.json /opt/tale/playwright-mcp/args.json RUN python3 -Es /usr/local/bin/tale-playwright-mcp --write-manifests /opt/tale/playwright-mcp/args.json diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 51f2003c41..0e21afb211 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -20,12 +20,15 @@ the proxy settings through its launcher (`tale-playwright-mcp`). Every managed agent turn lists the Playwright MCP server, but most never open a browser, and the server β€” a Node process that loads Playwright β€” holds about 100 MB while it runs. So the launcher answers the start of a turn itself (`initialize`, -`tools/list`, `ping`) from manifests of the real server's answers, recorded at -image build for the argument sets the platform passes +`tools/list`, `ping`, and the prompt and resource lists Qwen Code asks every +server for, with the server's own `Method not found` while it advertises +neither) from manifests of the real server's answers, recorded at image build +for the argument sets the platform passes ([`playwright-mcp-args.json`](playwright-mcp-args.json)), and starts the server only on the turn's first tool call, replaying the start to it. Unknown -arguments or protocol versions, and `TALE_PLAYWRIGHT_MCP_EAGER=1`, start the -server at once. +arguments or protocol versions, a server on `PATH` other than the image's (one +the session installed), `PLAYWRIGHT_MCP_*` settings in the environment, and +`TALE_PLAYWRIGHT_MCP_EAGER=1`, start the server at once. Python document libraries are baked into the shared Python 3.12 environment: openpyxl and xlrd for spreadsheets, pypdf for PDFs, PyYAML for safe YAML diff --git a/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts b/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts index 2e4eecf149..36eec9b2b0 100644 --- a/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts +++ b/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts @@ -10,6 +10,7 @@ import { mkdtempSync, readdirSync, readFileSync, + realpathSync, rmSync, writeFileSync, } from 'node:fs'; @@ -78,6 +79,8 @@ describe('headless Playwright MCP launcher', () => { env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ''}`, + HTTPS_PROXY: '', + NO_PROXY: '', TALE_PLAYWRIGHT_MCP_MANIFESTS: join(dir, 'no-manifests'), }, encoding: 'utf8', @@ -87,14 +90,16 @@ describe('headless Playwright MCP launcher', () => { }); }); -// A stand-in MCP server: it speaks two protocol versions, lists one tool, -// asks the client for its roots on a tool call when the client offered them, -// and writes every message it receives to its log, behind a `started` line. +// A stand-in MCP server: it speaks two protocol versions (others when +// STAND_IN_VERSIONS names them), lists one tool, asks the client for its roots +// on a tool call when the client offered them, answers any other request as +// the real server's SDK does, and writes every message it receives to its +// log, behind a `started` line. const STAND_IN = String.raw`#!/usr/bin/env python3 import json, os, sys log = open(os.environ['STAND_IN_LOG'], 'a') log.write('started ' + ' '.join(sys.argv[1:]) + '\n'); log.flush() -SUPPORTED = ['2025-06-18', '2024-11-05'] +SUPPORTED = os.environ.get('STAND_IN_VERSIONS', '2025-06-18,2024-11-05').split(',') def send(obj): sys.stdout.write(json.dumps(obj) + '\n'); sys.stdout.flush() roots = False @@ -122,6 +127,8 @@ for line in sys.stdin: send({'jsonrpc': '2.0', 'id': id_, 'result': {'content': [{'type': 'text', 'text': text}]}}) elif method == 'ping': send({'jsonrpc': '2.0', 'id': id_, 'result': {}}) + elif method is not None and id_ is not None: + send({'jsonrpc': '2.0', 'id': id_, 'error': {'code': -32601, 'message': 'Method not found'}}) sys.exit(int(os.environ.get('STAND_IN_EXIT', '0'))) `; @@ -183,6 +190,13 @@ describe('the start of a turn without the server', () => { const exited = new Promise((done) => { proc.on('exit', (code) => done(code)); }); + let errors = ''; + proc.stderr.on('data', (chunk: Buffer) => { + errors += chunk.toString(); + }); + const errorsEnded = new Promise((done) => { + proc.stderr.on('end', () => done()); + }); return { send(obj: Record) { proc.stdin.write(`${JSON.stringify(obj)}\n`); @@ -205,6 +219,11 @@ describe('the start of a turn without the server', () => { proc.stdin.end(); return exited; }, + /** What the launcher logged, once it has exited. */ + async stderr(): Promise { + await errorsEnded; + return errors; + }, }; } @@ -219,6 +238,22 @@ describe('the start of a turn without the server', () => { }, }); + const toolCall = (id: number) => ({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { name: 'browser_navigate', arguments: { url: 'about:blank' } }, + }); + + // What the real server's SDK answers a request it has no handler for (the + // pinned Playwright's mcpBundleImpl.js; it may register none for a list + // whose capability it does not advertise). + const methodNotFound = (id: number) => ({ + jsonrpc: '2.0', + id, + error: { code: -32601, message: 'Method not found' }, + }); + test('the image build records the server’s answer to each protocol version', () => { expect(written.status).toBe(0); const files = readdirSync(manifests).filter((name) => @@ -229,6 +264,10 @@ describe('the start of a turn without the server', () => { readFileSync(join(manifests, files[0] ?? ''), 'utf8'), ); expect(manifest.args).toEqual(ARGS); + // The server it recorded them from: another one gets no manifest. + expect(manifest.server).toBe( + realpathSync(join(bin, 'mcp-server-playwright')), + ); const spoken = Object.fromEntries( Object.entries(manifest.initialize).map(([asked, result]) => [ asked, @@ -282,6 +321,58 @@ describe('the start of a turn without the server', () => { expect(received()).toEqual([]); }); + test('Qwen Code’s discovery is answered as the server would, still without it', async () => { + // Qwen Code 0.23.3 asks for the latest protocol version its SDK knows, + // then, at the start of every turn, asks every server for its prompts and + // resources beside its tools, whatever it advertised, and reads `Method + // not found` as an empty list. + const mcp = client(); + mcp.send(initialize('2025-11-25')); + await mcp.answer(1); + mcp.send({ jsonrpc: '2.0', method: 'notifications/initialized' }); + mcp.send({ jsonrpc: '2.0', id: 2, method: 'prompts/list', params: {} }); + mcp.send({ jsonrpc: '2.0', id: 3, method: 'resources/list', params: {} }); + mcp.send({ jsonrpc: '2.0', id: 4, method: 'tools/list', params: {} }); + mcp.send({ + jsonrpc: '2.0', + id: 5, + method: 'resources/templates/list', + params: {}, + }); + expect(await mcp.answer(2)).toEqual(methodNotFound(2)); + expect(await mcp.answer(3)).toEqual(methodNotFound(3)); + expect(await mcp.answer(4)).toMatchObject({ + result: { tools: [{ name: 'browser_navigate' }] }, + }); + expect(await mcp.answer(5)).toEqual(methodNotFound(5)); + expect(await mcp.close()).toBe(0); + expect(received()).toEqual([]); + }); + + test('a list the server advertises is the server’s to answer', async () => { + const advertised = join(dir, 'manifests-advertised'); + mkdirSync(advertised, { recursive: true }); + for (const name of readdirSync(manifests)) { + const manifest = JSON.parse(readFileSync(join(manifests, name), 'utf8')); + for (const version of Object.keys(manifest.initialize)) { + manifest.initialize[version].capabilities.prompts = {}; + manifest.initialize[version].capabilities.resources = {}; + } + writeFileSync(join(advertised, name), JSON.stringify(manifest)); + } + const mcp = client({ TALE_PLAYWRIGHT_MCP_MANIFESTS: advertised }); + mcp.send(initialize('2025-06-18')); + expect(await mcp.answer(1)).toMatchObject({ + result: { capabilities: { prompts: {}, resources: {} } }, + }); + mcp.send({ jsonrpc: '2.0', id: 2, method: 'resources/list', params: {} }); + await mcp.answer(2); + await mcp.close(); + const log = received(); + expect(log[0]).toBe(`started ${ARGS.join(' ')}`); + expect(JSON.parse(log.at(-1) ?? '{}').method).toBe('resources/list'); + }); + test('starts the server on the first tool call, replaying the start to it', async () => { const mcp = client(); mcp.send(initialize('2024-11-05')); @@ -339,6 +430,63 @@ describe('the start of a turn without the server', () => { await mcp.close(); }); + test('a started server answering the version the client was told logs nothing', async () => { + // A version the server does not speak: the manifest's answer, and the + // started server's, is its latest. + const mcp = client(); + mcp.send(initialize('2025-11-25')); + expect(await mcp.answer(1)).toMatchObject({ + result: { protocolVersion: '2025-06-18' }, + }); + mcp.send(toolCall(2)); + await mcp.answer(2); + expect(await mcp.close()).toBe(0); + expect(received()[0]).toBe(`started ${ARGS.join(' ')}`); + expect(await mcp.stderr()).toBe(''); + }); + + test('a started server answering another version than the client was told is logged', async () => { + // The server now speaks the version the client asked for, while the + // client was told the recorded answer. + const mcp = client({ STAND_IN_VERSIONS: '2025-11-25,2025-06-18' }); + mcp.send(initialize('2025-11-25')); + expect(await mcp.answer(1)).toMatchObject({ + result: { protocolVersion: '2025-06-18' }, + }); + mcp.send(toolCall(2)); + await mcp.answer(2); + expect(await mcp.close()).toBe(0); + expect(await mcp.stderr()).toBe( + '[tale-playwright-mcp] the server speaks 2025-11-25, the client was told 2025-06-18\n', + ); + }); + + test('a server configured through PLAYWRIGHT_MCP_* starts at once', async () => { + // Its tool list then depends on more than the arguments the manifest is + // keyed by (PLAYWRIGHT_MCP_CAPS adds tools, PLAYWRIGHT_MCP_CONFIG names a + // file of settings). + const mcp = client({ PLAYWRIGHT_MCP_CAPS: 'vision' }); + mcp.send(initialize('2025-06-18')); + await mcp.answer(1); + await mcp.close(); + expect(received()[0]).toBe(`started ${ARGS.join(' ')}`); + expect(JSON.parse(received()[1] ?? '{}').id).toBe(1); + }); + + test('a server the session put ahead of the image’s on PATH starts at once', async () => { + const own = join(dir, 'session-bin'); + mkdirSync(own, { recursive: true }); + writeFileSync(join(own, 'mcp-server-playwright'), STAND_IN, { + mode: 0o755, + }); + const mcp = client({ PATH: `${own}:${baseEnv.PATH}` }); + mcp.send(initialize('2025-06-18')); + await mcp.answer(1); + await mcp.close(); + expect(received()[0]).toBe(`started ${ARGS.join(' ')}`); + expect(JSON.parse(received()[1] ?? '{}').id).toBe(1); + }); + test('a protocol version the manifest has no answer for gets the server at once', async () => { const mcp = client(); mcp.send(initialize('2099-01-01')); diff --git a/services/sandbox-runtime/tale-playwright-mcp b/services/sandbox-runtime/tale-playwright-mcp index a1653f4695..a2dacb25de 100755 --- a/services/sandbox-runtime/tale-playwright-mcp +++ b/services/sandbox-runtime/tale-playwright-mcp @@ -5,13 +5,17 @@ Every managed agent turn lists the Playwright MCP server among its tools, but most turns never open a browser, and the server is a Node process that loads Playwright as it starts: about 100 MB and a third of a second of CPU, held for the whole turn. So this launcher answers the start of the conversation itself -β€” `initialize`, `tools/list`, `ping` β€” from a manifest recorded from the real -server when the image was built, and starts the real server only when the turn -first asks for anything else (a tool call). It then replays the client's -`initialize` to it and passes every message through, both ways. Where no -manifest matches the server arguments, or the client asks for a protocol -version the manifest has no answer for, the real server starts at once, as it -always did; TALE_PLAYWRIGHT_MCP_EAGER=1 always starts it at once. +β€” `initialize`, `tools/list`, `ping`, and the prompt and resource lists of a +server that advertises neither (Qwen Code asks for them at the start of every +turn) β€” from a manifest recorded from the real server when the image was +built, and starts the real server only when the turn first asks for anything +else (a tool call). It then replays the client's `initialize` to it and passes +every message through, both ways. Where no manifest matches the server +arguments, the server on PATH is not the one the manifest was recorded from, +PLAYWRIGHT_MCP_* settings in the environment may change its tools, or the +client asks for a protocol version the manifest has no answer for, the real +server starts at once, as it always did; TALE_PLAYWRIGHT_MCP_EAGER=1 always +starts it at once. It also bridges the container's egress env to Chromium flags: Chromium ignores HTTPS_PROXY/NO_PROXY, and the sandbox network is internal-only, so without an @@ -30,6 +34,7 @@ agent adapters. import hashlib import json import os +import shutil import signal import subprocess import sys @@ -49,6 +54,15 @@ PROBED_VERSIONS = ( '2024-11-05', '2024-10-07', ) +# The lists a client may ask for at the start of a turn, by the capability a +# server must advertise to answer them: without it the server has no handler, +# and its SDK answers METHOD_NOT_FOUND. +LISTS_BY_CAPABILITY = { + 'prompts/list': 'prompts', + 'resources/list': 'resources', + 'resources/templates/list': 'resources', +} +METHOD_NOT_FOUND = {'code': -32601, 'message': 'Method not found'} # The id of the replayed `initialize`: the client's own ids never reach it. REPLAYED_INIT_ID = 'tale-playwright-mcp-initialize' # How long the image build waits for the real server to answer. @@ -75,6 +89,23 @@ def server_argv(args, env): return argv +def installed_server(env): + """The real server as the PATH in `env` finds it, or None.""" + return shutil.which(REAL_SERVER, path=env.get('PATH')) + + +def server_file(path): + """The file a server path names, links resolved: what a manifest records.""" + return os.path.realpath(path) if path is not None else None + + +def configured_in_env(env): + """Whether the environment holds server settings the manifest, keyed by + the arguments, did not see: PLAYWRIGHT_MCP_CAPS adds tools, + PLAYWRIGHT_MCP_CONFIG names a file of settings, and so on.""" + return any(key.startswith('PLAYWRIGHT_MCP_') and value for key, value in env.items()) + + def manifest_path(args): key = hashlib.sha256(json.dumps(args).encode()).hexdigest()[:32] return os.path.join(MANIFEST_DIR, f'{key}.json') @@ -165,6 +196,7 @@ def write_manifests(arg_sets_file): with open(arg_sets_file, encoding='utf-8') as handle: arg_sets = json.load(handle) env = server_env() + server = server_file(installed_server(env)) os.makedirs(MANIFEST_DIR, exist_ok=True) for args in arg_sets: argv = server_argv(args, env) @@ -175,7 +207,12 @@ def write_manifests(arg_sets_file): path = manifest_path(args) with open(f'{path}.tmp', 'w', encoding='utf-8') as handle: json.dump( - {'args': args, 'initialize': initialize, 'tools': tools}, + { + 'args': args, + 'server': server, + 'initialize': initialize, + 'tools': tools, + }, handle, ) os.replace(f'{path}.tmp', path) @@ -195,8 +232,13 @@ class LazyServer: self.pump = None self.out = sys.stdout.buffer self.out_lock = threading.Lock() - # The protocol version answered to the client, once it was. + # The protocol version the client asked for, once it was answered: the + # manifest's key for its answers. self.version = None + # What it was answered: the protocol version it was told, and the + # capabilities the server advertised. + self.told = None + self.capabilities = None self.init_params = None self.client_initialized = False # Notifications that came before the server: replayed to it. @@ -216,6 +258,9 @@ class LazyServer: def reply(self, id_, result): self.write(encode({'jsonrpc': '2.0', 'id': id_, 'result': result})) + def refuse(self, id_, error): + self.write(encode({'jsonrpc': '2.0', 'id': id_, 'error': error})) + def answered(self, msg, line): """Answer `msg` without the server; False when it needs the server.""" method = msg.get('method') @@ -224,9 +269,11 @@ class LazyServer: params = msg.get('params') version = params.get('protocolVersion') if isinstance(params, dict) else None result = self.manifest['initialize'].get(version) if isinstance(version, str) else None - if result is None: + if not isinstance(result, dict): return False self.version = version + self.told = result.get('protocolVersion') + self.capabilities = result.get('capabilities') self.init_params = params self.reply(msg['id'], result) return True @@ -244,6 +291,12 @@ class LazyServer: self.reply(msg['id'], self.manifest['tools'][self.version]) return True return False + if isinstance(method, str) and method in LISTS_BY_CAPABILITY and has_id: + capabilities = self.capabilities + if isinstance(capabilities, dict) and LISTS_BY_CAPABILITY[method] not in capabilities: + self.refuse(msg['id'], METHOD_NOT_FOUND) + return True + return False if isinstance(method, str) and not has_id: self.held.append(line) return True @@ -265,8 +318,8 @@ class LazyServer: if msg is not None and msg.get('id') == REPLAYED_INIT_ID: result = msg.get('result') spoken = result.get('protocolVersion') if isinstance(result, dict) else None - if spoken != self.version: - log(f'the server speaks {spoken}, the client was told {self.version}') + if spoken != self.told: + log(f'the server speaks {spoken}, the client was told {self.told}') break self.write(line) else: @@ -331,11 +384,17 @@ def main(): env = server_env() argv = server_argv(args, env) manifest = None - if env.get('TALE_PLAYWRIGHT_MCP_EAGER') != '1': + if env.get('TALE_PLAYWRIGHT_MCP_EAGER') != '1' and not configured_in_env(env): manifest = load_manifest(args) + # A server the session installed ahead of the image's on PATH is not the + # one the manifest was recorded from; the one that is starts by the path + # checked here. + server = installed_server(env) + if manifest is not None and (server is None or server_file(server) != manifest.get('server')): + manifest = None if manifest is None: os.execvpe(REAL_SERVER, argv, env) - lazy = LazyServer(argv, env, manifest) + lazy = LazyServer([server, *argv[1:]], env, manifest) signal.signal(signal.SIGTERM, lazy.stop) signal.signal(signal.SIGINT, lazy.stop) signal.signal(signal.SIGHUP, lazy.stop) From 59a565ebc58289beba76baa87e318b1b1c3f8999 Mon Sep 17 00:00:00 2001 From: yannickmonney <102406702+yannickmonney@users.noreply.github.com> Date: Sat, 3 Oct 2026 14:19:47 +0000 Subject: [PATCH 2/2] fix(sandbox): end a Playwright MCP server that never answers its start The lazy launcher replays the client's initialize to the server it starts on a turn's first tool call and waited for the answer without a bound, so a server whose start hangs stalled that tool call for as long as the client waits. After two minutes, the same bound the image build gives the server, the launcher now logs it, kills the server and exits with it, and the client sees the server gone. Refs #4117 --- .../tests/manual/reference/automation.md | 2 +- services/sandbox-runtime/README.md | 4 +- .../daemon/src/tale-playwright-mcp.test.ts | 37 +++++++++++++++++-- services/sandbox-runtime/tale-playwright-mcp | 16 +++++++- 4 files changed, 53 insertions(+), 6 deletions(-) diff --git a/services/platform/tests/manual/reference/automation.md b/services/platform/tests/manual/reference/automation.md index 3a462e5b20..5f8e46ebdd 100644 --- a/services/platform/tests/manual/reference/automation.md +++ b/services/platform/tests/manual/reference/automation.md @@ -189,7 +189,7 @@ Legend: βœ… fully automated Β· πŸ”Ά partially automated Β· β›” manual-only (no s | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed Claude Code agent turn on a model that is not Claude names its exec in every request (`ANTHROPIC_CUSTOM_HEADERS: x-bf-eh-x-tale-cache-affinity: `, which the gateway forwards upstream as `X-Tale-Cache-Affinity`), keeping any header the harness already sends; a Claude model, an exec without an id and a bring-your-own credential send none | πŸ”Ά backend | `lib/harnesses/exec-builder.test.ts`; whether a multi-replica balancer keeps the turn on one replica is a deployment check | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | A managed harness turn that ends cleanly with nothing at all from its model (no text, no tool call, no output tokens: the empty 200 a serving cluster answers when it fails mid-prefill) settles failed with β€œThe model returned an empty answer, so the agent did nothing this turn.”: an automation `agent` node as a retryable `harness_error`, a task run on the retryable `empty_turn` path with its conversation handle kept, and a resumed task start is not taken for a dead handle. A turn that only called tools (the operator question included) or only reported output tokens (a reasoning-only turn, for one) is not empty; Claude Code's turn totals come from its result | πŸ”Ά backend | `backend/core/chat/external_turn_shared.test.ts`, `lib/harnesses/parsers/claude-stream-json.test.ts` (the pinned-CLI `empty-answer-turn`, `token-only-turn` and `thinking-only-turn` captures), `backend/core/automations/agent_host.empty_answer.test.ts`, `backend/core/tasks/agent_run_host.empty_answer.test.ts`; a live empty answer from a failing model server stays a deployment check | | [projects](../suites/projects.md) | Runtime image carries every managed harness (Qwen Code included); Codex runs as its native binary, without the npm launcher's Node process as its parent for the whole run | βœ… automated | `tests/integration/container-sandbox-runtime-test.ts` (registry-driven: every `managed: true` harness's exec binary on the agent PATH; `codex` is the direct launcher and runs), `services/sandbox-runtime/daemon/src/tale-qwen-run.test.ts`, `tale-hermes-run.test.ts` (returned SDK failures end as errors; resume restores the stored conversation) | -| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` β€” as the server would for every protocol version MCP has named, the server's latest for one it does not speak β€” `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own, logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | βœ… automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | +| [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A managed agent turn that never opens a browser never starts the Playwright MCP server (a Node process holding ~100 MB), whichever harness runs it: the launcher answers `initialize` β€” as the server would for every protocol version MCP has named, the server's latest for one it does not speak β€” `tools/list`, `ping`, and `prompts/list`, `resources/list` and `resources/templates/list` with the server's own `-32601 Method not found` while the recorded capabilities lack prompts or resources (Qwen Code asks every server for both at the start of every turn), from manifests the image build records for the platform's argument sets, with the server file it recorded them from; it starts the server on the first other request, replaying the client's start under an id of its own (a server that does not answer it within two minutes is ended, and the launcher exits with it), logs a started server that speaks another protocol version than the client was told, and passes every message through both ways (a server request and the client's answer included); unknown arguments or protocol versions, a server on PATH other than the recorded one (a session's own install), `PLAYWRIGHT_MCP_*` settings in the environment and `TALE_PLAYWRIGHT_MCP_EAGER=1` start the server at once; the platform's argument sets and the image's record are held equal | βœ… automated | `services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts` (a stand-in server: the build's manifest and its server file, the start answered without it, Qwen Code's discovery answered without it, a list the recorded capabilities advertise left to the server, the start replayed on the first tool call, a start that never answers ended at the deadline, the version check against what the client was told, a roots request round trip, an unknown version, `PLAYWRIGHT_MCP_*` settings, a session's own server and the eager switch, the exit status, the proxy flags), `tests/integration/container-sandbox-runtime-test.ts` (the image's own server, for every argument set: not running after `tools/list` and Qwen Code's discovery, the tool list and the prompt and resource list answers equal to the server's; a `browser_navigate` through the server started then), `lib/harnesses/exec-builder.test.ts` (the argument sets) | | [settings](../suites/settings.md) / [tasks](../suites/tasks.md) | An exec's leftover processes are ended: what its command backgrounded (`cmd &`, `nohup`, a descendant in a session of its own) gets SIGTERM, then SIGKILL, when the command exits β€” or, while another exec of the session still runs, when the session's last running exec ends β€” and at once on a cancel or at the deadline (what an exited exec left waiting included, and the group SIGKILL while the exec's own process runs even when no process there shows the tag); leftovers that wait keep their output pipes; the exit is reported without waiting out the drain grace; each process is signalled once (the group as a whole, on its own only a tagged process that left it), and a group whose tagged processes all left is never signalled later; a dropped attach releases its subscriber and its active operation; a session stop passes SIGTERM on to every live exec and to what exited execs left waiting; a group known to be the exec's gets its signal before the process table is read, a scan answers with what it read after two seconds and skips a process whose read never came back, and runnerd ends itself by SIGKILL while such a read is out; a leftover that stayed in the exec's group without the tag is still reached through the group's recorded processes (pid and start time) once it waited, and by the SIGKILL after an exec that ended alone; a steer's restart cancels the old exec as a rotation (`?leftovers=keep`, passed on by the spawner): only its own group ends, what it left outside is held until an exec started after it ends (a later cancel of the old exec leaves it held; with no successor within ten minutes the hold lifts), and a Stop or a crash still ends everything; a cancelled Gemini, Qwen or Pi turn removes its staged settings and context file, and a second signal does not cut that cleanup short; every exec runs under the subreaper shim (`tale-exec-shim`), so a process that left the exec's group and session and replaced its environment is still found below it and ended, and a round whose every exec still has its shim reads `stat` alone; the shim's status pipe gives the command's group, its exit status (128 + N for signal N) or why it could not run, the shim's own exit standing in only when the pipe ended without one; a cancel that comes before the shim named the group signals the group once it does; a refused subreaper is logged once and the exec falls back to group and tag | βœ… automated | `services/sandbox-runtime/daemon/src/exec-manager.test.ts` (exec tag in the environment, background child ended at exit and on cancel, one SIGTERM per cancel, an untagged leader still SIGKILLed, leftovers kept while another exec runs and keeping their pipes, a cancel during the drain, the daemon's stop of live and waiting execs, the leftover prune, a `setsid` descendant found by its tag on Linux, a dropped consumer settles its attach), `process-reaper.test.ts` (tag and process-group match, one signal per process, no stale group, one scan per round, init and runnerd never, a known group signalled before a hanging read, the scan deadline and the skipped stalled read, the stat-only group record, a recorded member's proof and a reused pid's none, a shim's descendants whatever their group, session or tag, a stat-only scan while every shim runs, the tag again once a shim has exited, an unreadable environment still walked through), `exec-shim.test.ts` (on Linux the shim built from its source: output and exit status, 128 + N for a signal, a spawn error, a `setsid env -i` escapee ended with its exec, while another exec runs and after a rotation, and out of reach without the shim, a cancel before the group is named; everywhere, stand-in shims for the status pipe: its exit over the shim's, a killed shim, a spawn error, a refused subreaper said once), `tests/integration/container-sandbox-runtime-test.ts` (the image's runnerd names its shim and ends an escapee), `daemon-exit.test.ts` (the SIGKILL exit while a read is out, under Node), `main.test.ts` (`?leftovers=keep` over HTTP on Linux), `harness-wrapper-cancel.test.ts` (each wrapper's staged files removed after one and after two signals); the rotation in `exec-manager.test.ts` (the group ended, the held server ended once the next exec ends, a hold outlasting an earlier exec and a late cancel, a `setsid` server on Linux) and the untagged in-group leftover after a deferral and after an exec that ended alone (Linux); `services/sandbox/src/server.test.ts` + `services/sandbox/src/session/session-routes.test.ts` (the flag reaches runnerd); `backend/core/node_only/sandbox/helpers/session_client.test.ts` (the query) and `backend/core/tasks/agent_run_host.reap.test.ts` (the restart lane rotates, a Stop and a crash cancel in full) | | [projects](../suites/projects.md) / [tasks](../suites/tasks.md) | A Gemini CLI agent on a model whose id ends in "flash" (`deepseek-flash`, `glm-5.3-flash`, `qwen3.6-flash`, OpenRouter `google/gemini-3.5-flash`, …) requests that model, not the CLI's own gemini-3.5-flash | βœ… automated | `lib/harnesses/exec-builder.test.ts` (the gemini exec carries `experimental.dynamicModelConfiguration` on both lanes and passes `--model` verbatim), `lib/harnesses/golden-exec.test.ts`, `tests/integration/container-sandbox-runtime-test.ts` (the pinned CLI through `tale-gemini-run` against a loopback gateway stand-in keeps a flash-suffixed id in the request path; the control run without the setting still shows the rewrite) | | [tasks](../suites/tasks.md) / [automations](../suites/automations.md) | `TASK-F35` (the image half): runnerd links every built-in skill baked into the runtime image into each harness's native user-level skill directory (`.claude/skills`, `.agents/skills`, `.hermes/skills`), keeping a directory or live link of someone's own; before every exec it withdraws the link beside a same-named skill the workspace repository ships in `.claude/skills` or `.agents/skills`, and restores it once the repository drops it. Every managed harness names `visual-aspect-analyzer` in its first model request, and with a repository copy in both directories lists that copy (Hermes, which reads no project skills, keeps the baked one) | πŸ”Ά image + stub model | `services/sandbox-runtime/daemon/src/baked-skills.test.ts`, `exec-manager.test.ts` (the reconcile runs before each spawn), `tests/integration/container-sandbox-runtime-test.ts` (every registry harness has a directory; each managed harness's golden exec through runnerd against a request-recording stub; links withdrawn and restored); a live model reading and running the skill stays `TASK-F35` | diff --git a/services/sandbox-runtime/README.md b/services/sandbox-runtime/README.md index 0e21afb211..bf3b2241ae 100644 --- a/services/sandbox-runtime/README.md +++ b/services/sandbox-runtime/README.md @@ -25,7 +25,9 @@ server for, with the server's own `Method not found` while it advertises neither) from manifests of the real server's answers, recorded at image build for the argument sets the platform passes ([`playwright-mcp-args.json`](playwright-mcp-args.json)), and starts the server -only on the turn's first tool call, replaying the start to it. Unknown +only on the turn's first tool call, replaying the start to it (a server that +does not answer it within two minutes is ended, and the launcher with it, so +the tool call fails instead of waiting). Unknown arguments or protocol versions, a server on `PATH` other than the image's (one the session installed), `PLAYWRIGHT_MCP_*` settings in the environment, and `TALE_PLAYWRIGHT_MCP_EAGER=1`, start the server at once. diff --git a/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts b/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts index 36eec9b2b0..f79433f424 100644 --- a/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts +++ b/services/sandbox-runtime/daemon/src/tale-playwright-mcp.test.ts @@ -96,7 +96,7 @@ describe('headless Playwright MCP launcher', () => { // the real server's SDK does, and writes every message it receives to its // log, behind a `started` line. const STAND_IN = String.raw`#!/usr/bin/env python3 -import json, os, sys +import json, os, sys, time log = open(os.environ['STAND_IN_LOG'], 'a') log.write('started ' + ' '.join(sys.argv[1:]) + '\n'); log.flush() SUPPORTED = os.environ.get('STAND_IN_VERSIONS', '2025-06-18,2024-11-05').split(',') @@ -108,6 +108,8 @@ for line in sys.stdin: log.write(json.dumps(msg) + '\n'); log.flush() method, id_ = msg.get('method'), msg.get('id') if method == 'initialize': + if os.environ.get('STAND_IN_HANG'): + time.sleep(30) asked = msg['params']['protocolVersion'] roots = 'roots' in msg['params'].get('capabilities', {}) send({'jsonrpc': '2.0', 'id': id_, 'result': { @@ -166,9 +168,12 @@ describe('the start of a turn without the server', () => { : []; /** A client of the launcher: send lines, await answers by id. */ - function client(env: Record = {}) { + function client( + env: Record = {}, + run: string[] = [launcher], + ) { rmSync(standInLog, { force: true }); - const proc = spawn(python, ['-Es', launcher, ...ARGS], { + const proc = spawn(python, ['-Es', ...run, ...ARGS], { env: { ...baseEnv, ...env }, stdio: ['pipe', 'pipe', 'pipe'], }); @@ -487,6 +492,32 @@ describe('the start of a turn without the server', () => { expect(JSON.parse(received()[1] ?? '{}').id).toBe(1); }); + test('a server that never answers the replayed start is ended at the deadline', async () => { + // The launcher, with a deadline of one second in place of its own. + const mcp = client({ STAND_IN_HANG: '1' }, [ + '-c', + [ + 'import importlib.machinery, importlib.util, sys', + "loader = importlib.machinery.SourceFileLoader('launcher', sys.argv[1])", + "launcher = importlib.util.module_from_spec(importlib.util.spec_from_loader('launcher', loader))", + 'loader.exec_module(launcher)', + 'launcher.START_TIMEOUT_S = 1', + 'sys.argv = sys.argv[1:]', + 'launcher.main()', + ].join('\n'), + launcher, + ]); + mcp.send(initialize('2025-06-18')); + await mcp.answer(1); + mcp.send(toolCall(2)); + // Ended by SIGKILL: the launcher exits with it, the call unanswered. + expect(await mcp.close()).toBe(137); + expect(mcp.lines.map((line) => line.id)).toEqual([1]); + expect(await mcp.stderr()).toBe( + '[tale-playwright-mcp] the server did not answer its start within 1 s, ending it\n', + ); + }); + test('a protocol version the manifest has no answer for gets the server at once', async () => { const mcp = client(); mcp.send(initialize('2099-01-01')); diff --git a/services/sandbox-runtime/tale-playwright-mcp b/services/sandbox-runtime/tale-playwright-mcp index a2dacb25de..47123854f9 100755 --- a/services/sandbox-runtime/tale-playwright-mcp +++ b/services/sandbox-runtime/tale-playwright-mcp @@ -10,7 +10,9 @@ server that advertises neither (Qwen Code asks for them at the start of every turn) β€” from a manifest recorded from the real server when the image was built, and starts the real server only when the turn first asks for anything else (a tool call). It then replays the client's `initialize` to it and passes -every message through, both ways. Where no manifest matches the server +every message through, both ways; a server that does not answer that +`initialize` within START_TIMEOUT_S is ended, and the launcher exits with it. +Where no manifest matches the server arguments, the server on PATH is not the one the manifest was recorded from, PLAYWRIGHT_MCP_* settings in the environment may change its tools, or the client asks for a protocol version the manifest has no answer for, the real @@ -67,6 +69,10 @@ METHOD_NOT_FOUND = {'code': -32601, 'message': 'Method not found'} REPLAYED_INIT_ID = 'tale-playwright-mcp-initialize' # How long the image build waits for the real server to answer. PROBE_TIMEOUT_S = 120 +# How long a turn waits for the server it started to answer the replayed +# `initialize`. Then the server is ended, and the launcher with it, so the +# client sees the server gone instead of waiting on its tool call. +START_TIMEOUT_S = 120 def log(message): @@ -307,6 +313,9 @@ class LazyServer: self.argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=self.env ) if self.version is not None: + deadline = threading.Timer(START_TIMEOUT_S, self.end_unanswered) + deadline.daemon = True + deadline.start() self.send(encode({ 'jsonrpc': '2.0', 'id': REPLAYED_INIT_ID, @@ -316,6 +325,7 @@ class LazyServer: for line in self.server.stdout: msg = message(line) if msg is not None and msg.get('id') == REPLAYED_INIT_ID: + deadline.cancel() result = msg.get('result') spoken = result.get('protocolVersion') if isinstance(result, dict) else None if spoken != self.told: @@ -332,6 +342,10 @@ class LazyServer: self.pump = threading.Thread(target=self.relay_server, daemon=True) self.pump.start() + def end_unanswered(self): + log(f'the server did not answer its start within {START_TIMEOUT_S} s, ending it') + self.server.kill() + def send(self, data): try: self.server.stdin.write(data)