Commit b14b9ba9 authored by 王蔡翾's avatar 王蔡翾
Browse files

兼容性补充

parent 6b7eef03
...@@ -8,7 +8,8 @@ ...@@ -8,7 +8,8 @@
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "eslint .", "lint": "eslint .",
"preview": "vite preview", "preview": "vite preview",
"test:prototype": "node --experimental-strip-types scripts/verify-prototype.mjs" "test:prototype": "node --experimental-strip-types scripts/verify-prototype.mjs",
"test:uuid": "node --experimental-strip-types scripts/verify-uuid.mjs"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "^5.2.2", "@hookform/resolvers": "^5.2.2",
......
import assert from 'node:assert/strict'
import { createUuid } from '../src/lib/uuid.ts'
const originalCrypto = Object.getOwnPropertyDescriptor(globalThis, 'crypto')
const realCrypto = globalThis.crypto
const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
const useCrypto = value => Object.defineProperty(globalThis, 'crypto', { configurable: true, value })
try {
// 安全上下文沿用浏览器原生方法,并保留 Crypto 接收者,防止 Illegal invocation。
const nativeCrypto = {
randomUUID() {
assert.equal(this, nativeCrypto)
return '12345678-1234-4234-8234-123456789abc'
},
getRandomValues() { assert.fail('支持原生 UUID 时不应走兼容分支') },
}
useCrypto(nativeCrypto)
assert.equal(createUuid(), '12345678-1234-4234-8234-123456789abc')
// 模拟普通 HTTP 环境:crypto 存在,但没有 randomUUID;检查补零、版本位与变体位。
for (const [fill, expected] of [
[0, '00000000-0000-4000-8000-000000000000'],
[255, 'ffffffff-ffff-4fff-bfff-ffffffffffff'],
]) {
const httpCrypto = {
getRandomValues(bytes) {
assert.equal(this, httpCrypto)
assert.ok(bytes instanceof Uint8Array)
assert.equal(bytes.length, 16)
return bytes.fill(fill)
},
}
useCrypto(httpCrypto)
assert.equal(createUuid(), expected)
}
// 用真实随机源验证兼容分支连续生成的格式与唯一性,避免固定键让不同提交相互覆盖。
useCrypto({ getRandomValues: bytes => realCrypto.getRandomValues(bytes) })
const ids = Array.from({ length: 1000 }, () => createUuid())
assert.ok(ids.every(id => uuidV4.test(id)))
assert.equal(new Set(ids).size, ids.length)
} finally {
Object.defineProperty(globalThis, 'crypto', originalCrypto)
}
console.log('UUID 兼容性检查通过(原生方法、HTTP 兼容分支、格式与唯一性)')
import { createUuid } from '../lib/uuid'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { FileUp, X } from 'lucide-react' import { FileUp, X } from 'lucide-react'
import { api } from '../lib/api' import { api } from '../lib/api'
...@@ -48,7 +49,7 @@ export function AddProjectDialog({ onClose, onAdded }: { onClose: () => void; on ...@@ -48,7 +49,7 @@ export function AddProjectDialog({ onClose, onAdded }: { onClose: () => void; on
if (saved) { await onAdded(); onClose(); return } if (saved) { await onAdded(); onClose(); return }
const data = { title: form.title.trim(), url: form.url.trim(), purchaser: form.purchaser.trim(), region: form.region.trim(), budgetWan: form.budget === '' ? null : Number(form.budget), fileId: file?.id ?? null } const data = { title: form.title.trim(), url: form.url.trim(), purchaser: form.purchaser.trim(), region: form.region.trim(), budgetWan: form.budget === '' ? null : Number(form.budget), fileId: file?.id ?? null }
const body = JSON.stringify(data) const body = JSON.stringify(data)
if (pending.current?.body !== body) pending.current = { body, commandId: crypto.randomUUID() } if (pending.current?.body !== body) pending.current = { body, commandId: createUuid() }
await api('/watch/manual', { method: 'POST', body: JSON.stringify({ ...data, commandId: pending.current.commandId }) }) await api('/watch/manual', { method: 'POST', body: JSON.stringify({ ...data, commandId: pending.current.commandId }) })
// 保存后即使刷新列表失败,也不能在关闭弹窗时删除已绑定的附件。 // 保存后即使刷新列表失败,也不能在关闭弹窗时删除已绑定的附件。
setFile(null); pending.current = null; setSaved(true) setFile(null); pending.current = null; setSaved(true)
......
import { createUuid } from '../lib/uuid'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { Send, Loader2 } from 'lucide-react' import { Send, Loader2 } from 'lucide-react'
...@@ -42,10 +43,11 @@ export function ConversationView({ id: initialId, scope: initialScope, embedded ...@@ -42,10 +43,11 @@ export function ConversationView({ id: initialId, scope: initialScope, embedded
const ask = async (raw = input) => { const ask = async (raw = input) => {
if (inFlight.current || !raw.trim() || !scope) return if (inFlight.current || !raw.trim() || !scope) return
inFlight.current = true; setBusy(true); setError('') inFlight.current = true; setBusy(true); setError('')
const body = { question: raw.trim(), scope }
const signature = JSON.stringify(body)
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID(), conversationId: id }
try { try {
// 生成提交键也属于提交流程;即使本地准备失败,finally 仍须解除发送锁以便重试。
const body = { question: raw.trim(), scope }
const signature = JSON.stringify(body)
if (pending.current?.signature !== signature) pending.current = { signature, key: createUuid(), conversationId: id }
if (!pending.current.conversationId) { if (!pending.current.conversationId) {
const c = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) }) const c = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) })
pending.current.conversationId = c.id pending.current.conversationId = c.id
......
import { createUuid } from '../lib/uuid'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { api } from '../lib/api' import { api } from '../lib/api'
import type { Tag, WatchItem } from '../lib/day2' import type { Tag, WatchItem } from '../lib/day2'
...@@ -25,7 +26,7 @@ export function ProjectTags({ projectId, onClose, showDone = true }: { projectId ...@@ -25,7 +26,7 @@ export function ProjectTags({ projectId, onClose, showDone = true }: { projectId
if (create) await api('/tags', { method: 'POST', body: JSON.stringify({ name: tag.trim() }) }) if (create) await api('/tags', { method: 'POST', body: JSON.stringify({ name: tag.trim() }) })
const selected = create ? [...new Set([...row.tags, tag.trim()])] : row.tags.includes(tag) ? row.tags.filter(t => t !== tag) : [...row.tags, tag] const selected = create ? [...new Set([...row.tags, tag.trim()])] : row.tags.includes(tag) ? row.tags.filter(t => t !== tag) : [...row.tags, tag]
const body = JSON.stringify({ tags: selected, version: row.version }) const body = JSON.stringify({ tags: selected, version: row.version })
if (pending.current?.body !== body) pending.current = { body, key: crypto.randomUUID() } if (pending.current?.body !== body) pending.current = { body, key: createUuid() }
await api(`/watch/${encodeURIComponent(projectId)}/tags`, { method: 'PUT', body, headers: { 'Idempotency-Key': pending.current.key } }) await api(`/watch/${encodeURIComponent(projectId)}/tags`, { method: 'PUT', body, headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null pending.current = null
const [all, rows] = await Promise.all([api<Tag[]>('/tags'), api<WatchItem[]>('/watch')]) const [all, rows] = await Promise.all([api<Tag[]>('/tags'), api<WatchItem[]>('/watch')])
......
import { createUuid } from '../lib/uuid'
import { Check, CircuitBoard, Loader2 } from 'lucide-react' import { Check, CircuitBoard, Loader2 } from 'lucide-react'
import { useRef, useState } from 'react' import { useRef, useState } from 'react'
import { api } from '../lib/api' import { api } from '../lib/api'
...@@ -49,7 +50,7 @@ export function ResearchTask({ id, onTask }: { id: string; onTask?: (task: Agent ...@@ -49,7 +50,7 @@ export function ResearchTask({ id, onTask }: { id: string; onTask?: (task: Agent
const body = { ...task.request, input: String(data.get('input') ?? task.request.input), maxCalls: Number(data.get('maxCalls') ?? task.request.maxCalls), maxCostUnits: Number(data.get('maxCostUnits') ?? task.request.maxCostUnits), const body = { ...task.request, input: String(data.get('input') ?? task.request.input), maxCalls: Number(data.get('maxCalls') ?? task.request.maxCalls), maxCostUnits: Number(data.get('maxCostUnits') ?? task.request.maxCostUnits),
...(task.request.research ? { research: { ...task.request.research, selections, acknowledgedCalls: task.status === 'WAITING_BUDGET' ? task.calls.filter(c => c.provider !== 'LOCAL').length : task.request.research.acknowledgedCalls } } : {}) } ...(task.request.research ? { research: { ...task.request.research, selections, acknowledgedCalls: task.status === 'WAITING_BUDGET' ? task.calls.filter(c => c.provider !== 'LOCAL').length : task.request.research.acknowledgedCalls } } : {}) }
const signature = `${id}:${JSON.stringify(body)}` const signature = `${id}:${JSON.stringify(body)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() } if (pending.current?.signature !== signature) pending.current = { signature, key: createUuid() }
await api(`/agent/tasks/${id}/continue`, { method: 'POST', body: JSON.stringify(body), headers: { 'Idempotency-Key': pending.current.key } }) await api(`/agent/tasks/${id}/continue`, { method: 'POST', body: JSON.stringify(body), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null pending.current = null
} }
......
import { createUuid } from '../lib/uuid'
import { useState } from 'react' import { useState } from 'react'
import { NavLink, useLocation, useNavigate } from 'react-router' import { NavLink, useLocation, useNavigate } from 'react-router'
import { Compass, Star, MessagesSquare, Building2, Plus, Pencil, Trash2, Search, LogOut, X } from 'lucide-react' import { Compass, Star, MessagesSquare, Building2, Plus, Pencil, Trash2, Search, LogOut, X } from 'lucide-react'
...@@ -85,7 +86,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -85,7 +86,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<div className="flex min-h-0 flex-1 flex-col border-t border-line-soft/60 fade-up"> <div className="flex min-h-0 flex-1 flex-col border-t border-line-soft/60 fade-up">
<div className="flex items-center justify-between px-4 pt-3"> <div className="flex items-center justify-between px-4 pt-3">
<span className="text-xs font-medium text-ink-900">最近对话</span> <span className="text-xs font-medium text-ink-900">最近对话</span>
<button onClick={() => navigate(`/research?new=${crypto.randomUUID()}`)} <button onClick={() => navigate(`/research?new=${createUuid()}`)}
className="inline-flex items-center gap-1 rounded-full border border-line-soft px-2.5 py-1 text-[11px] text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500"> className="inline-flex items-center gap-1 rounded-full border border-line-soft px-2.5 py-1 text-[11px] text-ink-600 transition-colors hover:border-brand-500/40 hover:text-brand-500">
<Plus size={11} /> 新建对话 <Plus size={11} /> 新建对话
</button> </button>
......
/**
* 为提交幂等键、命令 ID 和新会话链接生成 UUID v4。
* randomUUID 只在安全上下文及受支持浏览器中提供;通过普通 HTTP 访问时,
* 使用同样具备安全随机性的 getRandomValues,避免请求尚未发出就抛出异常。
* 重试是否复用同一个 ID 仍由调用方的 pending 状态控制,这里只负责生成。
*/
export function createUuid(): string {
if (typeof globalThis.crypto.randomUUID === 'function') return globalThis.crypto.randomUUID()
const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16))
// UUID v4 的第 7 字节高四位固定为 0100,第 9 字节高两位固定为 10。
// 其余 122 位保留随机值;不能用时间戳或 Math.random 替代,避免幂等键碰撞。
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
import { createUuid } from '../lib/uuid'
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { Link, useSearchParams } from 'react-router' import { Link, useSearchParams } from 'react-router'
import { Search, Star, Sparkles, Building2, ArrowRight, ExternalLink, Layers, SlidersHorizontal, Play, Pencil, Trash2 } from 'lucide-react' import { Search, Star, Sparkles, Building2, ArrowRight, ExternalLink, Layers, SlidersHorizontal, Play, Pencil, Trash2 } from 'lucide-react'
...@@ -46,7 +47,7 @@ export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPan ...@@ -46,7 +47,7 @@ export function DiscoverPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPan
const pending = useRef<{ fingerprint: string; key: string } | null>(null) const pending = useRef<{ fingerprint: string; key: string } | null>(null)
const keyFor = (value: unknown) => { const keyFor = (value: unknown) => {
const fingerprint = JSON.stringify(value) const fingerprint = JSON.stringify(value)
if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: crypto.randomUUID() } if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: createUuid() }
return pending.current.key return pending.current.key
} }
const reload = useCallback(async () => { const reload = useCallback(async () => {
......
import { createUuid } from '../lib/uuid'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router' import { useNavigate, useSearchParams } from 'react-router'
import { MessagesSquare, UserSearch, GitCompareArrows, Map, Send, X, Loader2 } from 'lucide-react' import { MessagesSquare, UserSearch, GitCompareArrows, Map, Send, X, Loader2 } from 'lucide-react'
...@@ -54,7 +55,7 @@ export function ResearchPage() { ...@@ -54,7 +55,7 @@ export function ResearchPage() {
const create = async (request: unknown, path = '/agent/tasks') => { const create = async (request: unknown, path = '/agent/tasks') => {
const signature = `${path}:${JSON.stringify(request)}` const signature = `${path}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() } if (pending.current?.signature !== signature) pending.current = { signature, key: createUuid() }
if (!pending.current.conversationId) { if (!pending.current.conversationId) {
const conversation = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) }) const conversation = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) })
pending.current.conversationId = conversation.id pending.current.conversationId = conversation.id
......
import { createUuid } from '../lib/uuid'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { api } from '../lib/api' import { api } from '../lib/api'
import { useTaskEvents } from '../hooks/useTaskEvents' import { useTaskEvents } from '../hooks/useTaskEvents'
...@@ -41,9 +42,9 @@ export function ServiceCheckPage() { ...@@ -41,9 +42,9 @@ export function ServiceCheckPage() {
const request = { operation, workflow: operation.startsWith('COMPANY_') ? 'COMPANY_INTEL' : 'TENDER_SEARCH', const request = { operation, workflow: operation.startsWith('COMPANY_') ? 'COMPANY_INTEL' : 'TENDER_SEARCH',
input, entityConfirmed: confirmed, maxCalls: Math.min(limits.maxCalls ?? 1, 1), maxCostUnits: Math.min(limits.maxCostUnits ?? 1, 1) } input, entityConfirmed: confirmed, maxCalls: Math.min(limits.maxCalls ?? 1, 1), maxCostUnits: Math.min(limits.maxCostUnits ?? 1, 1) }
const signature = JSON.stringify(request) const signature = JSON.stringify(request)
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('') setBusy(true); setError('')
try { try {
if (pending.current?.signature !== signature) pending.current = { signature, key: createUuid() }
const created = await api<{ id: string }>('/agent/tasks', { method: 'POST', body: signature, headers: { 'Idempotency-Key': pending.current.key } }) const created = await api<{ id: string }>('/agent/tasks', { method: 'POST', body: signature, headers: { 'Idempotency-Key': pending.current.key } })
setTaskId(created.id); setHistory(ids => [created.id, ...ids.filter(id => id !== created.id)]) setTaskId(created.id); setHistory(ids => [created.id, ...ids.filter(id => id !== created.id)])
pending.current = null pending.current = null
...@@ -66,9 +67,9 @@ export function ServiceCheckPage() { ...@@ -66,9 +67,9 @@ export function ServiceCheckPage() {
entityConfirmed: confirmed || task.request.entityConfirmed, entityConfirmed: confirmed || task.request.entityConfirmed,
maxCalls: task.status === 'WAITING_BUDGET' ? Math.min(limits.maxCalls ?? 1, task.calls.length + 1) : task.request.maxCalls } maxCalls: task.status === 'WAITING_BUDGET' ? Math.min(limits.maxCalls ?? 1, task.calls.length + 1) : task.request.maxCalls }
const signature = `${task.id}:${JSON.stringify(request)}` const signature = `${task.id}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('') setBusy(true); setError('')
try { try {
if (pending.current?.signature !== signature) pending.current = { signature, key: createUuid() }
await api(`/agent/tasks/${task.id}/continue`, { method: 'POST', body: JSON.stringify(request), headers: { 'Idempotency-Key': pending.current.key } }) await api(`/agent/tasks/${task.id}/continue`, { method: 'POST', body: JSON.stringify(request), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null pending.current = null
setTaskId(null); setTimeout(() => setTaskId(task.id), 0) setTaskId(null); setTimeout(() => setTaskId(task.id), 0)
......
import { createUuid } from '../lib/uuid'
import * as Popover from '@radix-ui/react-popover' import * as Popover from '@radix-ui/react-popover'
import { ProjectTags } from '../components/ProjectTags' import { ProjectTags } from '../components/ProjectTags'
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
...@@ -34,7 +35,7 @@ export function WatchPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPanelS ...@@ -34,7 +35,7 @@ export function WatchPage({ onOpenPanel }: { onOpenPanel: (state: AnalysisPanelS
// 相同编辑保留同一命令键,网络结果不确定时重试不会重复写入历史。 // 相同编辑保留同一命令键,网络结果不确定时重试不会重复写入历史。
const commandKey = (value: unknown) => { const commandKey = (value: unknown) => {
const fingerprint = JSON.stringify(value) const fingerprint = JSON.stringify(value)
if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: crypto.randomUUID() } if (pending.current?.fingerprint !== fingerprint) pending.current = { fingerprint, key: createUuid() }
return pending.current.key return pending.current.key
} }
const reload = useCallback(async () => { const reload = useCallback(async () => {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment