Files
shumai/packages/core/src/transcript/transcript.test.ts
T

452 lines
17 KiB
TypeScript
Raw Normal View History

import { prisma, UserType, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
2026-12-04 13:49:25 +08:00
import { setupTestDbHooks } from '@shumai/db/test'
import { transcriptionErrors } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { transcriptService } from './transcript'
describe('TranscriptService', () => {
setupTestDbHooks()
let assetId: string
let projectId: string
let agentId: string
2026-12-04 13:49:25 +08:00
const model = 'whisper-tiny'
const segments = [{ startMs: 125, endMs: 1425, text: 'Original segment' }]
const media: PrismaJson.MediaInfo = {
proxyType: 'video',
duration: 2,
filesize: 0,
frames: 50,
imageTranscodes: [],
videoTranscodes: [{ key: 'files/transcript-video-480p.mp4', width: 854, height: 480 }],
finishedAt: '2026-01-01T00:00:00Z',
metadata: null,
original: null,
}
beforeEach(async () => {
vi.stubEnv('EMBEDDING_PROVIDER', 'gemma-embedding-2-openai')
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
2026-12-04 13:49:25 +08:00
const team = await prisma.team.create({ data: { name: 'Transcript test' } })
const agent = await prisma.agent.create({
data: {
type: 'transcription',
team: { connect: { id: team.id } },
config: { provider: '', model: '' },
user: {
create: {
name: 'Transcript Agent',
email: 'transcript-agent@example.test',
type: UserType.agent,
},
},
},
})
agentId = agent.id
2026-12-04 13:49:25 +08:00
const project = await prisma.project.create({
data: { name: 'Transcript test', teamId: team.id },
})
projectId = project.id
const asset = await prisma.asset.create({
data: {
name: 'Video',
type: 'file',
status: 'processed',
mediaType: 'video/mp4',
media,
project: { connect: { id: projectId } },
storageKey: { create: { key: 'files/transcript-video.mp4' } },
},
})
assetId = asset.id
vi.spyOn(globalThis, 'fetch').mockImplementation(async () =>
Response.json({
model,
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh', name: 'Chinese' },
],
}),
)
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
async function generateAndStart(language: string | null) {
const result = await transcriptService.generate(assetId, language)
if (result.kind !== 'queued') throw new Error(`Unexpected generation result ${result.kind}`)
await prisma.workflowTask.update({
where: { id: result.taskId },
data: { status: 'processing' },
})
return result.taskId
}
it('lists only the asset’s saved languages and reads every segment in position order', async () => {
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const save = (id: string, language: string) =>
prisma.assetTranscript.create({
data: {
assetId: id,
language,
model,
workflowTaskId: 'test-task',
segments: {
create: [
{ position: 1, startMs: 2000, endMs: 3000, text: 'Second' },
{ position: 0, startMs: 125, endMs: 1425, text: 'First' },
],
},
},
include: { segments: true },
})
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
const english = await save(assetId, 'en')
await save(assetId, 'zh')
await save(otherAsset.id, 'ko')
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
const savedLanguages = await transcriptService.listSavedLanguages(assetId)
expect(savedLanguages.languages.sort()).toEqual(['en', 'zh'])
const transcript = await transcriptService.getSavedTranscript(assetId, 'en')
expect(transcript).toEqual({
id: english.id,
language: 'en',
segments: [
{
id: english.segments.find(({ position }) => position === 0)?.id,
startMs: 125,
endMs: 1425,
text: 'First',
},
{
id: english.segments.find(({ position }) => position === 1)?.id,
startMs: 2000,
endMs: 3000,
text: 'Second',
},
],
})
await expect(transcriptService.getSavedTranscript(assetId, 'ko')).rejects.toMatchObject({
status: 404,
})
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(transcriptService.listSavedLanguages(assetId)).resolves.toEqual({ languages: [] })
await expect(transcriptService.getSavedTranscript(assetId, 'en')).rejects.toMatchObject({
status: 404,
})
expect(fetch).not.toHaveBeenCalled()
})
it('validates provider capability, language and asset eligibility before queuing', async () => {
await expect(transcriptService.listLanguages()).resolves.toEqual({
model,
languages: [
{ code: 'en', name: 'English' },
{ code: 'zh-Hans', name: 'Chinese (Simplified)' },
{ code: 'zh-Hant', name: 'Chinese (Traditional)' },
],
})
2026-12-04 13:49:25 +08:00
await expect(transcriptService.generate(assetId, 'xx')).rejects.toMatchObject({ status: 400 })
await prisma.asset.update({ where: { id: assetId }, data: { mediaType: 'image/png' } })
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({ status: 400 })
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('only offers Chinese scripts when the provider supports Chinese', async () => {
const list = { model, languages: [{ code: 'en', name: 'English' }] }
vi.mocked(fetch).mockImplementation(async () => Response.json(list))
await expect(transcriptService.listLanguages()).resolves.toEqual(list)
await expect(transcriptService.generate(assetId, 'zh-Hans')).rejects.toMatchObject({
status: 400,
})
await expect(transcriptService.generate(assetId, 'zh-Hant')).rejects.toMatchObject({
status: 400,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
2026-12-04 13:49:25 +08:00
})
it('requires an enabled Transcript Agent before contacting the provider or queuing', async () => {
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', 'false')
await expect(transcriptService.isGenerationEnabled()).resolves.toBe(false)
vi.stubEnv('ENABLE_TRANSCRIPTION_AGENT', undefined)
await prisma.agent.update({ where: { id: agentId }, data: { enabled: false } })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 503 })
await prisma.agent.delete({ where: { id: agentId } })
await expect(transcriptService.listLanguages()).rejects.toMatchObject({ status: 503 })
expect(fetch).not.toHaveBeenCalled()
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
2026-12-04 13:49:25 +08:00
it('serializes requests for an asset and uses its project and workflow type', async () => {
const results = await Promise.all([
transcriptService.generate(assetId, 'en'),
transcriptService.generate(assetId, 'zh'),
])
expect(results.map((result) => result.kind).sort()).toEqual(['busy', 'queued'])
const tasks = await prisma.workflowTask.findMany({ where: { assetId } })
expect(tasks).toHaveLength(1)
expect(tasks[0]).toMatchObject({
projectId,
type: WorkflowTaskType.ai_transcription,
status: 'pending',
})
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: tasks[0].id,
status: 'pending',
})
})
it('requires completed transcoding and a full proxy before queuing', async () => {
await prisma.asset.update({ where: { id: assetId }, data: { status: 'processing' } })
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({ status: 400 })
const preview = { key: 'files/transcript-video-180p.mp4', width: 320, height: 180 }
await prisma.asset.update({
where: { id: assetId },
data: {
status: 'processed',
media: { ...media, videoTranscodes: [], videoPreview: preview },
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it.each(['archiving', 'archived', 'restoring'] as const)(
'queues generation from a full proxy while the video is %s',
async (status) => {
await prisma.asset.update({ where: { id: assetId }, data: { status } })
await expect(transcriptService.generate(assetId, 'en')).resolves.toMatchObject({
kind: 'queued',
})
},
)
it('lists each live project file with a pending or running transcription once', async () => {
const project = await prisma.project.findUniqueOrThrow({ where: { id: projectId } })
const otherProject = await prisma.project.create({
data: { name: 'Another project', teamId: project.teamId },
})
const [running, finished, deleted, external, transcoding] = await Promise.all(
[
{ projectId, name: 'Running video' },
{ projectId, name: 'Finished video' },
{ projectId, name: 'Deleted video', isDeleted: true },
{ projectId: otherProject.id, name: 'External video' },
{ projectId, name: 'Transcoding video' },
].map((file) =>
prisma.asset.create({ data: { ...file, type: 'file', status: 'processed' } }),
),
)
await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual([])
await prisma.workflowTask.createMany({
data: [
{ assetId, status: WorkflowTaskStatus.pending },
{ assetId, status: WorkflowTaskStatus.processing },
{ assetId, status: WorkflowTaskStatus.failed },
{ assetId: running.id, status: WorkflowTaskStatus.processing },
{ assetId: finished.id, status: WorkflowTaskStatus.completed },
{ assetId: finished.id, status: WorkflowTaskStatus.failed },
{ assetId: deleted.id, status: WorkflowTaskStatus.pending },
{ assetId: external.id, status: WorkflowTaskStatus.processing },
{
assetId: transcoding.id,
status: WorkflowTaskStatus.pending,
type: WorkflowTaskType.transcode_video,
},
].map((job) => ({ type: WorkflowTaskType.ai_transcription, ...job })),
})
await expect(transcriptService.listActiveAssetIds(projectId)).resolves.toEqual(
[assetId, running.id].sort().reverse(),
)
await expect(transcriptService.listActiveAssetIds(otherProject.id)).resolves.toEqual([
external.id,
])
})
it('rejects an archived video without a full proxy', async () => {
await prisma.asset.update({
where: { id: assetId },
data: { status: 'archived', media: { ...media, videoTranscodes: [] } },
})
await expect(transcriptService.generate(assetId, 'en')).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it.each(['archiving', 'archived', 'restoring'] as const)(
'saves a transcript when the video has become %s while the job runs',
async (status) => {
const taskId = await generateAndStart('en')
await prisma.asset.update({ where: { id: assetId }, data: { status } })
await expect(
transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments }),
).resolves.toBe(true)
await expect(transcriptService.getSavedTranscript(assetId, 'en')).resolves.toMatchObject({
segments,
})
},
)
2026-12-04 13:49:25 +08:00
it('rejects an audio-only proxy even when the file was uploaded with a video MIME type', async () => {
await prisma.asset.update({
where: { id: assetId },
data: {
media: {
...media,
proxyType: 'audio',
videoTranscodes: [{ key: 'files/transcript-video-audio-proxy.mp4', width: 0, height: 0 }],
},
},
})
await expect(transcriptService.generate(assetId, null)).rejects.toMatchObject({
status: 400,
message: transcriptionErrors.noProxy,
})
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(0)
})
it('persists languages independently and preserves saved text on replay and requests for an existing language', async () => {
const enTaskId = await generateAndStart('en')
const first = { taskId: enTaskId, assetId, model, language: 'en', segments }
await transcriptService.saveResult(first)
const en = await prisma.assetTranscript.findUniqueOrThrow({
where: { assetIdLanguage: { assetId, language: 'en' } },
})
const segment = await prisma.assetTranscriptSegment.findUniqueOrThrow({
where: { transcriptIdPosition: { transcriptId: en.id, position: 0 } },
})
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Edited'),
).resolves.toEqual({
id: segment.id,
startMs: 125,
endMs: 1425,
text: 'Edited',
})
await transcriptService.saveResult(first)
expect(await transcriptService.generate(assetId, 'en')).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
const autoTaskId = await generateAndStart(null)
await transcriptService.saveResult({ ...first, taskId: autoTaskId })
expect(await transcriptService.generate(assetId, null)).toEqual({
kind: 'existing',
transcriptId: en.id,
language: 'en',
})
expect(
await prisma.assetTranscriptSegment.findMany({ where: { transcriptId: en.id } }),
).toMatchObject([
{
position: 0,
startMs: 125,
endMs: 1425,
text: 'Edited',
},
])
const zhTaskId = await generateAndStart('zh')
await transcriptService.saveResult({ ...first, taskId: zhTaskId, language: 'zh' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(2)
expect(await prisma.workflowTask.count({ where: { assetId } })).toBe(3)
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId: zhTaskId,
status: 'completed',
})
await prisma.asset.delete({ where: { id: assetId } })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
expect(await prisma.assetTranscriptSegment.count({ where: { transcriptId: en.id } })).toBe(0)
})
it('saves empty segment text with generation disabled and scopes writes to the asset and language', async () => {
const taskId = await generateAndStart('en')
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
const otherAsset = await prisma.asset.create({
data: { name: 'Another video', type: 'file', status: 'processed', projectId },
})
const [segment] = (await transcriptService.getSavedTranscript(assetId, 'en')).segments
vi.stubEnv('EMBEDDING_PROVIDER', 'gemini-embedding-2')
for (const [fileId, language, segmentId] of [
[otherAsset.id, 'en', segment.id],
[assetId, 'zh', segment.id],
[assetId, 'en', 'missing-segment'],
]) {
await expect(
transcriptService.updateSegmentText(fileId, language, segmentId, 'Unexpected edit'),
).rejects.toMatchObject({ status: 404 })
}
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(segment)
const cleared = { ...segment, text: '' }
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, ''),
).resolves.toEqual(cleared)
expect((await transcriptService.getSavedTranscript(assetId, 'en')).segments).toEqual([cleared])
await prisma.asset.update({ where: { id: assetId }, data: { isDeleted: true } })
await expect(
transcriptService.updateSegmentText(assetId, 'en', segment.id, 'Restored'),
).rejects.toMatchObject({
status: 404,
})
expect(
await prisma.assetTranscriptSegment.findUnique({ where: { id: segment.id } }),
).toMatchObject(cleared)
})
it('completes silence without creating a row for an unknown language', async () => {
const taskId = await generateAndStart(null)
await transcriptService.saveResult({ taskId, assetId, model, language: null, segments: [] })
expect(await transcriptService.getStatus(assetId)).toEqual({ taskId, status: 'no_speech' })
expect(await transcriptService.generate(assetId, null)).toEqual({ kind: 'no_speech' })
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
})
it.each(['tooLarge', 'noProxy'] as const)(
'preserves a failed job with reason %s',
async (reason) => {
const taskId = await generateAndStart(null)
await prisma.workflowTask.update({
where: { id: taskId },
data: {
status: 'failed',
output: { error: transcriptionErrors[reason] },
},
})
await transcriptService.saveResult({ taskId, assetId, model, language: 'en', segments })
expect(await transcriptService.getStatus(assetId)).toEqual({
taskId,
status: 'failed',
reason,
})
expect(await prisma.assetTranscript.count({ where: { assetId } })).toBe(0)
},
)
})