"""Durable private task status cards. No task body, credentials or approval buttons.""" import hashlib import json import time EXECUTION={'queued':'排队中','running':'执行中','waiting_for_approval':'等待本人确认', 'completed':'执行完成','failed':'执行失败','cancelled':'已取消','interrupted':'已中断','unknown':'状态待核对'} DELIVERY={None:'尚未接收结果','ready':'已接收结果,等待投递','sending':'正在投递结果', 'replied':'结果已发送到当前会话','unknown':'结果投递待核对','discarded':'结果已停止交付'} def card_content(task_id,execution,delivery): execution=execution if execution in EXECUTION else 'unknown' color='green' if execution=='completed' else 'red' if execution=='failed' else 'orange' if execution in {'waiting_for_approval','unknown'} else 'blue' elements=[{'tag':'div','text':{'tag':'plain_text','content':'任务状态:'+EXECUTION[execution]}}, {'tag':'div','text':{'tag':'plain_text','content':'结果交付:'+DELIVERY.get(delivery,'状态待核对')}}, {'tag':'note','elements':[{'tag':'plain_text','content':'任务编号:'+task_id}]}] if execution=='waiting_for_approval': elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':'请在客户端查看并确认具体操作。本卡片暂不提供远程批准。'}}) if execution=='completed' and delivery!='replied': elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':'任务已执行完成,结果交付请看下方状态。'}}) return {'config':{'wide_screen_mode':True,'enable_forward':False}, 'header':{'template':color,'title':{'tag':'plain_text','content':'海诺任务进度'}},'elements':elements} class TaskCards: def __init__(self,state,platform,worker_id,clock=time.time): self.state,self.db,self.platform,self.worker_id,self.clock=state,state.db,platform,worker_id,clock with self.db: self.db.execute('''CREATE TABLE IF NOT EXISTS work_task_cards_v3( task_id TEXT PRIMARY KEY,message_id TEXT NOT NULL,digest TEXT NOT NULL, status TEXT NOT NULL,worker_id TEXT NOT NULL,updated_at DOUBLE PRECISION NOT NULL)''') def valid(self,task): device=self.state.store.device(task['host_id']) if task else None return bool(device and not device['revoked'] and device['owner']==task['owner'] and device['binding_generation']==task['binding_generation'] and task['source_message_id'] and task['chat_id']) def snapshot(self,task): row=self.db.execute('SELECT execution_state FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() delivery=self.db.execute('SELECT status FROM work_result_outbox_v2 WHERE task_id=?',(task['turn_id'],)).fetchone() execution=row['execution_state'] if row else 'unknown' if task['status']=='unknown' and execution not in {'completed','failed','cancelled','interrupted'}:execution='unknown' if task['deadline']<=self.clock() and execution not in {'completed','failed','cancelled','interrupted'}:execution='unknown' return card_content(task['turn_id'],execution,delivery['status'] if delivery else None) async def flush(self): # Bound one maintenance pass; business result delivery remains independent. rows=self.db.execute('''SELECT * FROM work_tasks_v2 WHERE environment=? AND app_id=? AND source_message_id<>'' AND chat_id<>'' AND updated_at>? ORDER BY updated_at DESC LIMIT 100''', (self.state.environment,self.state.app_id,self.clock()-86400)).fetchall() sent=0 for raw in rows: if sent>=10:break task=dict(raw) if not self.valid(task):continue card=self.snapshot(task) digest=hashlib.sha256(json.dumps(card,sort_keys=True,ensure_ascii=True).encode()).hexdigest() old=self.db.execute('SELECT * FROM work_task_cards_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() if old and (old['status']=='unknown' or old['digest']==digest or self.clock()-old['updated_at']<5):continue if not old and task['deadline']<=self.clock():continue try:token=await self.platform.tenant_token() except Exception:continue with self.db: self.state._owner_lock(task['owner']) task=self.state.task(task['turn_id']) if not self.valid(task):continue old=self.db.execute('SELECT * FROM work_task_cards_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() if old and old['status']=='sending': # A lost creation receipt cannot safely become another card. if self.clock()-old['updated_at']>=60: self.db.execute("UPDATE work_task_cards_v3 SET status=? WHERE task_id=?", ('ready' if old['message_id'] else 'unknown',task['turn_id'])) continue if old and (old['status']=='unknown' or old['digest']==digest or self.clock()-old['updated_at']<5):continue # Recompute after token/lock awaits so an older observation cannot overwrite new status. card=self.snapshot(task) digest=hashlib.sha256(json.dumps(card,sort_keys=True,ensure_ascii=True).encode()).hexdigest() message_id=old['message_id'] if old else '' if not old: self.db.execute('INSERT INTO work_task_cards_v3 VALUES(?,?,?,?,?,?)', (task['turn_id'],'','','sending',self.worker_id,self.clock())) else: self.db.execute("UPDATE work_task_cards_v3 SET status='sending',worker_id=?,updated_at=? WHERE task_id=?", (self.worker_id,self.clock(),task['turn_id'])) try: sent+=1 if message_id:await self.platform.update_task_card(message_id,card,token=token) else: delivery_id=hashlib.sha256(('task-card-v3\0'+self.state.environment+'\0'+self.state.app_id+'\0'+task['turn_id']).encode()).hexdigest()[:32] message_id=await self.platform.reply_task_card(task['source_message_id'],card,delivery_id,token=token) status='ready';saved_digest=digest except Exception: status='ready' if message_id else 'unknown';saved_digest=old['digest'] if old else '' with self.db: self.db.execute("UPDATE work_task_cards_v3 SET message_id=?,digest=?,status=?,updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?", (message_id,saved_digest,status,self.clock(),task['turn_id'],self.worker_id))