5a26dfde2a
后端变更: - 新增 risk_config.py: 风险配置数据类,支持环境变量驱动 - 新增 risk_control.py: 风险控制控制器,管理并发和预算 - 新增 session_store.py: 匿名会话存储,基于 cookie 的 session ID - 新增 audit_store.py: API 审计日志存储,记录请求和 LLM 调用 - 新增 captcha_api.py: 验证码 API,用于验证用户操作真实性 - 新增 llm_policy.py: LLM 策略配置,管理 completion/pro/vision 模型 - main.py: 集成 middleware、risk/audit/session 模块 (+467/-7) - job_handlers.py: LLM 执行流程重构,新增 risk/audit 集成 (+207/-4) - llm.py: 异步客户端封装,新增 max_output_tokens 参数 (+78/-1) - job_system.py: stream_events 逻辑优化,支持心跳检测 (+12/-4) - pro_completions.py: SSE heartbeat 机制,防止连接超时 (+14/-4) - prompt.py: _normalize_preferences 支持 Mapping 类型 (+13/-0) - tts_asr.py: asyncio loop 初始化,router export (+10/-0) 前端变更: - src/components/CaptchaComponent.vue: 新增验证码组件 (NEW) - src/utils/cookie_policy.js: Cookie 策略工具 (NEW) - SettingsPanel.vue: 集成验证码组件,新增安全设置部分 (+59/-0) - MilkdownEditor.vue: 移除硬编码 API_KEY,新增 credentials (+32/-10) - ProBlockCrepe.vue: 样式简化,移除渐变动画 (+18/-4) - proBlockPlugin.ts: 重构 schema/serializer 引用方式,通过 Ctx 管理 (+40/-10) - api.js: 新增 credentials,重构 headers 条件逻辑 (+50/-14) - config.js: API 基址改为 https://api.imageteach.tech:8002 (+8/-4) - convert.js, docsApi.js, i18n.js: 新增 credentials 和验证码 i18n (+54/-12) - proAccept.js: 重构正则和转义处理,修复捕获组索引 (+14/-4) 配置和基础设施: - docker-compose.yml: 新增端口映射 8001:8001 (+2/-0) - docker/nginx.conf: 改为 307 redirect,优化代理配置 (+8/-6) - vite.config.js: 移除 proxy 配置,直接调用远程 API (+8/-4) - .env.example: 新增 VITE_API_BASE_URL, VITE_API_KEY (+3/-1) - backend/.env.example: 大量 RISK_*, SESSION_*, CORS_* 配置 (+54/-0) - pytest.ini: 扩展 coverage 范围到整个 backend,移除 fail_under (+3/-2) - .coveragerc: 移除 fail_under = 90 (+0/-1) - .gitignore: 新增 docker-data/ (+3/-0) - package.json: 新增 vue3-captcha 依赖 (+3/-1) - AGENTS.md, README.md: 更新 Docker 部署和前端网络约定 (+20/-5) - public/sw.js: Service Worker cache 版本从 v1 升级到 v2 (+0/-1) 测试变更: - test_main_endpoints.py: 新增 session/risk/audit reset,新增测试用例 (+63/-4) - test_main_cancel.py: 新增 reset 调用 (+6/-0) - test_pro_completions.py: 新增 preferences 序列化和测试 (+23/-0) 总计: 45 个文件变更,+1009/-280 行
401 lines
10 KiB
JavaScript
401 lines
10 KiB
JavaScript
import {
|
|
API_URL,
|
|
API_KEY,
|
|
PRO_URL,
|
|
PRO_FRONTEND_TIMEOUT_MS,
|
|
TTS_URL,
|
|
TTS_STATUS_URL,
|
|
TTS_CONFIG_URL,
|
|
COMPRESS_SUBMIT_URL,
|
|
COMPRESS_STATUS_URL,
|
|
JOB_LOAD_URL,
|
|
} from './config.js'
|
|
import { useSettingsStore } from '../stores/settings'
|
|
|
|
function generateRequestId() {
|
|
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
|
return crypto.randomUUID()
|
|
}
|
|
return `${Date.now()}-${Math.random().toString(16).slice(2)}`
|
|
}
|
|
|
|
function normalizeAbortReason(reason) {
|
|
if (typeof reason === 'string' && reason.trim()) {
|
|
return reason.trim().slice(0, 64)
|
|
}
|
|
return 'abort'
|
|
}
|
|
|
|
function parseSseEvent(rawEvent) {
|
|
const lines = String(rawEvent || '').replace(/\r/g, '').split('\n')
|
|
let event = 'message'
|
|
const dataLines = []
|
|
|
|
for (const line of lines) {
|
|
if (!line) continue
|
|
if (line.startsWith('event:')) {
|
|
event = line.slice(6).trim() || 'message'
|
|
continue
|
|
}
|
|
if (line.startsWith('data:')) {
|
|
dataLines.push(line.slice(5).trimStart())
|
|
}
|
|
}
|
|
|
|
return {
|
|
event,
|
|
data: dataLines.join('\n'),
|
|
}
|
|
}
|
|
|
|
function createAbortError(message = 'Request aborted') {
|
|
const error = new Error(message)
|
|
error.name = 'AbortError'
|
|
return error
|
|
}
|
|
|
|
async function sendCancelRequest(cancelUrl, requestId, reason) {
|
|
try {
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
if (API_KEY) {
|
|
headers['X-API-Key'] = API_KEY
|
|
}
|
|
await fetch(cancelUrl, {
|
|
method: 'POST',
|
|
headers,
|
|
credentials: 'include',
|
|
body: JSON.stringify({
|
|
request_id: requestId,
|
|
reason,
|
|
}),
|
|
})
|
|
} catch {
|
|
// Best-effort cancel only
|
|
}
|
|
}
|
|
|
|
function getCancelUrl(apiUrl) {
|
|
const normalized = String(apiUrl || '').replace(/\/+$/, '')
|
|
if (/\/v1\/pro\/completions$/i.test(normalized)) {
|
|
return normalized.replace(/\/v1\/pro\/completions$/i, '/v1/pro/completions/cancel')
|
|
}
|
|
if (/\/v1\/completions$/i.test(normalized)) {
|
|
return normalized.replace(/\/v1\/completions$/i, '/v1/completions/cancel')
|
|
}
|
|
return `${normalized}/cancel`
|
|
}
|
|
|
|
function buildCompletionBody(settings, prefix, suffix, languageId, extra = {}) {
|
|
return {
|
|
prefix,
|
|
suffix,
|
|
languageId,
|
|
model_thinking: settings.modelThinking,
|
|
privacy_mode: settings.privacyMode,
|
|
user_preferences: {
|
|
language: settings.language,
|
|
currency: settings.currency,
|
|
timezone: settings.detectedTimezone,
|
|
},
|
|
...extra,
|
|
}
|
|
}
|
|
|
|
async function consumeSseJson({
|
|
url,
|
|
body,
|
|
requestId,
|
|
signal,
|
|
timeoutMs,
|
|
onChunk,
|
|
onEvent,
|
|
onDone,
|
|
}) {
|
|
const requestController = new AbortController()
|
|
const timeoutId = timeoutMs ? setTimeout(() => requestController.abort('timeout'), timeoutMs) : null
|
|
const cancelUrl = getCancelUrl(url)
|
|
|
|
const relayAbort = () => {
|
|
requestController.abort(signal?.reason || 'abort')
|
|
}
|
|
|
|
const onAbort = () => {
|
|
const reason = normalizeAbortReason(requestController.signal.reason)
|
|
void sendCancelRequest(cancelUrl, requestId, reason)
|
|
}
|
|
|
|
requestController.signal.addEventListener('abort', onAbort, { once: true })
|
|
if (signal) {
|
|
if (signal.aborted) {
|
|
relayAbort()
|
|
} else {
|
|
signal.addEventListener('abort', relayAbort, { once: true })
|
|
}
|
|
}
|
|
|
|
try {
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
'X-Request-Id': requestId,
|
|
}
|
|
if (API_KEY) {
|
|
headers['X-API-Key'] = API_KEY
|
|
}
|
|
const res = await fetch(url, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify(body),
|
|
credentials: 'include',
|
|
signal: requestController.signal,
|
|
})
|
|
|
|
if (!res.ok) {
|
|
const errorText = await res.text()
|
|
throw new Error(`HTTP ${res.status}: ${errorText}`)
|
|
}
|
|
if (!res.body) {
|
|
throw new Error('流式响应不可用')
|
|
}
|
|
|
|
const reader = res.body.getReader()
|
|
const decoder = new TextDecoder()
|
|
let buffer = ''
|
|
let finalPayload = null
|
|
|
|
while (true) {
|
|
const { done, value } = await reader.read()
|
|
if (done) break
|
|
buffer += decoder.decode(value, { stream: true })
|
|
|
|
let boundary = buffer.indexOf('\n\n')
|
|
while (boundary >= 0) {
|
|
const chunk = buffer.slice(0, boundary)
|
|
buffer = buffer.slice(boundary + 2)
|
|
const parsed = parseSseEvent(chunk)
|
|
const data = parsed.data ? JSON.parse(parsed.data) : {}
|
|
|
|
onEvent?.(parsed.event, data)
|
|
|
|
if (parsed.event === 'result') {
|
|
onChunk?.(data)
|
|
} else if (parsed.event === 'done') {
|
|
finalPayload = data.result || data
|
|
return onDone ? onDone(finalPayload) : finalPayload
|
|
} else if (parsed.event === 'error') {
|
|
throw new Error(String(data.error || '请求失败'))
|
|
} else if (parsed.event === 'cancelled') {
|
|
throw createAbortError('请求已取消')
|
|
}
|
|
|
|
boundary = buffer.indexOf('\n\n')
|
|
}
|
|
}
|
|
|
|
if (requestController.signal.aborted) {
|
|
throw createAbortError('请求已中止')
|
|
}
|
|
return onDone ? onDone(finalPayload || {}) : finalPayload
|
|
} finally {
|
|
if (timeoutId) clearTimeout(timeoutId)
|
|
requestController.signal.removeEventListener('abort', onAbort)
|
|
if (signal) {
|
|
signal.removeEventListener('abort', relayAbort)
|
|
}
|
|
}
|
|
}
|
|
|
|
export async function fetchSuggestion(prefix, suffix, languageId, signal, apiUrl = API_URL) {
|
|
let normalizedLanguageId = 'markdown'
|
|
if (typeof languageId === 'string' && languageId.trim()) {
|
|
normalizedLanguageId = languageId.trim()
|
|
} else if (languageId && typeof languageId === 'object' && 'aborted' in languageId) {
|
|
signal = languageId
|
|
}
|
|
if (typeof signal === 'string') {
|
|
apiUrl = signal
|
|
signal = undefined
|
|
}
|
|
|
|
const settings = useSettingsStore()
|
|
const requestId = generateRequestId()
|
|
let finalContent = ''
|
|
|
|
const result = await consumeSseJson({
|
|
url: apiUrl,
|
|
body: buildCompletionBody(settings, prefix, suffix, normalizedLanguageId),
|
|
requestId,
|
|
signal,
|
|
onChunk(data) {
|
|
if (typeof data.content === 'string') {
|
|
finalContent = data.content
|
|
} else if (typeof data.delta === 'string') {
|
|
finalContent += data.delta
|
|
}
|
|
},
|
|
onDone(data) {
|
|
return typeof data.content === 'string' ? data.content : finalContent
|
|
},
|
|
})
|
|
|
|
return result || ''
|
|
}
|
|
|
|
export async function fetchProSuggestionStream(payload, apiUrl = PRO_URL) {
|
|
const {
|
|
prefix = '',
|
|
suffix = '',
|
|
languageId = 'markdown',
|
|
instruction = '',
|
|
signal,
|
|
timeoutMs = PRO_FRONTEND_TIMEOUT_MS,
|
|
onChunk,
|
|
onEvent,
|
|
} = payload || {}
|
|
|
|
const settings = useSettingsStore()
|
|
const requestId = generateRequestId()
|
|
let finalContent = ''
|
|
|
|
return consumeSseJson({
|
|
url: apiUrl,
|
|
requestId,
|
|
signal,
|
|
timeoutMs,
|
|
body: {
|
|
prefix,
|
|
suffix,
|
|
languageId: String(languageId || 'markdown').trim() || 'markdown',
|
|
instruction,
|
|
pro_thinking: settings.proThinking || 'medium',
|
|
privacy_mode: settings.privacyMode,
|
|
user_preferences: {
|
|
language: settings.language,
|
|
currency: settings.currency,
|
|
timezone: settings.detectedTimezone,
|
|
},
|
|
},
|
|
onChunk(data) {
|
|
const delta = String(data.delta || data.content || '')
|
|
if (delta) {
|
|
finalContent += delta
|
|
onChunk?.(delta)
|
|
}
|
|
},
|
|
onEvent(event, data) {
|
|
if (event === 'progress' && data.phase === 'thinking') {
|
|
onEvent?.('thinking', data)
|
|
return
|
|
}
|
|
if (event === 'queued' || event === 'started' || event === 'resource') {
|
|
onEvent?.(event, data)
|
|
}
|
|
},
|
|
onDone(data) {
|
|
return String(data.content || finalContent || '')
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function fetchTTS(text, instruct = '', apiUrl = TTS_URL) {
|
|
const requestId = generateRequestId()
|
|
return consumeSseJson({
|
|
url: apiUrl,
|
|
requestId,
|
|
body: { text, instruct, speaker: 'Vivian', format: 'wav' },
|
|
onDone(data) {
|
|
return data
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function fetchTTSStatus(apiUrl = TTS_STATUS_URL) {
|
|
const res = await fetch(apiUrl, {
|
|
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
|
credentials: 'include',
|
|
})
|
|
if (!res.ok) throw new Error(`TTS Status HTTP ${res.status}`)
|
|
return res.json()
|
|
}
|
|
|
|
export async function fetchTTSConfig(apiUrl = TTS_CONFIG_URL) {
|
|
const res = await fetch(apiUrl, {
|
|
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
|
credentials: 'include',
|
|
})
|
|
if (!res.ok) throw new Error(`TTS Config HTTP ${res.status}`)
|
|
return res.json()
|
|
}
|
|
|
|
export async function submitCompress(content, docType = 'txt', apiUrl = COMPRESS_SUBMIT_URL) {
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
}
|
|
if (API_KEY) {
|
|
headers['X-API-Key'] = API_KEY
|
|
}
|
|
const res = await fetch(apiUrl, {
|
|
method: 'POST',
|
|
headers,
|
|
credentials: 'include',
|
|
body: JSON.stringify({ content, docType }),
|
|
})
|
|
|
|
if (!res.ok) {
|
|
const errorText = await res.text()
|
|
throw new Error(`压缩提交失败 HTTP ${res.status}: ${errorText}`)
|
|
}
|
|
|
|
return res.json()
|
|
}
|
|
|
|
export function pollCompressStatus(taskId, onStateChange, apiUrl = COMPRESS_STATUS_URL) {
|
|
let consecutiveErrors = 0
|
|
|
|
const interval = setInterval(async () => {
|
|
try {
|
|
const res = await fetch(`${apiUrl}?task_id=${encodeURIComponent(taskId)}`, {
|
|
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
|
credentials: 'include',
|
|
})
|
|
|
|
if (!res.ok) {
|
|
consecutiveErrors++
|
|
if (consecutiveErrors >= 5) {
|
|
clearInterval(interval)
|
|
onStateChange('error', '', `请求失败 HTTP ${res.status}`)
|
|
}
|
|
return
|
|
}
|
|
|
|
consecutiveErrors = 0
|
|
const data = await res.json()
|
|
onStateChange(data.status, data.content || '', data.message, data)
|
|
|
|
if (['completed', 'error', 'cancelled'].includes(data.status)) {
|
|
clearInterval(interval)
|
|
}
|
|
} catch (err) {
|
|
consecutiveErrors++
|
|
if (consecutiveErrors >= 5) {
|
|
clearInterval(interval)
|
|
onStateChange('error', '', `网络异常: ${err.message || err}`)
|
|
}
|
|
}
|
|
}, 1000)
|
|
|
|
return { stop: () => clearInterval(interval) }
|
|
}
|
|
|
|
export async function fetchJobLoad(apiUrl = JOB_LOAD_URL) {
|
|
const res = await fetch(apiUrl, {
|
|
headers: API_KEY ? { 'X-API-Key': API_KEY } : {},
|
|
credentials: 'include',
|
|
})
|
|
if (!res.ok) {
|
|
throw new Error(`Job Load HTTP ${res.status}`)
|
|
}
|
|
return res.json()
|
|
}
|