Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(copilot): add tests for user interruption handling and update normalizer logic

Dev jacob5801b42b4f6a
diff --git a/cli/src/engines/copilot/normalizer.spec.ts b/cli/src/engines/copilot/normalizer.spec.ts
index 16a46a771..cb134aa1c 100644
--- a/cli/src/engines/copilot/normalizer.spec.ts
+++ b/cli/src/engines/copilot/normalizer.spec.ts
@@ -99,6 +99,73 @@ describe('copilot normalizer, over real recorded sessions', () => {
})
})
+describe('a turn the user interrupted with Esc', () => {
+ // Copied off a live session (Copilot CLI 1.0.83, 2026-09-09). This is the ONLY record Copilot
+ // writes for a cancel: the `agentStop` hook — this engine's only other turn boundary — never
+ // fires, so before `abort` was read the turn stayed open for the rest of the session. `cli.ts`
+ // heartbeats every 5s while `turnOpen`, so every client watching turn state believed the agent
+ // was still working, and the desktop's model picker (which disables itself mid-turn) stayed
+ // disabled from the first cancel until the next prompt.
+ const prompt = JSON.stringify({ type: 'user.message', data: { content: 'mcp grid web có chưa' }, id: 'u1', parentId: '' })
+ const toolStart = JSON.stringify({ type: 'tool.execution_start', data: { toolCallId: 't1', toolName: 'bash' }, id: 'e1', parentId: '' })
+ const abort = JSON.stringify({ type: 'abort', data: { reason: 'user_abort' }, id: 'a1', parentId: '' })
+
+ const ingestAll = (lines: readonly string[]) => {
+ const normalizer = new CopilotNormalizer()
+ const events: LiveEvent[] = []
+ for (const line of lines) events.push(...normalizer.ingest(line))
+ return { normalizer, events }
+ }
+
+ it('ends the turn, and says it was cut short', () => {
+ const { events } = ingestAll([prompt, abort])
+ const ended = events.filter((e) => e.type === 'turn_ended')
+ expect(ended).toHaveLength(1)
+ // Not a plain close: a turn the user stopped did not produce the answer a finished one did, and
+ // this flag is what the log line and a device recap read.
+ expect(ended[0].payload).toEqual({ aborted: true })
+ })
+
+ it('stops reporting the turn as open, which is what kept the heartbeat alive', () => {
+ const { normalizer } = ingestAll([prompt])
+ expect(normalizer.turnOpen).toBe(true)
+ const after = new CopilotNormalizer()
+ for (const line of [prompt, abort]) after.ingest(line)
+ expect(after.turnOpen).toBe(false)
+ })
+
+ it('closes a running tool as interrupted rather than failed', () => {
+ // Nothing went wrong with it — it was stopped. `isError` is what draws the card red, and a
+ // cancel the user asked for is not an error to show them.
+ const { events } = ingestAll([prompt, toolStart, abort])
+ const end = events.find((e) => e.type === 'tool_end')
+ expect(end?.payload).toMatchObject({ id: 't1', tool: 'Bash', isError: false })
+ expect(end?.payload.output).toContain('interrupted')
+ })
+
+ it('is inert when no turn is open', () => {
+ // A second Esc, or one pressed at an idle prompt. Emitting a turn_ended here would close a turn
+ // that does not exist and leave every client one end ahead of its starts.
+ expect(ingestAll([abort]).events).toEqual([])
+ expect(ingestAll([prompt, abort, abort]).events.filter((e) => e.type === 'turn_ended')).toHaveLength(1)
+ })
+
+ it('emits no lifecycle frame in replay, like every other opener and closer here', () => {
+ const replayed: LiveEvent[] = copilotMessagesToEvents([prompt, abort])
+ expect(replayed.some((e) => e.type === 'turn_started')).toBe(false)
+ expect(replayed.some((e) => e.type === 'turn_ended')).toBe(false)
+ })
+
+ it('does not resume a session that ended in a cancel as still running', () => {
+ // Esc during a model round-trip leaves the last `assistant.turn_start` unmatched, so reading
+ // ends off `assistant.turn_end` alone brings the session back mid-turn — and nothing is coming
+ // to close it, because the process that would have is gone.
+ const roundTrip = JSON.stringify({ type: 'assistant.turn_start', data: { turnId: '0' }, id: 'r1', parentId: '' })
+ expect(copilotHistoryTurnOpen([prompt, roundTrip])).toBe(true)
+ expect(copilotHistoryTurnOpen([prompt, roundTrip, abort])).toBe(false)
+ })
+})
+
describe('copilot tool names', () => {
it('maps what was measured and title-cases the rest', () => {
expect(copilotToolName('bash')).toBe('Bash')
diff --git a/cli/src/engines/copilot/normalizer.ts b/cli/src/engines/copilot/normalizer.ts
index 84a0c396e..b1e6d64de 100644
--- a/cli/src/engines/copilot/normalizer.ts
+++ b/cli/src/engines/copilot/normalizer.ts
@@ -15,6 +15,16 @@
*
* The real boundary is the `agentStop` hook (`stopReason: "end_turn"`, and it names this very file in
* `transcriptPath`), handled in `cli.ts`. A turn opens here on `user.message`.
+ *
+ * ⚠️ **That hook does not fire when the user presses Esc** — and it is the only close this engine
+ * has, so an interrupted turn stayed open for the rest of the session. Nothing then ended it but the
+ * NEXT prompt (the re-open below), which meant `turnOpen` stayed true, the 5s heartbeat in `cli.ts`
+ * kept firing for a turn nobody was running, and every client watching turn state believed the agent
+ * was still working: the desktop's model picker disables itself mid-turn, so it was disabled from the
+ * first cancel until the next message. What Copilot writes instead is a top-level
+ * `{"type":"abort","data":{"reason":"user_abort"}}` record, handled below — measured 2026-09-09 on
+ * 1.0.83, an `assistant.turn_end` 2ms ahead of it and no `hook.start` of type `agentStop` anywhere
+ * after it.
*/
import type { EngineNormalizer } from '../types.js'
@@ -150,6 +160,23 @@ export function copilotEventToEvents(event: CopilotEvent, state: CopilotTurnStat
return events
}
+ // Esc. The turn is over, and this record is the only thing that says so — see the header.
+ //
+ // `aborted: true` rather than a plain close: the difference is what the log prints and what a
+ // device shows for a recap, and a turn the user cut short did not produce the answer a completed
+ // one did. Rows opened by it are `interrupted`, not `failed` — nothing went wrong with them, they
+ // were stopped — which also keeps `isError` off cards the user themselves cancelled.
+ //
+ // Replay leaves the state alone for the same reason `user.message` does: a replayed history opens
+ // no turns, so there is none here to close.
+ if (type === 'abort') {
+ if (mode !== 'live' || !state.open) return events
+ closeRows(state, events, 'interrupted')
+ state.open = false
+ events.push({ type: 'turn_ended', payload: { aborted: true } })
+ return events
+ }
+
if (type === 'assistant.message') {
// `toolRequests` announces the calls, but `tool.execution_start` carries the same ids a moment
// later — opening rows from both would double every card.
@@ -264,7 +291,10 @@ export function copilotHistoryTurnOpen(lines: string[]): boolean {
const event = copilotEvent(line)
if (!event) return
if (event.type === 'user.message' || event.type === 'assistant.turn_start') lastOpener = index
- else if (event.type === 'assistant.turn_end') lastEnd = index
+ // `abort` counts as an end, and it is the case `assistant.turn_end` alone gets wrong: Esc during
+ // a model round-trip leaves the last `assistant.turn_start` unmatched, so a resumed session would
+ // come back believing that turn was still running.
+ else if (event.type === 'assistant.turn_end' || event.type === 'abort') lastEnd = index
else if (event.type === 'session.shutdown') shutdown = index
})
// A shutdown after the last activity ends the conversation whatever came before it.
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index 00aed5bbf..49379748d 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -428,6 +428,12 @@ describe('web tools (grid ADR 0041)', () => {
expect(at, 'claude was not given --mcp-config').toBeGreaterThanOrEqual(0)
return JSON.parse(args[at + 1] as string)
}
+ const copilotMcpJson = (override = WITH_MCP) => {
+ const args = launchOf('copilot', override).args
+ const at = args.indexOf('--additional-mcp-config')
+ expect(at, 'copilot was not given --additional-mcp-config').toBeGreaterThanOrEqual(0)
+ return JSON.parse(args[at + 1] as string)
+ }
const codexArg = (key: string, override = WITH_MCP): string | undefined => {
const args = launchOf('codex', override).args
return args.find((arg) => arg.startsWith(`${key}=`))
@@ -457,6 +463,27 @@ describe('web tools (grid ADR 0041)', () => {
expect(launchOf('claude', WITH_MCP).args).not.toContain('--strict-mcp-config')
})
+ it('hands Copilot the SAME document, under its own flag', () => {
+ // Measured 2026-09-09 against a header-logging listener on loopback, Copilot CLI 1.0.83: it
+ // expands `${VAR}` in a header exactly as Claude Code does, and sends `${env:VAR}` and
+ // `{env:VAR}` through verbatim — so the opencode spelling would have put the literal string on
+ // the wire and failed authentication with nothing naming why.
+ expect(copilotMcpJson().mcpServers['grid-web'])
+ .toEqual({ type: 'http', url: MCP_URL, headers: { Authorization: 'Bearer ${GRID_API_KEY}' } })
+ // One document, not two that merely look alike — this is what makes the shared builder honest.
+ const at = launchOf('copilot', WITH_MCP).args.indexOf('--additional-mcp-config')
+ const claudeAt = launchOf('claude', WITH_MCP).args.indexOf('--mcp-config')
+ expect(launchOf('copilot', WITH_MCP).args[at + 1])
+ .toBe(launchOf('claude', WITH_MCP).args[claudeAt + 1])
+ })
+
+ it("leaves Copilot the user's own MCP servers too", () => {
+ // The flag is `--additional-mcp-config`: it augments ~/.copilot/mcp-config.json for the session
+ // rather than replacing it, which is why no dotfile is written and none of theirs is dropped.
+ expect(launchOf('copilot', WITH_MCP).args.filter((arg) => arg.startsWith('--')))
+ .toEqual(['--additional-mcp-config'])
+ })
+
it("points Codex at it through env_http_headers, which carries the WHOLE header value", () => {
expect(codexArg('mcp_servers.grid-web.url')).toBe(`mcp_servers.grid-web.url="${MCP_URL}"`)
expect(codexArg('mcp_servers.grid-web.env_http_headers.Authorization'))
@@ -508,6 +535,7 @@ describe('web tools (grid ADR 0041)', () => {
// misses on the other. Codex is where this is easy to get wrong: its config keys are dotted TOML
// paths, which look like they could not carry a `-`. They can.
expect(Object.keys(claudeMcpJson().mcpServers)).toEqual(['grid-web'])
+ expect(Object.keys(copilotMcpJson().mcpServers)).toEqual(['grid-web'])
expect(Object.keys(opencodeConfig().mcp)).toEqual(['grid-web'])
expect(Object.keys(JSON.parse(launchOf('hermes', WITH_MCP).configDir!.files[0]!.content).mcp_servers))
.toEqual(['grid-web'])
@@ -518,7 +546,7 @@ describe('web tools (grid ADR 0041)', () => {
})
it('never writes the key to disk or to an argv', () => {
- for (const engine of ['claude', 'codex', 'opencode', 'hermes'] as const) {
+ for (const engine of ['claude', 'codex', 'copilot', 'opencode', 'hermes'] as const) {
const launch = launchOf(engine, WITH_MCP)
for (const arg of launch.args) expect(arg, `${engine} argv`).not.toContain(WIRE.apiKey)
for (const file of launch.configDir?.files ?? []) {
@@ -535,16 +563,20 @@ describe('web tools (grid ADR 0041)', () => {
// the argument, `${GRID_API_KEY}` would become the key — in a command line `ps` shows to every
// user on the machine. `exec "$@"` passes positionals through untouched, which is what keeps
// the reference a reference; this pins it against a future change to the wrapper.
- const launch = launchOf('claude', WITH_MCP)
- const argv = buildEngineLaunchArgv('claude', { extraArgs: launch.args })
- expect(argv.join(' ')).toContain('Bearer ${GRID_API_KEY}')
- expect(argv.join(' ')).not.toContain(WIRE.apiKey)
+ for (const engine of ['claude', 'copilot'] as const) {
+ const launch = launchOf(engine, WITH_MCP)
+ const argv = buildEngineLaunchArgv(engine, { extraArgs: launch.args })
+ expect(argv.join(' '), engine).toContain('Bearer ${GRID_API_KEY}')
+ expect(argv.join(' '), engine).not.toContain(WIRE.apiKey)
+ }
})
it('adds nothing at all when the desktop sends no mcpUrl', () => {
// An older desktop, and the no-regression promise: the launch is byte-for-byte what it was.
expect(launchOf('claude', WITH_MODEL).args).toEqual([])
expect(launchOf('claude', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
+ expect(launchOf('copilot', WITH_MODEL).args).toEqual([])
+ expect(launchOf('copilot', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
expect(codexArg('mcp_servers.grid-web.url', WITH_MODEL)).toBeUndefined()
expect(launchOf('codex', WITH_MODEL).env.GRID_MCP_AUTHORIZATION).toBeUndefined()
expect(opencodeConfig(WITH_MODEL).mcp).toBeUndefined()
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index db4777e3c..2cfe62ae2 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -41,7 +41,7 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
import {
- claudeMcpConfig,
+ mcpServersConfig,
codexMcpArgs,
GRID_MCP_AUTH_VAR,
GRID_MCP_SERVER_NAME,
@@ -472,7 +472,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// below, and setting it otherwise would leave a key in the pane that nothing reads.
...(override.mcpUrl ? { [GRID_KEY_VAR]: override.apiKey } : {}),
},
- args: override.mcpUrl ? ['--mcp-config', claudeMcpConfig(override.mcpUrl, GRID_KEY_VAR)] : [],
+ args: override.mcpUrl ? ['--mcp-config', mcpServersConfig(override.mcpUrl, GRID_KEY_VAR)] : [],
}),
},
@@ -650,6 +650,10 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// GitHub's documented BYOK path for Copilot CLI (docs.github.com … /use-byok-models). Copilot
// will not start against a custom provider without being told the model, so that is enforced
// here rather than left to fail inside the app.
+ //
+ // Web tools ride the same JSON document Claude Code is handed, under Copilot's own flag. The flag
+ // is `--additional-mcp-config` rather than a `--mcp-config`: it AUGMENTS `~/.copilot/mcp-config.json`
+ // for the session, which is the behaviour wanted here and the reason no dotfile is written.
copilot: {
requiresModel: true,
build: (override) => ({
@@ -657,8 +661,13 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
COPILOT_PROVIDER_BASE_URL: relayBaseUrl(override.baseUrl),
COPILOT_PROVIDER_API_KEY: override.apiKey,
...(override.model ? { COPILOT_MODEL: override.model } : {}),
+ // Same rule as claude: the variable exists only to be referenced by the config below, so it
+ // is set only when there is a config to reference it.
+ ...(override.mcpUrl ? { [GRID_KEY_VAR]: override.apiKey } : {}),
},
- args: [],
+ args: override.mcpUrl
+ ? ['--additional-mcp-config', mcpServersConfig(override.mcpUrl, GRID_KEY_VAR)]
+ : [],
}),
},
}
diff --git a/cli/src/lib/gridWebMcp.ts b/cli/src/lib/gridWebMcp.ts
index 86db52944..0ab29248a 100644
--- a/cli/src/lib/gridWebMcp.ts
+++ b/cli/src/lib/gridWebMcp.ts
@@ -12,9 +12,10 @@
* `GridLaunchOverride.apiKey`: ADR 0041 D-b asks for the per-grid access token and requires no scope
* of it, `consumer` included, which is exactly what the desktop mints.
*
- * The same three harnesses `grid mcp config` prints for, and for the same reason — these are the
- * ones whose header handling was measured on the wire rather than read off a vendor page. An engine
- * with no wiring here launches on the grid exactly as it did before, with no web tools.
+ * The harnesses `grid mcp config` prints for, plus the ones since measured the same way — what every
+ * entry here has in common is that its header handling was read off the wire rather than off a vendor
+ * page. An engine with no wiring here launches on the grid exactly as it did before, with no web
+ * tools.
*
* ⚠️ **The key still never reaches a file or an argv**, which is `gridLaunch.ts`'s rule and NOT ADR
* 0041's. That ADR rejects the environment outright, and it is right about the caller it was written
@@ -27,10 +28,18 @@
* no file at all and its argv carries the variable's NAME.
* * Codex reads `env_http_headers`, settable entirely through `-c`.
* * opencode expands `{env:VAR}` in `headers`, in the config file the launch already writes it.
+ * * Copilot CLI expands `${VAR}` too, in the same JSON-string form, behind
+ * `--additional-mcp-config`.
*
* Measured 2026-09-08 against a header-logging listener on loopback — Claude Code 2.1.263, Codex
- * 0.144.6, opencode 1.18.29, the first two being the versions ADR 0041 itself measured. Each sent
- * `Authorization: Bearer <the variable's value>` on every request, the GET discovery included.
+ * 0.144.6, opencode 1.18.29, the first two being the versions ADR 0041 itself measured — and Copilot
+ * CLI 1.0.83 the same way on 2026-09-09. Each sent `Authorization: Bearer <the variable's value>` on
+ * every request, the GET discovery included.
+ *
+ * ⚠️ The reference syntax is NOT interchangeable, which is why each was measured rather than
+ * assumed. Copilot expands `${VAR}` and sends `${env:VAR}` and `{env:VAR}` through VERBATIM — the
+ * opencode spelling would have put the literal string on the wire and the tools would have failed
+ * authentication with nothing naming why.
*/
/**
@@ -60,18 +69,24 @@ export function mcpAuthorizationHeader(apiKey: string): string {
}
/**
- * Claude Code's `--mcp-config`, as a JSON string rather than a file.
- *
- * `${…}` is Claude Code's own expansion, performed when it reads the config, so this names [keyVar]
- * and never the key itself — and nothing is written to disk. That variable belongs to the launch,
- * which is why it arrives as an argument rather than being imported: this module is about what an
- * agent can reach, not about the key it reaches with.
- *
- * Deliberately NOT accompanied by `--strict-mcp-config`, which would drop every MCP server the user
- * configured for themselves. Picking a grid adds web tools; it does not take an agent's own tools
- * away.
+ * The `{ mcpServers: … }` document Claude Code and Copilot CLI both read, as a JSON string rather
+ * than a file — `--mcp-config` for the first, `--additional-mcp-config` for the second.
+ *
+ * One function because it is one document, byte for byte: the same keys, and the same `${…}`
+ * expansion performed by each harness when it reads the config. So this names [keyVar] and never the
+ * key itself, and nothing is written to disk. That variable belongs to the launch, which is why it
+ * arrives as an argument rather than being imported: this module is about what an agent can reach,
+ * not about the key it reaches with.
+ *
+ * Copilot's `tools` filter is deliberately absent. Its CLI documents the default as `"*"`, so
+ * writing one would restate the default for one harness in a document the other does not read.
+ *
+ * Neither flag is accompanied by anything that narrows the config to this server alone — Claude
+ * Code's `--strict-mcp-config` would drop every MCP server the user configured for themselves, and
+ * Copilot's flag is *additional* by name and by behaviour. Picking a grid adds web tools; it does
+ * not take an agent's own tools away.
*/
-export function claudeMcpConfig(mcpUrl: string, keyVar: string): string {
+export function mcpServersConfig(mcpUrl: string, keyVar: string): string {
return JSON.stringify({
mcpServers: {
[GRID_MCP_SERVER_NAME]: {