Files
PaperClipAI/tests/speko-native/live-browser.mjs
T
TonioandClaude Fable 5.2 a336e295f6 feat(ui): turn Connectors into a Plugins marketplace (#22869)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents reach outside tools through connectors, which people add on
the Connectors page
> - That page is one long list. Each row mixes the catalog entry with
its accounts, so it is hard to scan and hard to tell what is installed
> - Some connectors also bring skills, but the page does not show them
> - This pull request renames the page to Plugins and changes the browse
view into a marketplace of small cards grouped by category. Each card
opens a plugin page that holds the accounts, the skills and the tool
permissions
> - The benefit is a catalog that people can scan fast, with one place
per connector for its accounts and its skills. Connector behavior does
not change

## Linked Issues or Issue Description

**Subsystem affected**

UI: the Connectors (Apps catalog) pages under `ui/src/pages/apps/` and
the navigation labels that point to them.

**Problem or motivation**

The Connectors browse page is a vertical list of large rows. A row shows
the catalog entry and every account under it. People must expand rows to
see what is connected. The page does not show which skills come with a
connector.

**Proposed solution**

- Rename the page from Connectors to Plugins in the navigation, the
breadcrumbs, and the page titles. A single app is still called a
connector.
- Remove the Browse / Review rail. The page header carries the title, a
Review shortcut, and an Add menu for a custom MCP server, a pasted
config, or an assistant connection.
- Show the catalog as a marketplace under one "All" tab: "Most used" and
"New and noteworthy" for first-party connectors, then one block per
category. Composio and Arcade connectors sit in the same blocks. A block
shows at most nine plugins, its total, and a "See all" link to a
category page at `/apps/category/:categoryId`.
- Use a compact card: logo, name, description, and one corner control.
The control is a plus to connect, a check when connected, or a warning
when an account needs attention.
- Open a plugin page at `/apps/plugin/:pluginKey` from each card. The
page has Connect in its header and groups Accounts, Connector, Skills,
Tool permissions, and Information as blocks. Tool permissions shows a
connected account's actions as Reads and Writes, each with a group
policy and per-action policies.
- Start sign-in straight from the card for a one-click connector: one
OAuth method that Paperclip can start itself, with nothing to fill in
and no warning to read. The success screen states who can use the
connection and links to where that changes.
- Search reads plugin titles only.
- Keep the account list on the Installed filter.

**Related pull requests**

A search of open and closed pull requests for the Connectors browse
page, a plugins or connectors marketplace, connector categories, and
one-click sign-in found no duplicate. #22863 compresses connector logo
files and does not overlap with these pages.

**Alternatives considered**

- An experimental setting that keeps the old page. The product owner
chose to replace the page for everyone.
- A new backend link between connectors and catalog skills. This pull
request stays in the front end. The pairing for GitHub is a constant in
`PluginSkills.tsx`.
- Real categories for Composio apps. Its public catalog file has names
only, so those apps are sorted by keywords in the name and the rest go
to "Other". Arcade's catalog states a category, which is now carried
through `AggregatorAppCatalogEntry.category`.

## What Changed

- `Browse.tsx`: keeps all data loading, connect logic, and dialogs. The
render now has five views: marketplace, category page, flat results
grid, Installed list, and plugin page. The default source is `all`; the
`paperclip` source is removed.
- `PluginMarketplace.tsx` (new): `PluginTile`, `PluginShelf` (count and
"See all"), `PluginCategories`, and the category labels.
- `PluginsHeader.tsx` (new): page title, Review shortcut with the
pending count, and the Add menu.
- `PluginPageSections.tsx` (new): plugin page header, Connector row, and
Information facts read from the app definition.
- `PluginPermissions.tsx` (new): Reads and Writes blocks for a connected
account. Saves go through `useConnectionPermissionSave` and restate
agent access exactly as the per-connection page does. The four helpers
it shares with that page moved from `AppDetail.tsx` to
`app-detail/saved-permissions.ts` with no behavior change.
- `PluginSkills.tsx` (new): lists built-in connector skills, skills that
a connected server publishes, and paired catalog skills. "Add skill"
calls the existing catalog install endpoint.
- `plugin-categories.ts` (new): maps Arcade categories onto the Plugins
categories and guesses a category from the name for apps that state
none.
- `features/connections/one-click-oauth.ts` (new): the one-click rule
and the hand-over of the sign-in window from the card's click to the
connect flow. A browser only opens that window during a click, so the
card opens it and `ConnectionSetupFlow` takes it over. If the window is
blocked, or the page is reloaded, the ordinary confirmation screen
shows.
- `ConnectionSetupFlow.tsx`: takes the handed-over window, starts
sign-in when the app qualifies, and adds a "Change" link beside the
stated default on the success screen.
- `apps-rail.ts` (new), `AppsSidebar*.tsx`, `Layout*.tsx`: the
marketplace pages have no second rail. Chat setup and detail keep
theirs, and the developer pages keep one while a developer tab is on.
- `ConnectorCard`: new `variant="page"` that renders the accounts as one
block with "Add account" at the bottom.
- `ConnectorsToolbar.tsx`: source filters first, a wider "Search
plugins" field on the right.
- `App.tsx`, `Layout.tsx`, `Layout.production.tsx`: new
`apps/plugin/:pluginKey` and `apps/category/:categoryId` routes and
reserved subpaths.
- Navigation and breadcrumb labels: "Connectors" becomes "Plugins" in 19
files, and the instance plugin system becomes "System plugins".
- `packages/shared/src/aggregator-app-catalog.ts`: optional `category`
on a catalog entry, set from Arcade's catalog.
- `ui/storybook/prototypes/ConnectorCatalogNavigation.tsx`: keeps its
own five-source list so the older prototype still builds.
- Tests: label renames in the specs and stories that named Connectors or
"Search connectors". Seven specs now reach the custom-server setup
through the Add menu. New specs: `one-click-connect`, `plugins-browse`.
`apps-prosumer-mcp-flow` also covers the plugin page permissions and the
success-screen link.

Kept on purpose, so current flows and specs continue to work: the
`Connector list` list label, `data-app-slug` and `data-connected` on
each card, and the `<Verb> <App name>` button names.

## Verification

- `cd ui && pnpm typecheck`: pass.
- `pnpm run check:token-gates`: pass.
- `cd ui && npx vitest run`: 564 files, 7,059 tests pass, 1 skipped.
- `cd packages/shared && npx vitest run
src/aggregator-app-catalog.test.ts`: 9 tests pass.
- `PAPERCLIP_RUNNER_BINARY=/usr/bin/true npx playwright test --config
tests/e2e/playwright.config.ts` for the 15 spec files under
`tests/e2e/*.spec.ts` that touch the Plugins pages, plus
`one-click-connect` and `plugins-browse`: all pass (3 skipped by their
own conditions).
- Storybook: built this branch and master and ran the interaction tests
of the 253 stories in the files that mount the browse page. Master
passes 230; this branch passes the same 230. The 23 that fail do so on
master too.
- Manual: opened Plugins, a category page, a plugin page, the Installed
filter, and Review on a local instance.
- Not run locally: `execution-recovery/recovery.spec.ts`,
`in-feed-native/connections.spec.ts`, the runner e2e tests, and the
repo-wide typecheck (it needs the Rust toolchain). A real provider
sign-in was not completed; the one-click test stops at the point the
flow starts. `pnpm verify` exits 2 and names CI as the source of broad
coverage.

## Risks

- The page changes for every user. People who know the old list must
learn the new layout. The Installed filter keeps the old account list.
- The instance plugin system is renamed "System plugins" in the settings
navigation, breadcrumbs, and its management page, so the two areas no
longer share a name. URLs and lower-case mentions of "plugin" inside
sentences are unchanged.
- One-click connect skips the screen that states the access default
("Connects for everyone in your organization, available to all agents")
and offers Change. The default is applied without being shown first; the
success screen states it and links to the permissions page.
- Most Composio apps (about 1,100 of 1,583) land in "Other", and the
keyword guess is sometimes wrong. Correct categories need category data
in the catalog file.
- The plugin page can now save action permissions. It uses the same save
path and access derivation as the per-connection page and waits for all
four reads before it enables the controls. The account picker for
several accounts and the read-only view have no test.
- The Smoke Lab developer page has no link from the browse page; it is
reachable by URL.
- e2e specs that this pull request did not run locally can fail on
selectors. CI must confirm them.
- "New and noteworthy" is a fixed list in code. The catalog has no date
to sort by.
- Skill pairing is a front-end constant. Nothing records that a skill
came from a connector, so removing a connector does not remove the
skill.
- The per-connection permissions page is not restyled in this pull
request.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Fable 5.2 (`claude-fable-5-2`) through Claude Code, with tool
use, code execution, and subagents for read-only code search.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [ ] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [ ] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 19:16:24 +00:00

275 lines
20 KiB
JavaScript

/** Explicit live acceptance; real browser UI + Speko, synthetic microphone only.
* Requires the disposable server and prior provider-persona authorization.
* No Playwright traces: setup carries a provider credential.
*/
import { chromium, expect } from '@playwright/test';
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { homedir } from 'node:os';
import { dirname, resolve } from 'node:path';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
const origin = `http://127.0.0.1:${Number(process.env.SPEKO_NATIVE_PORT ?? 3449)}`;
const privateRoot = resolve(homedir(), '.paperclip/speko-proof');
const resumeIssueId = process.env.SPEKO_NATIVE_RESUME_ISSUE_ID;
const diskScenario = process.env.SPEKO_NATIVE_SCENARIO === 'disk';
const delayedTemplate = process.env.SPEKO_NATIVE_SCENARIO === 'template-delayed';
const templateScenario = diskScenario || delayedTemplate || process.env.SPEKO_NATIVE_SCENARIO === 'template';
const expectedWord = process.env.SPEKO_NATIVE_EXPECTED_WORD ?? 'marigold';
const evidencePath = process.env.SPEKO_NATIVE_EVIDENCE_PATH;
if (delayedTemplate && !evidencePath) throw new Error('The delayed real-agent scenario requires SPEKO_NATIVE_EVIDENCE_PATH for durable follow-up assertions');
const fixturePath = process.env.SPEKO_NATIVE_FIXTURE_PATH ?? resolve(privateRoot, templateScenario ? 'native-template-fixture.json' : 'native-fixture.json');
const fixture = JSON.parse(await readFile(fixturePath, 'utf8'));
const out = resolve(privateRoot, `native-browser-${Date.now()}`);
await mkdir(out, { mode: 0o700 });
const changedFiles = execFileSync('git', ['ls-files', '-m', '-o', '--exclude-standard', '-z'], { encoding: 'utf8' }).split('\0').filter(Boolean);
const hashes = {};
for (const file of changedFiles) { try { hashes[file] = createHash('sha256').update(await readFile(file)).digest('hex'); } catch { hashes[file] = 'deleted'; } }
await writeFile(resolve(out, 'source.json'), JSON.stringify({ commit: execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(), changedFiles: hashes }, null, 2), { mode: 0o600 });
const key = (await readFile(resolve(homedir(), '.secrets'), 'utf8')).match(/^export SPEKO_MCP_API_KEY=['"]([^'"]+)['"]/m)?.[1];
if (!key) throw new Error('Saved Speko credential missing');
const browser = await chromium.launch({ headless: true, args: ['--autoplay-policy=no-user-gesture-required'] });
const page = await browser.newPage({ viewport: { width: 1280, height: 960 } });
const events = [], started = Date.now();
const idleProbe = process.env.SPEKO_NATIVE_IDLE_PROBE === "1";
if (idleProbe) await page.route("**/voice-sessions/*/notification", (route) => route.fulfill({ status: 200, contentType: "application/json", body: "null" }));
let session, progress;
let executionProvider = "unknown";
const event = (kind, details = {}) => { events.push({ kind, elapsedMs: Date.now() - started, ...details }); console.log(JSON.stringify({ kind, ...details })); };
page.on('response', async (response) => {
if (response.request().method() === 'POST' && /\/voice-sessions$/.test(new URL(response.url()).pathname) && response.ok()) {
const result = await response.json(); session = result.session;
await writeFile(resolve(out, 'session.json'), JSON.stringify(session), { mode: 0o600 });
event('session_created', { sessionId: session.id, issueId: session.issueId });
}
});
await page.addInitScript(() => {
const state = window.spekoFixture = { tracks: [], events: [], context: null, destination: null, chunks: [], recorder: null, audioEdges: [], recordingStartedAt: null };
navigator.mediaDevices.getUserMedia = async () => {
state.context ??= new AudioContext({ sampleRate: 48000 });
await state.context.resume();
if (!state.destination) {
state.destination = state.context.createMediaStreamDestination();
const silence = state.context.createConstantSource(); silence.offset.value = 0.00001; silence.connect(state.destination); silence.start(); state.silence = silence;
}
const stream = state.destination.stream.clone(); state.tracks.push(...stream.getTracks());
return stream;
};
new MutationObserver(() => {
const audio = [...document.querySelectorAll('audio')].find((node) => node.srcObject);
if (!audio || state.recorder) return;
state.recorder = new MediaRecorder(audio.srcObject);
state.recorder.ondataavailable = (event) => { if (event.data.size) state.chunks.push(event.data); };
state.recordingStartedAt = Date.now();
state.recorder.start();
// Measure received audio, independently of the model's transcript/state.
state.context ??= new AudioContext({ sampleRate: 48000 });
const source = state.context.createMediaStreamSource(audio.srcObject);
const analyser = state.context.createAnalyser(); analyser.fftSize = 1024;
const sink = state.context.createGain(); sink.gain.value = 0;
source.connect(analyser); analyser.connect(sink); sink.connect(state.context.destination);
const samples = new Float32Array(analyser.fftSize); let audible = false;
state.audioTimer = setInterval(() => {
analyser.getFloatTimeDomainData(samples);
const rms = Math.sqrt(samples.reduce((sum, value) => sum + value * value, 0) / samples.length);
const next = rms > 0.01;
if (next) state.lastAudibleAt = Date.now();
if (next !== audible) { state.audioEdges.push({ at: Date.now(), audible: next }); audible = next; }
}, 20);
}).observe(document, { childList: true, subtree: true });
});
async function speak(name) {
const audioPath = process.env.SPEKO_NATIVE_AUDIO_DIR ? resolve(process.env.SPEKO_NATIVE_AUDIO_DIR, `${name}.pcm`) : new URL(`../../.paperclip-local/speko-proof-audio/${name}.pcm`, import.meta.url);
const bytes = [...await readFile(audioPath)];
event('input_started', { name });
await page.evaluate(async (bytes) => {
const state = window.spekoFixture, raw = new DataView(new Uint8Array(bytes).buffer);
const buffer = state.context.createBuffer(1, bytes.length / 2, 48000);
const channel = buffer.getChannelData(0);
for (let i = 0; i < channel.length; i++) channel[i] = raw.getInt16(i * 2, true) / 32768;
const source = state.context.createBufferSource(); source.buffer = buffer; source.connect(state.destination);
await new Promise((done) => { source.onended = done; source.start(); }); source.disconnect();
}, bytes);
event('input_ended', { name });
}
try {
await expect.poll(async () => fetch(`${origin}/api/health`).then((response) => response.ok).catch(() => false), { timeout: 30000 }).toBe(true);
await page.goto(origin);
if (resumeIssueId) {
await page.goto(`${origin}/${fixture.companyPrefix}/issues/${resumeIssueId}`);
await page.getByRole('button', { name: `Talk to ${fixture.agentName}`, exact: true }).click();
} else if (process.env.SPEKO_NATIVE_CONNECTED === '1') {
if (!fixture.endpointId) throw new Error('Connected qualification requires the verified endpoint fixture');
const taskResponse = await page.request.post(`${origin}/api/companies/${fixture.companyId}/issues`, {headers: {Origin: origin}, data: {title: "Speko live browser qualification", assigneeAgentId: fixture.agentId, status: "todo"}});
if (!taskResponse.ok()) throw new Error(`Qualification task creation rejected (${taskResponse.status()})`);
const task = await taskResponse.json();
await page.goto(`${origin}/${fixture.companyPrefix}/issues/${task.id}`);
await page.getByRole('button', {name: `Talk to ${fixture.agentName}`, exact: true}).click();
event('qualification_task_created', {issueId: task.id});
event('existing_connection_used', {endpointId: fixture.endpointId});
} else {
await page.getByRole('link', { name: 'Plugins', exact: true }).first().click();
if (fixture.endpointId) {
// Resume the saved setup using the same UI route after an earlier failed test.
await page.goto(`${origin}/${fixture.companyPrefix}/apps/chat/connect?provider=speko&resume=${fixture.endpointId}`);
} else {
await page.locator('[data-app-slug="speko"]').getByRole('button', { name: /^(Connect Speko|Add connection Speko)$/ }).click();
await page.getByRole('button', { name: 'Choose an active agent', exact: true }).click();
await page.getByRole('button', { name: `Select ${fixture.agentName ?? 'Existing Paperclip Agent'}`, exact: true }).click();
await page.getByRole('button', { name: 'Continue', exact: true }).click();
}
await expect(page.getByLabel('Speko API key', { exact: true }).or(page.getByRole('button', { name: 'Start voice', exact: true })).filter({ visible: true }).first()).toBeVisible({ timeout: 30000 });
if (await page.getByLabel('Speko API key', { exact: true }).isVisible()) {
await page.getByRole('textbox', { name: 'Speko agent ID', exact: true }).fill(fixture.providerAgentId);
await page.getByLabel('Speko API key', { exact: true }).fill(key);
const responsePromise = page.waitForResponse((r) => r.request().method() === 'POST' && /\/chat-endpoints\/[^/]+\/setup$/.test(new URL(r.url()).pathname), { timeout: 60000 });
await page.getByRole('button', { name: /^(Connect|Reconnect) Speko$/ }).click();
const response = await responsePromise;
if (!response.ok()) throw new Error(`Setup rejected (${response.status()}): ${(await response.json()).error}`);
const endpoint = await response.json(); fixture.endpointId = endpoint.id;
await writeFile(fixturePath, JSON.stringify(fixture), { mode: 0o600 });
event('native_setup_verified', { endpointId: endpoint.id, status: endpoint.status });
}
}
await expect(page.getByRole('button', { name: 'Start voice', exact: true })).toBeVisible({ timeout: 30000 });
await page.screenshot({ path: resolve(out, 'before-call.png'), fullPage: true });
await writeFile(resolve(out, 'intent.json'), JSON.stringify({ action: 'start_browser_voice', at: new Date().toISOString(), endpointId: fixture.endpointId }), { mode: 0o600 });
if (process.env.SPEKO_NATIVE_FRESH_CONVERSATION === '1') await page.getByRole('combobox', { name: 'Conversation', exact: true }).selectOption('new');
await page.getByRole('button', { name: 'Start voice', exact: true }).click();
await expect(page.getByRole('button', { name: 'Mute', exact: true })).toBeEnabled({ timeout: 30000 });
expect(session?.assignedAgentId).toBe(fixture.agentId);
event('media_connected');
const agentResponse = await page.request.get(`${origin}/api/agents/${session.assignedAgentId}`);
if (agentResponse.ok()) {
const agent = await agentResponse.json();
if (typeof agent.adapterType === 'string') executionProvider = agent.adapterType;
}
event('execution_provider_inspected', {executionProvider});
if (resumeIssueId) { expect(session?.issueId).toBe(resumeIssueId); event('existing_task_resumed', { issueId: resumeIssueId }); }
progress = setInterval(() => { void page.locator('body').innerText().then((text) => writeFile(resolve(out, 'latest-visible.txt'), text, { mode: 0o600 })).catch(() => {}); }, 3000);
await expect(page.getByRole('list', { name: 'Conversation transcript' }).getByRole('listitem')).not.toHaveCount(0, { timeout: 20000 });
await expect(page.getByRole('status').filter({ hasText: /^Listening$/ })).toBeVisible({ timeout: 20000 });
await page.waitForFunction(() => window.spekoFixture.lastAudibleAt && Date.now() - window.spekoFixture.lastAudibleAt > 900, undefined, { timeout: 15000 });
await speak(diskScenario ? 'disk-request' : resumeIssueId ? 'template-resume' : delayedTemplate ? 'template-delayed-start' : templateScenario ? 'template-start' : 'start');
await expect(page.getByRole('status').filter({ hasText: /^Speaking$/ })).toBeVisible({ timeout: 20000 });
event('acknowledgment_speaking');
if (evidencePath) {
await expect.poll(async () => {
const evidence = JSON.parse(await readFile(evidencePath, 'utf8'));
return evidence.tools.filter(tool => tool.sessionId === session.id && tool.tool === 'submit_request' && tool.response?.status === 'accepted').length;
}, { timeout: 20000 }).toBeGreaterThanOrEqual(1);
event('first_request_durably_accepted');
}
if (diskScenario) await speak('disk-followup');
if (!resumeIssueId && !diskScenario) await speak(delayedTemplate ? 'template-delayed-followup' : templateScenario ? 'template-followup' : 'followup');
const transcript = page.getByRole('list', { name: 'Conversation transcript', exact: true });
if (evidencePath && !resumeIssueId) {
await expect.poll(async () => {
try {
const evidence = JSON.parse(await readFile(evidencePath, 'utf8'));
return evidence.tools.filter((tool) => tool.sessionId === session.id && tool.tool === 'submit_request' && tool.response?.status === 'accepted').length;
} catch { return 0; }
}, { timeout: 30000 }).toBeGreaterThanOrEqual(2);
event('followup_durably_accepted');
}
const agentTranscript = transcript.getByRole('listitem').filter({ has: page.locator('span').filter({ hasText: fixture.agentName ?? 'Existing Paperclip Agent' }) });
await expect(agentTranscript).toContainText([diskScenario ? /(?:10|ten) gigabytes[\s\S]*?(?:9[.,]7|nine point seven) gigabytes/i : templateScenario ? new RegExp(expectedWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i') : /verification number/i], { timeout: templateScenario ? 180000 : 100000 });
if (diskScenario) {
await expect.poll(async () => {
const response = await page.request.get(`${origin}/api/issues/${session.issueId}/comments`);
if (!response.ok()) return false;
return (await response.json()).some(comment => comment.authorAgentId === fixture.agentId
&& Date.parse(comment.createdAt) >= started && /(?:disk|space|storage|filesystem)/i.test(comment.body)
&& /(?:available|free)/i.test(comment.body));
}, {timeout: 180000}).toBe(true);
event('real_agent_disk_result_persisted');
}
if (delayedTemplate) {
await expect.poll(async () => {
const response = await page.request.get(`${origin}/api/issues/${session.issueId}/comments`);
if (!response.ok()) return false;
return (await response.json()).some((comment) => comment.authorAgentId === fixture.agentId && /silver lantern/i.test(comment.body));
}, { timeout: 60000 }).toBe(true);
await expect(agentTranscript.filter({ hasText: new RegExp(expectedWord, "i") })).toContainText([/silver lantern/i], { timeout: 60000 });
event('followup_applied_by_agent');
const comments = await (await page.request.get(`${origin}/api/issues/${session.issueId}/comments`)).json();
const runIds = [...new Set(comments.map((comment) => comment.createdByRunId).filter(Boolean))];
const runs = await Promise.all(runIds.map(async (id) => (await page.request.get(`${origin}/api/heartbeat-runs/${id}`)).json()));
const executionMs = Math.max(...runs.filter((run) => run.status === 'succeeded').map((run) => Date.parse(run.finishedAt) - Date.parse(run.startedAt)));
expect(executionMs).toBeGreaterThanOrEqual(65000);
event('real_delayed_execution_verified', { executionMs, runIds });
}
if (!templateScenario && evidencePath) {
const executionPath = resolve(dirname(evidencePath), 'execution.jsonl');
await expect.poll(async () => {
const executions = (await readFile(executionPath, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
return executions.some(run => run.event === 'completed' && run.issueId === session.issueId && run.elapsedMs >= 60_000 && run.requests >= 2);
}, { timeout: 30_000 }).toBe(true);
const executions = (await readFile(executionPath, 'utf8')).trim().split('\n').map(line => JSON.parse(line));
const execution = executions.find(run => run.event === 'completed' && run.issueId === session.issueId);
await expect.poll(async () => (await agentTranscript.allTextContents()).join(' ').replaceAll('*', '').includes(String(execution.number)), { timeout: 30_000 }).toBe(true);
// Wait for the queued amendment to be retrieved too. Ending as soon as the
// first answer appears would hide the very self-interruption being tested.
await expect.poll(async () => {
const evidence = JSON.parse(await readFile(evidencePath, 'utf8'));
return new Set(evidence.tools.filter(tool => tool.sessionId === session.id && tool.tool === 'get_updates').flatMap(tool => (tool.response?.updates ?? []).map(update => update.publicationId))).size;
}, { timeout: 30_000 }).toBeGreaterThanOrEqual(2);
event('delayed_execution_and_two_publications_verified', { executionMs: execution.elapsedMs, requests: execution.requests, runId: execution.runId });
}
if (!templateScenario) await expect(transcript).toContainText(/(?:received|included)[\s\S]{0,100}(?:one|1)[\s\S]{0,60}follow.up|(?:one|1)[\s\S]{0,60}follow.up[\s\S]{0,100}(?:received|included)/i, { timeout: 30000 });
await expect(page.getByRole('status').filter({ hasText: /^Listening$/ })).toBeVisible({ timeout: 30000 });
await expect(agentTranscript.last()).not.toContainText(' · Speaking', { timeout: 30000 });
await page.waitForFunction(() => window.spekoFixture.lastAudibleAt && Date.now() - window.spekoFixture.lastAudibleAt > 1800, undefined, { timeout: 20000 });
event('delayed_result_visible');
await page.screenshot({ path: resolve(out, 'delayed-result.png'), fullPage: true });
await page.getByRole('button', { name: 'Mute', exact: true }).click();
await expect(page.getByRole('button', { name: 'Unmute', exact: true })).toHaveAttribute('aria-pressed', 'true');
expect(await page.evaluate(() => window.spekoFixture.tracks.every((track) => !track.enabled))).toBe(true);
await page.getByRole('button', { name: 'Unmute', exact: true }).click();
event('mute_verified');
} catch (error) {
event('failed', { message: error.message.replaceAll(key, '[redacted]') });
await page.screenshot({ path: resolve(out, 'failure.png'), fullPage: true }).catch(() => {});
process.exitCode = 1;
} finally {
clearInterval(progress);
try {
const text = await page.locator('body').innerText({ timeout: 2000 }).catch(() => 'unavailable');
await writeFile(resolve(out, 'visible.txt'), text.replaceAll(key, '[redacted]'), { mode: 0o600 });
const audio = await page.evaluate(async () => {
const state = window.spekoFixture;
if (!state?.recorder) return null;
if (state.recorder.state !== 'inactive') await new Promise((done) => { state.recorder.onstop = done; state.recorder.stop(); });
return [...new Uint8Array(await new Blob(state.chunks, { type: 'audio/webm' }).arrayBuffer())];
}).catch(() => null);
const audioMeasurements = await page.evaluate(() => {
const state = window.spekoFixture; if (!state) return null;
clearInterval(state.audioTimer);
return { recordingStartedAt: state.recordingStartedAt, edges: state.audioEdges, resolutionMs: 20, rmsThreshold: 0.01 };
}).catch(() => null);
if (audioMeasurements) await writeFile(resolve(out, 'audio-measurements.json'), JSON.stringify(audioMeasurements), { mode: 0o600 });
if (audio) await writeFile(resolve(out, 'received.webm'), Buffer.from(audio), { mode: 0o600 });
} catch { event('evidence_failed'); process.exitCode = 1; } finally {
// Evidence failures must never bypass hangup of a paid provider session.
if (session) {
try {
const button = page.getByRole('button', { name: /^(End call|Retry ending call)$/ });
if (await button.count()) await button.click();
} catch { event('ui_cleanup_unavailable'); }
try {
const response = await page.request.post(`${origin}/api/companies/${fixture.companyId}/voice-sessions/${session.id}/end`, { headers: { Origin: origin }, data: {} });
event('end_requested', { status: response.status() });
await expect.poll(async () => {
const inspected = await page.request.get(`${origin}/api/companies/${fixture.companyId}/voice-sessions/${session.id}`);
return inspected.ok() ? (await inspected.json()).state : 'unavailable';
}, { timeout: 30000, intervals: [500, 1000, 2000] }).toMatch(/^(ended|failed|expired)$/);
expect(await page.evaluate(() => window.spekoFixture.tracks.every((track) => track.readyState === 'ended'))).toBe(true);
event('cleanup_verified');
} catch { event('cleanup_unconfirmed'); process.exitCode = 1; }
}
try {
await writeFile(resolve(out, 'report.json'), JSON.stringify({ startedAt: new Date(started).toISOString(), events, session, browserNotificationDisabledForIdleProbe: idleProbe, syntheticMicrophone: true, audioReview: 'required independently; script success does not confirm complete spoken playback', resumedIssueId: resumeIssueId, diskScenario, delayedTemplate, expectedWord: templateScenario ? expectedWord : undefined, executionProvider, server: 'real', speko: 'live' }, null, 2), { mode: 0o600 });
console.log(JSON.stringify({ evidence: out }));
} finally { await browser.close(); }
}
}