Download web/src/pulse/Pages.tsx from loveaa/OneAlign: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/spaces/loveaa/OneAlign/resolve/main/web/src/pulse/Pages.tsx
- Command line
-
hf download hf://spaces/loveaa/OneAlign/web/src/pulse/Pages.tsx
-
curl -L -o Pages.tsx https://huggingface.co/spaces/loveaa/OneAlign/resolve/main/web/src/pulse/Pages.tsx
22.4 kB
| import {useEffect,useRef,useState,type ReactNode} from 'react' | |
| import {Link,useParams} from 'react-router' | |
| import {Activity,ArrowDownToLine,ArrowLeft,ArrowUpRight,Bell,BookOpen,Check,ChevronRight,Clock3,Heart,House,KeyRound,Package,PawPrint,Plus,Search,ShieldCheck,Sparkles,Video,X} from 'lucide-react' | |
| import {api,categoryMeta,count,dateTime,download,handlingNames,latency,levelNames,statusNames,time,type Category,type StateEvent,type Watch} from './api' | |
| import {usePulse} from './context' | |
| export function CloudBuddy({small=false}:{small?:boolean}){return <span className={'pulse-cloud '+(small?'small':'')} aria-hidden="true"><i className="cloud-wing left"/><i className="cloud-wing right"/><i className="cloud-body"/><i className="cloud-gloss"/><span className="cloud-face"><i/><i/><b/></span></span>} | |
| export function CategoryIcon({category,size=21}:{category:Category;size?:number}){const Icon={security:ShieldCheck,care:PawPrint,memory:Sparkles,routine:KeyRound}[category];return <Icon size={size}/>} | |
| export function Empty({title,children,action}:{title:string;children?:ReactNode;action?:ReactNode}){return <div className="pulse-empty"><span className="pulse-empty-icon"><Heart size={24}/></span><h3>{title}</h3>{children&&<p>{children}</p>}{action}</div>} | |
| export function Back({to,label='返回'}:{to:string;label?:string}){return <Link className="pulse-text-button pulse-back" to={to}><ArrowLeft size={17}/>{label}</Link>} | |
| export function SectionTitle({title,to,label='全部',children}:{title:string;to?:string;label?:string;children?:ReactNode}){return <div className="pulse-section-title"><h2>{children}{title}</h2>{to&&<Link to={to}>{label}<ChevronRight size={15}/></Link>}</div>} | |
| export function WatchTile({watch,base}:{watch:Watch;base:string}){ | |
| const {data}=usePulse(),color=categoryMeta[watch.category].color,latest=watch.observations[0],tone=latest?.unknown||latest?.pending?'pending':data.events.some(e=>e.watchId===watch.id&&!e.visualRecoveryAt)?'attention':'' | |
| return <Link className={'pulse-watch-tile '+color} to={base+'/watch/'+watch.id}><div className="pulse-tile-top"><span className={'pulse-tile-icon '+color}><CategoryIcon category={watch.category}/></span><ChevronRight size={17}/></div><h3>{watch.title}</h3><b className={watch.lastResult?'pulse-watch-result '+tone:'pulse-watch-status'}>{watch.lastResult||statusNames[watch.observationStatus]||'等待观察'}</b><small>{watch.lastConfirmedAt?time(watch.lastConfirmedAt)+' · 最近一次确认':watch.binding.targetName+' · '+watch.binding.regionName}</small><div className="pulse-tile-bottom"><span className={'pulse-dot '+(watch.sourceOnline&&watch.state==='active'&&!watch.needsReconfirmation?'green':'')}/>{statusNames[watch.observationStatus]}<span>{levelNames[watch.attentionLevel]}</span></div></Link> | |
| } | |
| const objectGroup=(w:Watch)=>/狗|猫|宠物|Buddy/i.test(w.binding.targetName+' '+w.title)?'宠物':/包裹|快递/.test(w.title)?'包裹':/钥匙|出门/.test(w.title)?'日常':/庭院|院子/.test(w.title)?'院子':/门|访客/.test(w.title)?'门口':'其他' | |
| const groupIcons:Record<string,typeof PawPrint>={宠物:PawPrint,门口:House,包裹:Package,日常:KeyRound,院子:ShieldCheck,其他:Heart} | |
| export function HomePage({base}:{base:string}){ | |
| const {data,loading}=usePulse(),[filter,setFilter]=useState('全部') | |
| const watches=data.watches.filter(w=>w.state!=='replaced'),active=watches.filter(w=>w.state==='active'),connected=active.filter(w=>w.sourceOnline&&!w.needsReconfirmation),attention=data.events.filter(e=>!e.closedAt&&e.attentionLevel>=2),unconfirmed=active.length-connected.length | |
| const groups=[...new Set(watches.map(objectGroup))],m=data.metrics?.model | |
| const headline=loading?'正在了解家的近况':attention.length?'有件事,需要你看一眼':!watches.length?'把家的小事,放在心上。':unconfirmed?'有份关注,需要重新连接。':'家的近况,正在为你留意。' | |
| return <> | |
| <section className="pulse-home-hero"><div className="pulse-sky-orbit"/><span className="pulse-floating-home"><House size={22}/></span><span className="pulse-floating-shield"><ShieldCheck size={19}/></span><CloudBuddy/><h1>{headline}</h1><div className="pulse-home-summary"><span><b>{connected.length}</b> 份守护已开启</span><i/><span><b className="orange">{attention.length}</b> 项需要关注</span><i/><span><b>{unconfirmed}</b> 项需要连接</span></div><p>让每一份关心,都有刚刚好的回应。</p></section> | |
| <div className="pulse-object-filters" aria-label="关注对象筛选">{['全部',...groups].map(group=>{const Icon=groupIcons[group]||Heart;return <button className={filter===group?'active':''} key={group} onClick={()=>setFilter(group)}><Icon size={18}/>{group==='全部'?'我的关注':group}</button>})}</div> | |
| {!watches.length?<div className="pulse-start-grid"><button className="pulse-start-card" onClick={()=>location.assign(base+'/agent')}><span className="pulse-tile-icon mint"><PawPrint size={25}/></span><h2>小家伙,今天怎么样?</h2><p>确认你在意的对象,<br/>一起约定什么时候告诉你。</p><span className="pulse-start-link">添加第一份关注<Plus size={17}/></span></button><div className="pulse-home-photo"><img src="/media/posters/cat-active.jpg" alt="家中宠物活动的片刻"/><div><span>A LITTLE MOMENT AT HOME</span><h3>平常的一刻,<br/>也值得被惦记。</h3></div></div></div>:groups.filter(g=>filter==='全部'||g===filter).map(group=>{const list=watches.filter(w=>objectGroup(w)===group),Icon=groupIcons[group];return <section className="pulse-object-section" key={group}><SectionTitle title={group==='宠物'?list[0].binding.targetName:group} to={base+'/watches'}><span className="pulse-object-symbol"><Icon size={23}/></span><small>{list.length} 项关注</small></SectionTitle><div className="pulse-watch-grid">{list.map(w=><WatchTile key={w.id} watch={w} base={base}/>)}</div></section>})} | |
| {attention.length>0&&<section><SectionTitle title="需要你看一眼" to={base+'/notifications'}/><div className="pulse-event-stack">{attention.slice(0,3).map(e=><EventTile event={e} base={base} key={e.id}/>)}</div></section>} | |
| <section className="pulse-overview-section"><SectionTitle title="每一次关心,都有迹可循" to={base+'/metrics'} label="运行记录"/><div className="pulse-overview-metrics"><div><span className="pulse-tile-icon blue"><Video size={18}/></span><b>{count(m?.captures)}</b><small>今日采集画面</small></div><div><span className="pulse-tile-icon lilac"><Activity size={18}/></span><b>{m?.average==null?'—':(m.average/1000).toFixed(1)}<em> s</em></b><small>平均模型响应</small></div><div><span className="pulse-tile-icon mint"><Check size={18}/></span><b>{m?.successRate==null?'—':m.successRate}<em> %</em></b><small>请求成功率</small></div></div></section> | |
| <Link to={base+'/agent'} className="pulse-ask-strip"><Plus size={19}/><span>还有什么,想让我帮你留意?</span><CloudBuddy small/></Link> | |
| </> | |
| } | |
| export function WatchesPage({base}:{base:string}){ | |
| const {data}=usePulse(),[search,setSearch]=useState(''),[filter,setFilter]=useState('全部') | |
| const rows=data.watches.filter(w=>w.state!=='replaced'&&(filter==='全部'||w.state===(filter==='启用中'?'active':'paused'))&&(w.title+w.binding.targetName).toLowerCase().includes(search.toLowerCase())) | |
| return <><div className="pulse-page-heading"><div><span className="pulse-eyebrow">THE THINGS YOU CARE ABOUT</span><h1>我的关注</h1><p>每一份牵挂,都有明确的守护方式。</p></div><Link className="pulse-button compact" to={base+'/agent'}><Plus size={17}/>新建</Link></div><div className="pulse-toolbar"><label className="pulse-search"><Search size={17}/><input aria-label="搜索关注" placeholder="找一份关注…" value={search} onChange={e=>setSearch(e.target.value)}/></label><div className="pulse-segments">{['全部','启用中','已暂停'].map(f=><button className={f===filter?'active':''} key={f} onClick={()=>setFilter(f)}>{f}</button>)}</div></div>{rows.length?<div className="pulse-watch-grid full-grid">{rows.map(w=><WatchTile key={w.id} watch={w} base={base}/>)}</div>:<Empty title={search?'没有找到这份关注':'把一份关心,留在这里。'} action={<Link className="pulse-button" to={base+'/agent'}><Plus size={16}/>添加关注</Link>}>从小狗、钥匙,或者你在意的某一刻开始。</Empty>}<Link className="pulse-utility-link" to={base+'/memories'}><BookOpen size={18}/><span>对象记忆<small>我们已经认识的对象与位置</small></span><ChevronRight size={17}/></Link></> | |
| } | |
| export function EventTile({event,base}:{event:StateEvent;base:string}){return <Link to={base+'/event/'+event.id} className={'pulse-event-tile '+categoryMeta[event.category].color}><span className={'pulse-tile-icon '+categoryMeta[event.category].color}><CategoryIcon category={event.category}/></span><div><small>{categoryMeta[event.category].pattern} · {time(event.createdAt||event.occurredAt)}</small><h3>{event.title}</h3><span>{event.visualRecoveryAt?'画面已确认恢复':handlingNames[event.handlingState]} · {levelNames[event.attentionLevel]}</span></div>{event.handlingState==='unread'?<i className="pulse-unread"/>:<ChevronRight size={16}/>}</Link>} | |
| export function NotificationsPage({base}:{base:string}){ | |
| const {data}=usePulse(),[filter,setFilter]=useState('全部'),events=data.events.filter(e=>e.attentionLevel>0&&(filter==='全部'||filter==='待处理'&&!e.closedAt||filter==='已结束'&&e.closedAt)) | |
| return <><div className="pulse-page-heading"><div><span className="pulse-eyebrow">JUST THE RIGHT MOMENT</span><h1>家的消息</h1><p>知道发生了什么,再决定怎么回应。</p></div><span className="pulse-round-icon"><Bell size={22}/></span></div><div className="pulse-segments">{['全部','待处理','已结束'].map(f=><button key={f} className={filter===f?'active':''} onClick={()=>setFilter(f)}>{f}</button>)}</div><div className="pulse-event-stack">{events.map(e=><EventTile key={e.id} event={e} base={base}/>)}</div>{!events.length&&<Empty title="现在,没有新的消息。">值得关注的变化,会出现在这里。</Empty>}</> | |
| } | |
| export function EventPage({base}:{base:string}){ | |
| const {id}=useParams(),{data,clientId,refresh,notify}=usePulse(),[error,setError]=useState(''),[busy,setBusy]=useState(false),[evidence,setEvidence]=useState<Watch|null>(null),read=useRef('') | |
| const event=data.events.find(e=>e.id===id) | |
| useEffect(()=>{if(!event)return;void api<Watch>('/watches/'+event.watchId).then(setEvidence).catch(()=>{});if(event.handlingState==='unread'&&read.current!==event.id&&clientId){read.current=event.id;void api('/events/'+event.id+'/actions',{clientId,action:'read',expectedRevision:event.revision}).then(refresh).catch(()=>refresh())}},[event?.id,clientId,refresh]) | |
| const act=async(action:string)=>{if(!event||busy)return;setBusy(true);setError('');try{await api('/events/'+event.id+'/actions',{clientId,action,expectedRevision:event.revision});await refresh();notify(action==='take_over'?'已记录,我来处理':action==='user_completed'?'已记录你的处理结果':'事件已更新')}catch(e){setError((e as Error).message);await refresh()}finally{setBusy(false)}} | |
| if(!event)return <><Back to={base+'/notifications'}/><Empty title="这条消息暂时不在这里。"/></> | |
| return <><Back to={base+'/notifications'} label="家的消息"/><div className={'pulse-detail-hero '+categoryMeta[event.category].color}><span className={'pulse-detail-symbol '+categoryMeta[event.category].color}><CategoryIcon category={event.category} size={38}/></span><p>{categoryMeta[event.category].pattern}</p><h1>{event.title}</h1><span className={'pulse-pill '+categoryMeta[event.category].color}>{event.visualRecoveryAt?'已确认恢复':handlingNames[event.handlingState]}</span><small>{dateTime(event.createdAt||event.occurredAt)}</small></div><div className="pulse-detail-grid"><section className="pulse-card"><SectionTitle title="这次发生了什么"><span className="pulse-section-symbol blue"><Activity size={14}/></span></SectionTitle><div className="pulse-timeline"><div><time>{time(event.createdAt||event.occurredAt)}</time><span>画面满足约定条件</span></div>{event.actions.map((a,i)=><div key={i}><time>{time(a.at)}</time><span>{({read:'你查看了这条消息',take_over:'你选择了「我来处理」',user_completed:'你确认已经处理',dismiss:'本次事件结束',reopen:'重新跟进这次变化'} as Record<string,string>)[a.action]}</span></div>)}{event.visualRecoveryAt&&<div className="recovered"><time>{time(event.visualRecoveryAt)}</time><span>后续画面确认状态已恢复</span></div>}</div><div className="pulse-fact-note"><CheckCircleMark/><p>{event.visualRecoveryAt?'本次变化已经恢复。':event.userCompletedAt?'你已经处理,后续画面继续跟进。':'确认当前情况,选择适合的处理方式。'}</p></div></section><section className="pulse-card"><SectionTitle title="相关画面"/>{evidence?.observations.find(o=>o.evidence)?.evidence?<img className="pulse-evidence-image" src={evidence.observations.find(o=>o.evidence)?.evidence} alt="最近一次观察画面"/>:<img className="pulse-evidence-image" src={evidence?.binding.referenceImage} alt="这份关注确认时的参考画面"/>}<p className="pulse-helper">{evidence?.observations.find(o=>o.evidence)?'最近一次观察 · '+dateTime(evidence?.lastConfirmedAt):'关注建立时的参考画面'}</p><Link className="pulse-button soft full" to={base+'/watch/'+event.watchId}><Video size={16}/>查看关注与新画面</Link></section></div><div className="pulse-event-actions">{!event.closedAt&&<><button className="pulse-button soft" disabled={busy||event.handlingState==='handling'} onClick={()=>void act('take_over')}>我来处理</button><button className="pulse-button" disabled={busy} onClick={()=>void act('user_completed')}><Check size={17}/>已经处理</button></>}{event.closedAt&&!event.visualRecoveryAt&&<button className="pulse-button soft" disabled={busy} onClick={()=>void act('reopen')}>继续跟进</button>}</div>{error&&<div role="alert" className="pulse-error">{error}</div>}</> | |
| } | |
| function CheckCircleMark(){return <span className="pulse-tile-icon mint"><Check size={17}/></span>} | |
| export function MemoriesPage({base}:{base:string}){ | |
| const {data,refresh,notify}=usePulse(),[selected,setSelected]=useState<string|null>(null),[cascade,setCascade]=useState(false),[error,setError]=useState(''),[busy,setBusy]=useState(false) | |
| const remove=async()=>{if(!selected)return;setBusy(true);try{await api('/memories/'+selected+'/delete',{confirmed:true,cascade});setSelected(null);await refresh();notify('对象记忆已删除')}catch(e){setError((e as Error).message)}finally{setBusy(false)}} | |
| return <><Back to={base+'/watches'} label="我的关注"/><div className="pulse-page-heading"><div><span className="pulse-eyebrow">FAMILIAR THINGS AT HOME</span><h1>我们已经认识了。</h1><p>你确认过的对象,下次可以直接选用。</p></div><BookOpen size={26}/></div><div className="pulse-memory-grid">{data.memories.map(m=><article className="pulse-card pulse-memory-card" key={m.id}><div className="pulse-memory-image"><img src={m.thumbnail||m.targetCrop} alt={m.targetName}/><span className="pulse-pill mint"><Check size={12}/>已确认</span></div><h2>{m.targetName}</h2><p>{m.regionName} · {m.source.camera}</p><small>{dateTime(m.confirmedAt)}</small><div className="pulse-memory-actions"><Link className="pulse-button soft" to={base+'/agent?memory='+m.id}>用它新建关注<ChevronRight size={15}/></Link><button className="pulse-icon" aria-label={'删除记忆 '+m.targetName} onClick={()=>{setSelected(m.id);setCascade(false);setError('')}}><X size={17}/></button></div></article>)}</div>{!data.memories.length&&<Empty title="先认识,再记住。" action={<Link to={base+'/agent'} className="pulse-button">一起认识一个对象</Link>}>创建关注时,你可以选择保存对象与位置。</Empty>}{selected&&<ConfirmDialog title="删除这份对象记忆?" onClose={()=>setSelected(null)}><p>删除后,这个对象将不再出现在复用列表。</p><label className="pulse-check"><input type="checkbox" checked={cascade} onChange={e=>setCascade(e.target.checked)}/>同时删除仍在使用它的关注</label>{error&&<p className="pulse-error">{error}</p>}<button disabled={busy} className="pulse-button danger full" onClick={()=>void remove()}>确认删除</button></ConfirmDialog>}</> | |
| } | |
| export function ConfirmDialog({title,children,onClose}:{title:string;children:ReactNode;onClose:()=>void}){ | |
| const ref=useRef<HTMLDialogElement>(null) | |
| useEffect(()=>{ref.current?.showModal();return()=>ref.current?.close()},[]) | |
| return <dialog ref={ref} className="pulse-dialog" onCancel={onClose}><div className="pulse-section-title"><h2>{title}</h2><button autoFocus className="pulse-icon" aria-label="关闭确认" onClick={onClose}><X size={18}/></button></div>{children}</dialog> | |
| } | |
| export function ReviewPage({base}:{base:string}){ | |
| const {data}=usePulse(),[range,setRange]=useState('今天'),day=(value:string|number)=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(value)),today=day(Date.now()),start=range==='今天'?today:day(Date.now()-6*86400000) | |
| const rows=data.events.filter(e=>day(e.createdAt)>=start&&day(e.createdAt)<=today),memory=rows.filter(e=>e.category==='memory') | |
| return <><div className="pulse-page-heading"><div><span className="pulse-eyebrow">LITTLE MOMENTS, KEPT CLOSE</span><h1>把日常,慢慢收好。</h1><p>那些发生过的变化,和想留下来的片刻。</p></div><span className="pulse-round-icon lilac"><Sparkles size={24}/></span></div><div className="pulse-segments">{['今天','近七天'].map(r=><button key={r} className={range===r?'active':''} onClick={()=>setRange(r)}>{r}</button>)}</div><section className="pulse-review-hero"><CloudBuddy/><div><span>家的回顾</span><h2>{rows.length?`${rows.length} 次变化,都记在这里。`:'平常的一天,也值得珍惜。'}</h2><p>{memory.length?`${memory.length} 个生活片刻 · ${rows.filter(e=>e.visualRecoveryAt).length} 件事已恢复`:'在日常发生时,留下一点值得回看的东西。'}</p></div></section><section><SectionTitle title="发生过的片刻"/><div className="pulse-event-stack">{rows.map(e=><EventTile key={e.id} event={e} base={base}/>)}</div>{!rows.length&&<Empty title="今天的故事,正在发生。">新的状态事件和生活片刻会汇入这份回顾。</Empty>}</section><div className="pulse-link-cards"><Link to={base+'/memories'}><BookOpen size={20}/><div><b>对象记忆</b><small>已确认的对象和范围</small></div><ChevronRight size={17}/></Link><Link to="/review"><Clock3 size={20}/><div><b>历史生活回顾</b><small>查看原工作台记录</small></div><ArrowUpRight size={16}/></Link></div><button className="pulse-text-button" onClick={()=>download('Home-Pulse-回顾.json',{range,events:rows})}><ArrowDownToLine size={16}/>导出这份回顾</button></> | |
| } | |
| export function MetricsPage({base}:{base:string}){ | |
| const {data}=usePulse(),m=data.metrics?.model,a=data.metrics?.app,max=Math.max(1,...(m?.hourly.map(h=>h.captures)||[])) | |
| return <><Back to={base+'/settings'} label="我的空间"/><div className="pulse-page-heading"><div><span className="pulse-eyebrow">EVERY DECISION, ACCOUNTED FOR</span><h1>每一步,都看得见。</h1><p>今天的观察、响应和每次判断。</p></div><Activity size={26}/></div><div className="pulse-stats-grid">{[['采集画面',count(m?.captures),'blue'],['模型请求',count(m?.requests),'lilac'],['成功率',m?.successRate==null?'—':m.successRate+'%','mint'],['失败率',m?.failureRate==null?'—':m.failureRate+'%','coral'],['P50 响应',latency(m?.p50),'blue'],['P95 响应',latency(m?.p95),'lilac'],['规则决策',count(m?.decisions),'mint'],['暂未确认',count(m?.unknown),'peach']].map(([label,value,color])=><div className={'pulse-card pulse-stat '+color} key={label}><small>{label}</small><b>{value}</b></div>)}</div><section className="pulse-card pulse-chart-card"><SectionTitle title="今天的采集节奏"/><div className="pulse-hour-chart" role="img" aria-label="今日每小时采集画面数">{(m?.hourly||Array.from({length:24},(_,hour)=>({hour,captures:0}))).map(h=><div key={h.hour} title={h.hour+'时:'+h.captures+'次'}><i style={{height:Math.max(3,h.captures/max*110)}}/><span>{h.hour%6===0?String(h.hour).padStart(2,'0'):''}</span></div>)}</div></section><div className="pulse-detail-grid"><section className="pulse-card"><SectionTitle title="设备与动作"/><dl className="pulse-definition-list"><div><dt>设备在线</dt><dd>{a?.onlineDevices||0} / {a?.devices||0}</dd></div><div><dt>24 小时硬件事件</dt><dd>{count(a?.hardwareEvents24h)}</dd></div><div><dt>24 小时唯一观察画面</dt><dd>{count(a?.uniqueFrames24h)}</dd></div><div><dt>24 小时观察运行</dt><dd>{count(a?.observationRuns24h)}</dd></div><div><dt>SDK 执行成功率</dt><dd>{a?.sdkSuccessRate==null?'—':Math.round(a.sdkSuccessRate*100)+'%'}</dd></div><div><dt>效果验证通过率</dt><dd>{a?.verificationRate==null?'—':Math.round(a.verificationRate*100)+'%'}</dd></div></dl></section><section className="pulse-card"><SectionTitle title="需要留意的连接"/>{m?.failures.length?m.failures.map((f,i)=><div className="pulse-failure-row" key={i}><p>{f.reason}</p><b>{f.count} 次</b></div>):<p className="pulse-helper">当前没有已记录的失败。</p>}</section></div><section className="pulse-card"><SectionTitle title="逐次运行记录"/><div className="pulse-records">{m?.records.slice(0,40).map(r=><div key={r.id}><span className={'pulse-dot '+(r.status==='error'?'red':'green')}/><div><b>{r.itemName||r.sourceName||'视觉观察'}</b><small>{time(r.startedAt)} · {r.status==='error'?r.error:r.verdict||r.choice||r.status}</small></div><span><b>{latency(r.latencyMs)}</b><small>决策 {latency(r.engineMs)}</small></span></div>)}{!m?.records.length&&<p className="pulse-helper">完成一次试观察后,这里就会有第一条记录。</p>}</div></section><button className="pulse-text-button" onClick={()=>download('Home-Pulse-运行记录.json',data.metrics)}><ArrowDownToLine size={16}/>导出运行记录</button></> | |
| } | |