fix(speko): preserve cleanup on media failure and report actual runtime

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 21:34:07 -05:00
1 parent 3b3a9c1af9
commit 27f6d9aa36
5 files changed
+61 -4

No files matched your search

@@ -85,3 +85,5 @@ Harness review repairs: successful local cleanup operations are tracked individu
Interrupted setup qualification: safe secret-presence serialization and production-component recovery regressions pass, alongside UI/server typecheck and token gates. The 155-story build and all 32 affected provider-setup interaction/accessibility checks passed across both themes and desktop/mobile widths.
Callback rotation review repair: ownership receipts now bind the provider identity and exact old callback independently from the replacement secret. Legacy receipts use the previous vaulted key and are upgraded before provider changes. Five focused real-database ownership/rotation/uncertain-creation tests and server typecheck passed; current and legacy simultaneous URL/key rotation and foreign callback rejection are covered.
Qualification provenance and media repair: the live browser report reads the assigned agent’s actual adapter type instead of inferring Claude from the scenario name. Synthetic media pump failures are observed immediately, release blocked input, and enter the hangup/evidence finally path. Ten focused cleanup/media/redaction tests pass; this repair placed no live calls.
+8 -1
View File
@@ -33,6 +33,7 @@ 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()) {
@@ -137,6 +138,12 @@ try {
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 });
@@ -260,7 +267,7 @@ try {
} 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: templateScenario ? 'claude_local' : 'fixture', server: 'real', speko: 'live' }, null, 2), { mode: 0o600 });
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(); }
}
+7 -3
View File
@@ -9,6 +9,7 @@ import { setTimeout as sleep } from "node:timers/promises";
import { once } from "node:events";
import { createHash } from "node:crypto";
import { Room, RoomEvent, AudioSource, AudioFrame, AudioStream, LocalAudioTrack, TrackPublishOptions, TrackSource, TrackKind, dispose } from "@livekit/rtc-node";
import { createMediaFailure } from "./media-failure.mjs";
import { createProof, createProofServer, DELAY_MS } from "./proof.mjs";
const API = "https://api.speko.dev";
@@ -60,6 +61,7 @@ let stopping = false;
let utterance;
let expectedRequests = 0;
let protocolFailure;
const mediaFailure = createMediaFailure(() => event("audio_input_failed"));
let mediaDisconnected = false;
let interrupted = false;
const interrupt = () => { interrupted = true; };
@@ -130,6 +132,7 @@ async function until(predicate, timeout, label) {
while (!predicate()) {
if (interrupted) throw new Error("Probe interrupted");
if (protocolFailure) throw new Error(protocolFailure);
if (mediaFailure.error) throw mediaFailure.error;
if (mediaDisconnected) throw new Error("Media disconnected before the scenario completed");
if (performance.now() >= end) throw new Error(`Timed out waiting for ${label}`);
await sleep(100);
@@ -141,7 +144,7 @@ async function input(text, file, label) {
if (mode === "text") await room.localParticipant.sendText(text, { topic: "lk.chat" });
else {
const data = inputAudio.get(file);
await new Promise((done) => { utterance = { data, offset: 0, done }; });
await mediaFailure.waitFor(() => new Promise((done) => { utterance = { data, offset: 0, done }; }));
}
event("input_end", { label });
}
@@ -163,7 +166,7 @@ try {
const options = new TrackPublishOptions();
options.source = TrackSource.SOURCE_MICROPHONE;
await room.localParticipant.publishTrack(track, options);
pump = (async () => {
pump = mediaFailure.observe((async () => {
while (!stopping) {
const frame = new Int16Array(960);
let finished;
@@ -176,7 +179,7 @@ try {
await source.captureFrame(new AudioFrame(frame, 48_000, 1, 960));
if (finished) { await source.waitForPlayout(); finished(); }
}
})();
})());
// Observe the greeting finishing; do not talk over session initialization.
await until(() => firstAudio !== undefined && performance.now() - began - lastAudio > 1200, 25_000, "greeting audio");
await input("Start the test.", process.env.SPEKO_PROOF_START_AUDIO, "start");
@@ -250,6 +253,7 @@ try {
await writeFile(resolve(out, "output.pcm"), Buffer.concat(audioFrames.map((f) => f.data)), {mode: 0o600});
if (resultAt !== undefined) await writeFile(resolve(out, "result.pcm"), Buffer.concat(audioFrames.filter((f) => f.at >= resultAt - 250).map((f) => f.data)), {mode: 0o600});
} catch (error) { cleanupFailures.push({operation: "audio_evidence", reason: error.message}); }
failure ??= mediaFailure.error?.message;
const report = { cleanupFailures, startedAt, sourceDigests, sessionId, mode, provider, notifyReady, notifyViaJoin, interruptAcknowledgment, failure: failure ?? null, firstAudio, resultAt, resultAudioAt, lastAudio, audioBursts, audioFrames: audioFrames.length, proof: proof.evidence(), events, syntheticTranscript: transcript, qualification: "requires_audio_and_transport_review" };
await writeFile(resolve(out, "report.json"), JSON.stringify(report, null, 2), { mode: 0o600 });
console.log(JSON.stringify({ reportPath: resolve(out, "report.json"), resultReturned: report.proof.resultReturned, acceptedRequests: report.proof.acceptedRequests, failure: report.failure }));
+17
View File
@@ -0,0 +1,17 @@
/** Observe media rejection immediately and release any pending scenario wait. */
export function createMediaFailure(onFailure) {
let error, reject;
const failure = new Promise((_, fail) => { reject = fail; });
failure.catch(() => {}); // A failure can occur between scenario waits.
return {
get error() { return error; },
observe(pump) {
return pump.catch(cause => {
error ??= cause;
reject(error);
onFailure(error);
});
},
waitFor(action) { return Promise.race([Promise.resolve().then(action), failure]); },
};
}
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createMediaFailure} from './media-failure.mjs';
for (const operation of ['captureFrame', 'waitForPlayout']) {
test(`${operation} failure releases pending input and runs hangup and evidence cleanup`, async () => {
let fail, hungUp = false, reportSaved = false, observed;
const media = createMediaFailure(error => { observed = error; });
const sourceFailure = new Error(`${operation} failed`);
const source = {captureFrame: async () => {}, waitForPlayout: async () => {}};
source[operation] = () => new Promise((_, reject) => { fail = reject; });
const pump = media.observe((async () => { await source.captureFrame(); await source.waitForPlayout(); })());
const input = media.waitFor(() => new Promise(() => {}));
while (!fail) await Promise.resolve();
fail(sourceFailure);
let failure;
try { await input; }
catch (error) { failure = error; }
finally { hungUp = true; reportSaved = true; }
await pump;
assert.equal(failure, sourceFailure);
assert.equal(observed, sourceFailure);
assert.equal(media.error, sourceFailure);
assert.equal(hungUp && reportSaved, true);
await assert.rejects(media.waitFor(() => new Promise(() => {})), sourceFailure);
});
}