Merge remote-tracking branch 'origin/main' into feature/batch-image-foundation

# Conflicts:
#	.github/audit-exceptions.yml
This commit is contained in:
Turtle_Li
2026-07-07 10:53:17 +08:00
33 changed files with 2201 additions and 337 deletions
@@ -55,6 +55,17 @@
/>
</div>
<div v-if="isOpenAIAccount" class="space-y-1.5">
<label class="text-sm font-medium text-gray-700 dark:text-gray-300">
{{ t('admin.accounts.openai.testMode') }}
</label>
<Select
v-model="testMode"
:options="openAITestModeOptions"
:disabled="status === 'connecting'"
/>
</div>
<div v-if="supportsImageTest" class="space-y-1.5">
<TextArea
v-model="testPrompt"
@@ -276,6 +287,12 @@ const loadingModels = ref(false)
let abortController: AbortController | null = null
const generatedImages = ref<PreviewImage[]>([])
const previewImageUrl = ref('')
const testMode = ref<'default' | 'compact'>('default')
const isOpenAIAccount = computed(() => props.account?.platform === 'openai')
const openAITestModeOptions = computed(() => [
{ value: 'default', label: t('admin.accounts.openai.testModeDefault') },
{ value: 'compact', label: t('admin.accounts.openai.testModeCompact') }
])
const prioritizedGeminiModels = ['gemini-3.1-flash-image', 'gemini-2.5-flash-image', 'gemini-3.5-flash', 'gemini-2.5-flash', 'gemini-2.5-pro', 'gemini-3-flash-preview', 'gemini-3-pro-preview', 'gemini-2.0-flash']
const supportsGeminiImageTest = computed(() => {
const modelID = selectedModelId.value.toLowerCase()
@@ -309,6 +326,7 @@ watch(
async (newVal) => {
if (newVal && props.account) {
testPrompt.value = ''
testMode.value = 'default'
resetState()
await loadAvailableModels()
} else {
@@ -400,6 +418,18 @@ const startTest = async () => {
abortController = new AbortController()
try {
const requestBody: {
model_id: string
prompt: string
mode?: 'default' | 'compact'
} = {
model_id: selectedModelId.value,
prompt: supportsImageTest.value ? testPrompt.value.trim() : ''
}
if (isOpenAIAccount.value) {
requestBody.mode = testMode.value
}
// Use the configured API base; EventSource does not support POST.
const url = buildApiUrl(`/admin/accounts/${props.account.id}/test`)
@@ -410,10 +440,7 @@ const startTest = async () => {
Authorization: `Bearer ${localStorage.getItem('auth_token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model_id: selectedModelId.value,
prompt: supportsImageTest.value ? testPrompt.value.trim() : ''
}),
body: JSON.stringify(requestBody),
signal: abortController.signal
})
@@ -505,6 +532,12 @@ const handleEvent = (event: {
}
break
case 'status':
if (event.text) {
addLine(event.text, 'text-cyan-300')
}
break
case 'test_complete':
// Move streaming content to output lines
if (streamingContent.value) {
@@ -19,13 +19,23 @@
<div>
<label class="input-label">{{ t('admin.accounts.dataImportFile') }}</label>
<div
class="flex items-center justify-between gap-3 rounded-lg border border-dashed border-gray-300 bg-gray-50 px-4 py-3 dark:border-dark-600 dark:bg-dark-800"
class="flex items-center justify-between gap-3 rounded-lg border border-dashed px-4 py-3 transition-colors"
:class="dragActive
? 'border-primary-400 bg-primary-50/70 dark:border-primary-500 dark:bg-primary-900/20'
: 'border-gray-300 bg-gray-50 dark:border-dark-600 dark:bg-dark-800'"
@dragenter.prevent="handleDragEnter"
@dragover.prevent
@dragleave.prevent="handleDragLeave"
@drop.prevent="handleDrop"
>
<div class="min-w-0">
<div class="truncate text-sm text-gray-700 dark:text-dark-200">
{{ fileName || t('admin.accounts.dataImportSelectFile') }}
<div class="truncate text-sm text-gray-700 dark:text-dark-200" :title="fileListTitle">
{{ selectedFilesLabel || t('admin.accounts.dataImportSelectFile') }}
</div>
<div class="text-xs text-gray-500 dark:text-dark-400">
JSON (.json)
<span v-if="files.length > 1"> · {{ fileListTitle }}</span>
</div>
<div class="text-xs text-gray-500 dark:text-dark-400">JSON (.json)</div>
</div>
<button type="button" class="btn btn-secondary shrink-0" @click="openFilePicker">
{{ t('common.chooseFile') }}
@@ -36,6 +46,7 @@
type="file"
class="hidden"
accept="application/json,.json"
multiple
@change="handleFileChange"
/>
</div>
@@ -90,7 +101,7 @@ import { useI18n } from 'vue-i18n'
import BaseDialog from '@/components/common/BaseDialog.vue'
import { adminAPI } from '@/api/admin'
import { useAppStore } from '@/stores/app'
import type { AdminDataImportResult } from '@/types'
import type { AdminDataImportResult, AdminDataPayload } from '@/types'
interface Props {
show: boolean
@@ -108,11 +119,19 @@ const { t } = useI18n()
const appStore = useAppStore()
const importing = ref(false)
const file = ref<File | null>(null)
const files = ref<File[]>([])
const dragDepth = ref(0)
const dragActive = computed(() => dragDepth.value > 0)
const hasCreatedData = ref(false)
const result = ref<AdminDataImportResult | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)
const fileName = computed(() => file.value?.name || '')
const selectedFilesLabel = computed(() => {
if (files.value.length === 0) return ''
if (files.value.length === 1) return files.value[0]?.name || ''
return t('admin.accounts.selectedCount', { count: files.value.length })
})
const fileListTitle = computed(() => files.value.map((item) => item.name).join(', '))
const errorItems = computed(() => result.value?.errors || [])
@@ -120,7 +139,9 @@ watch(
() => props.show,
(open) => {
if (open) {
file.value = null
files.value = []
dragDepth.value = 0
hasCreatedData.value = false
result.value = null
if (fileInput.value) {
fileInput.value.value = ''
@@ -135,14 +156,56 @@ const openFilePicker = () => {
const handleFileChange = (event: Event) => {
const target = event.target as HTMLInputElement
file.value = target.files?.[0] || null
setSelectedFiles(target.files)
target.value = ''
}
const handleClose = () => {
if (importing.value) return
if (hasCreatedData.value) {
hasCreatedData.value = false
emit('imported')
}
emit('close')
}
const isJsonFile = (sourceFile: File) => {
const name = sourceFile.name.toLowerCase()
return name.endsWith('.json') || sourceFile.type === 'application/json'
}
const setSelectedFiles = (sourceFiles: FileList | File[] | null | undefined) => {
if (importing.value) return
const incoming = Array.from(sourceFiles || [])
const picked = incoming.filter(isJsonFile)
if (!picked.length) {
appStore.showError(t('admin.accounts.dataImportSelectFile'))
return
}
if (picked.length < incoming.length) {
appStore.showWarning(
t('admin.accounts.dataImportIgnoredFiles', { count: incoming.length - picked.length })
)
}
files.value = picked
result.value = null
}
const handleDragEnter = () => {
if (importing.value) return
dragDepth.value += 1
}
const handleDragLeave = () => {
dragDepth.value = Math.max(0, dragDepth.value - 1)
}
const handleDrop = (event: DragEvent) => {
dragDepth.value = 0
if (importing.value) return
setSelectedFiles(event.dataTransfer?.files)
}
const readFileAsText = async (sourceFile: File): Promise<string> => {
if (typeof sourceFile.text === 'function') {
return sourceFile.text()
@@ -161,16 +224,74 @@ const readFileAsText = async (sourceFile: File): Promise<string> => {
})
}
const SUPPORTED_DATA_TYPES = ['sub2api-data', 'sub2api-bundle']
const SUPPORTED_DATA_VERSION = 1
// 与后端 validateDataHeader 对齐:合并前逐文件校验,避免坏文件混入合并 payload 后
// 报错无法定位来源,或绕过后端本会对单文件做的 type/version 检查。
const isValidDataPayload = (payload: unknown): payload is AdminDataPayload => {
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return false
const candidate = payload as Record<string, unknown>
if (
candidate.type !== undefined &&
candidate.type !== '' &&
!SUPPORTED_DATA_TYPES.includes(candidate.type as string)
) {
return false
}
if (
candidate.version !== undefined &&
candidate.version !== 0 &&
candidate.version !== SUPPORTED_DATA_VERSION
) {
return false
}
return Array.isArray(candidate.proxies) && Array.isArray(candidate.accounts)
}
const mergeDataPayloads = (payloads: AdminDataPayload[]): AdminDataPayload => {
const [firstPayload] = payloads
if (payloads.length === 1 && firstPayload) return firstPayload
return {
type: payloads.find((item) => typeof item.type === 'string')?.type,
version: payloads.find((item) => typeof item.version === 'number')?.version,
exported_at: new Date().toISOString(),
proxies: payloads.flatMap((item) => item.proxies),
accounts: payloads.flatMap((item) => item.accounts),
skipped_shadows: payloads.reduce((sum, item) => {
const count = Number(item.skipped_shadows || 0)
return Number.isFinite(count) ? sum + count : sum
}, 0)
}
}
const handleImport = async () => {
if (!file.value) {
if (files.value.length === 0) {
appStore.showError(t('admin.accounts.dataImportSelectFile'))
return
}
importing.value = true
try {
const text = await readFileAsText(file.value)
const dataPayload = JSON.parse(text)
const dataPayloads: AdminDataPayload[] = []
for (const sourceFile of files.value) {
let parsed: unknown
try {
parsed = JSON.parse(await readFileAsText(sourceFile))
} catch {
appStore.showError(
t('admin.accounts.dataImportParseFailedFile', { name: sourceFile.name })
)
return
}
if (!isValidDataPayload(parsed)) {
appStore.showError(t('admin.accounts.dataImportInvalidFile', { name: sourceFile.name }))
return
}
dataPayloads.push(parsed)
}
const dataPayload = mergeDataPayloads(dataPayloads)
const res = await adminAPI.accounts.importData({
data: dataPayload,
@@ -187,17 +308,17 @@ const handleImport = async () => {
proxy_failed: res.proxy_failed,
}
if (res.account_failed > 0 || res.proxy_failed > 0) {
// 部分成功也创建了数据;弹窗关闭时通过 imported 通知父组件刷新列表
if (res.account_created > 0 || res.proxy_created > 0) {
hasCreatedData.value = true
}
appStore.showError(t('admin.accounts.dataImportCompletedWithErrors', msgParams))
} else {
appStore.showSuccess(t('admin.accounts.dataImportSuccess', msgParams))
emit('imported')
}
} catch (error: any) {
if (error instanceof SyntaxError) {
appStore.showError(t('admin.accounts.dataImportParseFailed'))
} else {
appStore.showError(error?.message || t('admin.accounts.dataImportFailed'))
}
appStore.showError(error?.message || t('admin.accounts.dataImportFailed'))
} finally {
importing.value = false
}
@@ -182,4 +182,38 @@ describe('AccountTestModal', () => {
prompt: ''
})
})
it('OpenAI Compact 探测会携带 compact 测试模式', async () => {
getAvailableModels.mockResolvedValue([
{ id: 'gpt-5.4', display_name: 'GPT-5.4' }
])
global.fetch = vi.fn().mockResolvedValue(
createStreamResponse([
'data: {"type":"test_complete","success":true}\n'
])
) as any
const wrapper = mountModal({
id: 42,
name: 'OpenAI OAuth',
platform: 'openai',
type: 'oauth',
status: 'active'
})
await wrapper.setProps({ show: true })
await flushPromises()
;(wrapper.vm as any).selectedModelId = 'gpt-5.4'
;(wrapper.vm as any).testMode = 'compact'
await (wrapper.vm as any).startTest()
await flushPromises()
expect(global.fetch).toHaveBeenCalledTimes(1)
const [, request] = (global.fetch as any).mock.calls[0]
expect(JSON.parse(request.body)).toMatchObject({
model_id: 'gpt-5.4',
prompt: '',
mode: 'compact'
})
})
})