gongxiangp2/lib/__tests__/detail-text-recovery.test.ts

92 lines
6.6 KiB
TypeScript

/** @jest-environment node */
import { prepareDetailTextRecovery } from '@/lib/detail-generator/repository'
import { detailTextDispatchKey, detailTextRecoveryOptions, readDetailTextRecovery } from '@/lib/detail-generator/text-recovery'
import { assertAiModelAdminForWrite } from '@/lib/ai-model-access'
import { DetailGeneratorError } from '@/lib/detail-generator/access'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/ai-model-access', () => ({ assertAiModelAdminForWrite: jest.fn() }))
const db = { $queryRawUnsafe: jest.fn() }
jest.mock('@/lib/prisma', () => ({ prisma: { $transaction: jest.fn(async callback => callback(db)) } }))
const requestId = 'a1111111-1111-4111-8111-111111111111'
const facts = '{"facts":["型号A"],"warnings":["材质待确认"]}'
let current: any, revision: number, busy: boolean
beforeEach(() => {
jest.clearAllMocks(); revision = 1; busy = false
current = { id: 'job-1', ownerId: 'owner-1', projectId: 'project-1', projectRevision: 1, kind: 'analyze', status: 'unknown', requestId, checkpoint: { stage: 'product-analysis', dispatchKey: 'job-1-product-analysis', dispatchPending: true }, payload: {}, createdAt: new Date(), updatedAt: new Date() }
;(assertAiModelAdminForWrite as jest.Mock).mockResolvedValue(undefined)
db.$queryRawUnsafe.mockImplementation(async (sql, ...args) => {
if (sql.includes('FROM detail_generator_jobs WHERE id=$1')) return args[1] === current.ownerId ? [{ ...current }] : []
if (sql.includes('FROM detail_generator_projects')) return [{ id: 'project-1', ownerId: 'owner-1', revision, createdAt: new Date(), updatedAt: new Date() }]
if (sql.includes('UNION ALL SELECT v.id FROM ai_model_verifications')) return busy ? [{ id: 'another-unknown' }] : []
if (sql.startsWith('UPDATE detail_generator_jobs')) { current = { ...current, status: args[2], checkpoint: JSON.parse(args[3]), requestId: args[4], leaseToken: args[5] }; return [{ ...current }] }
return []
})
})
test('an original text query acquires one lease, fixes the original UUID and never queues a new generation', async () => {
const result = await prepareDetailTextRecovery('job-1', 'owner-1', 'query')
expect(result.status).toBe('running')
expect(result.leaseToken).toMatch(/^[a-f0-9-]{36}$/)
expect(readDetailTextRecovery(result.checkpoint)).toEqual({ mode: 'query-only', stage: 'product-analysis', requestId })
expect(result.checkpoint.textRecoveryLog).toEqual([expect.objectContaining({ action: 'query', requestId })])
await expect(prepareDetailTextRecovery('job-1', 'owner-1', 'query')).rejects.toMatchObject({ code: 'recovery_not_available' })
})
test.each(['other-owner', 'revoked', 'revision', 'request-conflict', 'missing-id'] as const)('rejects %s before creating a lease', async mode => {
let owner = 'owner-1', supplied: string | undefined
if (mode === 'other-owner') owner = 'other'
if (mode === 'revoked') (assertAiModelAdminForWrite as jest.Mock).mockRejectedValue(new DetailGeneratorError('已撤权', 403))
if (mode === 'revision') revision = 2
if (mode === 'request-conflict') supplied = 'b1111111-1111-4111-8111-111111111111'
if (mode === 'missing-id') current.requestId = null
await expect(prepareDetailTextRecovery('job-1', owner, 'query', supplied)).rejects.toBeInstanceOf(DetailGeneratorError)
expect(db.$queryRawUnsafe.mock.calls.some(([sql]) => sql.startsWith('UPDATE'))).toBe(false)
})
function analysisReady() {
current.checkpoint = { stage: 'selling-points', dispatchPending: false, facts, recoveredText: { stage: 'product-analysis', requestId, dispatchKey: 'job-1-product-analysis' } }
}
test('repeated query after recovered analysis is a no-op; explicit continuation keeps facts and only queues the unfinished stage', async () => {
analysisReady()
expect(detailTextRecoveryOptions(current)).toEqual({ canQuery: false, canContinue: true, needsRequestId: false })
expect((await prepareDetailTextRecovery('job-1', 'owner-1', 'query')).status).toBe('unknown')
expect(db.$queryRawUnsafe.mock.calls.some(([sql]) => sql.startsWith('UPDATE'))).toBe(false)
const result = await prepareDetailTextRecovery('job-1', 'owner-1', 'continue')
expect(result).toMatchObject({ status: 'queued', leaseToken: null, requestId: null, checkpoint: { facts, dispatchPending: false, stage: 'selling-points' } })
})
test('another unresolved model test blocks a new continuation but does not block a GET-only query', async () => {
busy = true; analysisReady()
await expect(prepareDetailTextRecovery('job-1', 'owner-1', 'continue')).rejects.toMatchObject({ code: 'user_capacity' })
current.checkpoint = { stage: 'product-analysis', dispatchPending: true, dispatchKey: 'job-1-product-analysis' }
await expect(prepareDetailTextRecovery('job-1', 'owner-1', 'query')).resolves.toMatchObject({ status: 'running' })
})
test('invalid recovered facts, unsupported stages and mismatched dispatch keys never advertise continuation or querying', () => {
analysisReady(); current.checkpoint.facts = 'not-json'
expect(detailTextRecoveryOptions(current).canContinue).toBe(false)
current.checkpoint = { stage: 'screen-one', dispatchPending: true, dispatchKey: 'job-1-screen-one' }
expect(detailTextRecoveryOptions(current).canQuery).toBe(false)
current.checkpoint = { stage: 'outline', dispatchPending: true, dispatchKey: 'different-job-outline' }
expect(detailTextRecoveryOptions(current).canQuery).toBe(false)
})
test('a definitely failed copy gets one persisted new attempt, keeps facts and never reuses an unknown request', async () => {
current.status = 'failed'; current.requestId = null
current.checkpoint = { stage: 'outline', dispatchPending: false, dispatchKey: 'job-1-outline', facts }
expect(detailTextRecoveryOptions(current).canContinue).toBe(true)
const result = await prepareDetailTextRecovery('job-1', 'owner-1', 'continue')
expect(result.requestId).toBeNull()
expect(result.checkpoint.facts).toBe(facts)
expect(result.checkpoint.copyAttempt).toMatchObject({ source: 'known-failed-copy', id: expect.stringMatching(/^[a-f0-9-]{36}$/) })
const nextKey = detailTextDispatchKey('job-1', 'outline', result.checkpoint)
expect(nextKey).not.toBe('job-1-outline')
expect(detailTextDispatchKey('job-1', 'outline', result.checkpoint)).toBe(nextKey)
current.status = 'unknown'; current.checkpoint = { ...result.checkpoint, stage: 'outline', dispatchPending: true, dispatchKey: nextKey }
expect(detailTextRecoveryOptions(current)).toMatchObject({ canQuery: true, canContinue: false })
await expect(prepareDetailTextRecovery('job-1', 'owner-1', 'continue')).rejects.toMatchObject({ code: 'recovery_not_available' })
})