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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ row counts, ids and foreign keys, and run it twice.
safe until the bridge sends `start`; `web/src/chat/store.ts` keeps an outbox in localStorage
for sends that never reached it.
- **A chat turn starts in `startChatTurn`, whoever starts it.** The composer's `POST /api/chat` and the queue's drain (`drainChatQueue`, on every run's end) share it, and a run's `outcome` (set before `done`) is what decides whether the queue moves on or holds. A new way to start or end a chat run that skips either leaves queued messages waiting for ever, or starts them after a stop.
- **A reply's `start` comes before it can be steered.** `run.steer` is set only after the skill lookup and the browser grant, so anything that steers a run goes through `steerRun`/`steerableRun`, which wait on `run.steerReady` (settled false for a compaction, a skill command or the run's end) instead of refusing a steer sent straight after `start`.
- **A downstream gets a deadline to connect, never to answer a call.** The gateway times `initialize`, `notifications/initialized` and each `tools/list` page (30 s, 15 s per page, 45 s per server overall; `DEFAULT_TIMEOUTS` in `mcp-gateway.mjs`), caps listing at 50 pages and stops on a repeated cursor. A server that misses its deadline is closed (its whole process tree killed, its HTTP requests aborted) and shows in `--status` and `totem_list_connections` as `{ ok:false, timedOut:true, phase, error }`. Before this, one server that never answered `initialize` kept the gateway from serving anything, built-ins included. `tools/call` stays untimed on purpose: `ask_questions`, totems and long manifest tools legitimately take minutes or hours (next gotcha). An OAuth token refresh is never cut short by those deadlines or by `close()` either: the authorization server may already have rotated the refresh token, so the refresh runs to the end on its own 60 s timeout and saves the result, and the gateway waits for it before exiting (`settleRefreshes`). The gateway answers the runtime's `initialize` at once; `tools/list` waits for the connects, so every runtime still sees one complete list.
- **A question can wait for hours, so nothing on its path may time out.** `ask_questions` answers as an SSE stream with a comment every 15 s (Node's fetch, which the gateway uses, drops a body that stays silent for five minutes), each CLI is told a day-long tool timeout (Claude's per-server `timeout`, Codex's `tool_timeout_sec`, which defaults to 60 s), and the run's clock is held while it waits (`holdableTimeout`). A new spawn path that times out an agent must take `holds` too.
- **Offering the browser must stay free.** Every chat run is offered it, so `grantBrowserAccess` only mints a token and `/agent-mcp`'s `initialize`/`tools/list` answer from static descriptors; Chromium starts on the first `preview_*` call that needs a page. Anything added to the grant or the handshake that touches Playwright launches a browser on every chat turn (`chat/reach.test.mjs` checks the launch count). Watching is free too: `watch` returns null for a chat with no browser, and the panel's socket never creates a session.
Expand Down
28 changes: 27 additions & 1 deletion bridge.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10060,6 +10060,11 @@ async function startChatTurn(body, { idle = null } = {}) {
assistantMessageId: assistantId,
execute: async ({ emit: push, signal, run }) => {
const t0 = Date.now()
// Steering is wired up only after `start` and some async work (skills, the
// browser grant), so a steer landing in between waits here (steerableRun)
// rather than being refused. Settled false where this reply takes none.
let steerReady = () => {}
run.steerReady = new Promise((resolve) => { steerReady = resolve })
// A new message settles a browser handoff left waiting from an earlier reply.
const leftOver = browserHandoffs.get(threadId)
if (leftOver) { dropHandoff(threadId); handoffWaits.dismiss(leftOver.id); push({ type: 'handoff', handoff: null }) }
Expand Down Expand Up @@ -10276,6 +10281,7 @@ async function startChatTurn(body, { idle = null } = {}) {
// `/compact` (chat/context.mjs): the chat's own session summarises itself.
// The reply is only its divider, so it never counts as an answer to read.
if (isCompaction) {
steerReady(false)
const part = { id: `cmp-${assistant.id.slice(0, 8)}`, trigger: compactTrigger || 'manual' }
const fail = (reason) => forward({ type: 'compaction', compaction: { ...part, status: 'failed', reason, endedAt: Date.now() } })
const own = thread.sessions?.[provider]
Expand Down Expand Up @@ -10305,6 +10311,7 @@ async function startChatTurn(body, { idle = null } = {}) {
// A skill command ($morning, /journal, …) runs the skill rather than chatting.
const matchedSkill = !body.regenerate && !files.length ? await lookupSkillCommand(text.toLowerCase(), text) : null
if (matchedSkill) {
steerReady(false)
const agentOptions = { onActivity: (a) => push({ type: 'activity', text: a }), cursorModel: choice.cursorModel }
const channel = SKILL_CHAT_CHANNELS[matchedSkill.id] || 'web'
const viaRunner = SKILL_CHAT_RUNNERS[matchedSkill.id]
Expand Down Expand Up @@ -10365,6 +10372,7 @@ async function startChatTurn(body, { idle = null } = {}) {
log(`web chat [${provider}] steered (${via}):`, words.slice(0, 100), attachments.length ? `+${attachments.length} files` : '')
return shown
}
steerReady(true)
let attempts = 0
const runOnce = async ({ fresh, steers = null }) => {
// Codex numbers its items per process (item_0, item_1…), so a resumed
Expand Down Expand Up @@ -10496,6 +10504,7 @@ async function startChatTurn(body, { idle = null } = {}) {
error = status === 'error' ? String(e?.message || e) : ''
} finally {
steering.close()
steerReady(false)
delete run.steer
delete run.questions
if (pending) { clearTimeout(pending); pending = null }
Expand Down Expand Up @@ -10596,9 +10605,25 @@ async function startChatTurn(body, { idle = null } = {}) {

const uploadIds = (list) => (Array.isArray(list) ? list : []).map((a) => (typeof a === 'string' ? a : a?.id)).filter(validUploadId).slice(0, 20)

/**
* The thread's running reply once it can take a steer, or null if it never will.
* A reply sends `start` before its steering is set up, so a steer sent straight
* after waits for it (run.steerReady) rather than being refused.
*/
async function steerableRun(threadId, ms = 10_000) {
const run = chatRuns.active(threadId)
if (!run || run.steer) return run?.steer ? run : null
if (!run.steerReady) return null
let timer
await Promise.race([run.steerReady, new Promise((resolve) => { timer = setTimeout(resolve, ms) })])
clearTimeout(timer)
const now = chatRuns.active(threadId)
return now?.steer ? now : null
}

/** Send the owner's words (and files) into the thread's running reply. Null when nothing is running that can take them. */
async function steerRun(threadId, words, ids = []) {
if (!chatRuns.active(threadId)?.steer) return null
if (!await steerableRun(threadId)) return null
const files = await loadChatFiles(ids.map((id) => ({ id })))
const images = await readSteerImages(files)
// Looked up again: the run may have ended while the files were read.
Expand Down Expand Up @@ -10673,6 +10698,7 @@ async function changeChatQueue(body) {
return queueView(t)
}
if (action === 'steer') {
await steerableRun(threadId)
let item = null
const t = await threadStore.update(threadId, (t) => {
item = t.queue?.find((x) => x.id === id)
Expand Down
4 changes: 3 additions & 1 deletion chat/refs-bridge.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ const call = async (method, path, body, raw) => {
return text ? JSON.parse(text.startsWith('data:') ? 'null' : text) : null
}
const upload = (name, mime, body) => call('POST', `/api/chat/uploads?name=${encodeURIComponent(name)}&mime=${encodeURIComponent(mime)}`, null, Buffer.from(body))
const prompts = () => readFileSync(B.log, 'utf8').trim().split('\n').filter(Boolean).map((l) => JSON.parse(l).prompt)
// The fake appends a line while this polls, so the last one may be half written:
// only lines that end in a newline are read.
const prompts = () => readFileSync(B.log, 'utf8').split('\n').slice(0, -1).filter(Boolean).map((l) => JSON.parse(l).prompt)
const until = async (fn, ms = 15_000) => {
const deadline = Date.now() + ms
for (;;) {
Expand Down
32 changes: 26 additions & 6 deletions chat/settle-bridge.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,23 +32,43 @@ const canConnect = (port) => new Promise((resolve) => {
socket.once('error', () => resolve(false))
})

// Claude Code's stream-json, trimmed to what the bridge reads; the reply waits
// for a file named after the prompt, so a test can steer and queue while it runs.
// Claude Code's stream-json, trimmed to what the bridge reads; a reply whose
// message says hold-<name> waits for a file of that name, so a test can steer
// and queue while it runs. A chat run sends its prompt on stdin (it can be
// steered), not after "--", so the fake reads it from there as the CLI does;
// read from argv it saw "-p", held nothing, and every test raced its exit.
const FAKE_CLAUDE = `#!/usr/bin/env node
const fs = require('node:fs')
const path = require('node:path')
const args = process.argv.slice(2)
const prompt = args[args.indexOf('--') + 1] || ''
const out = (e) => process.stdout.write(JSON.stringify({ session_id: 'sess-1', ...e }) + '\\n')
out({ type: 'system', subtype: 'init', model: 'claude-opus-5-5' })
const release = path.join(process.env.FAKE_RELEASE_DIR, prompt.replace(/[^a-z0-9-]/gi, '_'))
const finish = () => {
out({ type: 'assistant', parent_tool_use_id: null, message: { model: 'claude-opus-5-5', content: [{ type: 'text', text: 'ok' }], usage: { input_tokens: 10, output_tokens: 1 } } })
out({ type: 'result', subtype: 'success', result: 'ok', usage: { input_tokens: 10, output_tokens: 1 } })
process.exit(0)
}
if (!prompt.startsWith('hold')) finish()
else setInterval(() => { if (fs.existsSync(release)) finish() }, 50)
const begin = (prompt) => {
const hold = [...prompt.matchAll(/\\bhold-[a-z0-9-]+/gi)].pop()?.[0]
if (!hold) return finish()
const release = path.join(process.env.FAKE_RELEASE_DIR, hold.replace(/[^a-z0-9-]/gi, '_'))
setInterval(() => { if (fs.existsSync(release)) finish() }, 50)
}
if (args.includes('--')) begin(args[args.indexOf('--') + 1] || '')
else {
// The first stdin line is the message; later ones are steers, which only need taking.
let buf = ''
let started = false
process.stdin.on('data', (d) => {
if (started) return
buf += d
const nl = buf.indexOf('\\n')
if (nl < 0) return
started = true
const content = JSON.parse(buf.slice(0, nl)).message?.content
begin(typeof content === 'string' ? content : (content || []).filter((b) => b.type === 'text').map((b) => b.text).join('\\n'))
})
}
process.stdin.resume()
`

Expand Down
6 changes: 4 additions & 2 deletions mcp-gateway.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,9 @@ test('--status against a hung manifest exits within the budget and names the hun

test('serving: initialize is answered at once, tools/list waits for the budget and lists built-ins', { timeout: 15_000 }, async (t) => {
const { dir, pidFile } = tempDir(t)
const timeouts = { handshakeMs: 1500, pageMs: 1500, serverMs: 2000 }
// Wide enough that a slow Node start on a busy runner still answers inside the
// hung server's handshake budget; a gateway that waited for it could not.
const timeouts = { handshakeMs: 4000, pageMs: 4000, serverMs: 5000 }
const { child, exited } = spawnGateway(t, [], gatewayEnv(dir, { stuck: stdioServer('launcher', pidFile) }, timeouts))
const replies = new Map()
createInterface({ input: child.stdout }).on('line', (line) => { const m = JSON.parse(line); replies.set(m.id, { ...m, at: Date.now() }) })
Expand All @@ -244,7 +246,7 @@ test('serving: initialize is answered at once, tools/list waits for the budget a

send({ method: 'notifications/initialized' })
send({ id: 2, method: 'tools/list' })
assert.ok(await waitFor(() => replies.has(2), 8000))
assert.ok(await waitFor(() => replies.has(2), 10_000))
const names = replies.get(2).result.tools.map((tool) => tool.name)
assert.ok(names.includes('tasks__get_tasks'))
assert.ok(!names.some((n) => n.startsWith('stuck__')))
Expand Down
Loading