Skip to content

The agent that grows with you

test(desktop-core): clarify and approval round trips (C20)

teknium10015e4038b76
diff --git a/apps/desktop/e2e/core/boot-lifecycle.spec.ts b/apps/desktop/e2e/core/boot-lifecycle.spec.ts
index 27c36282016..f6c641c61de 100644
--- a/apps/desktop/e2e/core/boot-lifecycle.spec.ts
+++ b/apps/desktop/e2e/core/boot-lifecycle.spec.ts
@@ -37,7 +37,11 @@ import {
import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
import { gate, startScriptedProvider } from './provider'
-const nonce = Math.random().toString(36).slice(2, 8).replace(/[^a-z0-9]/g, 'x').padEnd(4, 'q')
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
const U = (n: number) => `U${n}-${nonce}`
const A = (n: number) => `A${n}-${nonce}`
const TOOL_TAG = `core-orphan-${nonce}`
@@ -77,6 +81,7 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
// Background census: every backend pid ever observed.
const seenBackends = new Set<number>()
+
const census = setInterval(() => {
for (const proc of backendProcesses(sandbox)) {
seenBackends.add(proc.pid)
@@ -113,10 +118,16 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
expect(victim).toBeTruthy()
process.kill(victim!.pid, 'SIGKILL')
await expect
- .poll(() => backendProcesses(sandbox).map(p => p.pid).filter(pid => pid !== victim!.pid).length, {
- timeout: 120_000,
- message: 'a replacement backend is spawned'
- })
+ .poll(
+ () =>
+ backendProcesses(sandbox)
+ .map(p => p.pid)
+ .filter(pid => pid !== victim!.pid).length,
+ {
+ timeout: 120_000,
+ message: 'a replacement backend is spawned'
+ }
+ )
.toBe(1)
await waitForInteractive(app, page)
provider.script(U(2), [{ text: [`${A(2)} `, 'after ', 'respawn'] }])
@@ -134,21 +145,32 @@ test('boot handshake, supervised respawn, and zero orphans on quit', async () =>
await test.step('quit mid-turn with a running tool child: zero processes remain', async () => {
const hold = gate()
provider.script(U(3), [
- { text: [`${A(3)} `, 'starting ', 'tool'], toolCalls: [{ name: 'terminal', args: { command: `exec -a ${TOOL_TAG} sleep 3600` } }] },
+ {
+ text: [`${A(3)} `, 'starting ', 'tool'],
+ toolCalls: [{ name: 'terminal', args: { command: `exec -a ${TOOL_TAG} sleep 3600` } }]
+ },
{ text: [`${A(3)}b `, 'never ', 'reached'], holdAfterFirstChunk: hold }
])
await send(page, `${U(3)} long tool`, 'Enter', ws)
- await expect.poll(() => taggedProcesses(TOOL_TAG).length, { timeout: 120_000, message: 'tool child running' }).toBeGreaterThan(0)
+ await expect
+ .poll(() => taggedProcesses(TOOL_TAG).length, { timeout: 120_000, message: 'tool child running' })
+ .toBeGreaterThan(0)
expect(sandboxProcesses(sandbox).length).toBeGreaterThan(0)
await app.close()
closed = true
clearInterval(census)
await expect
- .poll(() => [...sandboxProcesses(sandbox), ...taggedProcesses(TOOL_TAG)].map(p => `${p.pid} ${p.cmdline.slice(0, 120)}`), {
- timeout: 60_000,
- message: 'no sandbox process (backend, tool child, Electron helper) survives quit'
- })
+ .poll(
+ () =>
+ [...sandboxProcesses(sandbox), ...taggedProcesses(TOOL_TAG)].map(
+ p => `${p.pid} ${p.cmdline.slice(0, 120)}`
+ ),
+ {
+ timeout: 60_000,
+ message: 'no sandbox process (backend, tool child, Electron helper) survives quit'
+ }
+ )
.toEqual([])
hold.open()
})
@@ -188,7 +210,9 @@ test('relaunching the same home: one backend per boot, zero after each quit, tra
const ws = recordWebSockets(page)
await waitForInteractive(app, page)
await installDuplicateSampler(page)
- await expect.poll(() => backendProcesses(sandbox).length, { message: `one backend on launch ${launch}` }).toBe(1)
+ await expect
+ .poll(() => backendProcesses(sandbox).length, { message: `one backend on launch ${launch}` })
+ .toBe(1)
if (launch === 1) {
provider.script(U(1), [{ text: [`${A(1)} `, 'persisted ', 'across ', 'launches'] }])
@@ -202,7 +226,9 @@ test('relaunching the same home: one backend per boot, zero after each quit, tra
await page.evaluate(id => {
window.location.hash = `#/${encodeURIComponent(id)}`
}, session.sessionId)
- await expect(page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()).toContainText(A(1), {
+ await expect(
+ page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+ ).toContainText(A(1), {
timeout: 60_000
})
}
diff --git a/apps/desktop/e2e/core/harness.ts b/apps/desktop/e2e/core/harness.ts
index 8042a45e6b2..4037bfbb12e 100644
--- a/apps/desktop/e2e/core/harness.ts
+++ b/apps/desktop/e2e/core/harness.ts
@@ -59,7 +59,9 @@ export function createCoreSandbox(label: string): CoreSandbox {
// depend on the runner's keyring rather than on Hermes.
const bin = path.join(root, 'bin')
fs.mkdirSync(bin, { recursive: true })
- fs.writeFileSync(path.join(bin, 'gh'), '#!/bin/sh\necho "no oauth token found for github.com" >&2\nexit 1\n', { mode: 0o755 })
+ fs.writeFileSync(path.join(bin, 'gh'), '#!/bin/sh\necho "no oauth token found for github.com" >&2\nexit 1\n', {
+ mode: 0o755
+ })
return {
root,
@@ -75,7 +77,7 @@ export function createCoreSandbox(label: string): CoreSandbox {
}
}
-export function providerConfigYaml(providerUrl: string, extra = ''): string {
+export function providerConfigYaml(providerUrl: string, extra = '', approvals: 'manual' | 'off' = 'off'): string {
return `model:
default: mock-model
provider: mock
@@ -92,13 +94,18 @@ auxiliary:
title_generation:
enabled: false
approvals:
- mode: "off"
+ mode: "${approvals}"
${extra}`
}
-export function writeProviderHome(dir: string, providerUrl: string, extra = ''): void {
+export function writeProviderHome(
+ dir: string,
+ providerUrl: string,
+ extra = '',
+ approvals: 'manual' | 'off' = 'off'
+): void {
fs.mkdirSync(dir, { recursive: true })
- fs.writeFileSync(path.join(dir, 'config.yaml'), providerConfigYaml(providerUrl, extra))
+ fs.writeFileSync(path.join(dir, 'config.yaml'), providerConfigYaml(providerUrl, extra, approvals))
fs.writeFileSync(path.join(dir, '.env'), 'MOCK_API_KEY=core-e2e-key\n')
}
@@ -291,11 +298,13 @@ export function startTcpProxy(targetPort: number): Promise<TcpProxy> {
const server = net.createServer(client => {
const upstream = net.connect(targetPort, '127.0.0.1')
live.add(client)
+
const forget = () => {
live.delete(client)
client.destroy()
upstream.destroy()
}
+
client.on('error', forget)
upstream.on('error', forget)
client.on('close', forget)
@@ -343,6 +352,7 @@ export async function routePrimaryWebSocket(app: ElectronApplication, backendPor
const handlers = (ipcMain as any)._invokeHandlers as Map<string, (...args: any[]) => Promise<any>>
const from = `ws://127.0.0.1:${backendPort}/`
const to = `ws://127.0.0.1:${proxyPort}/`
+
const rewrite = (value: any): any => {
if (typeof value === 'string') {
return value.startsWith(from) ? to + value.slice(from.length) : value
@@ -449,9 +459,7 @@ export async function waitForInteractive(app: ElectronApplication, page: Page, t
await expect
.poll(
() =>
- app
- .evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false)
- .catch(() => false),
+ app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false).catch(() => false),
{ timeout, intervals: [250] }
)
.toBe(true)
@@ -539,7 +547,11 @@ export function storedSessionForMarker(sandbox: CoreSandbox, profile: string, ma
}
/** The backend's persisted display transcript (REST, the same read the renderer hydrates from). */
-export async function persistedTranscript(page: Page, sessionId: string, profile?: string): Promise<PersistedMessage[]> {
+export async function persistedTranscript(
+ page: Page,
+ sessionId: string,
+ profile?: string
+): Promise<PersistedMessage[]> {
const query = profile ? `&profile=${encodeURIComponent(profile)}` : ''
const result = await page.evaluate(
diff --git a/apps/desktop/e2e/core/interactive-prompts.spec.ts b/apps/desktop/e2e/core/interactive-prompts.spec.ts
new file mode 100644
index 00000000000..db5b08cf439
--- /dev/null
+++ b/apps/desktop/e2e/core/interactive-prompts.spec.ts
@@ -0,0 +1,166 @@
+/**
+ * C20 core: blocking interactive prompts round-trip through the real chain.
+ *
+ * Real Electron + real `hermes serve`, approvals in manual mode; only the LLM
+ * is faked. For each prompt kind the invariant is end to end, not "a card
+ * rendered":
+ * - clarify: exactly one card; the choice the user clicks is exactly what
+ * the model receives in the tool result on its next request; the turn
+ * completes; transcript oracle holds.
+ * - approval (run once): exactly one approval card; the gated command has
+ * NOT run before the click and HAS run after it (observable side effect);
+ * the turn completes; transcript oracle holds.
+ * - approval (deny): the command never runs; the turn still completes (no
+ * wedged busy state); transcript oracle holds.
+ */
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import { expect, type Page, test } from '@playwright/test'
+
+import {
+ coreAppEnv,
+ createCoreSandbox,
+ currentSessionId,
+ launchCoreApp,
+ recordWebSockets,
+ send,
+ waitForInteractive,
+ writeProviderHome
+} from './harness'
+import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { type RecordedCompletion, startScriptedProvider } from './provider'
+
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
+const U = (n: number) => `U${n}-${nonce}`
+const A = (n: number) => `A${n}-${nonce}`
+const AI = (n: number) => `A${n}i-${nonce}`
+
+function viewport(page: Page) {
+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+}
+
+/** Text of the tool results the model received in `completion`'s request. */
+function toolResults(completion: RecordedCompletion | undefined): string {
+ const messages: any[] = completion?.body?.messages ?? []
+
+ return messages
+ .filter(m => m?.role === 'tool')
+ .map(m => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content)))
+ .join('\n')
+}
+
+test('clarify and approval prompts round-trip exactly once', async () => {
+ const provider = await startScriptedProvider()
+ const sandbox = createCoreSandbox('prompts')
+ writeProviderHome(sandbox.hermesHome, provider.url, '', 'manual')
+ const { app, page } = await launchCoreApp(coreAppEnv(sandbox))
+ const ws = recordWebSockets(page)
+ const session: OracleTarget = { sessionId: '', expectUserMarkers: [] }
+
+ const finished = (marker: string, step = 0) =>
+ expect
+ .poll(() => provider.completions.some(c => c.marker === marker && c.step === step && c.finished), {
+ timeout: 120_000,
+ message: `provider finished ${marker} step ${step}`
+ })
+ .toBe(true)
+
+ const completion = (marker: string, step: number) =>
+ provider.completions.find(c => c.marker === marker && c.step === step)
+
+ try {
+ await waitForInteractive(app, page)
+ await installDuplicateSampler(page)
+
+ await test.step('clarify: the clicked choice is exactly what the model receives', async () => {
+ const question = `Q1-${nonce} which drink`
+ const pick = `mate-${nonce}`
+ const other = `chai-${nonce}`
+ provider.script(U(1), [
+ {
+ text: [`${AI(1)} `, 'asking'],
+ toolCalls: [{ name: 'clarify', args: { questions: [{ question, choices: [other, pick] }] } }]
+ },
+ { text: [`${A(1)} `, 'noted ', 'your ', 'choice'] }
+ ])
+ await send(page, `${U(1)} ask me`, 'Enter', ws)
+ // The open (unanswered) clarify form: single-question or batch shape.
+ const openForms = page.locator('form[data-clarify-choices], form[data-clarify-batch]').filter({ visible: true })
+ await expect(openForms).toHaveCount(1, { timeout: 120_000 })
+ await expect(viewport(page).getByText(question)).toHaveCount(1)
+ await openForms.getByRole('button', { name: new RegExp(pick) }).click()
+ const submit = openForms.locator('button[type="submit"]')
+ await expect(submit).toBeEnabled()
+ await submit.click()
+ await finished(U(1), 1)
+ const received = toolResults(completion(U(1), 1))
+ expect(received, 'model received the clicked choice').toContain(pick)
+ expect(received, 'model did not receive the other choice as the answer').not.toMatch(
+ new RegExp(`answer[^\\n]*${other}`, 'i')
+ )
+ await expect(
+ page.locator('form[data-clarify-choices], form[data-clarify-batch]').filter({ visible: true })
+ ).toHaveCount(0)
+ await expect(page.locator('[data-clarify-settled]').filter({ visible: true })).toHaveCount(1)
+ await expect.poll(() => currentSessionId(page)).not.toBe('')
+ session.sessionId = await currentSessionId(page)
+ session.expectUserMarkers.push(U(1))
+ await assertTranscriptOracle(page, ws, provider, session, 'clarify round trip')
+ await expect(viewport(page).getByText(question)).toHaveCount(1)
+ })
+
+ await test.step('approval (run once): the command runs only after the click', async () => {
+ const victim = path.join(sandbox.root, `victim-run-${nonce}`)
+ fs.mkdirSync(victim)
+ provider.script(U(2), [
+ {
+ text: [`${AI(2)} `, 'needs ', 'approval'],
+ toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${victim}` } }]
+ },
+ { text: [`${A(2)} `, 'deleted ', 'it'] }
+ ])
+ await send(page, `${U(2)} delete run dir`, 'Enter', ws)
+ const run = page.locator('[data-approval-run]').filter({ visible: true })
+ await expect(run).toHaveCount(1, { timeout: 120_000 })
+ expect(fs.existsSync(victim), 'gated command must not run before approval').toBe(true)
+ await run.click()
+ await finished(U(2), 1)
+ expect(fs.existsSync(victim), 'approved command ran').toBe(false)
+ await expect(page.locator('[data-approval-run]').filter({ visible: true })).toHaveCount(0)
+ session.expectUserMarkers.push(U(2))
+ await assertTranscriptOracle(page, ws, provider, session, 'approval run once')
+ })
+
+ await test.step('approval (deny): the command never runs, the turn still completes', async () => {
+ const victim = path.join(sandbox.root, `victim-deny-${nonce}`)
+ fs.mkdirSync(victim)
+ provider.script(U(3), [
+ {
+ text: [`${AI(3)} `, 'needs ', 'approval'],
+ toolCalls: [{ name: 'terminal', args: { command: `rm -rf ${victim}` } }]
+ },
+ { text: [`${A(3)} `, 'left ', 'it ', 'alone'] }
+ ])
+ await send(page, `${U(3)} delete deny dir`, 'Enter', ws)
+ const deny = page.locator('[data-approval-deny]').filter({ visible: true })
+ await expect(deny).toHaveCount(1, { timeout: 120_000 })
+ await deny.click()
+ await finished(U(3), 1)
+ expect(fs.existsSync(victim), 'denied command never ran').toBe(true)
+ expect(toolResults(completion(U(3), 1)), 'the denial reached the model as the tool result').not.toBe('')
+ await expect(page.locator('[data-approval-deny]').filter({ visible: true })).toHaveCount(0)
+ session.expectUserMarkers.push(U(3))
+ await assertTranscriptOracle(page, ws, provider, session, 'approval deny')
+ })
+ } finally {
+ await app.close().catch(() => undefined)
+ await provider.close()
+ sandbox.cleanup()
+ }
+})