feat(work): recover text and attachment delivery independently

This commit is contained in:
ex_tianzy
2026-11-23 14:49:51 +08:00
parent 1b3fded4ae
commit 3f4b8f983b
7 changed files with 210 additions and 24 deletions
+29 -7
View File
@@ -55,6 +55,8 @@ class WorkFiles:
key_id TEXT NOT NULL,ciphertext TEXT NOT NULL,status TEXT NOT NULL,
platform_key TEXT NOT NULL,platform_message TEXT NOT NULL,
updated DOUBLE PRECISION NOT NULL,expires DOUBLE PRECISION NOT NULL)''')
self.db.execute('''CREATE INDEX IF NOT EXISTS work_files_task_receipts_idx
ON work_files_v1(environment,app_id,task_id,direction)''')
self.router=APIRouter()
self.router.add_api_route('/work/v2/files/list',self.list_files,methods=['POST'])
self.router.add_api_route('/work/v2/files/download',self.download,methods=['POST'])
@@ -144,6 +146,16 @@ class WorkFiles:
def metadata(self,row):
return {k:row[k]for k in ('file_id','direction','name','size','sha256','status')}
def output_receipts(self,task):
"""Project persisted output states for an already authenticated task."""
rows=self.db.execute("""SELECT file_id,name,size,sha256,status FROM work_files_v1
WHERE environment=? AND app_id=? AND task_id=? AND owner=? AND host_id=?
AND binding_generation=? AND chat_id=? AND source_message_id=? AND direction='output'
ORDER BY file_id""",
(self.environment,self.app_id,task['turn_id'],task['owner'],task['host_id'],
task['binding_generation'],task['chat_id'],task['source_message_id'])).fetchall()
return [{**dict(row),'platform_sent':row['status']=='sent'} for row in rows]
async def list_files(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request);self.current(body)
rows=self.db.execute("SELECT * FROM work_files_v1 WHERE environment=? AND app_id=? AND task_id=? AND expires>? ORDER BY file_id",(self.environment,self.app_id,body.task_id,time.time())).fetchall()
@@ -181,7 +193,7 @@ class WorkFiles:
with self.db:
self.state._owner_lock(task['owner']);self.current(body)
old=self.db.execute('SELECT * FROM work_files_v1 WHERE file_id=?',(fid,)).fetchone()
if old and (old['expires']<=time.time()or old['status']in {'expired','discarded'}):raise HTTPException(410,'file_expired')
if old and (old['expires']<=time.time()or old['status']in {'expired','discarded','failed'}):raise HTTPException(410,'file_not_available')
if not old:
count=self.db.execute("SELECT COUNT(*) AS n FROM work_files_v1 WHERE task_id=? AND direction='output'",(body.task_id,)).fetchone()['n']
if count>=self.s.work_file_batch_limit:raise HTTPException(413,'artifact_count_limit')
@@ -198,7 +210,10 @@ class WorkFiles:
async def flush(self):
now=time.time()
with self.db:
self.db.execute("UPDATE work_files_v1 SET status='expired',ciphertext='',platform_key='' WHERE environment=? AND app_id=? AND expires<? AND ciphertext!=''",(self.environment,self.app_id,now))
self.db.execute("""UPDATE work_files_v1 SET status=CASE WHEN status IN ('uploading','sending','unknown')
THEN 'unknown' ELSE 'expired' END,ciphertext='',platform_key='',updated=?
WHERE environment=? AND app_id=? AND expires<=? AND ciphertext!=''""",
(now,self.environment,self.app_id,now))
self.db.execute("UPDATE work_files_v1 SET status='failed',size=0,ciphertext='',updated=? WHERE environment=? AND app_id=? AND status='receiving' AND updated<?",(now,self.environment,self.app_id,now-120))
# Interrupted mutating platform calls remain ambiguous, never replayed.
self.db.execute("UPDATE work_files_v1 SET status='unknown',updated=? WHERE environment=? AND app_id=? AND status IN ('uploading','sending') AND updated<?",(now,self.environment,self.app_id,now-120))
@@ -206,7 +221,7 @@ class WorkFiles:
for raw_row in rows:
row=dict(raw_row);task=self.state.task(row['task_id'])
if not self.state.task_current(task):
with self.db:self.db.execute("UPDATE work_files_v1 SET status='discarded',ciphertext='',platform_key='' WHERE file_id=?",(row['file_id'],))
with self.db:self.db.execute("UPDATE work_files_v1 SET status='discarded',ciphertext='',platform_key='' WHERE file_id=? AND status=?",(row['file_id'],row['status']))
continue
try:token=await self.platform.tenant_token()
except Exception:continue
@@ -214,13 +229,20 @@ class WorkFiles:
self.state._owner_lock(row['owner'])
if not self.state.task_current(self.state.task(row['task_id'])):continue
working='uploading'if row['status']=='ready'else'sending'
changed=self.db.execute('UPDATE work_files_v1 SET status=?,updated=? WHERE file_id=? AND status=?',(working,time.time(),row['file_id'],row['status'])).rowcount
claimed_at=time.time()
changed=self.db.execute('UPDATE work_files_v1 SET status=?,updated=? WHERE file_id=? AND status=? AND expires>?',(working,claimed_at,row['file_id'],row['status'],claimed_at)).rowcount
if changed!=1:continue
if working=='uploading':
try:
content=self.keyring.decrypt(row['key_id'],row['ciphertext'],self._aad(row))
if len(content)!=row['size'] or hashlib.sha256(content).hexdigest()!=row['sha256']:raise ValueError()
mime=FORMATS[PurePosixPath(row['name']).suffix.lower()]
except Exception:
with self.db:self.db.execute("UPDATE work_files_v1 SET status='failed',ciphertext='',updated=? WHERE file_id=? AND status='uploading'",(time.time(),row['file_id']))
continue
try:
if working=='uploading':
content=self.keyring.decrypt(row['key_id'],row['ciphertext'],self._aad(row))
if hashlib.sha256(content).hexdigest()!=row['sha256']:raise ValueError()
key=await self.platform.upload_file(row['name'],content,FORMATS[PurePosixPath(row['name']).suffix.lower()],token=token)
key=await self.platform.upload_file(row['name'],content,mime,token=token)
with self.db:self.db.execute("UPDATE work_files_v1 SET status='uploaded',platform_key=?,updated=? WHERE file_id=? AND status='uploading'",(key,time.time(),row['file_id']))
else:
response=await self.platform.reply_file(task['source_message_id'],row['platform_key'],hashlib.sha256(row['file_id'].encode()).hexdigest()[:32],token=token)