Skip to content

Commit e83e376

Browse files
committed
feat: add abort signal handling for agent speech transcription and audio streaming
1 parent 97dad3c commit e83e376

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

index.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,14 +417,26 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
417417
filename: req.file.originalname,
418418
mimeType: req.file.mimetype,
419419
language: "auto",
420+
abortSignal,
420421
});
421422
} catch (error) {
423+
if (abortSignal.aborted) {
424+
logger.info("Agent speech transcription aborted by the client");
425+
stream.end();
426+
return null;
427+
}
428+
422429
logger.error(`Agent speech transcription failed:\n${error.message}`);
423430
stream.error("Speech transcription failed. Check server logs for details.");
424431
stream.end();
425432
return null;
426433
}
427434

435+
if (abortSignal.aborted) {
436+
stream.end();
437+
return null;
438+
}
439+
428440
const prompt = transcription.text;
429441
if (!prompt) {
430442
stream.error("Speech transcription is empty");
@@ -476,23 +488,39 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
476488
stream: true,
477489
streamFormat: "audio",
478490
format: "mp3",
491+
abortSignal,
479492
});
480493

481494
stream.audioStart(speech.mimeType, speech.format);
482495

483496
const reader = speech.audioStream.getReader();
497+
const cancelAudioStream = () => {
498+
void reader.cancel();
499+
};
484500

485501
try {
502+
abortSignal.addEventListener("abort", cancelAudioStream, { once: true });
503+
486504
while (true) {
505+
if (abortSignal.aborted) {
506+
await reader.cancel();
507+
break;
508+
}
509+
487510
const { value, done } = await reader.read();
488511

489512
if (done) {
490513
break;
491514
}
492515

516+
if (abortSignal.aborted) {
517+
break;
518+
}
519+
493520
stream.audioDelta(value);
494521
}
495522
} finally {
523+
abortSignal.removeEventListener("abort", cancelAudioStream);
496524
reader.releaseLock();
497525
}
498526

0 commit comments

Comments
 (0)