feat(diy): keep solid door colors consistent in AI renders

Share verified color standards across single and batch renders, add conservative result color review, and support signed development reference URLs.

(cherry picked from commit 56e24b0b5f21c233cf5525c9839762bf6dc51133)
This commit is contained in:
WuYongJie 2026-11-02 11:44:35 +08:00
parent 01f7a4a191
commit e2ff1cab4f
26 changed files with 515 additions and 9 deletions

View File

@ -0,0 +1,9 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { getDiySolidDoorColorReview } from '@/server/services/diy-solid-door-color-review.service'
export async function GET(request: NextRequest, context: { params: Promise<{ id: string }> }) {
return handleRequest(request, async ctx => jsonSuccess(await getDiySolidDoorColorReview(
(await context.params).id, request.nextUrl.searchParams.get('storageKey') || '', ctx.user,
), 200, ctx.requestId), { requireAuth: true })
}

View File

@ -0,0 +1,10 @@
import { NextRequest } from 'next/server'
import { handleRequest, jsonSuccess } from '@/server/core/response'
import { getDiySolidDoorStandards } from '@/server/services/diy-solid-door-colors.service'
export async function GET(request: NextRequest) {
return handleRequest(request, async ctx => jsonSuccess(await getDiySolidDoorStandards({
catalogHash: request.nextUrl.searchParams.get('catalogHash'),
codes: request.nextUrl.searchParams.getAll('code'),
}, ctx.user), 200, ctx.requestId), { requireAuth: true })
}

View File

@ -5,6 +5,7 @@ import Button from '@/components/ui/Button'
import { RenderInspectorPromptTagPicker } from '@/app/ai-render-workbench/RenderInspectorPromptTagPicker'
import type { DiyAiRenderInput } from '@/lib/diy/ai-render'
import type { DiyAiRenderController } from '../hooks/useDiyAiRender'
import DiySolidDoorColors from './DiySolidDoorColors'
const field = 'w-full rounded-[4px] border border-black/[0.04] bg-white px-2.5 py-1.5 text-[11px] leading-[18px] text-[#2d3335] outline-none focus:border-[#47646b]/30 disabled:opacity-50'
const box = 'rounded-[6px] border border-black/[0.04] bg-white'
@ -16,6 +17,7 @@ export default function DiyAiPromptForm({ ai, hasItems }: { ai:DiyAiRenderContro
onClick={() => ai.setMode(mode)} className={`h-8 rounded-[5px] text-[11px] font-semibold transition ${ai.mode===mode?'bg-white text-[#2d3335] shadow-sm ring-1 ring-black/[0.04]':'text-[#5a6062]/60 hover:bg-white/70'}`}>
{mode==='scene'?'效果图':'白底图'}</button>)}
</div>
<DiySolidDoorColors colors={ai.solidColors} disabled={busy}/>
<details className={box}>
<summary className="cursor-pointer px-2.5 py-2 text-[11px] font-semibold text-[#5a6062]/75">当前视角参考图</summary>
<div className="px-2.5 pb-2">

View File

@ -5,6 +5,7 @@ import Button from '@/components/ui/Button'
import type { DiyAiRenderDTO } from '@/lib/diy/ai-render'
import type { DiyImageSelection } from '@/lib/diy/image-tools'
import type { DiyAiRenderController } from '../hooks/useDiyAiRender'
import DiySolidDoorColorReview from './DiySolidDoorColorReview'
export const diyRenderLabel = (record: DiyAiRenderDTO) => record.operation === 'local-preview' ? '本地截图'
: record.operation === 'text-replace' ? '文字替换' : record.operation === 'layout-replace' ? '排版图' : record.mode === 'scene' ? '效果图' : '白底图'
@ -38,6 +39,7 @@ export default function DiyAiResultCard({ record, ai, onPreview, onEdit, onLayou
<img src={image.thumbnailUrl} alt={`${record.name} ${index + 1}`} loading="lazy" className="aspect-[4/3] w-full object-contain"/>
<span className="absolute bottom-2 right-2 rounded-full bg-white/85 px-2 py-0.5 text-[10px] text-zinc-500">{image.width} × {image.height}</span>
</button>
<DiySolidDoorColorReview record={record} image={image}/>
<div className="flex items-center gap-0.5 border-t border-black/[0.04] bg-white p-1" aria-label="图片操作">
<Button size="small" variant="plain" className={action} onClick={() => onEdit(selection)}><SlidersHorizontal size={13}/>编辑</Button>
{canLayout && <Button size="small" variant="plain" className={action} onClick={() => onLayout(selection)}><Wand2 size={13}/>排版</Button>}

View File

@ -0,0 +1,42 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import type { DiyAiRenderDTO, DiyAiRenderImage } from '@/lib/diy/ai-render'
import type { SolidDoorColorReview } from '@/lib/diy/solid-door-colors'
import { readDiySolidDoorColorReview } from '../lib/solid-door-colors-api'
export default function DiySolidDoorColorReview({ record, image }: { record: DiyAiRenderDTO; image: DiyAiRenderImage }) {
const root = useRef<HTMLDivElement>(null), [visible, setVisible] = useState(false), [revision, setRevision] = useState(0)
const [state, setState] = useState<{ key: string; review?: SolidDoorColorReview; error?: string } | null>(null)
const requestKey = `${record.id}:${image.storageKey}:${revision}`
const review = state?.key === requestKey ? state.review : undefined, error = state?.key === requestKey ? state.error : undefined
const applicable = Boolean(record.solidDoorColors?.length) && !record.operation
useEffect(() => {
if (!applicable || !root.current) return
const observer = new IntersectionObserver(entries => { if (entries.some(entry => entry.isIntersecting)) { setVisible(true); observer.disconnect() } })
observer.observe(root.current); return () => observer.disconnect()
}, [applicable])
useEffect(() => {
if (!applicable || !visible) return
let live = true
void readDiySolidDoorColorReview(record.id, image.storageKey).then(result => { if (live) setState({ key: requestKey, review: result }) })
.catch(err => { if (live) setState({ key: requestKey, error: err instanceof Error ? err.message : '核色失败' }) })
return () => { live = false }
}, [record.id, image.storageKey, applicable, visible, requestKey])
if (!applicable) return null
return <div ref={root} className="mt-1 px-0.5 text-[10px] leading-4">
{error ? <button type="button" onClick={() => setRevision(value => value + 1)} title={error} className="text-amber-700">核色未完成 · 重试</button>
: !review ? <span className="text-zinc-400">正在辅助核色…</span> : <details>
<summary className={`cursor-pointer ${review.status === 'suspect' ? 'font-medium text-red-600' : 'text-amber-700'}`}>
{review.status === 'suspect' ? '疑似偏色 · 请核对' : review.status === 'manual' ? '请人工核色' : '未检出明显偏色 · 待确认'}
</summary>
<div className="mt-1 space-y-1 text-zinc-500">
{review.colors.map(color => <div key={color.itemCode} className="flex items-start gap-1.5">
<i className="mt-0.5 h-3 w-3 shrink-0 rounded-sm border border-black/10" style={{ backgroundColor: color.hex }}/>
<span>{color.name}:{color.reason}</span>
</div>)}
{record.referenceImageUrl && <a href={record.referenceImageUrl} target="_blank" rel="noreferrer" className="inline-block text-[#47646b] underline">查看原始参考图</a>}
</div>
</details>}
</div>
}

View File

@ -0,0 +1,23 @@
'use client'
import type { DiySolidDoorColorsController } from '../hooks/useDiySolidDoorColors'
export default function DiySolidDoorColors({ colors, disabled = false }: { colors: DiySolidDoorColorsController; disabled?: boolean }) {
if (!colors.hasColors) return null
return <div className="space-y-1.5 text-[11px] text-zinc-600" aria-label="纯色门板一致性">
<label className="flex cursor-pointer items-center gap-1.5">
<input type="checkbox" checked={colors.enabled} disabled={disabled} onChange={event => colors.setEnabled(event.target.checked)}
className="!h-3.5 !min-h-0 !w-3.5 !min-w-0 accent-[#47646b]"/>统一纯色门板颜色
</label>
{colors.enabled && <>
{colors.loading && <p role="status" className="text-[10px] text-zinc-400">正在读取素材标准色…</p>}
{colors.error && <p role="alert" className="text-[10px] text-red-600">{colors.error} <button type="button" disabled={disabled} onClick={colors.retry} className="underline">重试</button></p>}
<div className="flex flex-wrap gap-x-3 gap-y-1">
{colors.standards.map(color => <span key={color.itemCode} title={`${color.itemCode} · ${color.hex}`} className="inline-flex items-center gap-1">
<i className="h-3.5 w-3.5 shrink-0 rounded-sm border border-black/10" style={{ backgroundColor: color.hex }}/><span>{color.name}</span>
</span>)}
</div>
{!colors.error && !colors.loading && <p className="text-[10px] text-zinc-400">同批共用素材标准色,保留自然明暗;成图仍需核色。</p>}
</>}
</div>
}

View File

@ -8,6 +8,7 @@ import type { DiyAiRenderImage } from '@/lib/diy/ai-render'
import type { DiyAiRenderAccess } from '@/lib/diy/ai-render'
import type { DiyBatchImageActions } from '../../hooks/useDiyBatchImageActions'
import type { DiyImageSelection } from '@/lib/diy/image-tools'
import DiySolidDoorColorReview from '../DiySolidDoorColorReview'
const actionClass = '!h-6 !min-h-0 !min-w-0 !px-1 !py-0 !text-[10px] focus:!px-1 focus:!py-0'
export default function DiyBatchRecord({ record, image, index, actions: a, access }: {
@ -38,6 +39,7 @@ export default function DiyBatchRecord({ record, image, index, actions: a, acces
{diyBatchRecordState(record)}
</span>
</div>
{image && <DiySolidDoorColorReview record={record} image={image}/>}
{entry && source && <div aria-label="图片操作" className="mt-1 flex flex-wrap items-center gap-x-0.5">
<Button size="small" variant="plain" className={actionClass} disabled={busy} onClick={() => a.setEditing(source)}>编辑</Button>
{canLayout && <Button size="small" variant="plain" className={actionClass} disabled={busy} onClick={() => a.setLayout(source)}>排版</Button>}

View File

@ -1,6 +1,7 @@
'use client'
import type { DiyAiBatchController, DiyBatchSettings } from '../../hooks/useDiyAiBatch'
import DiySolidDoorColors from '../DiySolidDoorColors'
const field = '!min-h-0 !min-w-0 w-full rounded-md border border-zinc-200 bg-white px-2 py-1.5 text-[11px] leading-5 outline-none focus:border-zinc-500 disabled:opacity-60'
const singleLineField = `${field} !h-7 !py-0`
@ -13,6 +14,7 @@ export default function DiyBatchSettings({ batch: b }: { batch: DiyAiBatchContro
aria-pressed={b.settings.mode===mode.value} onClick={() => change('mode',mode.value)}
className={`!h-7 !min-h-0 !min-w-0 flex-1 rounded px-2 py-0 text-[11px] ${b.settings.mode===mode.value ? 'bg-white font-medium text-zinc-800 shadow-sm' : 'text-zinc-500'}`}>{mode.label}</button>)}
</div>
<DiySolidDoorColors colors={b.solidColors} disabled={disabled}/>
<label className="block space-y-1 text-[11px] text-zinc-500"><span>{b.settings.mode==='scene' ? '统一场景提示词(必填)' : '统一白底要求(选填)'}</span>
<textarea aria-label="批量统一提示词" value={b.settings.userPrompt} onChange={event => change('userPrompt',event.target.value)} maxLength={2000} rows={3}
placeholder={b.settings.mode==='scene' ? '例如:明亮的现代客厅,柔和自然光' : '默认生成纯白背景产品图'} className={field}/></label>

View File

@ -8,6 +8,7 @@ import type { DiyReferenceCapture } from '../lib/ai-capture'
import { DEFAULT_BATCH_VIEW, type DiyBatchView } from '../lib/batch-camera'
import { listDiyAiBatches, submitDiyAiBatchItem } from '../lib/batch-api'
import { buildDiyAiPrompts } from '../lib/ai-prompts'
import { useDiySolidDoorColors } from './useDiySolidDoorColors'
export type DiyBatchSettings = Pick<DiyAiRenderInput, 'mode'|'userPrompt'|'aspectRatio'|'imageCount'|'imageSize'> & { negativePrompt:string }
export type DiyBatchTab = 'setup'|'results'
@ -19,6 +20,7 @@ export function useDiyAiBatch(catalog: DiyCatalogDTO, initial: DiySchemeDTO[], i
const [selection,setSelection] = useState(initial),[selectedIndex,setSelectedIndex] = useState(0)
const [view,setView] = useState(initialView),[revision,setRevision] = useState(0),[settings,setSettings] = useState(defaults)
const [tab,setTab] = useState<DiyBatchTab>(initialTab)
const solidColors = useDiySolidDoorColors(catalog.sourceHash, selection.map(record => record.snapshot), tab === 'setup')
const [batches,setBatches] = useState<DiyAiBatchDTO[]>([]),[loading,setLoading] = useState(false)
const [preparing,setPreparing] = useState(false),[stage,setStage] = useState(''),[error,setError] = useState(''),[notice,setNotice] = useState('')
const [captureTask,setCaptureTask] = useState<CaptureTask | null>(null)
@ -70,6 +72,7 @@ export function useDiyAiBatch(catalog: DiyCatalogDTO, initial: DiySchemeDTO[], i
try {
if (!submission.current) {
const id = crypto.randomUUID(), frozenView = { ...view }, frozenSettings = { ...settings }, inputs: DiyAiBatchItemInput[] = []
const solidDoorColorLock = solidColors.freeze()
for (let index = 0; index < selection.length; index++) {
const record = selection[index]
setStage(`正在准备参考图 ${index+1}/${selection.length}:${record.name}`)
@ -79,6 +82,7 @@ export function useDiyAiBatch(catalog: DiyCatalogDTO, initial: DiySchemeDTO[], i
const prompts = await buildDiyAiPrompts({ ...frozenSettings,...reference,name:record.name,snapshot })
inputs.push({ requestId:diyBatchRequestId(id,index),name:record.name,schemeCode:record.code,catalogHash:catalog.sourceHash,
snapshot,cameraView:reference.cameraView,referenceImageDataUrl:reference.dataUrl,...frozenSettings,...prompts,
...(solidDoorColorLock ? { solidDoorColorLock } : {}),
batch:{ id,index,total:selection.length,previousRequestId:index ? diyBatchRequestId(id,index-1) : null } })
}
submission.current = { inputs,next:0 }
@ -113,6 +117,6 @@ export function useDiyAiBatch(catalog: DiyCatalogDTO, initial: DiySchemeDTO[], i
record.id !== id ? [record] : result.record ? [{ ...record, ...result.record }] : []) })))
}
return { selection,selectedIndex,setSelectedIndex,view,setView,revision,preset,settings,setSettings,tab,setTab,
batches,loading,refresh,preparing,stage,error,notice,setError,setNotice,onDeleted,captureTask,onCaptured,start,retry,resumeAvailable }
batches,loading,refresh,preparing,stage,error,notice,setError,setNotice,onDeleted,captureTask,onCaptured,start,retry,resumeAvailable,solidColors }
}
export type DiyAiBatchController = ReturnType<typeof useDiyAiBatch>

View File

@ -9,6 +9,8 @@ import type { DiyCaptureRef, DiyReferenceCapture } from '../lib/ai-capture'
import { downloadDiyFile } from '../lib/download'
import type { DiyWorkbenchController } from './useDiyWorkbench'
import { useDiyAiDeletion } from './useDiyAiDeletion'
import { useDiySolidDoorColors } from './useDiySolidDoorColors'
import { solidDoorCodes } from '@/lib/diy/solid-door-colors'
interface Preview extends DiyReferenceCapture { snapshot: DiySnapshot; name: string; catalogHash: string; schemeCode: string | null }
async function compositionKey(snapshot: DiySnapshot) {
@ -19,6 +21,7 @@ const message = (error: unknown) => error instanceof Error ? error.message : '
export function useDiyAiRender(controller: DiyWorkbenchController, captureRef: DiyCaptureRef, access: DiyAiRenderAccess) {
const [open,setOpen] = useState(false)
const solidColors = useDiySolidDoorColors(controller.catalog.sourceHash, [controller.snapshot], open)
const [mode,setMode] = useState<DiyAiRenderMode>('white-background')
const [prompts,setPrompts] = useState<Record<DiyAiRenderMode,string>>({'white-background':'',scene:''})
const prompt = prompts[mode]
@ -92,11 +95,12 @@ export function useDiyAiRender(controller: DiyWorkbenchController, captureRef: D
const settings = { mode, userPrompt: prompt, negativePrompt, aspectRatio, imageCount, imageSize }
try {
const reference = await capture()
const solidDoorColorLock = solidColors.freeze(solidDoorCodes([reference.snapshot]).join(','))
const builtPrompts = await buildDiyAiPrompts({ ...reference, ...settings })
setStage('AI 正在生成,可切回配色与柜门继续编辑')
const record = await generateDiyAiRender({ requestId: crypto.randomUUID(), name:reference.name, schemeCode:reference.schemeCode,
catalogHash:reference.catalogHash, snapshot:reference.snapshot, cameraView:reference.cameraView, ...settings, ...builtPrompts,
referenceImageDataUrl: reference.dataUrl }, setStage)
referenceImageDataUrl: reference.dataUrl, ...(solidDoorColorLock ? { solidDoorColorLock } : {}) }, setStage)
setRecords(previous => [record,...previous.filter(item => item.id!==record.id)].slice(0,60))
if(diyCompositionText(record.snapshot)!==diyCompositionText(live.current.controller.saveSnapshot())) {
live.current.scope='all';setScope('all')
@ -127,6 +131,6 @@ export function useDiyAiRender(controller: DiyWorkbenchController, captureRef: D
}
return { open, setOpen, openPanel, refreshReference, mode, setMode, prompt, setPrompt, negativePrompt, setNegativePrompt,
aspectRatio, setAspectRatio, imageCount, setImageCount, imageSize, setImageSize, preview, records, scope, setScope,
loading, stage, generating, optimizing, error, notice, optimization, refresh, generate, optimize, download, downloading, deletion, access }
loading, stage, generating, optimizing, error, notice, optimization, refresh, generate, optimize, download, downloading, deletion, access, solidColors }
}
export type DiyAiRenderController = ReturnType<typeof useDiyAiRender>

View File

@ -0,0 +1,21 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { useDiySolidDoorColors } from './useDiySolidDoorColors'
import { readDiySolidDoorStandards } from '../lib/solid-door-colors-api'
jest.mock('../lib/solid-door-colors-api', () => ({ readDiySolidDoorStandards: jest.fn() }))
const standards = [{ itemCode: 'SJ038039' as const, name: '蓝色', hex: '#2a4d8f', sourceHash: 'a'.repeat(64) }]
beforeEach(() => { jest.clearAllMocks(); jest.mocked(readDiySolidDoorStandards).mockResolvedValue(standards) })
test('freezes a batch union, rejects stale or failed standards, and permits explicit opt-out', async () => {
const { result, rerender } = renderHook(({ hash }) => useDiySolidDoorColors(hash, [{ doors: { a: 'SJ038039' } }, { doors: { b: 'SJ038039', c: 'SJ038079' } }]), { initialProps: { hash: 'one' } })
await waitFor(() => expect(result.current.loading).toBe(false))
const lock = result.current.freeze()
expect(lock?.standards).toEqual(standards)
expect(lock?.standards).not.toBe(standards)
expect(() => result.current.freeze('SJ038037')).toThrow('尚未准备好')
jest.mocked(readDiySolidDoorStandards).mockRejectedValue(new Error('读取失败'))
rerender({ hash: 'two' })
await waitFor(() => expect(result.current.error).toBe('读取失败'))
expect(() => result.current.freeze()).toThrow('读取失败')
act(() => result.current.setEnabled(false))
expect(result.current.freeze()).toBeUndefined()
})

View File

@ -0,0 +1,33 @@
'use client'
import { useEffect, useState } from 'react'
import { solidDoorCodes, type SolidDoorColorLock, type SolidDoorStandard } from '@/lib/diy/solid-door-colors'
import type { DiySnapshot } from '@/lib/diy/types'
import { readDiySolidDoorStandards } from '../lib/solid-door-colors-api'
export function useDiySolidDoorColors(catalogHash: string, snapshots: Pick<DiySnapshot, 'doors'>[], active = true) {
const codes = solidDoorCodes(snapshots).join(','), identity = `${catalogHash}:${codes}`
const [enabled, updateEnabled] = useState(true), [revision, setRevision] = useState(0)
const requestKey = `${identity}:${revision}`
const [state, setState] = useState<{ key: string; standards: SolidDoorStandard[]; error: string }>({ key: '', standards: [], error: '' })
const setEnabled = (next: boolean) => { updateEnabled(next); if (next) setRevision(value => value + 1) }
useEffect(() => {
if (!active || !enabled || !codes) return
const abort = new AbortController()
void readDiySolidDoorStandards(catalogHash, codes.split(','), abort.signal).then(standards => {
if (!abort.signal.aborted) setState({ key: requestKey, standards, error: '' })
}).catch(error => { if (!abort.signal.aborted) setState({ key: requestKey, standards: [], error: error instanceof Error ? error.message : '标准色读取失败' }) })
return () => abort.abort()
}, [catalogHash, codes, enabled, active, requestKey])
const current = state.key === requestKey
const ready = current && !state.error && state.standards.length === codes.split(',').length
const freeze = (snapshotCodes = codes): SolidDoorColorLock | undefined => {
if (!enabled || !snapshotCodes) return undefined
if (snapshotCodes !== codes || !ready) throw new Error(current && state.error || '标准色尚未准备好,请稍后重试')
return { version: 1, standards: state.standards.map(color => ({ ...color })) }
}
return { enabled, setEnabled, hasColors: Boolean(codes), standards: current ? state.standards : [],
loading: enabled && Boolean(codes) && !current,
error: current ? state.error : '', freeze, retry: () => setRevision(value => value + 1) }
}
export type DiySolidDoorColorsController = ReturnType<typeof useDiySolidDoorColors>

View File

@ -0,0 +1,31 @@
import type { SolidDoorColorReview, SolidDoorStandard } from '@/lib/diy/solid-door-colors'
async function request<T>(path: string, signal?: AbortSignal): Promise<T> {
const response = await fetch(path, { cache: 'no-store', signal })
const data = await response.json().catch(() => null)
if (!response.ok || !data?.success) throw new Error(data?.error?.message || '读取颜色信息失败,请重试')
return data.data
}
export function readDiySolidDoorStandards(catalogHash: string, codes: string[], signal?: AbortSignal) {
const params = new URLSearchParams({ catalogHash }); codes.forEach(code => params.append('code', code))
return request<SolidDoorStandard[]>(`/api/diy/ai-renders/color-standards?${params}`, signal)
}
const reviews = new Map<string, Promise<SolidDoorColorReview>>()
let running = 0
const queue: (() => void)[] = []
async function limited<T>(task: () => Promise<T>) {
if (running >= 2) await new Promise<void>(resolve => queue.push(resolve))
else running++
try { return await task() }
finally { const next = queue.shift(); if (next) next(); else running-- }
}
export function readDiySolidDoorColorReview(recordId: string, storageKey: string) {
const key = `${recordId}:${storageKey}`
let pending = reviews.get(key)
if (!pending) {
if (reviews.size >= 100) reviews.delete(reviews.keys().next().value!)
pending = limited(() => request<SolidDoorColorReview>(`/api/diy/ai-renders/${encodeURIComponent(recordId)}/color-review?${new URLSearchParams({ storageKey })}`))
reviews.set(key, pending); void pending.catch(() => { if (reviews.get(key) === pending) reviews.delete(key) })
}
return pending
}

View File

@ -0,0 +1,23 @@
import { reviewSolidDoorColors } from '../solid-door-color-analysis'
import { solidDoorCodes, type SolidDoorStandard } from '../solid-door-colors'
const blue: SolidDoorStandard = { itemCode: 'SJ038039', name: '宝石蓝色', hex: '#2a4d8f', sourceHash: 'a'.repeat(64) }
const pixels = (rgb: number[]) => Uint8Array.from(Array.from({ length: 500 }, () => rgb).flat())
test('gray shadows preserve hue and saturation while desaturated blue is flagged', () => {
const reference = pixels([42, 77, 143])
expect(reviewSolidDoorColors([blue], reference, pixels([29, 54, 100])).status).toBe('no-obvious-shift')
expect(reviewSolidDoorColors([blue], reference, pixels([100, 113, 135])).status).toBe('suspect')
})
test('near-white backgrounds and similar door hues never produce a false pass', () => {
const white = { ...blue, itemCode: 'SJ038037' as const, hex: '#eee8df' }
expect(reviewSolidDoorColors([white], pixels([238, 232, 223]), pixels([255, 255, 255])).status).toBe('manual')
const other = { ...blue, itemCode: 'SJ038042' as const, hex: '#6791be' }
expect(reviewSolidDoorColors([blue, other], pixels([42, 77, 143]), pixels([42, 77, 143])).colors.every(c => c.status === 'manual')).toBe(true)
})
test('insufficient reference is inconclusive; missing output color is suspicious', () => {
expect(reviewSolidDoorColors([blue], pixels([255, 255, 255]), pixels([255, 255, 255])).status).toBe('manual')
expect(reviewSolidDoorColors([blue], pixels([42, 77, 143]), pixels([255, 255, 255])).status).toBe('suspect')
})
test('pattern and wood door identities are excluded from a batch palette', () => {
expect(solidDoorCodes([{ doors: { a: 'SJ038039', b: 'SJ038079', c: 'SJ038043' } }, { doors: { a: 'SJ038037', b: 'SJ038039' } }])).toEqual(['SJ038037', 'SJ038039'])
})

View File

@ -1,5 +1,6 @@
import { z } from 'zod'
import type { DiySnapshot } from './types'
import { solidDoorColorLockSchema, type SolidDoorStandard } from './solid-door-colors'
export const diyAiRenderSchema = z.object({
requestId: z.string().uuid(),
@ -18,6 +19,7 @@ export const diyAiRenderSchema = z.object({
imageSize: z.enum(['1K', '2K', '4K']),
referenceImageDataUrl: z.string().max(17 * 1024 * 1024),
structureReferenceImageDataUrls: z.array(z.string().max(17 * 1024 * 1024)).max(1).optional(),
solidDoorColorLock: solidDoorColorLockSchema.optional(),
}).superRefine((value, ctx) => {
if (value.mode === 'scene' && !value.userPrompt) ctx.addIssue({ code: 'custom', path: ['userPrompt'], message: '请填写场景提示词' })
})
@ -39,6 +41,7 @@ export interface DiyAiRenderDTO {
mode: DiyAiRenderMode; status: 'PENDING' | 'SUCCEEDED' | 'FAILED'
referenceImageUrl: string | null; images: DiyAiRenderImage[]; userPrompt: string
errorMessage: string | null; createdAt: string; snapshot: DiySnapshot; cameraView: DiyAiCameraView
solidDoorColors?: SolidDoorStandard[]
}
export interface DiyAiRenderAccess { canView: boolean; canGenerate: boolean; canDownload: boolean; canDelete: boolean }
export interface DiyAiRenderList { records: DiyAiRenderDTO[]; access: DiyAiRenderAccess }

View File

@ -0,0 +1,40 @@
import type { SolidDoorColorReview, SolidDoorStandard } from './solid-door-colors'
type Hsv = { h: number; s: number; v: number }
export function rgbToHsv(r: number, g: number, b: number): Hsv {
const max = Math.max(r, g, b), min = Math.min(r, g, b), delta = max - min
const sector = !delta ? 0 : max === r ? (g - b) / delta : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4
return { h: (sector * 60 + 360) % 360, s: max ? delta / max : 0, v: max / 255 }
}
const distance = (a: number, b: number) => Math.min(Math.abs(a - b), 360 - Math.abs(a - b))
const median = (values: number[]) => values.sort((a, b) => a - b)[Math.floor(values.length / 2)] || 0
const fromHex = (hex: string) => rgbToHsv(...[1, 3, 5].map(start => parseInt(hex.slice(start, start + 2), 16)) as [number, number, number])
function samples(pixels: Uint8Array, target: Hsv) {
const values: Hsv[] = []
for (let i = 0; i < pixels.length; i += 3) {
const hsv = rgbToHsv(pixels[i], pixels[i + 1], pixels[i + 2])
if (hsv.v > 0.18 && hsv.s > 0.09 && distance(hsv.h, target.h) < 28) values.push(hsv)
}
return { count: values.length, saturation: median(values.map(v => v.s)), hue: median(values.map(v => ((v.h - target.h + 540) % 360) - 180)) }
}
/** Coarse hue populations, not door segmentation. Never certifies an image as color accurate. */
export function reviewSolidDoorColors(standards: SolidDoorStandard[], reference: Uint8Array, result: Uint8Array): SolidDoorColorReview {
const colors = standards.map(color => {
const target = fromHex(color.hex)
const base = { itemCode: color.itemCode, name: color.name, hex: color.hex }
const manual = (reason: string) => ({ ...base, status: 'manual' as const, reason })
if (target.s < 0.2 || target.v > 0.88 && target.s < 0.35) return manual('浅色接近背景,请人工核对')
if (target.h >= 20 && target.h <= 70) return manual('暖色容易与木色混淆,请人工核对')
if (standards.some(other => other !== color && distance(fromHex(other.hex).h, target.h) < 40)) return manual('相近色门板无法可靠区分,请人工核对')
const before = samples(reference, target), after = samples(result, target)
const enough = (n: number, bytes: Uint8Array) => n >= Math.max(35, bytes.length / 3 * 0.003)
if (!enough(before.count, reference)) return manual('参考图可见色面不足,请人工核对')
if (!enough(after.count, result)) return { ...base, status: 'suspect' as const, reason: '成图缺少对应色面,可能偏色或被遮挡' }
if (after.saturation < before.saturation * 0.7 && before.saturation - after.saturation > 0.12 ||
Math.abs(after.hue - before.hue) > 14) {
return { ...base, status: 'suspect' as const, reason: '色相或饱和度变化较大,请对照标准色核实' }
}
return { ...base, status: 'no-obvious-shift' as const, reason: '未检出明显偏色,仍需人工确认' }
})
return { status: colors.some(c => c.status === 'suspect') ? 'suspect' : colors.some(c => c.status === 'manual') ? 'manual' : 'no-obvious-shift', colors }
}

View File

@ -0,0 +1,25 @@
import { z } from 'zod'
import type { DiySnapshot } from './types'
// Explicit catalog identities: patterned and wood doors must never become solid colors.
export const SOLID_DOOR_CODES = ['SJ038037', 'SJ038038', 'SJ038039', 'SJ038040', 'SJ038041', 'SJ038042'] as const
export const isSolidDoorCode = (code: string) => (SOLID_DOOR_CODES as readonly string[]).includes(code)
export function solidDoorCodes(snapshots: Pick<DiySnapshot, 'doors'>[]) {
return [...new Set(snapshots.flatMap(snapshot => Object.values(snapshot.doors)).filter(isSolidDoorCode))].sort()
}
export const solidDoorStandardSchema = z.object({
itemCode: z.enum(SOLID_DOOR_CODES), name: z.string().min(1).max(100),
hex: z.string().regex(/^#[0-9a-f]{6}$/), sourceHash: z.string().regex(/^[a-f0-9]{64}$/),
}).strict()
export const solidDoorColorLockSchema = z.object({
version: z.literal(1), standards: z.array(solidDoorStandardSchema).min(1).max(6),
}).strict().refine(value => new Set(value.standards.map(color => color.itemCode)).size === value.standards.length, '标准色不能重复')
export const solidDoorStandardsRequestSchema = z.object({
catalogHash: z.string().min(1).max(100), codes: z.array(z.enum(SOLID_DOOR_CODES)).max(6),
}).strict()
export type SolidDoorStandard = z.infer<typeof solidDoorStandardSchema>
export type SolidDoorColorLock = z.infer<typeof solidDoorColorLockSchema>
export interface SolidDoorColorReview {
status: 'suspect' | 'manual' | 'no-obvious-shift'
colors: { itemCode: string; name: string; hex: string; status: SolidDoorColorReview['status']; reason: string }[]
}

View File

@ -0,0 +1,37 @@
/** @jest-environment node */
import sharp from 'sharp'
import { getDiySolidDoorColorReview } from '../diy-solid-door-color-review.service'
import { assertDiyAiRenderAccess } from '../diy-ai-render.access'
import { readOwnedDiyAiRenderImage } from '../diy-ai-render.image'
import { readDiyToolImage } from '../diy-image-template.service'
import { diyAiRenderRepository } from '@/server/repositories/diy-ai-render.repository'
import type { AuthUser } from '@/server/core/types'
jest.mock('../diy-ai-render.access', () => ({ assertDiyAiRenderAccess: jest.fn() }))
jest.mock('../diy-ai-render.image', () => ({ readOwnedDiyAiRenderImage: jest.fn() }))
jest.mock('../diy-image-template.service', () => ({ readDiyToolImage: jest.fn() }))
jest.mock('@/server/repositories/diy-ai-render.repository', () => ({ diyAiRenderRepository: { findOwned: jest.fn() } }))
const user = { id: 'color-reviewer' } as AuthUser, id = 'color-review-record', key = `diy/ai-renders/${user.id}/${id}/result-1.png`
const row = { id, params: { solidDoorColorLock: { version: 1, standards: [{ itemCode: 'SJ038039', name: '蓝色', hex: '#2a4d8f', sourceHash: 'a'.repeat(64) }] } },
workspaceSnapshot: { snapshot: { doors: { cell: 'SJ038039' } } }, resultImages: [{ storageKey: key }], referenceImageUrl: '/api/storage/object?key=diy%2Freference.png' }
beforeEach(async () => {
jest.clearAllMocks()
jest.mocked(diyAiRenderRepository.findOwned).mockResolvedValue(row as never)
const buffer = await sharp({ create: { width: 80, height: 80, channels: 3, background: '#2a4d8f' } }).png().toBuffer()
const image = { buffer, width: 80, height: 80, contentType: 'image/png' }
jest.mocked(readOwnedDiyAiRenderImage).mockResolvedValue(image)
jest.mocked(readDiyToolImage).mockResolvedValue(image)
})
test('review works with view permission and rechecks ownership on cached responses', async () => {
expect((await getDiySolidDoorColorReview(id, key, user)).status).toBe('no-obvious-shift')
expect(assertDiyAiRenderAccess).toHaveBeenCalledWith(user)
jest.mocked(diyAiRenderRepository.findOwned).mockResolvedValue(null)
await expect(getDiySolidDoorColorReview(id, key, user)).rejects.toThrow('图片不存在')
})
test('foreign images and old records cannot trigger storage reads', async () => {
await expect(getDiySolidDoorColorReview(id, 'foreign.png', user)).rejects.toThrow('图片不存在')
jest.mocked(diyAiRenderRepository.findOwned).mockResolvedValue({ ...row, params: {} } as never)
await expect(getDiySolidDoorColorReview(id, key, user)).rejects.toThrow('没有保存标准色')
expect(readOwnedDiyAiRenderImage).not.toHaveBeenCalled()
expect(readDiyToolImage).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,45 @@
/** @jest-environment node */
import sharp from 'sharp'
import { getDiySolidDoorStandards, prepareDiySolidDoorLock } from '../diy-solid-door-colors.service'
import { assertDiyAiRenderAccess } from '../diy-ai-render.access'
import { readDiyToolImage } from '../diy-image-template.service'
import { diyCatalogService } from '../diy-catalog.service'
import { catalogFixture } from '@/lib/diy/__tests__/catalog.fixture'
import type { AuthUser } from '@/server/core/types'
import type { DiySnapshot } from '@/lib/diy/types'
jest.mock('../diy-ai-render.access', () => ({ assertDiyAiRenderAccess: jest.fn() }))
jest.mock('../diy-image-template.service', () => ({ readDiyToolImage: jest.fn() }))
jest.mock('../diy-catalog.service', () => ({ diyCatalogService: { getWorkbenchCatalog: jest.fn() } }))
const user = { id: 'tester' } as AuthUser
const catalog = { ...catalogFixture, patterns: [...catalogFixture.patterns, { itemCode: 'SJ038039', name: '宝石蓝色', barcode: '', image: '/api/storage/object?key=product-development/diy/SJ0380/blue.png' }] }
const snapshot = { doors: { cell: 'SJ038039' } } as unknown as DiySnapshot
beforeEach(async () => {
jest.clearAllMocks()
jest.mocked(diyCatalogService.getWorkbenchCatalog).mockResolvedValue(catalog)
const buffer = await sharp({ create: { width: 100, height: 100, channels: 3, background: '#2a4d8f' } }).png().toBuffer()
jest.mocked(readDiyToolImage).mockResolvedValue({ buffer, width: 100, height: 100, contentType: 'image/png' })
})
test('extracts a deterministic color from catalog bytes and prepares the shared chart', async () => {
const standards = await getDiySolidDoorStandards({ catalogHash: catalogFixture.sourceHash, codes: ['SJ038039'] }, user)
expect(standards[0].hex).toBe('#2a4d8f')
const prepared = await prepareDiySolidDoorLock({ version: 1, standards }, catalog, snapshot)
expect(prepared?.prompt).toContain('SJ038039')
expect(prepared?.prompt).toContain('#2a4d8f')
expect((await sharp(prepared!.reference.buffer).metadata()).format).toBe('png')
expect(assertDiyAiRenderAccess).toHaveBeenCalledWith(user)
})
test('rejects client color tampering, omitted installed color, and outdated source identity', async () => {
const standards = await getDiySolidDoorStandards({ catalogHash: catalogFixture.sourceHash, codes: ['SJ038039'] }, user)
await expect(prepareDiySolidDoorLock({ version: 1, standards: [{ ...standards[0], hex: '#ffffff' }] }, catalog, snapshot)).rejects.toThrow('素材已更新')
await expect(prepareDiySolidDoorLock({ version: 1, standards: [{ ...standards[0], sourceHash: 'b'.repeat(64) }] }, catalog, snapshot)).rejects.toThrow('素材已更新')
await expect(prepareDiySolidDoorLock({ version: 1, standards: [] }, catalog, snapshot)).rejects.toThrow('标准不完整')
await expect(getDiySolidDoorStandards({ catalogHash: 'old', codes: ['SJ038039'] }, user)).rejects.toThrow('素材已更新')
})
test('disabled lock preserves historical requests; external arbitrary URLs cannot become a standard', async () => {
expect(await prepareDiySolidDoorLock(undefined, catalogFixture, snapshot)).toBeNull()
const catalog = { ...catalogFixture, sourceHash: 'c'.repeat(64), patterns: [{ ...catalogFixture.patterns[0], itemCode: 'SJ038039', image: 'http://127.0.0.1/secret' }] }
jest.mocked(diyCatalogService.getWorkbenchCatalog).mockResolvedValue(catalog)
await expect(getDiySolidDoorStandards({ catalogHash: catalog.sourceHash, codes: ['SJ038039'] }, user)).rejects.toThrow('素材不可读取')
expect(readDiyToolImage).not.toHaveBeenCalled()
})

View File

@ -0,0 +1,22 @@
/** @jest-environment node */
import { createHmac } from 'node:crypto'
import { createNativeImageReferenceUrl } from '../native-image-reference-url'
import { createObjectReadUrl } from '@/lib/storage'
jest.mock('@/lib/storage', () => ({ createObjectReadUrl: jest.fn(() => 'storage-url') }))
const key = `native-ai-inputs/${'a'.repeat(64)}/${'b'.repeat(64)}/00000000-0000-0000-0000-000000000000/0.png`
const environment = { ...process.env }
afterEach(() => { process.env = { ...environment } })
test('production and unconfigured development keep the existing storage path', () => {
process.env = { ...environment, NODE_ENV: 'production', LOCAL_AI_REFERENCE_BASE_URL: 'https://test.trycloudflare.com', LOCAL_AI_REFERENCE_SECRET: 'x'.repeat(64) }
expect(createNativeImageReferenceUrl(key, 100)).toBe('storage-url')
expect(createObjectReadUrl).toHaveBeenCalledWith(key, 100)
process.env = { ...environment, NODE_ENV: 'development' }; delete process.env.LOCAL_AI_REFERENCE_BASE_URL
expect(createNativeImageReferenceUrl(key, 100)).toBe('storage-url')
})
test('only AI inputs receive a signature, and query tampering invalidates it', () => {
process.env = { ...environment, NODE_ENV: 'development', LOCAL_AI_REFERENCE_BASE_URL: 'https://test.trycloudflare.com', LOCAL_AI_REFERENCE_SECRET: 'x'.repeat(64) }
const url = new URL(createNativeImageReferenceUrl(key, 100)), expires = url.searchParams.get('expires')!
expect(url.pathname).toBe('/reference')
expect(url.searchParams.get('signature')).toBe(createHmac('sha256', 'x'.repeat(64)).update(`${key}\n${expires}`).digest('hex'))
expect(() => createNativeImageReferenceUrl('other/private.png', 100)).toThrow('通道配置无效')
})

View File

@ -14,6 +14,7 @@ import { enqueueNativeImageGeneration } from './native-image-generation.service'
import { nativeRenderRequestFingerprint, assertNativeRenderRequestMatches } from './native-render-request'
import type { DiyAiBatchMetadata } from '@/lib/diy/ai-batch'
import { prepareDiySolidDoorLock } from './diy-solid-door-colors.service'
const json = (value: unknown) => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser, catalog: DiyCatalogDTO, requestFingerprint = nativeRenderRequestFingerprint(input), batch?: DiyAiBatchMetadata) {
@ -21,6 +22,7 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser,
if (!config.enabled || !config.baseUrl || !config.apiKey || !config.model) throw new AppError(ErrorCode.VALIDATION_FAILED, 'AI 生图服务未启用或未配置,请在 AI 出图中配置')
const reference = decodeReferenceImageDataUrl(input.referenceImageDataUrl)
const structures = input.mode === 'white-background' ? decodeReferenceImageDataUrls(input.structureReferenceImageDataUrls) : []
const colors = await prepareDiySolidDoorLock(input.solidDoorColorLock, catalog, input.snapshot)
const compositionKey = createHash('sha256').update(diyCompositionText(input.snapshot)).digest('hex')
const codes = new Set(input.snapshot.items.map(item => item.code))
const materials = input.snapshot.items.flatMap(item => Object.values(resolveDiyMaterials(catalog, item)).filter(Boolean))
@ -34,10 +36,11 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser,
const modeLock = input.mode === 'white-background'
? 'Use a pure white seamless background, soft studio lighting and a tight natural contact shadow. No room, floor texture, UI, grid, selection outlines, green targets or material swatches. '
: 'Use the scene request only for the surrounding room and lighting. Do not alter the furniture, current composition, camera angle or door artwork. '
const prompt = (lock + modeLock + input.prompt).slice(0, 5000)
const prompt = (lock + (colors?.prompt || '') + modeLock + input.prompt).slice(0, 5000)
const keys: string[] = []
const params = { requestFingerprint, source: 'diy', name: input.name, schemeCode: input.schemeCode || null, compositionKey, userPrompt: input.userPrompt,
imageCount: input.imageCount, aspectRatio: input.aspectRatio, imageSize: input.imageSize, mode: input.mode, stage: 'generating', ...(batch ? { batch } : {}) }
imageCount: input.imageCount, aspectRatio: input.aspectRatio, imageSize: input.imageSize, mode: input.mode, stage: 'generating',
...(colors ? { solidDoorColorLock: { version: 1, standards: colors.standards } } : {}), ...(batch ? { batch } : {}) }
const data = { id: input.requestId, createdBy: user.id, prompt, negativePrompt: input.negativePrompt || null,
outputMode: input.mode === 'scene' ? 'SCENE' as const : 'WHITE_BACKGROUND' as const, storageClass: 'PERMANENT' as const, params: json(params),
workspaceSnapshot: json({ source: 'diy', snapshot: input.snapshot, cameraView: input.cameraView }), assetSnapshot: json(assets), status: 'PENDING' as const }
@ -47,7 +50,8 @@ export async function createDiyAiRender(input: DiyAiRenderInput, user: AuthUser,
input: { serviceType: 'ai-render', prompt, negativePrompt: input.negativePrompt,
imageCount: input.imageCount, aspectRatio: input.aspectRatio, imageSize: input.imageSize,
referenceImage: { ...reference, fileName: `diy-current-view.${reference.extension}` },
additionalReferenceImages: structures.map((image,index) => ({ ...image, fileName: `same-view-structure-${index + 1}.${image.extension}` })) },
additionalReferenceImages: [...structures.map((image,index) => ({ ...image, fileName: `same-view-structure-${index + 1}.${image.extension}` })),
...(colors ? [colors.reference] : [])] },
completion: { kind: 'render', renderId: input.requestId, source: 'diy',
...(batch?.previousRequestId ? { afterJobId: `render:${batch.previousRequestId}` } : {}) },
}, (persistJob) => nativeRenderRepository.createWithJob({ ...data, referenceImageUrl: upload.url }, persistJob))

View File

@ -13,16 +13,20 @@ import { deleteDiyAiRender } from './diy-ai-render.delete'
import { promptOptimizerService } from './prompt-optimizer.service'
import { decodeReferenceImageDataUrl, toRecord } from './assisted-assembly-ai-render.validation'
import type { DiyAiBatchMetadata } from '@/lib/diy/ai-batch'
import { solidDoorColorLockSchema, solidDoorCodes } from '@/lib/diy/solid-door-colors'
export function toDiyAiRenderDTO(row: AssistedAssemblyAiRender): DiyAiRenderDTO {
const params = toRecord(row.params), workspace = toRecord(row.workspaceSnapshot)
const colors = solidDoorColorLockSchema.safeParse(params.solidDoorColorLock)
const active = workspace.snapshot ? solidDoorCodes([workspace.snapshot as DiyAiRenderDTO['snapshot']]) : []
return { id: row.id, name: String(params.name || '组合方案'), schemeCode: typeof params.schemeCode === 'string' ? params.schemeCode : null,
...(params.operation === 'layout-replace' ? { operation: 'layout-replace' as const, templateUrl: typeof params.templateUrl === 'string' ? params.templateUrl : null } : {}),
...(params.operation === 'text-replace' || params.operation === 'local-preview' ? { operation: params.operation } : {}),
compositionKey: String(params.compositionKey || ''), mode: row.outputMode === 'SCENE' ? 'scene' : 'white-background',
status: row.status, referenceImageUrl: row.referenceImageUrl, images: row.resultImages as unknown as DiyAiRenderDTO['images'],
userPrompt: String(params.userPrompt || ''), errorMessage: row.errorMessage, createdAt: row.createdAt.toISOString(),
snapshot: workspace.snapshot as DiyAiRenderDTO['snapshot'], cameraView: workspace.cameraView as DiyAiRenderDTO['cameraView'] }
snapshot: workspace.snapshot as DiyAiRenderDTO['snapshot'], cameraView: workspace.cameraView as DiyAiRenderDTO['cameraView'],
...(colors.success && !params.operation ? { solidDoorColors: colors.data.standards.filter(color => active.includes(color.itemCode)) } : {}) }
}
export const diyAiRenderService = {
async delete(id: string, input: unknown, user: AuthUser): Promise<DiyAiRenderDeleteResult> {

View File

@ -0,0 +1,41 @@
import sharp from 'sharp'
import { diyAiRenderIdSchema } from '@/lib/diy/ai-render'
import { solidDoorColorLockSchema, solidDoorCodes, type SolidDoorColorReview } from '@/lib/diy/solid-door-colors'
import { reviewSolidDoorColors } from '@/lib/diy/solid-door-color-analysis'
import { readObjectStorageKeyFromUrl } from '@/lib/storage'
import { AppError, ErrorCode } from '@/server/core/errors'
import type { AuthUser } from '@/server/core/types'
import { diyAiRenderRepository } from '@/server/repositories/diy-ai-render.repository'
import { assertDiyAiRenderAccess } from './diy-ai-render.access'
import { readOwnedDiyAiRenderImage } from './diy-ai-render.image'
import { readDiyToolImage } from './diy-image-template.service'
import { toRecord } from './assisted-assembly-ai-render.validation'
const cache = new Map<string, Promise<SolidDoorColorReview>>()
const pixels = (buffer: Buffer) => sharp(buffer).rotate().toColorspace('srgb').resize(256, 256, { fit: 'contain', background: '#ffffff' }).flatten({ background: '#ffffff' }).removeAlpha().raw().toBuffer()
export async function getDiySolidDoorColorReview(id: string, storageKey: string, user: AuthUser) {
await assertDiyAiRenderAccess(user)
if (!diyAiRenderIdSchema.safeParse(id).success || !storageKey || storageKey.length > 1024) throw new AppError(ErrorCode.VALIDATION_FAILED, '核色参数无效')
const row = await diyAiRenderRepository.findOwned(id, user.id)
if (!row || !Array.isArray(row.resultImages) || !row.resultImages.some(image => toRecord(image).storageKey === storageKey)) throw new AppError(ErrorCode.FILE_NOT_FOUND, '图片不存在')
const lock = solidDoorColorLockSchema.safeParse(toRecord(row.params).solidDoorColorLock)
const workspace = toRecord(row.workspaceSnapshot), snapshot = toRecord(workspace.snapshot)
if (!lock.success || !snapshot.doors || !row.referenceImageUrl) throw new AppError(ErrorCode.VALIDATION_FAILED, '此记录没有保存标准色,请人工核对')
const active = solidDoorCodes([{ doors: snapshot.doors as Record<string, string> }])
const standards = lock.data.standards.filter(color => active.includes(color.itemCode))
const referenceKey = readObjectStorageKeyFromUrl(row.referenceImageUrl)
if (!referenceKey || !standards.length || toRecord(row.params).operation) throw new AppError(ErrorCode.VALIDATION_FAILED, '此图片请人工核对颜色')
// Ownership and image membership are rechecked even on cache hits.
const key = `${user.id}:${id}:${storageKey}:${JSON.stringify(lock.data)}`
let pending = cache.get(key)
if (!pending) {
if (cache.size >= 80) cache.delete(cache.keys().next().value!)
pending = (async () => {
const [image, reference] = await Promise.all([readOwnedDiyAiRenderImage({ recordId: id, storageKey }, user), readDiyToolImage(referenceKey)])
const [before, after] = await Promise.all([pixels(reference.buffer), pixels(image.buffer)])
return reviewSolidDoorColors(standards, before, after)
})()
cache.set(key, pending); void pending.catch(() => { if (cache.get(key) === pending) cache.delete(key) })
}
return pending
}

View File

@ -0,0 +1,61 @@
import sharp from 'sharp'
import { createHash } from 'node:crypto'
import { readObjectStorageKeyFromUrl } from '@/lib/storage'
import { solidDoorCodes, solidDoorStandardsRequestSchema, type SolidDoorColorLock, type SolidDoorStandard } from '@/lib/diy/solid-door-colors'
import type { DiyCatalogDTO, DiySnapshot } from '@/lib/diy/types'
import { AppError, ErrorCode } from '@/server/core/errors'
import type { AuthUser } from '@/server/core/types'
import { assertDiyAiRenderAccess } from './diy-ai-render.access'
import { diyCatalogService } from './diy-catalog.service'
import { readDiyToolImage } from './diy-image-template.service'
const cache = new Map<string, Promise<SolidDoorStandard>>()
async function extractStandard(catalog: DiyCatalogDTO, code: string): Promise<SolidDoorStandard> {
const pattern = catalog.patterns.find(p => p.itemCode === code && !p.deletedAt)
const key = pattern && readObjectStorageKeyFromUrl(pattern.image)
if (!pattern || !key) throw new AppError(ErrorCode.VALIDATION_FAILED, '纯色门板素材不可读取,请检查素材管理')
const image = await readDiyToolImage(key)
const { data, info } = await sharp(image.buffer).rotate().toColorspace('srgb').resize(80, 80, { fit: 'fill' }).ensureAlpha().raw().toBuffer({ resolveWithObject: true })
const channels: number[][] = [[], [], []]
// Ignore border, hinges and transparent margins. Median tolerates texture and small highlights.
for (let y = 20; y < 60; y++) for (let x = 20; x < 60; x++) {
const offset = (y * info.width + x) * 4
if (data[offset + 3] < 240) continue
channels.forEach((values, index) => values.push(data[offset + index]))
}
if (channels[0].length < 300) throw new AppError(ErrorCode.VALIDATION_FAILED, '门板素材有效色面不足,请检查原图')
const hex = '#' + channels.map(values => values.sort((a, b) => a - b)[Math.floor(values.length / 2)].toString(16).padStart(2, '0')).join('')
return { itemCode: code as SolidDoorStandard['itemCode'], name: pattern.name, hex, sourceHash: createHash('sha256').update(image.buffer).digest('hex') }
}
export function loadSolidDoorStandard(catalog: DiyCatalogDTO, code: string) {
const key = `${catalog.sourceHash}:${code}:${catalog.patterns.find(p => p.itemCode === code)?.image}`
let pending = cache.get(key)
if (!pending) {
if (cache.size >= 48) cache.delete(cache.keys().next().value!)
pending = extractStandard(catalog, code); cache.set(key, pending)
void pending.catch(() => { if (cache.get(key) === pending) cache.delete(key) })
}
return pending
}
export async function getDiySolidDoorStandards(raw: unknown, user: AuthUser) {
await assertDiyAiRenderAccess(user)
const parsed = solidDoorStandardsRequestSchema.safeParse(raw)
if (!parsed.success) throw new AppError(ErrorCode.VALIDATION_FAILED, '标准色参数无效')
const catalog = await diyCatalogService.getWorkbenchCatalog()
if (catalog.sourceHash !== parsed.data.catalogHash) throw new AppError(ErrorCode.VALIDATION_FAILED, '素材已更新,请刷新 DIY')
return Promise.all([...new Set(parsed.data.codes)].sort().map(code => loadSolidDoorStandard(catalog, code)))
}
export async function prepareDiySolidDoorLock(lock: SolidDoorColorLock | undefined, catalog: DiyCatalogDTO, snapshot: DiySnapshot) {
if (!lock) return null
const activeCodes = solidDoorCodes([snapshot])
if (activeCodes.some(code => !lock.standards.some(color => color.itemCode === code))) throw new AppError(ErrorCode.VALIDATION_FAILED, '纯色标准不完整,请重新准备出图')
const standards = await Promise.all(lock.standards.map(color => loadSolidDoorStandard(catalog, color.itemCode)))
if (standards.some((color, index) => color.sourceHash !== lock.standards[index].sourceHash || color.hex !== lock.standards[index].hex)) {
throw new AppError(ErrorCode.VALIDATION_FAILED, '纯色素材已更新,请重新准备出图')
}
const active = standards.filter(color => activeCodes.includes(color.itemCode))
const swatches = standards.map((color, index) => `<g transform="translate(${index % 3 * 220},${Math.floor(index / 3) * 170})"><rect x="15" y="15" width="190" height="110" fill="${color.hex}" stroke="#999"/><text x="15" y="145" font-size="17" fill="#222">${color.itemCode} ${color.hex}</text></g>`).join('')
const buffer = await sharp(Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="660" height="${Math.ceil(standards.length / 3) * 170}"><rect width="100%" height="100%" fill="white"/>${swatches}</svg>`)).png().toBuffer()
const prompt = active.length ? `SOLID DOOR COLOR STANDARD (shared across this batch): ${active.map(c => `${c.itemCode} ${c.name} = sRGB ${c.hex}`).join('; ')}. The LAST reference is a color chart ONLY. Match the base paint hue and saturation of each installed solid door to its labeled swatch, consistently across ALL doors and outputs. Use neutral soft product lighting and neutral white balance; keep natural shading without gray/desaturated or recolored paint. In scenes, keep colored ambient light off these door faces. The PRIMARY image alone fixes placement, camera and which door uses which paint. Other swatches are not installed in this arrangement: never add doors, colors, charts, text or swatches to the result. Preserve wood grain and patterned artwork as in the primary image. ` : ''
return { standards, active, prompt, reference: { buffer, contentType: 'image/png', extension: 'png', fileName: 'solid-door-standard-colors.png' } }
}

View File

@ -1,6 +1,7 @@
import { createHash, randomUUID } from 'node:crypto'
import type { Prisma } from '@prisma/client'
import { createObjectReadUrl, deleteObject, readObjectStorageKeyFromUrl, uploadBufferToObjectStorageWithMetadata } from '@/lib/storage'
import { deleteObject, readObjectStorageKeyFromUrl, uploadBufferToObjectStorageWithMetadata } from '@/lib/storage'
import { createNativeImageReferenceUrl } from './native-image-reference-url'
import { AppError, ErrorCode } from '@/server/core/errors'
import { nativeImageGenerationRepository } from '@/server/repositories/native-image-generation.repository'
import type { CallExternalImageGenerateApiInput } from './external-image-generate.service'
@ -104,7 +105,7 @@ export async function enqueueNativeImageGeneration(
const uploaded = await uploadBufferToObjectStorageWithMetadata(file.buffer, key, file.contentType)
uploadedKeys.push(uploaded.storageKey)
// Freeze the exact signed URL before the first POST: retries must have identical payloads.
referenceImageUrls.push(createObjectReadUrl(uploaded.storageKey, NATIVE_IMAGE_INPUT_URL_TTL_SECONDS))
referenceImageUrls.push(createNativeImageReferenceUrl(uploaded.storageKey, NATIVE_IMAGE_INPUT_URL_TTL_SECONDS))
}
const request: NativeImageRequest = {
model: config.model, prompt: input.prompt, negativePrompt: input.negativePrompt,

View File

@ -0,0 +1,15 @@
import { createHmac } from 'node:crypto'
import { createObjectReadUrl } from '@/lib/storage'
/** Optional development bridge: signed, expiring access to uploaded AI inputs only. */
export function createNativeImageReferenceUrl(key: string, ttlSeconds: number) {
const base = process.env.LOCAL_AI_REFERENCE_BASE_URL, secret = process.env.LOCAL_AI_REFERENCE_SECRET
if (process.env.NODE_ENV !== 'development' || !base) return createObjectReadUrl(key, ttlSeconds)
const url = new URL(base)
if (url.protocol !== 'https:' || url.username || url.password || url.port || url.pathname !== '/' || url.search || url.hash || !secret || secret.length < 32 ||
!/^native-ai-inputs\/[a-f0-9]{64}\/[a-f0-9]{64}\/[a-f0-9-]{36}\/\d{1,2}\.(png|jpg|webp)$/.test(key)) throw new Error('本地 AI 参考图通道配置无效')
const expires = String(Math.floor(Date.now() / 1000) + Math.min(ttlSeconds, 72 * 3600))
const signature = createHmac('sha256', secret).update(`${key}\n${expires}`).digest('hex')
url.pathname = '/reference'; url.search = new URLSearchParams({ key, expires, signature }).toString()
return url.toString()
}