File size: 14,711 Bytes
90d354b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import { useSyncExternalStore } from 'react'
import { TEMPLATES, type Template, LEVEL_META, type Level } from './templates'
import { adjudicate, templateOf, formatTime, type WatchItem, type Observation, type NotifyMode, type Verdict } from './domain'
import {groundedApi,contractTemplate,type Setup,type ContractResult} from './grounded'
export { templateOf, formatTime as nowLabel } from './domain'
export type { WatchItem, Observation, NotifyMode } from './domain'
export interface FeedEntry { id: string; at: string; time: string; text: string; tone: 'quiet' | 'notify' | 'warn' | 'unknown'; itemId?: string; changed?: boolean }
export interface Notice { id: string; at: string; time: string; level: Level; itemId: string; title: string; body: string; ack: boolean; feedback?: 'helpful' | 'too_many' }
export interface AppState { items: WatchItem[]; modelStatus: 'checking' | 'ready' | 'offline'; feed: FeedEntry[]; notices: Notice[]; storageError: boolean; revision?:number }
const KEY = 'home-pulse-v3'
const uid = () => crypto.randomUUID()
function newItem(t: Template, name: string, id = 'w-' + uid()): WatchItem {
  return { id, templateId: t.id, name, camera: t.camera, enabled: true, grounded: false, outcome: null, unknown: false, updatedAt: null, evidence: null, notifyMode: 'auto', observations: [], createdAt: new Date().toISOString(), trigger: 'event', interval: 3, windowStart: '18:00', windowEnd: '20:00', preferences: [] }
}
const initial = (): AppState => ({ items: TEMPLATES.slice(0,4).map((t,i) => newItem(t, t.itemName, ['w-package','w-cat','w-destroy','w-yard'][i])), modelStatus: 'checking', feed: [], notices: [], storageError: false })
export class Store {
  private state = initial()
  private listeners = new Set<() => void>()
  private lastSaved = ''
  constructor() {
    try {
      const raw = localStorage.getItem(KEY), old = raw ? null : localStorage.getItem('home-pulse-v2')
      if (raw) {this.state = { ...initial(), ...JSON.parse(raw), modelStatus: 'checking' };this.lastSaved=raw}
      else if (old) {
        const saved = JSON.parse(old)
        this.state.items = saved.items.map((i: WatchItem) => ({ ...newItem(templateOf(i), i.name, i.id), ...i, grounded: i.observations?.length > 0, outcome: i.evidence ? i.outcome : null, updatedAt: i.evidence ? i.updatedAt : null, observations: (i.observations || []).map(o => ({ ...o, id: String(o.id), capturedAt: '', sceneKey: 'legacy', frameKey: String(o.id), sourceName: '历史记录', mediaTime: 0 })), preferences: [] }))
        this.state.notices = (saved.notices || []).map((n: Notice) => ({ ...n, id: String(n.id), at: '' }))
        this.state.feed = (saved.feed || []).filter((f: { id: number }) => f.id > 3).map((f: FeedEntry) => ({ ...f, id: String(f.id), at: '' }))
      }
    } catch { /* Keep readable defaults if an archive is invalid. */ }
    if(typeof window!=='undefined')window.addEventListener('storage',event=>{if(event.key===KEY&&event.newValue){this.acceptSaved(event.newValue);this.listeners.forEach(fn=>fn())}})
  }
  private acceptSaved(raw:string){
    if(raw===this.lastSaved)return
    try{const saved=JSON.parse(raw);if(!Array.isArray(saved.items)||!Array.isArray(saved.notices)||(saved.revision||0)<(this.state.revision||0))return;this.state={...initial(),...saved,modelStatus:this.state.modelStatus};this.lastSaved=raw}catch{/* Ignore invalid writes from another tab. */}
  }
  private refreshFromDisk(){if(this.state.storageError)return;try{const raw=localStorage.getItem(KEY);if(raw)this.acceptSaved(raw)}catch{/* Keep the current state if storage is unavailable. */}}
  subscribe = (fn: () => void) => { this.listeners.add(fn); return () => { this.listeners.delete(fn) } }
  getState = () => this.state
  private emit(patch: Partial<AppState>) {
    this.state = { ...this.state, ...patch,revision:Math.max(Date.now(),(this.state.revision||0)+1) }
    const saved = { ...this.state, items: this.state.items.map(i => ({ ...i, observations: i.observations.slice(0,60).map((o,j) => ({ ...o, evidence: j < 3 ? o.evidence : null })) })) }
    try {const raw=JSON.stringify(saved);localStorage.setItem(KEY,raw);this.lastSaved=raw;this.state.storageError = false } catch { this.state.storageError = true }
    this.listeners.forEach(fn => fn())
  }
  setModelStatus(status: AppState['modelStatus']) { if (this.state.modelStatus !== status){this.state={...this.state,modelStatus:status};this.listeners.forEach(fn=>fn())} }
  addItem(t: Template, name: string, patch: Partial<WatchItem> = {}) {
    this.refreshFromDisk()
    const item = { ...newItem(t, name || t.itemName), ...patch }
    this.emit({ items: [...this.state.items, item] }); this.log('已添加「' + item.name + '」', 'quiet', item.id); return item
  }
  setItem(id: string, patch: Partial<WatchItem>) { this.refreshFromDisk();this.emit({ items: this.state.items.map(i => i.id === id ? { ...i, ...patch } : i) }) }
  addConfirmed(s:Setup,name:string,interval=3,replaceId?:string){
    this.refreshFromDisk()
    const existing=this.state.items.find(i=>i.contractId===s.id);if(existing)return existing
    const t=contractTemplate(s),item={...newItem(t,name||s.plan.title,replaceId||'w-'+s.id),contractId:s.id,contractPlan:s.plan,customTemplate:t,referenceSource:s.binding.source,memoryId:s.memoryId,confirmedAt:s.confirmedAt,grounded:true,enabled:true,interval,notifyMode:s.notification||'auto' as NotifyMode,evidence:s.binding.targetCrop,trigger:(s.plan.rules.some(r=>r.requires.length)?'external':s.plan.rules.some(r=>r.time_window)?'window':'interval') as WatchItem['trigger'],windowStart:s.plan.rules.find(r=>r.time_window)?.time_window?.start||'00:00',windowEnd:s.plan.rules.find(r=>r.time_window)?.time_window?.end||'23:59'}
    this.emit({items:replaceId?this.state.items.map(i=>i.id===replaceId?item:i):[...this.state.items,item]});this.log('已确认并启用「'+item.name+'」','quiet',item.id);return item
  }
  applyContractObservation(id:string,result:ContractResult,observation:Omit<Observation,'outcome'|'unknown'|'pending'>){
    this.refreshFromDisk()
    const item=this.state.items.find(i=>i.id===id);if(!item?.enabled||result.duplicate)return
    if(item.observations.some(o=>o.id===observation.id)){if(item.contractId)this.applyContractNotices(item.contractId,result.notices);return}
    const obs:Observation={...observation,outcome:result.outcome,unknown:!!result.unknown,pending:!!result.pending,text:result.text,details:result.details,engineMs:result.engineMs}
    const notices=result.notices.filter(n=>(item.notifyMode!=='quiet'||n.level===3)&&!this.state.notices.some(old=>old.id===n.eventId)).map(n=>({id:n.eventId,at:observation.capturedAt,time:formatTime(observation.capturedAt),level:n.level,itemId:id,title:item.name,body:n.title,ack:false}))
    this.emit({items:this.state.items.map(i=>i.id!==id?i:{...i,outcome:result.outcome,outcomeText:result.text,unknown:!!result.unknown,unknownReason:result.unknown?result.text:undefined,pending:undefined,effectiveLevel:notices.length?Math.max(...notices.map(n=>n.level)) as Level:0,evidence:observation.evidence,updatedAt:observation.capturedAt,latencyMs:result.latencyMs,observations:[obs,...i.observations].slice(0,100),lastFrameKey:observation.frameKey,sceneKey:observation.sceneKey}),notices:[...notices,...this.state.notices].slice(0,200)})
    this.log(item.name+' · '+result.text,result.unknown?'unknown':notices.length?'notify':'quiet',id,result.stateChanged)
  }
  applyContractNotices(registrationId:string,notices:ContractResult['notices']){
    this.refreshFromDisk()
    const item=this.state.items.find(i=>i.contractId===registrationId);if(!item?.enabled)return
    const fresh=notices.filter(n=>(item.notifyMode!=='quiet'||n.level===3)&&!this.state.notices.some(old=>old.id===n.eventId)).map(n=>({id:n.eventId,at:new Date(n.at*1000).toISOString(),time:formatTime(new Date(n.at*1000)),level:n.level,itemId:item.id,title:item.name,body:n.title,ack:false}))
    if(fresh.length)this.emit({notices:[...fresh,...this.state.notices].slice(0,200)})
  }
  syncContractHistory(registrationId:string,observations:Observation[]){
    if(!observations.length)return
    this.refreshFromDisk()
    const item=this.state.items.find(i=>i.contractId===registrationId);if(!item)return
    const currentIds=new Set(item.observations.map(o=>o.id));if(observations.every(o=>currentIds.has(o.id)))return
    const merged=[...new Map([...item.observations,...observations].map(o=>[o.id,o])).values()].sort((a,b)=>Date.parse(b.capturedAt)-Date.parse(a.capturedAt)).slice(0,100),last=merged[0]
    const recovered:FeedEntry[]=observations.filter(o=>!currentIds.has(o.id)).map(o=>({id:'observation-'+o.id,at:o.capturedAt,time:o.time,text:item.name+' · '+(o.text||'已记录'),tone:o.unknown?'unknown':o.outcome==='attention'?'notify':'quiet',itemId:item.id}))
    const feed=[...new Map([...this.state.feed,...recovered].map(f=>[f.id,f])).values()].sort((a,b)=>Date.parse(b.at)-Date.parse(a.at)).slice(0,300)
    this.emit({items:this.state.items.map(i=>i.id===item.id?{...i,observations:merged,outcome:last.outcome,outcomeText:last.text,updatedAt:last.capturedAt,evidence:last.evidence,unknown:last.unknown,latencyMs:last.latencyMs,effectiveLevel:last.outcome==='attention'?2:0}:i),feed})
  }
  removeItem(id: string) {
    this.refreshFromDisk()
    const item=this.state.items.find(i=>i.id===id)
    if(item?.contractId)void groundedApi('/api/contracts/archive',{registrationId:item.contractId}).catch(()=>this.log('关注已从页面收起,服务记录归档待重试','unknown'))
    this.emit({ items: this.state.items.filter(i => i.id !== id), notices: this.state.notices.filter(n => n.itemId !== id), feed: this.state.feed.filter(f => f.itemId !== id) })
  }
  ackNotice(id: string) { this.refreshFromDisk();this.emit({ notices: this.state.notices.map(n => n.id === id ? { ...n, ack: true } : n) }) }
  ackAll() { this.refreshFromDisk();this.emit({ notices: this.state.notices.map(n => ({ ...n, ack: true })) }) }
  noticeFeedback(id: string, feedback: Notice['feedback']) { this.refreshFromDisk();this.emit({ notices: this.state.notices.map(n => n.id === id ? { ...n, feedback } : n) }) }
  setPreference(id: string, mode: NotifyMode, reason = '手动调整') {
    this.refreshFromDisk()
    const i = this.state.items.find(x => x.id === id); if (!i) return
    if(i.contractId)void groundedApi('/api/contracts/preferences',{registrationId:i.contractId,notification:mode}).catch(()=>this.log('提醒偏好同步未完成,请重试','unknown',id))
    this.setItem(id, { notifyMode: mode, preferences: [{ id: uid(), at: new Date().toISOString(), mode, reason }, ...(i.preferences.length ? i.preferences : [{id:uid(),at:i.createdAt,mode:i.notifyMode,reason:'初始偏好'}])].slice(0,30) })
  }
  feedback(id: string, observationId: string, feedback: Observation['feedback']) {
    const item = this.state.items.find(i => i.id === id); if (item) this.setItem(id, { observations: item.observations.map(o => o.id === observationId ? { ...o, feedback } : o) })
  }
  log(text: string, tone: FeedEntry['tone'], itemId?: string, changed = false) {
    this.refreshFromDisk()
    const at = new Date().toISOString()
    this.emit({ feed: [{ id: uid(), at, time: formatTime(at), text, tone, itemId, changed }, ...this.state.feed].slice(0,300) })
  }
  applyObservation(itemId: string, answer: { choice: string | null; abstained: boolean }, observation: Omit<Observation,'outcome'|'unknown'|'pending'>): Verdict {
    this.refreshFromDisk()
    const item = this.state.items.find(i => i.id === itemId)
    if (!item) return { stateChanged: false, notified: false, level: 0, text: '事项已移除', pending: false, unknown: false, duplicate: false, outcome: null }
    const v = adjudicate(item, answer.choice, answer.abstained, observation.frameKey, observation.sceneKey)
    if (!item.enabled || v.duplicate) return v
    const obs: Observation = { ...observation, outcome: v.outcome, unknown: v.unknown, pending: v.pending }
    const patch: Partial<WatchItem> = { updatedAt: observation.capturedAt, evidence: observation.evidence, latencyMs: observation.latencyMs, observations: [obs, ...item.observations].slice(0,100), lastFrameKey: observation.frameKey }
    if (v.pending) {
      patch.pending = { choice: answer.choice!, count: 1, frameKey: observation.frameKey, sceneKey: observation.sceneKey }
      if (item.sceneKey !== observation.sceneKey) { patch.outcome = null; patch.unknown = false }
    } else {
      patch.pending = undefined; patch.unknown = v.unknown; patch.unknownReason = v.unknown ? observation.reason || '等待清晰画面' : undefined
      patch.outcome = v.outcome; patch.sceneKey = observation.sceneKey; patch.effectiveLevel = v.level
    }
    this.setItem(itemId, patch)
    if (v.notified) {
      const n: Notice = { id: uid(), at: observation.capturedAt, time: formatTime(observation.capturedAt), level: v.level, itemId, title: item.name, body: templateOf(item).labels[v.outcome!], ack: false }
      this.emit({ notices: [n,...this.state.notices].slice(0,200) })
    }
    this.log(item.name + ' · ' + v.text, v.unknown ? 'unknown' : v.notified ? (v.level >= 2 ? 'warn' : 'notify') : 'quiet', itemId, v.stateChanged)
    return v
  }
}
export const store = new Store()
export function useApp() { return useSyncExternalStore(store.subscribe, store.getState, store.getState) }
export function pendingNotices(state: AppState) { return state.notices.filter(n => !n.ack).length }
export function stateBadge(i: WatchItem) {
  if (!i.enabled) return { text: '已暂停', tone: 'muted' }
  if (i.pending) return { text: '等待确认', tone: 'amber' }
  if (i.unknown) return { text: '待补证', tone: 'muted' }
  if (!i.outcome) return { text: '等待观察', tone: 'muted' }
  const lv = i.effectiveLevel ?? templateOf(i).levels[i.outcome] ?? 0
  return { text: lv >= 2 ? '需要关注' : '已观察', tone: lv >= 2 ? 'amber' : 'green' }
}
export function itemStateText(i: WatchItem) { return !i.enabled ? '暂停期间保留历史记录' : i.outcomeText?i.outcomeText:i.pending ? '已获得一帧证据' : i.unknown ? i.unknownReason || '等待清晰画面' : i.outcome ? templateOf(i).labels[i.outcome] : '下一次观察,带回新的消息' }
export function downloadJSON(value: unknown, name: string) { const url = URL.createObjectURL(new Blob([JSON.stringify(value,null,2)], { type:'application/json' })); const a = document.createElement('a'); a.href = url; a.download = name; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000) }
export { LEVEL_META }