Commit 6b7eef03 authored by 王蔡翾's avatar 王蔡翾
Browse files

按照原型还原

parent 12121653
import { Check, CircuitBoard, Loader2 } from 'lucide-react'
import { useRef, useState } from 'react'
import { api } from '../lib/api'
import { useTaskEvents } from '../hooks/useTaskEvents'
import type { AgentTask } from '../hooks/useTaskEvents'
import type { ResearchReport } from '../lib/day3'
import { toolNames } from '../lib/day3'
import { inputClass, message } from '../lib/day2'
import { GhostButton, PrimaryButton } from './ui-ext/AiButton'
const labels: Record<string, string> = { fullname: '企业全称', name: '名称', title: '标题', province: '省份', city: '城市', county: '区县', industry: '行业', capital: '注册资本', size: '企业规模', business_status: '经营状态', establishment_date: '成立日期', business_scope: '经营范围', caller_count: '招标次数', winner_count: '中标次数', company_name: '企业', company_id: '主体编号', cooperation_count: '合作次数', cooperation_amount: '合作金额(元)', cooperation_amount_wan: '合作金额(万元)', last_cooperation_time: '最近合作时间', products: '合作品类', keywords: '业务词', partners: '合作伙伴', items: '公告记录', total: '平台总数', bid_id: '公告编号', pub_time: '发布时间', money: '金额(元)', money_wan: '金额(万元)', caller_name: '采购方', winner_names: '中标方', sm_names: '标的物', fulltext: '正文', competitors: '竞争者', co_bid_count: '共同投标次数', top_co_bid_products: '交锋品类', top_co_bid_callers: '共同客户', top_co_bid_provinces: '交锋区域', keyword: '关键词', count: '次数', amount: '金额(元)', buckets: '聚合结果', key: '分组', sum_amount: '金额合计(元)', total_count: '记录总数', total_amount: '金额合计(元)', content: '正文', results: '公开资料', snippet: '摘录', url: '原始来源', filename: '文件名', segments: '定位段落', locator: '位置', text: '正文', needsVision: '需视觉识别', price_stats: '价格统计', bidders: '潜在投标者', service_end_date: '服务截止时间', agency_name: '代理机构' }
function sectionTitle(section: ResearchReport['sections'][number]) {
if (section.key.endsWith(':customers')) return '历史客户'
if (section.key.endsWith(':suppliers')) return '历史供应商'
if (section.key.includes(':light:')) return `Top 竞对 ${Number(section.key.split(':').at(-1)) + 1} 基础画像`
return toolNames[section.tool] ?? section.tool
}
/** React 仅渲染文字节点,不解析供应商 HTML;外链再次限制 HTTP(S),保留签名参数。 */
function Facts({ value }: { value: unknown }) {
if (value == null || value === '') return <span className="text-ink-400">未提供</span>
if (typeof value === 'string') return /^https?:\/\//i.test(value) ? <a href={value} target="_blank" rel="noopener noreferrer" className="break-all text-brand-500 underline">查看原始来源</a> : <span className="whitespace-pre-wrap break-words">{value}</span>
if (typeof value === 'boolean') return <span>{value ? '是' : '否'}</span>
if (typeof value === 'number') return <span>{String(value)}</span>
if (Array.isArray(value)) return value.length ? <ul className="space-y-3">{value.map((item, i) => <li key={i} className="border-l-2 border-line-soft pl-3"><Facts value={item} /></li>)}</ul> : <span className="text-ink-400">本次未查到记录</span>
return <dl className="space-y-2">{Object.entries(value).map(([key, item]) => <div key={key}><dt className="text-xs text-ink-400">{labels[key] ?? key}</dt><dd className="mt-1"><Facts value={item} /></dd></div>)}</dl>
}
/** 四个调研入口共用真实 SSE、确认、取消、报告与费用组件,页面刷新只读取任务。 */
export function ResearchTask({ id, onTask }: { id: string; onTask?: (task: AgentTask) => void }) {
const [revision, setRevision] = useState(0)
const { task, error: streamError } = useTaskEvents(id, revision)
const [busy, setBusy] = useState(false), [error, setError] = useState('')
const pending = useRef<{ signature: string; key: string } | null>(null)
const report = task?.result as ResearchReport | null
const command = async (cancel: boolean, form?: HTMLFormElement) => {
if (!task || busy) return
setBusy(true); setError('')
try {
if (cancel) await api(`/agent/tasks/${id}/cancel`, { method: 'POST' })
else {
const data = new FormData(form)
const selections = { ...task.request.research?.selections }
for (const choice of report?.choices ?? []) {
const selected = data.get(choice.key)
if (selected) selections[choice.key] = String(selected)
}
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 } } : {}) }
const signature = `${id}:${JSON.stringify(body)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
await api(`/agent/tasks/${id}/continue`, { method: 'POST', body: JSON.stringify(body), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null
}
setRevision(x => x + 1)
onTask?.(await api<AgentTask>(`/agent/tasks/${id}`))
} catch (e) { setError(message(e)) } finally { setBusy(false) }
}
if (!task) return <p role="status">{streamError || '正在读取任务…'}</p>
const complete = ['SUCCEEDED', 'FAILED', 'PARTIAL', 'CANCELLED'].includes(task.status)
// 原型的回复由“Skill 调用进展 + 正文”组成,只把真实执行和报告映射到这两个区域。
// 调用账本、模型参数和刷新按钮不属于原型,不再额外插入消息内容。
return <section className="rounded-card border border-line-soft bg-white px-4 py-3 shadow-card">
<div className="mb-2 rounded-ctrl border border-line-soft bg-canvas px-3 py-2">
<div className="flex items-center gap-2 text-[12px] font-semibold text-brand-500">{complete ? <CircuitBoard size={13} /> : <Loader2 size={13} className="animate-spin" />} Skill 调用进展</div>
<ul className="mt-1 space-y-1">{task.calls.map(call => <li key={String(call.id)} className="flex items-center gap-1.5 text-[12px] text-ink-600">{call.status === 'SUCCEEDED' ? <Check size={12} className="text-ok-500" /> : <span className="h-3 w-3" />}{toolNames[String(call.tool_name)] ?? String(call.tool_name)}</li>)}</ul>
</div>
{(error || streamError) && <p role="alert" className="mb-2 text-xs text-bad-500">{error || streamError}</p>}
{(task.status.startsWith('WAITING_') || task.status === 'FAILED') && task.question && <p className="mb-3 text-[13px] text-ink-600">{task.question}</p>}
{task.status.startsWith('WAITING_') && <form key={`${id}:${revision}:${task.status}`} onSubmit={e => { e.preventDefault(); void command(false, e.currentTarget) }} className="space-y-3 rounded-ctrl bg-canvas p-4">
{task.status === 'WAITING_ENTITY' && report?.choices?.map(choice => <label key={choice.key} className="block text-sm">{choice.key.startsWith('entity:') ? `企业 ${Number(choice.key.split(':')[1]) + 1}` : choice.key === 'buyer:entity' ? '采购方主体' : '项目公告'}
<select name={choice.key} required defaultValue={choice.selected} className={`${inputClass} mt-1`}><option value="">选择本次明确主体</option>{choice.options.map(option => <option key={option.id} value={option.id}>{option.name} · {option.region || '地区未知'} · {option.id}</option>)}</select>
</label>)}
{task.status === 'WAITING_INPUT' && task.operation === 'BID_RESEARCH' && <label className="block text-sm">完整公开项目标题<input name="input" defaultValue={task.request.input} maxLength={2000} className={inputClass} /></label>}
{task.status === 'WAITING_BUDGET' && <><p className="text-xs text-ink-600">已发生费用保留。继续从下一步执行;未知积分需先核对账单,首个未知单价请求可能超出积分上限。</p><div className="grid grid-cols-2 gap-3"><label className="text-sm">累计调用上限<input name="maxCalls" type="number" min={1} max={task.request.research?.companies.length === 1 && task.operation === 'COMPANY_RESEARCH' ? 18 : 25} defaultValue={task.request.maxCalls} required className={inputClass} /></label><label className="text-sm">累计积分上限<input name="maxCostUnits" type="number" min="0.01" max="1000" step="0.01" defaultValue={task.request.maxCostUnits} required className={inputClass} /></label></div><label className="flex gap-2 text-sm"><input type="checkbox" required />我已核对现有调用与费用,确认继续后续请求</label></>}
<div className="flex gap-2"><GhostButton disabled={busy} onClick={() => void command(true)}>取消</GhostButton><PrimaryButton disabled={busy} type="submit">确认并继续</PrimaryButton></div>
</form>}
{report && <div className="space-y-4 text-sm leading-7 text-ink-600">
{report.observations?.map((item, index) => <p key={index}>{item.text}</p>)}
{report.ownFit && <div><h3 className="font-semibold text-ink-900">结合公司档案对照</h3><p>贴合度参考:{report.ownFit.match.score ?? '资料不足'} 分</p>{Object.entries(report.ownFit.match.dimensions).map(([key, dimension]) => <p key={key} className="text-[13px]">{dimension.basis}</p>)}</div>}
{report.commonCustomers && <div><h3 className="font-semibold text-ink-900">共同客户</h3><p>{report.commonCustomers.join('、') || '当前样本未检出共同客户'}</p></div>}
{report.sections?.map(section => <div key={section.key}><h3 className="mb-2 font-semibold text-ink-900">{sectionTitle(section)}</h3><Facts value={section.data} /></div>)}
{report.gaps?.length > 0 && <ul className="list-disc space-y-1 pl-5 text-[13px]">{report.gaps.map(gap => <li key={gap}>{gap}</li>)}</ul>}
</div>}
</section>
}
...@@ -4,6 +4,8 @@ import { Compass, Star, MessagesSquare, Building2, Plus, Pencil, Trash2, Search, ...@@ -4,6 +4,8 @@ import { Compass, Star, MessagesSquare, Building2, Plus, Pencil, Trash2, Search,
import { motion, AnimatePresence } from 'framer-motion' import { motion, AnimatePresence } from 'framer-motion'
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils'
import { useStore } from '@/lib/store' import { useStore } from '@/lib/store'
import { api } from '../lib/api'
import { conversationsChanged, useConversations } from '../lib/conversations'
import Pill from '@/components/ui-ext/Pill' import Pill from '@/components/ui-ext/Pill'
import { GhostButton, PrimaryButton } from '@/components/ui-ext/AiButton' import { GhostButton, PrimaryButton } from '@/components/ui-ext/AiButton'
...@@ -15,20 +17,26 @@ const NAV = [ ...@@ -15,20 +17,26 @@ const NAV = [
] ]
export default function Sidebar({ onLogout }: { onLogout: () => void }) { export default function Sidebar({ onLogout }: { onLogout: () => void }) {
const { profile, watch, research, saveConversation, deleteConversation } = useStore() const { profile, watch } = useStore()
const location = useLocation() const location = useLocation()
const navigate = useNavigate() const navigate = useNavigate()
const [renaming, setRenaming] = useState<string | null>(null) const [renaming, setRenaming] = useState<string | null>(null)
const [renameText, setRenameText] = useState('') const [renameText, setRenameText] = useState('')
const [histQuery, setHistQuery] = useState('') const [histQuery, setHistQuery] = useState('')
const [confirmDelete, setConfirmDelete] = useState<string | null>(null) const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
const { items: research, error: historyError, more, load } = useConversations(histQuery)
const [actionError, setActionError] = useState('')
const researchOpen = location.pathname === '/research' const researchOpen = location.pathname === '/research'
const filtered = research.filter(c => !histQuery.trim() || c.title.includes(histQuery.trim())) const filtered = research
const submitRename = (id: string) => { const submitRename = async (id: string) => {
const c = research.find(x => x.id === id) const c = research.find(x => x.id === id)
if (c && renameText.trim()) saveConversation({ ...c, title: renameText.trim() })
setRenaming(null) setRenaming(null)
if (!c || !renameText.trim() || renameText.trim() === c.title) return
try {
await api(`/conversations/${id}`, { method: 'PATCH', body: JSON.stringify({ title: renameText.trim(), version: c.version }) })
setActionError(''); conversationsChanged()
} catch (e) { setActionError(e instanceof Error ? e.message : '重命名失败') }
} }
return ( return (
...@@ -77,7 +85,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -77,7 +85,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=1')} <button onClick={() => navigate(`/research?new=${crypto.randomUUID()}`)}
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>
...@@ -90,6 +98,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -90,6 +98,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
</div> </div>
</div> </div>
<div className="mt-1 flex-1 space-y-0.5 overflow-y-auto px-2 pb-2 scrollbar-thin"> <div className="mt-1 flex-1 space-y-0.5 overflow-y-auto px-2 pb-2 scrollbar-thin">
{(historyError || actionError) && <p role="alert" className="p-2 text-xs text-red-700">{historyError || actionError}</p>}
{more && <button className="p-2 text-xs text-brand-500" onClick={() => void load(research.length).catch(e => setActionError(e.message))}>加载更多会话</button>}
{filtered.length === 0 ? ( {filtered.length === 0 ? (
<p className="px-3 py-6 text-center text-[11px] leading-relaxed text-ink-400"> <p className="px-3 py-6 text-center text-[11px] leading-relaxed text-ink-400">
{histQuery ? '没有匹配的对话' : '开始一次探索,对话会保存在这里'} {histQuery ? '没有匹配的对话' : '开始一次探索,对话会保存在这里'}
...@@ -101,8 +111,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -101,8 +111,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
{renaming === c.id ? ( {renaming === c.id ? (
<input autoFocus value={renameText} onChange={e => setRenameText(e.target.value)} <input autoFocus value={renameText} onChange={e => setRenameText(e.target.value)}
onClick={e => e.stopPropagation()} onClick={e => e.stopPropagation()}
onKeyDown={e => { if (e.key === 'Enter') submitRename(c.id); if (e.key === 'Escape') setRenaming(null) }} onKeyDown={e => { if (e.key === 'Enter') void submitRename(c.id); if (e.key === 'Escape') setRenaming(null) }}
onBlur={() => submitRename(c.id)} maxLength={128} onBlur={() => void submitRename(c.id)}
className="min-w-0 flex-1 rounded border border-brand-500 px-1.5 py-0.5 text-[12px] outline-none" /> className="min-w-0 flex-1 rounded border border-brand-500 px-1.5 py-0.5 text-[12px] outline-none" />
) : ( ) : (
<> <>
...@@ -128,8 +138,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -128,8 +138,8 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<img src="/avatar-user.png" alt="用户头像" className="h-9 w-9 rounded-full ring-2 ring-brand-50" /> <img src="/avatar-user.png" alt="用户头像" className="h-9 w-9 rounded-full ring-2 ring-brand-50" />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium text-ink-900">张晨</div> <div className="truncate text-sm font-medium text-ink-900">admin</div>
<div className="text-xs text-ink-400">商务拓展</div> <div className="text-xs text-ink-400">管理员</div>
</div> </div>
<button onClick={onLogout} title="退出登录" <button onClick={onLogout} title="退出登录"
className="rounded-full p-1.5 text-ink-400 transition-colors hover:bg-bad-500/10 hover:text-bad-500"> className="rounded-full p-1.5 text-ink-400 transition-colors hover:bg-bad-500/10 hover:text-bad-500">
...@@ -156,7 +166,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) { ...@@ -156,7 +166,7 @@ export default function Sidebar({ onLogout }: { onLogout: () => void }) {
<p className="mt-0.5 text-[13px] text-ink-400">删除后将无法恢复。</p> <p className="mt-0.5 text-[13px] text-ink-400">删除后将无法恢复。</p>
<div className="mt-4 flex justify-center gap-2"> <div className="mt-4 flex justify-center gap-2">
<GhostButton onClick={() => setConfirmDelete(null)}>再想想</GhostButton> <GhostButton onClick={() => setConfirmDelete(null)}>再想想</GhostButton>
<PrimaryButton onClick={() => { deleteConversation(confirmDelete); setConfirmDelete(null) }} <PrimaryButton onClick={() => { void api(`/conversations/${confirmDelete}`, { method: 'DELETE' }).then(() => { setConfirmDelete(null); conversationsChanged(); navigate('/research') }).catch(e => setActionError(e.message)) }}
className="!bg-bad-500 hover:!bg-bad-500/90 !shadow-[0_2px_8px_rgba(244,63,94,.25)]">确认删除</PrimaryButton> className="!bg-bad-500 hover:!bg-bad-500/90 !shadow-[0_2px_8px_rgba(244,63,94,.25)]">确认删除</PrimaryButton>
</div> </div>
</motion.div> </motion.div>
......
...@@ -18,10 +18,11 @@ export default function Topbar() { ...@@ -18,10 +18,11 @@ export default function Topbar() {
return () => window.clearInterval(t) return () => window.clearInterval(t)
}, []) }, [])
const p = (n: number) => String(n).padStart(2, '0') // 页面标注北京时间,不能直接使用访问者设备的本地时区。
const clock = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false }).format(now)
return ( return (
<header className="sticky top-0 z-40 flex h-16 items-center gap-5 border-b border-line-soft/50 bg-white/80 px-4 backdrop-blur-md sm:px-6 xl:px-8"> <header className="sticky top-0 z-40 flex h-16 shrink-0 items-center gap-5 border-b border-line-soft/50 bg-white/80 px-4 backdrop-blur-md sm:px-6 xl:px-8">
<div className="min-w-0"> <div className="min-w-0">
<h1 className="text-xl font-semibold leading-tight text-ink-900">{meta.title}</h1> <h1 className="text-xl font-semibold leading-tight text-ink-900">{meta.title}</h1>
<p className="text-xs text-ink-400 max-sm:hidden">{meta.sub}</p> <p className="text-xs text-ink-400 max-sm:hidden">{meta.sub}</p>
...@@ -29,7 +30,7 @@ export default function Topbar() { ...@@ -29,7 +30,7 @@ export default function Topbar() {
<div className="flex-1" /> <div className="flex-1" />
<div className="hidden items-center gap-2 text-xs text-ink-400 sm:flex"> <div className="hidden items-center gap-2 text-xs text-ink-400 sm:flex">
<span className="font-num"> <span className="font-num">
北京时间 {now.getFullYear()}-{p(now.getMonth() + 1)}-{p(now.getDate())} {p(now.getHours())}:{p(now.getMinutes())} 北京时间 {clock}
</span> </span>
</div> </div>
</header> </header>
......
...@@ -16,6 +16,7 @@ const AiButton = forwardRef<HTMLButtonElement, AiButtonProps>( ...@@ -16,6 +16,7 @@ const AiButton = forwardRef<HTMLButtonElement, AiButtonProps>(
({ children, loading, noIcon, className, ...props }, ref) => { ({ children, loading, noIcon, className, ...props }, ref) => {
return ( return (
<motion.button <motion.button
type="button"
ref={ref} ref={ref}
whileHover={{ scale: 1.02 }} whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }} whileTap={{ scale: 0.98 }}
...@@ -50,6 +51,7 @@ export function PrimaryButton({ ...@@ -50,6 +51,7 @@ export function PrimaryButton({
}: ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean }) { }: ButtonHTMLAttributes<HTMLButtonElement> & { loading?: boolean }) {
return ( return (
<motion.button <motion.button
type="button"
whileHover={{ scale: 1.02 }} whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }} whileTap={{ scale: 0.98 }}
{...(props as object)} {...(props as object)}
...@@ -66,7 +68,7 @@ export function PrimaryButton({ ...@@ -66,7 +68,7 @@ export function PrimaryButton({
) )
} }
/** 幽灵按钮:白底 1px 灰边 */ /** 幽灵按钮:白底 1px 灰边;默认普通按钮,避免弹窗“取消”触发表单提交。 */
export function GhostButton({ export function GhostButton({
children, children,
className, className,
...@@ -74,6 +76,7 @@ export function GhostButton({ ...@@ -74,6 +76,7 @@ export function GhostButton({
}: ButtonHTMLAttributes<HTMLButtonElement>) { }: ButtonHTMLAttributes<HTMLButtonElement>) {
return ( return (
<motion.button <motion.button
type="button"
whileHover={{ scale: 1.02 }} whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }} whileTap={{ scale: 0.98 }}
{...(props as object)} {...(props as object)}
......
import { useCallback, useEffect, useRef } from 'react'
// 流式输出 hook:把完整文本按字符逐步吐出,模拟 AI 生成过程
export function useStreaming() {
const timerRef = useRef<number | null>(null)
// 必须用 useCallback 固定引用:否则每次渲染都会生成新 stop,
// 使依赖 [stop] 的卸载 effect 在每次渲染时触发清理,把进行中的 trace 定时器一并清掉
const stop = useCallback(() => {
if (timerRef.current) window.clearInterval(timerRef.current)
timerRef.current = null
}, [])
useEffect(() => () => {
if (timerRef.current) window.clearInterval(timerRef.current)
}, [])
const stream = (
full: string,
onTick: (partial: string, done: boolean) => void,
speed = 12,
) => {
if (timerRef.current) window.clearInterval(timerRef.current)
let pos = 0
timerRef.current = window.setInterval(() => {
pos = Math.min(full.length, pos + 3)
onTick(full.slice(0, pos), pos >= full.length)
if (pos >= full.length && timerRef.current) {
window.clearInterval(timerRef.current)
timerRef.current = null
}
}, speed)
}
return { stream, stop }
}
// 逐条展示 Skill 调用步骤,全部完成后回调
export function runSkillTrace(
steps: string[],
onStep: (done: string[]) => void,
onComplete: () => void,
interval = 700,
): () => void {
let idx = 0
const done: string[] = []
const timer = window.setInterval(() => {
if (idx < steps.length) {
done.push(steps[idx++])
onStep([...done])
} else {
window.clearInterval(timer)
onComplete()
}
}, interval)
return () => window.clearInterval(timer)
}
import { useEffect, useRef, useState } from 'react'
import type { ResearchRequest } from '../lib/day3'
import type { SearchQuery } from '../lib/day2'
import type { QaScope } from '../lib/conversations'
import { api, ApiError } from '../lib/api'
export interface TaskEvent {
id: number
type: string
payload: { message?: string; text?: string; status?: string; [key: string]: unknown }
}
export interface AgentTask {
id: string
status: string
operation: string
question: string | null
result: unknown
usage?: { external_calls: number; zlbx_calls: number; known_cost_units: number; unknown_cost_calls: number; model_web_calls: number; input_tokens: number; output_tokens: number; unknown_token_calls: number }
request: { operation: string; workflow: string; input: string; entityConfirmed: boolean; maxCalls: number; maxCostUnits: number; opportunity?: SearchQuery; research?: ResearchRequest; qa?: QaScope }
children?: { id: string; status: string; operation: string; target?: { research?: ResearchRequest; qa?: QaScope } }[]
calls: Record<string, unknown>[]
evidence: { id: string; url: string | null; locator: string; excerpt: string; title?: string; verified?: boolean }[]
}
/** 原生 EventSource 用 Cookie 鉴权;游标只重放事件,不重复 POST 收费任务。 */
export function useTaskEvents(taskId: string | null, revision = 0) {
const [events, setEvents] = useState<TaskEvent[]>([])
const [task, setTask] = useState<AgentTask | null>(null)
const [error, setError] = useState('')
const cursor = useRef(0)
useEffect(() => {
if (!taskId) return
let active = true
let source: EventSource | null = null
let timer: ReturnType<typeof setTimeout> | undefined
let initial = true
let refreshVersion = 0
let retries = 0
cursor.current = 0
const refresh = async () => {
const version = ++refreshVersion
const next = await api<AgentTask>(`/agent/tasks/${taskId}`)
// 多页进度与终态可能相邻到达,只接受最近一次读取,防止慢响应覆盖最终报告。
if (active && version === refreshVersion) {
if (initial) { setEvents([]); setError(''); initial = false }
setTask(next)
}
return next
}
// 后端暂时不可达时持续只读恢复,延迟最多 15 秒;认证失效后停止,交给登录页处理。
const retry = (error?: unknown) => {
if (!active || (error instanceof ApiError && [401, 403, 404].includes(error.status))) {
if (active && error instanceof Error) setError(error.message)
return
}
setError('连接已中断,正在恢复事件与已有结果;不会重新发起收费请求')
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
void refresh().then(() => { if (active) connect() }).catch(retry)
}, Math.min(15000, 1000 * 2 ** Math.min(retries++, 4)))
}
const connect = () => {
if (!active) return
source = new EventSource(`/api/agent/tasks/${taskId}/events?after=${cursor.current}`)
source.addEventListener('task-event', event => {
const entry: TaskEvent = JSON.parse((event as MessageEvent).data)
if (!active || entry.id <= cursor.current) return
cursor.current = entry.id
setEvents(items => [...items, entry])
setError(''); retries = 0
if (['PAGE_COLLECTED', 'MARKET_COLLECTED', 'RESEARCH_STEP'].includes(entry.type)) void refresh().catch(error => { if (active) setError(error.message) })
})
source.addEventListener('idle', () => {
source?.close()
void refresh().catch(error => { if (active) setError(error.message) })
})
source.onerror = () => {
source?.close()
// 无论任务是否刚好完成,都重新订阅并追完游标之后的最终事件,直到收到 idle。
retry()
}
}
void refresh().then(() => { if (active) connect() }).catch(retry)
return () => { active = false; source?.close(); if (timer) clearTimeout(timer) }
}, [taskId, revision])
return { events, task: task?.id === taskId ? task : null, error }
}
This diff is collapsed.
/** 统一同源客户端。会话只放 HttpOnly Cookie;API Key 不进入前端环境或 localStorage。 */
export class ApiError extends Error {
readonly status: number
readonly code: string
constructor(status: number, code: string, message: string) {
super(message); this.status = status; this.code = code
}
}
let csrf: { token: string; headerName: string } | null = null
export async function refreshCsrf() {
const response = await fetch('/api/auth/csrf', { credentials: 'same-origin' })
if (!response.ok) throw new ApiError(response.status, 'CSRF_UNAVAILABLE', '无法连接登录服务,请检查后端是否启动')
csrf = await response.json()
}
/** 不自动重试写请求,尤其是可能收费的任务;幂等重试必须沿用调用方保留的键。 */
export async function api<T>(path: string, options: RequestInit = {}): Promise<T> {
const method = (options.method ?? 'GET').toUpperCase()
const headers = new Headers(options.headers)
if (!['GET', 'HEAD', 'OPTIONS'].includes(method)) {
if (!csrf) await refreshCsrf()
if (csrf) headers.set(csrf.headerName, csrf.token)
if (options.body && !(options.body instanceof FormData) && !headers.has('Content-Type')) headers.set('Content-Type', 'application/json')
}
let response: Response
try { response = await fetch(`/api${path}`, { ...options, method, headers, credentials: 'same-origin' }) }
catch { throw new ApiError(0, 'NETWORK_ERROR', '网络连接失败,请检查后端;提交结果未知时请保留原任务键重试') }
const data = await response.json().catch(() => ({}))
if (!response.ok) {
if (response.status === 401 && path !== '/auth/login') window.dispatchEvent(new Event('session-expired'))
if (response.status === 403) csrf = null
throw new ApiError(response.status, data.code ?? 'REQUEST_FAILED', data.message ?? '服务请求失败,请稍后重试')
}
return data as T
}
export async function login(username: string, password: string) {
await refreshCsrf()
await api('/auth/login', {
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ username, password }),
})
// Spring Security 在认证成功后轮换会话与 CSRF token,必须重新获取。
csrf = null
await refreshCsrf()
}
export async function logout() {
await api('/auth/logout', { method: 'POST' })
csrf = null
}
import { useCallback, useEffect, useRef, useState } from 'react'
import { api } from './api'
export interface Conversation { id: string; title: string; version: number; created_at: string; updated_at: string }
export interface ConversationMessage { id: string; role: string; content: string; task_id: string | null; created_at: string }
export interface QaScope { batchId: string | null; projectId: string | null }
export const conversationsChanged = () => window.dispatchEvent(new Event('conversations-changed'))
/** 会话列表从服务器搜索并分页;刷新、跨页面新建或改名后均回读,浏览器不持久化账号资料。 */
export function useConversations(query = '') {
const [items, setItems] = useState<Conversation[]>([])
const [error, setError] = useState('')
const [more, setMore] = useState(false)
const requestVersion = useRef(0)
const invalidate = useCallback(() => { requestVersion.current++ }, [])
const load = useCallback(async (offset = 0) => {
const version = ++requestVersion.current
const rows = await api<Conversation[]>(`/conversations?q=${encodeURIComponent(query)}&offset=${offset}`)
if (version !== requestVersion.current) return
setItems(current => offset ? [...current, ...rows] : rows); setMore(rows.length === 50); setError('')
}, [query])
useEffect(() => {
let active = true
const refresh = () => { void load().catch(e => { if (active) setError(e.message) }) }
const timer = setTimeout(refresh, 200)
window.addEventListener('conversations-changed', refresh)
return () => { active = false; invalidate(); clearTimeout(timer); window.removeEventListener('conversations-changed', refresh) }
}, [load, invalidate])
return { items, error, more, load }
}
import type { WatchStatus, StatusChange } from '../types'
/** 后端权威契约:万元与缺失值保持原样;浏览器不重新计算匹配分或收费。 */
export interface SearchQuery {
keywords: string[]
beginDate: string
endDate: string
stages: number[]
preference: 'COMPREHENSIVE' | 'REGION' | 'BUSINESS' | 'AMOUNT'
preferredRegions: string[]
budgetMinWan: number | null
budgetMaxWan: number | null
mode: 'SEARCH' | 'LEADS' | 'MARKET'
keywordMode: 'ANY' | 'ALL'
hardRegions: string[]
hardMinWan: number | null
hardMaxWan: number | null
}
export interface Candidate {
id: string; sourceId: string; title: string; purchaser: string; region: string
budgetWan: number | null; publishDate: string; stage: number | null; url: string | null
userFileId?: string | null; products: string[]; evidenceId: string | null; gaps: string[]
}
export interface RankedItem {
facts: Candidate; relevance: number; preferenceBonus: number; reasoning: string[]
analysis: null | {
projectNumber: string
summary: { construction: string; region: string; schedule: string[]; qualifications: string[]; gaps: string[]; evidenceId: string; locator: string; method: string }
match: { score: number | null; completeness: number; profileVersion: number; version: string; limitation: string
weights: Record<string, number>; dimensions: Record<string, { score: number; known: boolean; basis: string }> }
}
}
export interface SearchReport {
conditions: SearchQuery; rankingVersion: string
scope: { platformTotal: number | null; fetchedCount: number; uniqueCount: number; displayCount: number; pagesRead: number; stopReason: string; complete: boolean }
stageChains: { projectNumber: string; purchaser: string; notices: Candidate[]; basis: string }[]
items: RankedItem[]; limitations: string[]; referencesVerified: boolean
summaryProgress: { completed: number; total: number; method: string }
market?: { basis: string; buyers: Record<string, number>; suppliers: Record<string, number>; monthlyNotices: Record<string, number>; platformAggregations: { tool: string; evidenceId: string; scope: string; rows: { name: string; count: number | null; amountWan: number | null; url: string | null }[] }[] }
}
export interface SearchHistory { id: string; status: string; createdAt: string; schemeId: string | null; schemeName: string | null; schemeVersion: number | null }
export interface SearchScheme { id: string; name: string; conditions: SearchQuery; version: number }
export interface WatchItem {
fileId?: string | null; summary?: NonNullable<RankedItem['analysis']>['summary']
projectId: string; status: WatchStatus; note: string; version: number; tags: string[]
createdAt: string; history: StatusChange[]; group: string; project: Candidate
}
export interface Tag { id: string; name: string }
export const inputClass = 'w-full rounded-ctrl border border-line-soft bg-white px-3 py-2 text-sm outline-none focus:border-brand-500'
export const stageNames: Record<number, string> = { 1: '采购意向', 2: '预招标', 4: '招标', 5: '更正', 6: '终止', 7: '中标', 8: '合同', 9: '其他', 10: '其他' }
export const preferenceNames = { COMPREHENSIVE: '综合推荐', REGION: '地域优先', BUSINESS: '业务优先', AMOUNT: '金额优先' }
/** 时间快捷选项统一使用北京时间,避免午夜时浏览器时区改变查询日期。 */
export function beijingDate(offset = 0) {
return new Date(Date.now() + (8 * 60 * 60 * 1000) - offset * 86400000).toISOString().slice(0, 10)
}
export function initialQuery(): SearchQuery {
return { keywords: [], beginDate: beijingDate(89), endDate: beijingDate(), stages: [1, 2, 4, 7, 8], preference: 'COMPREHENSIVE', preferredRegions: [], budgetMinWan: null, budgetMaxWan: null, mode: 'LEADS', keywordMode: 'ANY', hardRegions: [], hardMinWan: null, hardMaxWan: null }
}
export function words(value: string) { return value.split(/[、,,;;\n]+/).map(s => s.trim()).filter(Boolean) }
export function message(error: unknown) { return error instanceof Error ? error.message : '请求失败,请重试' }
export function time(value: string) { return new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) }
/** 仅格式化原文明确写出的报名截止日期;不拿投标日期代替,也不把无效日期自动顺延。 */
export function registrationDate(schedule: string[] = []): string | null {
const match = schedule.join(';').match(/报名(?:时间)?(?:截止|截至)(?:时间)?\s*[::]?\s*(\d{4})[-年/.](\d{1,2})[-月/.](\d{1,2})/)
if (!match) return null
const value = `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`
const date = new Date(`${value}T00:00:00Z`)
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value ? value : null
}
/** D3 请求只传业务参数;工具路径、主体事实与费用一律由后端确定。 */
export interface ResearchRequest {
companies: string[]
selections: Record<string, string>
mode: 'QUICK' | 'FULL'
fileId: string | null
parentId: string | null
targetProjectId: string | null
focus: string | null
acknowledgedCalls: number
}
export interface ResearchReport {
kind: 'COMPANY_RESEARCH' | 'BID_RESEARCH' | 'SNAPSHOT_QA'
choices: { key: string; options: { id: string; name: string; region: string }[]; selected: string }[]
sections: { key: string; tool: string; evidenceId: string; kind: string; data: unknown }[]
observations: { text: string; evidenceIds: string[] }[]
ownFit?: { summary: { construction: string; qualifications: string[]; gaps: string[] }; match: { score: number | null; completeness: number; profileVersion: number; limitation: string; dimensions: Record<string, { basis: string; score: number; known: boolean }> } }
commonCustomers?: string[]
comparisonBasis?: string
gaps: string[]
scope: { beginDate?: string; basis: string; stepCount?: number; answerCount?: number; candidateCount?: number; platform_total?: number | null; fetched_count?: number; conditions?: { beginDate: string; endDate: string; keywords: string[] } }
}
export const taskStates: Record<string, string> = { RECEIVED: '已接收', PLANNING: '规划中', RUNNING: '执行中', WAITING_ENTITY: '等待主体选择', WAITING_INPUT: '等待补充', WAITING_BUDGET: '预算暂停', SUCCEEDED: '步骤完成', PARTIAL: '部分完成', FAILED: '失败', CANCELLED: '已取消' }
export const toolNames: Record<string, string> = {
search_company: '定位企业主体', get_company_profile: '基础画像', get_company_business_keywords: '业务关键词',
get_company_partners: '客户与供应商', query_bids_advanced: '历史公告明细', aggregate_bids_advanced: '历史聚合统计',
find_competitors: '真实投标竞对', search_bids: '定位项目公告', get_bid_detail: '项目正文', find_potential_bidders: '潜在投标者', get_price_trends: '品牌型号历史单价',
web_search: '检索公开资料', web_fetch: '读取公开网页', model_json: '生成有据建议', vision: '识别文件页面', FILE_PARSE: '本地文件提取', ENTITY_CACHE: '读取已确认主体(缓存)',
}
import type { CompanyProfile } from '../types'
/**
* 沿用原型的本地文本字段识别,只返回可供人工核对的草稿。
* 公司名称单独识别,避免名称中的“验收”“中标”等字样被误当成代表业绩;
* 移除明确的字段前缀,不补全文件未提供的企业信息,也不改动已保存档案。
*/
export function extractProfileFromText(text: string): Partial<CompanyProfile> {
const lines = text.split(/\r?\n/).map(line => line.trim().replace(/^[-*•\d.、\s]+/, '')).filter(Boolean)
const company = lines.find(line => /^(企业名称|公司名称)\s*[::]/.test(line))
?? lines.find(line => /^.{2,100}(有限公司|股份公司|集团)$/.test(line))
const out: Partial<CompanyProfile> = {}
const clean = (line: string) => line.replace(/^(企业名称|公司名称|企业简介|主营业务|主营|产品与服务|产品|核心优势|优势|服务地区|地区|客户类型|客户|项目类型偏好|项目类型|金额偏好|资质与认证|资质|代表业绩|业绩|交付与售后|交付|投标准备|参与边界)\s*[::]\s*/, '').slice(0, 300)
if (company) out.companyName = clean(company).slice(0, 200)
const fields: [keyof CompanyProfile, RegExp][] = [
['intro', /简介|成立于|是一家/], ['mainBusiness', /主营|专注于|从事/],
['products', /产品|服务包括|解决方案/], ['advantages', /优势|擅长|自研/],
['serviceRegions', /地区|区域|覆盖|浙江|江苏|上海|安徽|华东|全国/], ['customerTypes', /客户/],
['projectTypes', /项目类型|项目偏好/], ['amountPreference', /\d+\s*[-~至]\s*\d+\s*万/],
['qualifications', /资质|认证|证书|软著|专利/], ['trackRecord', /业绩|案例|验收|中标/],
['delivery', /交付|售后|驻场|响应/], ['bidPreparation', /标书|准备周期|投标准备/],
['boundaries', /不参与|边界|谨慎/],
]
for (const [key, pattern] of fields) {
const line = lines.find(value => value !== company && pattern.test(value))
if (line) Object.assign(out, { [key]: clean(line) })
}
return out
}
/* 既有 Context 模块同时导出 Provider、useStore 和共享工具;保持调用方兼容,只豁免 Fast Refresh 的组件独占限制。 */
/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'
import type { import type {
CompanyProfile, ResearchConversation, ScheduleTask, SearchBatch, SearchConditions, CompanyProfile, ScheduleTask, SearchBatch, SearchConditions,
WatchRecord, WatchStatus, WatchRecord, WatchStatus,
} from '../types' } from '../types'
import { emptyProfile, demoProfile, HISTORY_STATUSES } from '../types' import { emptyProfile, HISTORY_STATUSES } from '../types'
import { PROJECTS } from '../data/projects' import { PROJECTS } from '../data/projects'
import type { Project } from '../types' import type { Project } from '../types'
import { api } from './api'
// ---------- 本地持久化 ---------- // D1 档案与关注由后端保存;原型数据不自动迁移进真实数据库。
const LS_KEY = 'ruzhou-store-v1'
interface Persisted { interface Persisted {
profile: CompanyProfile profile: CompanyProfile
watch: WatchRecord[] watch: WatchRecord[]
tasks: ScheduleTask[] tasks: ScheduleTask[]
research: ResearchConversation[]
batches: SearchBatch[] batches: SearchBatch[]
customTags: string[] customTags: string[]
customProjects: Project[] customProjects: Project[]
} }
/** 旧版状态名 → 新状态名(状态体系细化后的数据迁移) */
const STATUS_MIGRATION: Record<string, WatchStatus> = {
已提交: '已提交投标文件',
已结束: '未中标',
}
const migrateStatus = (s: WatchStatus): WatchStatus => STATUS_MIGRATION[s] ?? s
function loadPersisted(): Persisted { function loadPersisted(): Persisted {
try { // 不加载旧浏览器演示公司、账号私有数据或虚构关注。
const raw = localStorage.getItem(LS_KEY) return { profile: { ...emptyProfile }, watch: [], tasks: [], batches: [], customTags: [], customProjects: [] }
if (raw) {
const parsed = JSON.parse(raw)
const savedProfile = { ...emptyProfile, ...parsed.profile }
return {
// 从未填写过档案时载入演示档案,便于直接演示匹配度打分;填过则尊重用户数据
profile: savedProfile.companyName.trim() ? savedProfile : { ...demoProfile },
watch: (parsed.watch ?? []).map((w: WatchRecord) => ({
...w,
tags: w.tags ?? [],
status: migrateStatus(w.status),
history: (w.history ?? []).map(h => ({ ...h, status: migrateStatus(h.status) })),
})),
tasks: parsed.tasks ?? [],
research: parsed.research ?? [],
batches: parsed.batches ?? [],
customTags: parsed.customTags ?? [],
customProjects: parsed.customProjects ?? [],
}
}
} catch { /* ignore */ }
return { profile: { ...demoProfile }, watch: [], tasks: [], research: [], batches: [], customTags: [], customProjects: [] }
} }
export function nowStr(): string { export function nowStr(): string {
...@@ -109,10 +81,11 @@ export function conditionsText(c: SearchConditions): string { ...@@ -109,10 +81,11 @@ export function conditionsText(c: SearchConditions): string {
// ---------- Context ---------- // ---------- Context ----------
interface Store { interface Store {
profile: CompanyProfile profile: CompanyProfile
saveProfile: (p: CompanyProfile) => void saveProfile: (p: CompanyProfile) => Promise<CompanyProfile>
watch: WatchRecord[] watch: WatchRecord[]
addWatch: (projectId: string) => void refreshWatch: () => Promise<void>
removeWatch: (projectId: string) => void addWatch: (projectId: string) => Promise<void>
removeWatch: (projectId: string) => Promise<void>
setWatchStatus: (projectId: string, status: WatchStatus) => void setWatchStatus: (projectId: string, status: WatchStatus) => void
setWatchNote: (projectId: string, note: string) => void setWatchNote: (projectId: string, note: string) => void
isWatched: (projectId: string) => boolean isWatched: (projectId: string) => boolean
...@@ -127,9 +100,6 @@ interface Store { ...@@ -127,9 +100,6 @@ interface Store {
saveTask: (t: ScheduleTask) => void saveTask: (t: ScheduleTask) => void
deleteTask: (id: string) => void deleteTask: (id: string) => void
runTaskNow: (id: string) => void runTaskNow: (id: string) => void
research: ResearchConversation[]
saveConversation: (c: ResearchConversation) => void
deleteConversation: (id: string) => void
batches: SearchBatch[] batches: SearchBatch[]
addBatch: (b: SearchBatch) => void addBatch: (b: SearchBatch) => void
} }
...@@ -139,32 +109,39 @@ const StoreContext = createContext<Store | null>(null) ...@@ -139,32 +109,39 @@ const StoreContext = createContext<Store | null>(null)
export function StoreProvider({ children }: { children: React.ReactNode }) { export function StoreProvider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<Persisted>(loadPersisted) const [state, setState] = useState<Persisted>(loadPersisted)
const [ready, setReady] = useState(false)
const [loadError, setLoadError] = useState('')
useEffect(() => { useEffect(() => {
try { localStorage.setItem(LS_KEY, JSON.stringify(state)) } catch { /* ignore */ } let active = true
}, [state]) Promise.all([api<CompanyProfile>('/company-profile'), api<WatchRecord[]>('/watch')])
.then(([profile, watch]) => {
const saveProfile = useCallback((p: CompanyProfile) => { if (!active) return
setState(s => ({ setState(s => ({ ...s, profile: { ...emptyProfile, ...profile }, watch }))
...s, setReady(true)
profile: { ...p, version: s.profile.version + 1, updatedAt: nowStr() }, }).catch(error => { if (active) setLoadError(error.message) })
})) return () => { active = false }
}, []) }, [])
const addWatch = useCallback((projectId: string) => { const saveProfile = useCallback(async (p: CompanyProfile) => {
setState(s => { const saved = await api<CompanyProfile>('/company-profile', { method: 'PUT', body: JSON.stringify(p) })
// 同一个项目只保留一条关注记录,不因重复来源产生多条 const profile = { ...emptyProfile, ...saved }
if (s.watch.some(w => w.projectId === projectId)) return s setState(s => ({ ...s, profile }))
const rec: WatchRecord = { return profile
projectId, status: '已关注', note: '', tags: [], createdAt: nowStr(),
history: [{ status: '已关注', time: nowStr(), note: '' }],
}
return { ...s, watch: [rec, ...s.watch] }
})
}, []) }, [])
const removeWatch = useCallback((projectId: string) => { // 服务器确认后再更新共享计数,保存失败时不显示虚假的关注成功。
setState(s => ({ ...s, watch: s.watch.filter(w => w.projectId !== projectId) })) const refreshWatch = useCallback(async () => {
const watch = await api<WatchRecord[]>('/watch')
setState(s => ({ ...s, watch }))
}, []) }, [])
const addWatch = useCallback(async (projectId: string) => {
await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'POST' })
await refreshWatch()
}, [refreshWatch])
const removeWatch = useCallback(async (projectId: string) => {
await api(`/watch/${encodeURIComponent(projectId)}`, { method: 'DELETE' })
await refreshWatch()
}, [refreshWatch])
const setWatchStatus = useCallback((projectId: string, status: WatchStatus) => { const setWatchStatus = useCallback((projectId: string, status: WatchStatus) => {
setState(s => ({ setState(s => ({
...@@ -207,7 +184,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) { ...@@ -207,7 +184,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
setState(s => { setState(s => {
if (s.customProjects.some(x => x.id === p.id) || PROJECTS.some(x => x.id === p.id)) return s if (s.customProjects.some(x => x.id === p.id) || PROJECTS.some(x => x.id === p.id)) return s
const rec: WatchRecord = { const rec: WatchRecord = {
projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(), version: 1, projectId: p.id, status: '已关注', note: '', tags: [], createdAt: nowStr(),
history: [{ status: '已关注', time: nowStr(), note: '' }], history: [{ status: '已关注', time: nowStr(), note: '' }],
} }
const watch = s.watch.some(w => w.projectId === p.id) ? s.watch : [rec, ...s.watch] const watch = s.watch.some(w => w.projectId === p.id) ? s.watch : [rec, ...s.watch]
...@@ -243,22 +220,6 @@ export function StoreProvider({ children }: { children: React.ReactNode }) { ...@@ -243,22 +220,6 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
})) }))
}, []) }, [])
const saveConversation = useCallback((c: ResearchConversation) => {
setState(s => {
const idx = s.research.findIndex(x => x.id === c.id)
if (idx >= 0) {
const next = [...s.research]
next[idx] = c
return { ...s, research: next }
}
return { ...s, research: [c, ...s.research] }
})
}, [])
const deleteConversation = useCallback((id: string) => {
setState(s => ({ ...s, research: s.research.filter(c => c.id !== id) }))
}, [])
const addBatch = useCallback((b: SearchBatch) => { const addBatch = useCallback((b: SearchBatch) => {
setState(s => ({ ...s, batches: [b, ...s.batches].slice(0, 30) })) setState(s => ({ ...s, batches: [b, ...s.batches].slice(0, 30) }))
}, []) }, [])
...@@ -267,7 +228,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) { ...@@ -267,7 +228,7 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
profile: state.profile, profile: state.profile,
saveProfile, saveProfile,
watch: state.watch, watch: state.watch,
addWatch, removeWatch, setWatchStatus, setWatchNote, refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote,
isWatched: (pid: string) => state.watch.some(w => w.projectId === pid), isWatched: (pid: string) => state.watch.some(w => w.projectId === pid),
toggleWatchTag, toggleWatchTag,
customTags: state.customTags, customTags: state.customTags,
...@@ -278,12 +239,13 @@ export function StoreProvider({ children }: { children: React.ReactNode }) { ...@@ -278,12 +239,13 @@ export function StoreProvider({ children }: { children: React.ReactNode }) {
findProject: (id: string) => state.customProjects.find(p => p.id === id) ?? PROJECTS.find(p => p.id === id), findProject: (id: string) => state.customProjects.find(p => p.id === id) ?? PROJECTS.find(p => p.id === id),
tasks: state.tasks, tasks: state.tasks,
saveTask, deleteTask, runTaskNow, saveTask, deleteTask, runTaskNow,
research: state.research,
saveConversation, deleteConversation,
batches: state.batches, batches: state.batches,
addBatch, addBatch,
}), [state, saveProfile, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, saveConversation, deleteConversation, addBatch]) }), [state, saveProfile, refreshWatch, addWatch, removeWatch, setWatchStatus, setWatchNote, toggleWatchTag, addCustomTag, removeCustomTag, addCustomProject, saveTask, deleteTask, runTaskNow, addBatch])
// 必须等真实档案加载后再挂载表单,避免空值覆盖已保存数据。
if (loadError) return <div role="alert" className="p-8 text-sm">{loadError}<button className="ml-4 underline" onClick={() => window.location.reload()}>重新连接</button></div>
if (!ready) return <div role="status" className="p-8 text-sm">正在读取公司档案…</div>
return <StoreContext.Provider value={value}>{children}</StoreContext.Provider> return <StoreContext.Provider value={value}>{children}</StoreContext.Provider>
} }
......
This diff is collapsed.
import { useState } from 'react' import { useState } from 'react'
import { login } from '../lib/api'
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { Compass, Sparkles, Bell, User, Lock, ArrowRight } from 'lucide-react' import { Compass, Sparkles, Bell, User, Lock, ArrowRight } from 'lucide-react'
import { PrimaryButton } from '../components/ui-ext/AiButton' import { PrimaryButton } from '../components/ui-ext/AiButton'
import { BEE_IMG } from '../lib/assets' import { BEE_IMG } from '../lib/assets'
/** 登录页:演示环境任意账号密码可登录;登录态记录在本地 */ /** 仅服务端密码验证成功后进入工作台;失败保留表单并显示统一错误。 */
export function LoginPage({ onLogin }: { onLogin: () => void }) { export function LoginPage({ onLogin }: { onLogin: () => void }) {
const navigate = useNavigate() const navigate = useNavigate()
const [account, setAccount] = useState('') const [account, setAccount] = useState('')
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const submit = () => { const submit = async () => {
if (busy) return
if (!account.trim()) { setError('请输入账号'); return } if (!account.trim()) { setError('请输入账号'); return }
if (!password.trim()) { setError('请输入密码'); return } if (!password.trim()) { setError('请输入密码'); return }
onLogin() setBusy(true)
navigate('/', { replace: true }) try {
await login(account.trim(), password)
onLogin()
navigate('/', { replace: true })
} catch (error) { setError(error instanceof Error ? error.message : '登录失败') }
finally { setBusy(false) }
} }
return ( return (
...@@ -58,34 +66,32 @@ export function LoginPage({ onLogin }: { onLogin: () => void }) { ...@@ -58,34 +66,32 @@ export function LoginPage({ onLogin }: { onLogin: () => void }) {
<div className="mt-7 space-y-4"> <div className="mt-7 space-y-4">
<div> <div>
<label className="text-[13px] font-medium text-ink-900">账号</label> <label htmlFor="login-account" className="text-[13px] font-medium text-ink-900">账号</label>
<div className="relative mt-1.5"> <div className="relative mt-1.5">
<User size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" /> <User size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" />
<input value={account} onChange={e => { setAccount(e.target.value); setError('') }} <input id="login-account" value={account} onChange={e => { setAccount(e.target.value); setError('') }}
onKeyDown={e => { if (e.key === 'Enter') submit() }} onKeyDown={e => { if (e.key === 'Enter') submit() }}
placeholder="请输入手机号或邮箱" placeholder="请输入手机号或邮箱" autoComplete="username"
className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" /> className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div> </div>
</div> </div>
<div> <div>
<label className="text-[13px] font-medium text-ink-900">密码</label> <label htmlFor="login-password" className="text-[13px] font-medium text-ink-900">密码</label>
<div className="relative mt-1.5"> <div className="relative mt-1.5">
<Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" /> <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400" />
<input type="password" value={password} onChange={e => { setPassword(e.target.value); setError('') }} <input id="login-password" type="password" value={password} onChange={e => { setPassword(e.target.value); setError('') }}
onKeyDown={e => { if (e.key === 'Enter') submit() }} onKeyDown={e => { if (e.key === 'Enter') submit() }}
placeholder="请输入密码" placeholder="请输入密码" autoComplete="current-password"
className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" /> className="w-full rounded-ctrl border border-line-soft bg-white py-2.5 pl-9 pr-3 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10" />
</div> </div>
</div> </div>
{error && <div className="text-xs text-bad-500">{error}</div>} {error && <div className="text-xs text-bad-500">{error}</div>}
<PrimaryButton onClick={submit} className="w-full !py-2.5 text-sm"> <PrimaryButton onClick={() => void submit()} disabled={busy} loading={busy} className="w-full !py-2.5 text-sm">
登 录 <ArrowRight size={15} /> 登 录 <ArrowRight size={15} />
</PrimaryButton> </PrimaryButton>
</div> </div>
<div className="mt-6 text-center text-xs text-ink-400"> <div className="mt-6 h-4" aria-hidden="true" />
演示环境:输入任意账号密码即可登录
</div>
</div> </div>
</div> </div>
</div> </div>
......
import { useRef, useState } from 'react' import { useRef, useState } from 'react'
import { Building2, Save, Upload, Sparkles } from 'lucide-react' import { Building2, Save, Upload, Sparkles } from 'lucide-react'
import type { CompanyProfile } from '../types' import type { CompanyProfile } from '../types'
import { extractProfileFromText } from '../lib/profileImport'
import { useStore } from '../lib/store' import { useStore } from '../lib/store'
import Pill from '../components/ui-ext/Pill' import Pill from '../components/ui-ext/Pill'
import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton' import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton'
...@@ -71,36 +72,6 @@ const GROUPS: { title: string; desc: string; fields: FieldDef[] }[] = [ ...@@ -71,36 +72,6 @@ const GROUPS: { title: string; desc: string; fields: FieldDef[] }[] = [
] ]
// 最低填写要求(演示口径):企业名称 + 主营业务 // 最低填写要求(演示口径):企业名称 + 主营业务
function meetsMinimum(p: CompanyProfile): boolean {
return p.companyName.trim() !== '' && p.mainBusiness.trim() !== ''
}
// 演示环境的 AI 导入抽取:基于关键词的启发式匹配,正式接入后由 AI 模型从文件中抽取
function extractProfileFromText(text: string): Partial<CompanyProfile> {
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean)
const pick = (re: RegExp) => {
const line = lines.find(l => re.test(l))
return line ? line.replace(/^[-*•\d.、\s]+/, '').slice(0, 300) : undefined
}
const out: Partial<CompanyProfile> = {}
const put = (key: keyof CompanyProfile, v?: string) => { if (v) (out as Record<string, string>)[key] = v }
put('companyName', pick(/有限公司|股份公司|集团/))
put('intro', pick(/简介|成立于|是一家/))
put('mainBusiness', pick(/主营|主营业务|专注于|从事/))
put('products', pick(/产品|服务包括|解决方案/))
put('advantages', pick(/优势|擅长|自研/))
put('serviceRegions', pick(/地区|区域|覆盖|浙江|江苏|上海|安徽|华东|全国/))
put('customerTypes', pick(/客户/))
put('projectTypes', pick(/项目类型|偏好/))
put('amountPreference', pick(/\d+\s*[-~至]\s*\d+\s*万/))
put('qualifications', pick(/资质|认证|证书|软著|专利/))
put('trackRecord', pick(/业绩|案例|验收|中标/))
put('delivery', pick(/交付|售后|驻场|响应/))
put('bidPreparation', pick(/标书|准备周期|投标准备/))
put('boundaries', pick(/不参与|边界|谨慎/))
return out
}
const FIELD_LABELS: Record<string, string> = Object.fromEntries( const FIELD_LABELS: Record<string, string> = Object.fromEntries(
GROUPS.flatMap(g => g.fields.map(f => [f.key, f.label])), GROUPS.flatMap(g => g.fields.map(f => [f.key, f.label])),
) )
...@@ -110,6 +81,8 @@ const inputCls = ...@@ -110,6 +81,8 @@ const inputCls =
export function ProfilePage() { export function ProfilePage() {
const { profile, saveProfile } = useStore() const { profile, saveProfile } = useStore()
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [form, setForm] = useState<CompanyProfile>({ ...profile }) const [form, setForm] = useState<CompanyProfile>({ ...profile })
const [savedTip, setSavedTip] = useState<string | null>(null) const [savedTip, setSavedTip] = useState<string | null>(null)
const fileRef = useRef<HTMLInputElement>(null) const fileRef = useRef<HTMLInputElement>(null)
...@@ -125,15 +98,17 @@ export function ProfilePage() { ...@@ -125,15 +98,17 @@ export function ProfilePage() {
const f = e.target.files?.[0] const f = e.target.files?.[0]
e.target.value = '' e.target.value = ''
if (!f) return if (!f) return
const text = await f.text() if (f.size > 2 * 1024 * 1024) { setImportError('介绍文件不能超过 2 MB,请精简后导入'); return }
const extracted = extractProfileFromText(text) try {
if (Object.keys(extracted).length === 0) { const text = await f.text()
setImportError('没有从文件中识别到可填入的内容,可换一份更完整的介绍文件再试。') const extracted = extractProfileFromText(text)
setImported(null) if (Object.keys(extracted).length === 0) {
return setImportError('没有从文件中识别到可填入的内容,可换一份更完整的介绍文件再试。')
} setImported(null)
setImportError('') return
setImported(extracted) }
setImportError(''); setImported(extracted)
} catch { setImportError('文件读取失败,请重新选择 TXT 或 Markdown 文件') }
} }
const applyImport = () => { const applyImport = () => {
...@@ -143,13 +118,16 @@ export function ProfilePage() { ...@@ -143,13 +118,16 @@ export function ProfilePage() {
setSavedTip(null) setSavedTip(null)
} }
const save = () => { const save = async () => {
const completed = meetsMinimum(form) if (busy) return
saveProfile({ ...form, completed }) setBusy(true); setError(''); setSavedTip(null)
setForm(f => ({ ...f, completed })) try {
setSavedTip(completed // 完善状态和版本必须使用服务端结果;保存失败时不显示成功或递增本地版本。
? '档案已保存并标记为「已完善」,项目分析将结合公司情况给出有依据的建议。' const saved = await saveProfile(form)
: '已保存,但尚未达到「已完善」的最低要求(需填写企业名称与主营业务),匹配度暂不生成。') setForm(saved)
setSavedTip(saved.completed ? '档案已保存,已达到企业名称与主营业务的最低要求。' : '档案已保存;补充企业名称与主营业务后才能生成匹配度。')
} catch (error) { setError(error instanceof Error ? error.message : '保存失败') }
finally { setBusy(false) }
} }
return ( return (
...@@ -159,18 +137,19 @@ export function ProfilePage() { ...@@ -159,18 +137,19 @@ export function ProfilePage() {
<h1 className="text-[17px] font-bold">公司档案</h1> <h1 className="text-[17px] font-bold">公司档案</h1>
<Pill status={profile.completed ? '已完善' : '未完善'} /> <Pill status={profile.completed ? '已完善' : '未完善'} />
{profile.completed && ( {profile.completed && (
<span className="text-xs text-ink-400">v<span className="font-num">{profile.version}</span> · 更新于 <span className="font-num">{profile.updatedAt}</span></span> <span className="text-xs text-ink-400">v<span className="font-num">{profile.version}</span> · 更新于 <span className="font-num">{profile.updatedAt ? new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', dateStyle: 'short', timeStyle: 'short', hour12: false }).format(new Date(profile.updatedAt)) : '尚未保存'}</span></span>
)} )}
<span className="flex-1" /> <span className="flex-1" />
<input ref={fileRef} type="file" accept=".txt,.md,.text,.markdown" className="hidden" onChange={onImportFile} /> <input ref={fileRef} type="file" accept=".txt,.md,.text,.markdown" className="hidden" onChange={onImportFile} />
<GhostButton onClick={() => fileRef.current?.click()}> <GhostButton onClick={() => fileRef.current?.click()} title="按关键词识别 TXT / Markdown 字段,核对后写入表单">
<Upload size={14} /> AI 导入 <Upload size={14} /> AI 导入
</GhostButton> </GhostButton>
<PrimaryButton onClick={save}> <PrimaryButton onClick={() => void save()} disabled={busy} loading={busy}>
<Save size={14} /> 保存档案 <Save size={14} /> 保存档案
</PrimaryButton> </PrimaryButton>
</div> </div>
{error && <p role="alert" className="mt-3 text-sm text-bad-500">{error}</p>}
{importError && ( {importError && (
<div className="mt-3 rounded-ctrl border border-warn-500/30 bg-warn-500/5 px-3.5 py-2.5 text-[13px] text-warn-500 fade-up"> <div className="mt-3 rounded-ctrl border border-warn-500/30 bg-warn-500/5 px-3.5 py-2.5 text-[13px] text-warn-500 fade-up">
{importError} {importError}
...@@ -181,7 +160,7 @@ export function ProfilePage() { ...@@ -181,7 +160,7 @@ export function ProfilePage() {
<section className="mt-3 rounded-card border-brand-gradient bg-white p-4 shadow-card fade-up"> <section className="mt-3 rounded-card border-brand-gradient bg-white p-4 shadow-card fade-up">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Sparkles size={14} className="shrink-0 text-brand-500" /> <Sparkles size={14} className="shrink-0 text-brand-500" />
<span className="text-[13px] font-medium text-brand-500">AI 已从文件抽取以下内容</span> <span className="text-[13px] font-medium text-brand-500">已从文件抽取以下内容</span>
<span className="text-xs text-ink-400">请核对后写入,写入前不会改动当前表单</span> <span className="text-xs text-ink-400">请核对后写入,写入前不会改动当前表单</span>
</div> </div>
<ul className="mt-2.5 space-y-1.5"> <ul className="mt-2.5 space-y-1.5">
...@@ -216,17 +195,17 @@ export function ProfilePage() { ...@@ -216,17 +195,17 @@ export function ProfilePage() {
<div className="mt-3 space-y-3"> <div className="mt-3 space-y-3">
{g.fields.map(f => ( {g.fields.map(f => (
<div key={f.key}> <div key={f.key}>
<label className="text-[13px] font-medium text-ink-900"> <label htmlFor={`profile-${f.key}`} className="text-[13px] font-medium text-ink-900">
{f.label} {f.label}
{(f.key === 'companyName' || f.key === 'mainBusiness') && ( {(f.key === 'companyName' || f.key === 'mainBusiness') && (
<span className="ml-1 text-xs font-normal text-warn-500">(最低必填)</span> <span className="ml-1 text-xs font-normal text-warn-500">(最低必填)</span>
)} )}
</label> </label>
{f.textarea ? ( {f.textarea ? (
<textarea rows={2} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder} <textarea id={`profile-${f.key}`} rows={2} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
className={cn(inputCls, 'mt-1 w-full resize-y scrollbar-thin')} /> className={cn(inputCls, 'mt-1 w-full resize-y scrollbar-thin')} />
) : ( ) : (
<input value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder} <input id={`profile-${f.key}`} value={form[f.key] as string} onChange={e => set(f.key, e.target.value)} placeholder={f.placeholder}
className={cn(inputCls, 'mt-1 w-full')} /> className={cn(inputCls, 'mt-1 w-full')} />
)} )}
</div> </div>
......
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useSearchParams } from 'react-router' import { useNavigate, useSearchParams } from 'react-router'
import { import { MessagesSquare, UserSearch, GitCompareArrows, Map, Send, X, Loader2 } from 'lucide-react'
MessagesSquare, UserSearch, GitCompareArrows, Map, Send, import { api } from '../lib/api'
X, Check, Loader2, CircuitBoard, import { conversationsChanged } from '../lib/conversations'
} from 'lucide-react' import type { Conversation } from '../lib/conversations'
import type { ChatMessage, ResearchConversation } from '../types' import type { AgentTask } from '../hooks/useTaskEvents'
import { useStore, uid, nowStr } from '../lib/store' import type { ResearchRequest } from '../lib/day3'
import { researchAnswer } from '../lib/ai' import { initialQuery, message, words } from '../lib/day2'
import { Markdown } from '../components/Markdown' import { ConversationView } from '../components/ConversationView'
import { useStreaming, runSkillTrace } from '../hooks/useStreaming' import { ResearchTask } from '../components/ResearchTask'
import { PrimaryButton } from '../components/ui-ext/AiButton' import { PrimaryButton } from '../components/ui-ext/AiButton'
type Entry = 'customer' | 'competitor' | 'market' | null
const ENTRIES = [ const ENTRIES = [
{ key: 'customer' as Entry, icon: UserSearch, title: '查目标客户', desc: '这家公司做什么,采购过什么?', placeholder: '输入完整企业名称,如:某某水务集团有限公司' }, { key: 'customer', icon: UserSearch, title: '查目标客户', desc: '这家公司做什么,采购过什么?', placeholder: '输入完整企业名称,如:某某水务集团有限公司' },
{ key: 'competitor' as Entry, icon: GitCompareArrows, title: '查竞争对手', desc: '这家公司的业务和客户情况怎样?', placeholder: '输入竞争对手的完整名称,可补充关注业务' }, { key: 'competitor', icon: GitCompareArrows, title: '查竞争对手', desc: '这家公司的业务和客户情况怎样?', placeholder: '输入竞争对手的完整名称,可补充关注业务' },
{ key: 'market' as Entry, icon: Map, title: '查区域市场', desc: '某地区智慧水务需求如何?', placeholder: '如:调研华东地区近一年的智慧水务市场' }, { key: 'market', icon: Map, title: '查区域市场', desc: '某地区智慧水务需求如何?', placeholder: '如:调研华东地区近一年的智慧水务市场' },
] ] as const
interface LocalMsg extends ChatMessage {
streaming?: boolean
pendingTrace?: boolean
}
/** 界面只使用原型的三个入口及输入框;真实任务仍在服务端创建、确认和保存。 */
export function ResearchPage() { export function ResearchPage() {
const { research, saveConversation } = useStore() const [params, setParams] = useSearchParams()
const [convId, setConvId] = useState<string | null>(null) const navigate = useNavigate()
const [messages, setMessages] = useState<LocalMsg[]>([]) const entry = params.get('entry') || ''
const [title, setTitle] = useState('') const selected = params.get('task')
const [entry, setEntry] = useState<Entry>(null) const conversationId = params.get('conv')
const [input, setInput] = useState('') const qaBatch = params.get('qaBatch'), qaProject = params.get('qaProject')
const [busy, setBusy] = useState(false) const [input, setInput] = useState(params.get('input') || '')
const scrollRef = useRef<HTMLDivElement>(null) const [busy, setBusy] = useState(false), [error, setError] = useState('')
const traceCancelRef = useRef<(() => void) | null>(null) const [budget, setBudget] = useState({ maxCalls: 18, maxCostUnits: 10 })
// 新对话的 convId 在流式输出完成后才入库;入库前先记入待持久化集合,避免被“对话已删除”守卫误清 const [fileId, setFileId] = useState<string | null>(null)
const pendingConvRef = useRef<Set<string>>(new Set()) const pending = useRef<{ signature: string; key: string; conversationId?: string } | null>(null)
const { stream, stop } = useStreaming()
const [searchParams, setSearchParams] = useSearchParams()
useEffect(() => { useEffect(() => {
scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth' }) let active = true
}, [messages]) // 请求保护沿用服务端上限,不为了展示技术参数增加原型没有的设置入口。
void api<{ maxCalls: number; maxCostUnits: number }>('/system/limits').then(value => {
useEffect(() => () => { stop(); traceCancelRef.current?.() }, [stop]) if (active) setBudget({ maxCalls: Math.min(18, value.maxCalls), maxCostUnits: Math.min(10, value.maxCostUnits) })
}).catch(e => { if (active) setError(message(e)) })
const messagesRef = useRef<LocalMsg[]>([]) return () => { active = false }
useEffect(() => { messagesRef.current = messages }, [messages]) }, [])
useEffect(() => {
const persist = (msgs: LocalMsg[], t: string, id: string | null): string => { const id = params.get('file')
const cid = id ?? uid('conv') if (!id) return
const existing = research.find(c => c.id === cid) let active = true
const conv: ResearchConversation = { // 从已有项目携带的附件仍须校验账号归属与有效期,不能信任 URL 中的文件 ID。
id: cid, void api<{ status: string }>(`/files/${encodeURIComponent(id)}`).then(file => {
title: t || existing?.title || '未命名调研', if (!active) return
createdAt: existing?.createdAt ?? nowStr(), if (file.status !== 'READY') { setError('文件已删除或过期,请重新上传'); return }
messages: msgs.map(({ streaming: _s, pendingTrace: _p, ...m }) => m), setFileId(id)
}).catch(e => { if (active) setError(message(e)) })
return () => { active = false }
}, [params])
const create = async (request: unknown, path = '/agent/tasks') => {
const signature = `${path}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
if (!pending.current.conversationId) {
const conversation = await api<Conversation>('/conversations', { method: 'POST', body: JSON.stringify({ title: '' }) })
pending.current.conversationId = conversation.id
} }
saveConversation(conv) // 响应未知时保留原键和会话;重试只回读同一次提交,不重复创建收费任务。
return cid const task = await api<AgentTask>(path, { method: 'POST', headers: { 'Idempotency-Key': pending.current.key }, body: JSON.stringify(request) })
const conv = pending.current.conversationId
await api(`/conversations/${conv}/tasks`, { method: 'POST', body: JSON.stringify({ taskId: task.id }) })
pending.current = null; conversationsChanged()
if (path === '/searches') navigate(`/?batch=${task.id}`)
else setParams({ conv })
} }
const start = async () => {
const ask = (raw: string) => { if (busy || (!input.trim() && !fileId)) return
const q = raw.trim() setBusy(true); setError('')
if (!q || busy) return try {
setBusy(true) if (entry === 'market') {
setInput('') await create({ conditions: { ...initialQuery(), keywords: words(input), mode: 'MARKET' }, ...budget }, '/searches')
} else {
const userMsg: LocalMsg = { role: 'user', content: q, time: nowStr() } const project = entry === 'project'
const result = researchAnswer(q, entry) const research: ResearchRequest = {
const assistantMsg: LocalMsg = { companies: project ? [] : [input.trim()], selections: {}, mode: 'QUICK', fileId: project ? fileId : null,
role: 'assistant', content: '', time: nowStr(), parentId: params.get('parent'), targetProjectId: params.get('project'), focus: null, acknowledgedCalls: 0,
skillTrace: [], pendingTrace: true,
}
setMessages([...messages, userMsg, assistantMsg])
const newTitle = title || result.title
if (!title) setTitle(newTitle)
const cid = convId ?? uid('conv')
if (!convId) setConvId(cid)
pendingConvRef.current.add(cid)
// 展示实际发生的 Skill 调用进展,再输出结果
traceCancelRef.current?.()
traceCancelRef.current = runSkillTrace(result.skillTrace, doneSteps => {
setMessages(m => {
const arr = [...m]
arr[arr.length - 1] = { ...arr[arr.length - 1], skillTrace: doneSteps, pendingTrace: true }
return arr
})
}, () => {
stream(result.markdown, (partial, done) => {
setMessages(m => {
const arr = [...m]
arr[arr.length - 1] = { ...arr[arr.length - 1], content: partial, streaming: !done, pendingTrace: false }
return arr
})
if (done) {
setBusy(false)
pendingConvRef.current.delete(cid)
persist(messagesRef.current, newTitle, cid)
} }
}) await create({ operation: project ? 'BID_RESEARCH' : 'COMPANY_RESEARCH', workflow: project ? 'BID_DECISION' : 'COMPANY_INTEL', input: project ? input.trim() : '', entityConfirmed: false, ...budget, research })
}) }
setEntry(null) } catch (e) { setError(message(e)) } finally { setBusy(false) }
}
const openConversation = (c: ResearchConversation) => {
stop(); traceCancelRef.current?.()
setConvId(c.id)
setTitle(c.title)
setMessages(c.messages.map(m => ({ ...m })))
setBusy(false)
}
const newConversation = () => {
stop(); traceCancelRef.current?.()
setConvId(null); setTitle(''); setMessages([]); setBusy(false); setEntry(null)
} }
// 左侧导航栏通过 URL 参数控制:?conv=<id> 打开历史对话,?new=1 新建对话 if (conversationId || qaBatch || qaProject) return <ConversationView key={conversationId ?? `${qaBatch}:${qaProject}`} id={conversationId ?? undefined} scope={qaBatch || qaProject ? { batchId: qaBatch, projectId: qaProject } : undefined} />
useEffect(() => { return <div className="flex h-full">
const conv = searchParams.get('conv') <div className="flex min-w-0 flex-1 flex-col">
const isNew = searchParams.get('new') <div className="flex-1 overflow-y-auto px-6 py-5 scrollbar-thin">
if (!conv && !isNew) return {selected ? <div className="mx-auto max-w-[820px] space-y-4"><ResearchTask id={selected} /></div> : <div className="mx-auto max-w-[720px] pt-10">
if (conv) { <div className="text-center">
const c = research.find(x => x.id === conv) <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl shadow-card-hover" style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}><MessagesSquare size={24} className="text-white" /></div>
if (c) openConversation(c) <h1 className="mt-4 text-[22px] font-bold">对话<span className="text-brand-gradient">调研</span></h1>
} else {
newConversation()
}
setSearchParams({}, { replace: true })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchParams])
// 当前对话在左侧导航被删除时,重置为新对话(待持久化的新对话除外)
useEffect(() => {
if (convId && !pendingConvRef.current.has(convId) && !research.some(c => c.id === convId)) newConversation()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [research, convId])
return (
<div className="flex h-full">
{/* 对话区 */}
<div className="flex min-w-0 flex-1 flex-col">
<div ref={scrollRef} className="flex-1 overflow-y-auto px-6 py-5 scrollbar-thin">
{messages.length === 0 ? (
<div className="mx-auto max-w-[720px] pt-10">
<div className="text-center">
<div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl shadow-card-hover"
style={{ background: 'linear-gradient(135deg, #6366F1 0%, #818CF8 100%)' }}>
<MessagesSquare size={24} className="text-white" />
</div>
<h1 className="mt-4 text-[22px] font-bold">
对话<span className="text-brand-gradient">调研</span>
</h1>
</div>
<div className="mt-7 grid grid-cols-3 gap-3">
{ENTRIES.map(e => (
<button key={e.key} onClick={() => { setEntry(e.key); setInput('') }}
className="rounded-card border border-line-soft bg-white p-4 text-left shadow-card transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-500/40 hover:shadow-card-hover">
<div className="flex h-9 w-9 items-center justify-center rounded-ctrl bg-brand-50">
<e.icon size={18} className="text-brand-500" />
</div>
<div className="mt-2.5 text-[14px] font-semibold text-ink-900">{e.title}</div>
<div className="mt-0.5 text-xs text-ink-400">{e.desc}</div>
</button>
))}
</div>
</div>
) : (
<div className="mx-auto max-w-[820px] space-y-4">
{messages.map((m, i) => (
<div key={i} className={m.role === 'user' ? 'flex justify-end' : ''}>
{m.role === 'user' ? (
<div className="max-w-[80%] rounded-2xl rounded-br-sm bg-brand-500 px-4 py-2 text-white shadow-[0_2px_8px_rgba(99,102,241,.25)]">{m.content}</div>
) : (
<div className="rounded-card border border-line-soft bg-white px-4 py-3 shadow-card">
{m.skillTrace && (
<div className="mb-2 rounded-ctrl border border-line-soft bg-canvas px-3 py-2">
<div className="flex items-center gap-2 text-[12px] font-semibold text-brand-500">
{m.pendingTrace ? <Loader2 size={13} className="animate-spin" /> : <CircuitBoard size={13} />}
Skill 调用进展
</div>
<ul className="mt-1 space-y-1">
{m.skillTrace.map((s, j) => (
<li key={j} className="flex items-center gap-1.5 text-[12px] text-ink-600 fade-up">
<Check size={12} className="text-ok-500" /> {s}
</li>
))}
</ul>
</div>
)}
{m.content ? <Markdown text={m.content} streaming={m.streaming} /> : null}
{m.time && !m.streaming && <div className="mt-2 font-num text-[11px] text-ink-400">{m.time}</div>}
</div>
)}
</div>
))}
</div>
)}
</div>
{/* 输入区 */}
<div className="border-t border-line-soft bg-white/75 px-6 py-3 backdrop-blur-md">
<div className="mx-auto max-w-[820px]">
{entry && (
<div className="mb-2 inline-flex items-center gap-2 rounded-full bg-brand-50 px-2.5 py-1 text-xs text-brand-500">
已选入口:{ENTRIES.find(e => e.key === entry)?.title}
<button onClick={() => setEntry(null)} className="hover:text-bad-500"><X size={12} /></button>
</div>
)}
<div className="flex items-end gap-2">
<textarea
value={input}
onChange={e => setInput(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); ask(input) } }}
rows={1}
placeholder={entry ? ENTRIES.find(e => e.key === entry)?.placeholder : '直接提出研究问题,如:「调研近一个月智慧水务市场」'}
className="max-h-32 flex-1 resize-none rounded-ctrl border border-line-soft px-3.5 py-2.5 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10 scrollbar-thin"
/>
<PrimaryButton onClick={() => ask(input)} disabled={!input.trim() || busy} className="!rounded-full !p-3">
{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}
</PrimaryButton>
</div>
</div> </div>
</div> <div className="mt-7 grid grid-cols-3 gap-3">{ENTRIES.map(item => <button key={item.key} onClick={() => { setParams({ entry: item.key }); setInput('') }} className="rounded-card border border-line-soft bg-white p-4 text-left shadow-card transition-all duration-200 hover:-translate-y-0.5 hover:border-brand-500/40 hover:shadow-card-hover">
<div className="flex h-9 w-9 items-center justify-center rounded-ctrl bg-brand-50"><item.icon size={18} className="text-brand-500" /></div>
<div className="mt-2.5 text-[14px] font-semibold text-ink-900">{item.title}</div><div className="mt-0.5 text-xs text-ink-400">{item.desc}</div>
</button>)}</div>
</div>}
{error && <p role="alert" className="mx-auto mt-4 max-w-[820px] text-xs text-bad-500">{error}</p>}
</div> </div>
{!selected && <div className="border-t border-line-soft bg-white/75 px-6 py-3 backdrop-blur-md"><form onSubmit={e => { e.preventDefault(); void start() }} className="mx-auto max-w-[820px]">
{ENTRIES.some(item => item.key === entry) && <div className="mb-2 inline-flex items-center gap-2 rounded-full bg-brand-50 px-2.5 py-1 text-xs text-brand-500">已选入口:{ENTRIES.find(item => item.key === entry)?.title}<button type="button" aria-label="清除所选入口" onClick={() => setParams({})} className="hover:text-bad-500"><X size={12} /></button></div>}
<div className="flex items-end gap-2">
<textarea aria-label="研究问题" value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); void start() } }} rows={1} maxLength={entry === 'project' ? 2000 : 128} placeholder={ENTRIES.find(item => item.key === entry)?.placeholder || '直接提出研究问题,如:「调研近一个月智慧水务市场」'} className="max-h-32 flex-1 resize-none rounded-ctrl border border-line-soft px-3.5 py-2.5 text-sm text-ink-900 outline-none transition-shadow placeholder:text-ink-400 focus:border-brand-500/60 focus:ring-2 focus:ring-brand-500/10 scrollbar-thin" />
<PrimaryButton type="submit" aria-label="发送" disabled={busy || (!input.trim() && !fileId)} className="!rounded-full !p-3">{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />}</PrimaryButton>
</div>
</form></div>}
</div> </div>
) </div>
} }
import { useEffect, useRef, useState } from 'react'
import { api } from '../lib/api'
import { useTaskEvents } from '../hooks/useTaskEvents'
import { PrimaryButton, GhostButton } from '../components/ui-ext/AiButton'
const OPERATIONS = [
['ZLBX_BALANCE', '知了账户余额'], ['BID_SEARCH', '知了公告检索(近 90 天全国,最多 3 条)'],
['BID_DETAIL', '知了公告详情(填写公告 ID)'], ['COMPANY_SEARCH', '知了企业主体搜索'],
['COMPANY_PROFILE', '知了企业画像(必须确认主体)'], ['MODEL_TEXT', 'DeepSeek 文本'],
['MODEL_JSON', 'DeepSeek 结构化 JSON'], ['MODEL_STREAM', 'DeepSeek 真实流式'],
['WEB_SEARCH', 'DeepSeek 联网搜索'], ['WEB_FETCH', 'DeepSeek 公开网页抓取'], ['VISION', 'DeepSeek 无敏感信息样图识别'],
] as const
const STATE_LABEL: Record<string, string> = {
RECEIVED: '已接收', PLANNING: '计划中', RUNNING: '执行中', SUCCEEDED: '单项完成', PARTIAL: '部分完成 / 中断',
FAILED: '失败', CANCELLED: '已取消', WAITING_INPUT: '等待补充配置或输入', WAITING_ENTITY: '等待确认主体', WAITING_BUDGET: '等待预算处理',
}
const EVENT_LABEL: Record<string, string> = { RECEIVED: '接收', STATE: '状态', TOOL_START: '实际请求开始', TOOL_COMPLETE: '实际请求完成', TOOL_FAILED: '实际请求失败', REPORT_FRAGMENT: '模型片段' }
/** D1 独立验证面板:每个按钮对应单个真实请求;没有凭证时明确等待,不输出演示报告。 */
export function ServiceCheckPage() {
const [ledger, setLedger] = useState<unknown>(null)
const [operation, setOperation] = useState<string>('ZLBX_BALANCE')
const [input, setInput] = useState('')
const [confirmed, setConfirmed] = useState(false)
const [taskId, setTaskId] = useState<string | null>(null)
const [history, setHistory] = useState<string[]>([])
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [limits, setLimits] = useState<Record<string, number>>({})
// 网络结果未知时保留同一幂等键;只在内容改变或成功拿到任务 ID 后更换。
const pending = useRef<{ signature: string; key: string } | null>(null)
const { events, task, error: streamError } = useTaskEvents(taskId)
useEffect(() => {
void api<string[]>('/agent/tasks').then(setHistory).catch(error => setError(error.message))
void api<Record<string, number>>('/system/limits').then(setLimits).catch(error => setError(error.message))
}, [])
const start = async () => {
if (busy) return
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) }
const signature = JSON.stringify(request)
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('')
try {
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)])
pending.current = null
} catch (error) { setError(error instanceof Error ? error.message : '任务创建失败') }
finally { setBusy(false) }
}
const cancel = async () => {
if (!taskId) return
setBusy(true)
try {
await api(`/agent/tasks/${taskId}/cancel`, { method: 'POST' })
// 重新挂载事件订阅,以回放取消状态和仍可能到达的实际用量。
setTaskId(null); setTimeout(() => setTaskId(taskId), 0)
} catch (error) { setError(error instanceof Error ? error.message : '取消失败') }
finally { setBusy(false) }
}
const resume = async () => {
if (!task) return
const request = { ...task.request, input: input || task.request.input,
entityConfirmed: confirmed || task.request.entityConfirmed,
maxCalls: task.status === 'WAITING_BUDGET' ? Math.min(limits.maxCalls ?? 1, task.calls.length + 1) : task.request.maxCalls }
const signature = `${task.id}:${JSON.stringify(request)}`
if (pending.current?.signature !== signature) pending.current = { signature, key: crypto.randomUUID() }
setBusy(true); setError('')
try {
await api(`/agent/tasks/${task.id}/continue`, { method: 'POST', body: JSON.stringify(request), headers: { 'Idempotency-Key': pending.current.key } })
pending.current = null
setTaskId(null); setTimeout(() => setTaskId(task.id), 0)
} catch (error) { setError(error instanceof Error ? error.message : '继续失败') }
finally { setBusy(false) }
}
return <div className="mx-auto max-w-5xl space-y-4 p-5">
<h1 className="text-lg font-bold">服务验证与用量核对</h1>
<details className="rounded-card border bg-white p-4 text-sm"><summary>本账号实际调用账本(只读,不查询供应商余额)</summary><GhostButton onClick={() => { void api('/usage').then(setLedger).catch(e => setError(e.message)) }}>读取 / 刷新本地用量</GhostButton>{ledger != null && <pre className="mt-2 overflow-auto whitespace-pre-wrap text-xs">{JSON.stringify(ledger, null, 2)}</pre>}</details>
<p className="text-sm text-ink-600">逐项核对知了与 DeepSeek 能力。每次创建最多发出一个请求,可能消耗供应商积分或 token。缺少密钥时显示等待配置。</p>
<div className="space-y-3 rounded-card border bg-white p-4">
<label className="block text-sm">验证能力<select value={operation} onChange={e => { setOperation(e.target.value); setConfirmed(false) }} className="mt-1 block w-full rounded border p-2">
{OPERATIONS.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
</select></label>
{!['ZLBX_BALANCE', 'VISION'].includes(operation) && <label className="block text-sm">关键词、完整企业名称、公告 ID 或公开 URL
<textarea value={input} onChange={e => setInput(e.target.value)} maxLength={2000} rows={2} className="mt-1 block w-full rounded border p-2" />
</label>}
{operation === 'COMPANY_PROFILE' && <label className="flex gap-2 text-sm"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />已通过主体搜索核对全称或 ID,不合并集团分支</label>}
<p className="text-xs text-ink-400">费用单价尚待账号核实,首个请求可能超过设置的积分保护值;不会自动重试。视觉只发送后端生成的“D1 8240”样图。</p>
<PrimaryButton onClick={() => void start()} disabled={busy} loading={busy}>创建验证任务</PrimaryButton>
</div>
{(error || streamError) && <div role="alert" className="text-sm text-red-700">{error || streamError}</div>}
{history.length > 0 && <label className="block text-sm">回查最近任务<select value={taskId ?? ''} onChange={e => setTaskId(e.target.value || null)} className="ml-3 max-w-full rounded border p-2">
<option value="">选择任务</option>{history.map(id => <option key={id} value={id}>{id}</option>)}
</select></label>}
{task && <section className="space-y-3 rounded-card border bg-white p-4">
<div className="flex flex-wrap items-center gap-3"><strong>{STATE_LABEL[task.status] ?? task.status}</strong><code className="text-xs">{task.id}</code>
{!['SUCCEEDED', 'FAILED', 'CANCELLED', 'PARTIAL'].includes(task.status) && <GhostButton disabled={busy} onClick={() => void cancel()}>取消任务</GhostButton>}
</div>
<p className="text-sm">{task.question}</p>
{task.status.startsWith('WAITING_') && <div className="space-y-2">
{task.status === 'WAITING_BUDGET' && <p className="text-xs text-ink-600">请先核对供应商余额。继续后允许累计最多 {Math.min(limits.maxCalls ?? 1, task.calls.length + 1)} 次实际请求,仍受部署预算限制。</p>}
<label className="block text-sm">补充该任务输入<textarea value={input} onChange={e => setInput(e.target.value)} className="mt-1 block w-full rounded border p-2" /></label>
{task.operation === 'COMPANY_PROFILE' && <label className="flex gap-2 text-sm"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)} />已核对并确认企业主体</label>}
<GhostButton disabled={busy} onClick={() => void resume()}>已补充配置或信息,继续此任务</GhostButton>
</div>}
<ol className="space-y-2 text-sm" aria-label="真实任务事件">{events.map(event => <li key={event.id}>
<span className="mr-2 text-ink-400">#{event.id} {EVENT_LABEL[event.type] ?? event.type}</span>{event.payload.message ?? event.payload.text}
</li>)}</ol>
<div className="overflow-x-auto"><table className="w-full text-left text-xs"><thead><tr>{['工具', '状态', '积分', '输入 token', '输出 token', '实际模型', '耗时 ms'].map(label => <th className="p-2" key={label}>{label}</th>)}</tr></thead>
<tbody>{task.calls.map(call => <tr key={String(call.id)}>{['tool_name', 'status', 'cost_units', 'input_tokens', 'output_tokens', 'actual_model', 'duration_ms'].map(field => <td className="p-2" key={field}>{call[field] == null ? '待核对' : String(call[field])}</td>)}</tr>)}</tbody>
</table></div>
{task.calls.length === 0 && <p className="text-xs text-ink-400">尚未发生实际外部请求。</p>}
{task.result != null && <details><summary className="cursor-pointer text-sm">查看实际响应</summary><pre className="mt-2 max-h-96 overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify(task.result, null, 2)}</pre></details>}
{task.evidence.length > 0 && <details><summary className="cursor-pointer text-sm">来源与证据</summary><ul className="space-y-2 text-xs">{task.evidence.map(item => <li key={item.id}>{item.excerpt}<br />
{item.url && /^https?:\/\//i.test(item.url) && <a className="underline" href={item.url} target="_blank" rel="noopener noreferrer">查看来源</a>}
</li>)}</ul></details>}
</section>}
</div>
}
This diff is collapsed.
...@@ -68,6 +68,7 @@ export interface StatusChange { ...@@ -68,6 +68,7 @@ export interface StatusChange {
} }
export interface WatchRecord { export interface WatchRecord {
version: number
projectId: string projectId: string
status: WatchStatus status: WatchStatus
note: string note: string
......
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