23 changed files with 726 additions and 67 deletions
+10
View File
@@ -0,0 +1,10 @@
# Work task dispatch and acceptance
The broker advertises `work-dispatch-v1` through signed Work status and uses it only for a paired capable client's private-chat assistant tasks. Older clients and direct read-only commands retain their existing path.
1. The connector atomically persists the original task identity, encrypted instruction and material assignments before it marks the event task as queued. Pending tasks are bounded per device (up to 20), subject to the original task deadline and binding generation.
2. A signed `POST /work/v2/tasks/next` returns the oldest eligible task for that same binding. Reading repeatedly does not mark it as accepted. The queued record does not depend on a WebSocket packet or the original connector process.
3. The client validates the task and digest and commits its encrypted local task record before signed `POST /work/v2/tasks/accept`. Identical acceptance retries return the original receipt. After acceptance the queue does not hand the task out again; the connector purges the queued body.
4. Execution starts only after confirmation. A client recovering a known native run polls the original run. If starting the run had an ambiguous outcome and no run ID was stored, the client does not start it again. Revoked, unbound and expired queued records cannot be accepted.
The guarantee starts at **queue commit**. Platform acknowledgment before queue commit is a separate ingress task. This slice does not queue requests submitted while the device is offline, add cancellation, or promise automatic recovery from lost client storage after acceptance.
+6
View File
@@ -10,6 +10,12 @@ All material/output bytes are AES-GCM encrypted using the existing server keyrin
Output stages: ready -> uploading -> uploaded -> sending -> sent. Failure after a mutating platform call is unknown and never automatically replayed. Client lost upload receipt first queries original file state before re-upload; ECS received is not platform sent, and sent is not user read. Stale uploading/sending states become unknown. Uploading to Work and replying to the original source_message_id are separate durable steps. Output stages: ready -> uploading -> uploaded -> sending -> sent. Failure after a mutating platform call is unknown and never automatically replayed. Client lost upload receipt first queries original file state before re-upload; ECS received is not platform sent, and sent is not user read. Stale uploading/sending states become unknown. Uploading to Work and replying to the original source_message_id are separate durable steps.
## Independent text and attachment recovery
Text and attachments have separate connector sweep loops. After restart only text in `ready` and attachments in `ready` or `uploaded` are processed. A completed send is skipped; an interrupted platform call is retained as `unknown`. A local integrity failure is `failed` because no platform call was made. Expiry purges encrypted content without turning an unknown platform send into a confirmed failure.
`POST /work/v2/tasks/state` includes a `delivery` projection for current, recoverable tasks. `POST /work/v2/tasks/delivery` is a read-only device-signed lookup of the original task, with access for the same current binding for up to seven days after the execution deadline when a durable delivery record exists. It does not extend the deadline or admit any new execution. The projection contains the text outbox state and each known attachment's ID, name, size, hash and state, never file keys, plaintext or platform credentials. It only reports records received by the relay. `platform_sent` indicates a platform acknowledgment, not that the recipient opened the message. Task cards surface file exceptions only when the relay has an actual failed or indeterminate attachment.
Deployment defaults (configurable, not measured product commitments): 10MiB/file, 20/task, 24h retention, 512MiB/owner and 2GiB/global encrypted payload allowance. Encryption/base64 and DB backups require extra capacity. Verify corporate reverse proxy limits too. Formatted documents are not executed; macro/embedded/external active-content handling remains PC policy. Deployment defaults (configurable, not measured product commitments): 10MiB/file, 20/task, 24h retention, 512MiB/owner and 2GiB/global encrypted payload allowance. Encryption/base64 and DB backups require extra capacity. Verify corporate reverse proxy limits too. Formatted documents are not executed; macro/embedded/external active-content handling remains PC policy.
Platform adapters use GET im/v1/messages/{message_id}/resources/{file_key}?type=file; POST im/v1/files multipart; POST im/v1/messages/{message_id}/reply file content. Scope and private-platform compatibility must be checked against internal docs and real synthetic test files. These are bot message resource APIs, distinct from user-token docx media download. Platform adapters use GET im/v1/messages/{message_id}/resources/{file_key}?type=file; POST im/v1/files multipart; POST im/v1/messages/{message_id}/reply file content. Scope and private-platform compatibility must be checked against internal docs and real synthetic test files. These are bot message resource APIs, distinct from user-token docx media download.
+7 -2
View File
@@ -5,7 +5,7 @@ from fastapi.responses import JSONResponse
from pydantic import Field from pydantic import Field
from .approval_callback import ApprovalCallbackVerifier,decision_toast from .approval_callback import ApprovalCallbackVerifier,decision_toast
from .approval_cards import ApprovalCardSender from .approval_cards import ApprovalCardSender,decision_response_card
from .approval_policy import describe_action from .approval_policy import describe_action
from .approval_store import ApprovalError from .approval_store import ApprovalError
from .common import no_cache,require_secret from .common import no_cache,require_secret
@@ -95,7 +95,12 @@ class ApprovalAPI:
return no_cache(JSONResponse({'toast':{'type':'warning', return no_cache(JSONResponse({'toast':{'type':'warning',
'content':'确认未完成或结果待核对,请查看原任务状态,勿重复发起操作。'}})) 'content':'确认未完成或结果待核对,请查看原任务状态,勿重复发起操作。'}}))
self._schedule('close',decision.approval_id) self._schedule('close',decision.approval_id)
return no_cache(JSONResponse(decision_toast(result))) # The callback response updates the clicked private card immediately;
# background PATCH remains only for other views/list state convergence.
response=decision_toast(result)
if result.get('state')in {'approved','rejected','expired','cancelled','consumed'}:
response['card']={'type':'raw','data':decision_response_card(result['state'])}
return no_cache(JSONResponse(response))
async def maintain(self): async def maintain(self):
await self.worker.call('close_unavailable') await self.worker.call('close_unavailable')
+13 -4
View File
@@ -24,7 +24,7 @@ def approval_card(material, clock=time.time):
buttons.append({'tag': 'button', 'text': {'tag': 'plain_text', 'content': label}, buttons.append({'tag': 'button', 'text': {'tag': 'plain_text', 'content': label},
'type': style, 'value': {'kind': 'hainuo.approval.v1', 'approval_id': reference, 'type': style, 'value': {'kind': 'hainuo.approval.v1', 'approval_id': reference,
'nonce': nonce, 'choice': choice}}) 'nonce': nonce, 'choice': choice}})
return {'config': {'wide_screen_mode': True, 'enable_forward': False}, return {'config': {'wide_screen_mode': True, 'enable_forward': False, 'update_multi': True},
'header': {'template': 'orange', 'title': {'tag': 'plain_text', 'content': '海诺操作确认'}}, 'header': {'template': 'orange', 'title': {'tag': 'plain_text', 'content': '海诺操作确认'}},
'elements': [ 'elements': [
{'tag': 'div', 'text': {'tag': 'plain_text', 'content': '准备做什么:' + summary}}, {'tag': 'div', 'text': {'tag': 'plain_text', 'content': '准备做什么:' + summary}},
@@ -57,8 +57,8 @@ class ApprovalCardSender:
raise raise
return {'state': 'sent'} return {'state': 'sent'}
async def update_closed(self,approval_id): async def update_closed(self,approval_id,refresh=False):
receipt=await self.approvals.call('closed_card_receipt',approval_id) receipt=await self.approvals.call('closed_card_receipt',approval_id,refresh)
if not receipt:return {'state':'no_closed_card'} if not receipt:return {'state':'no_closed_card'}
card=closed_approval_card(receipt['state']) card=closed_approval_card(receipt['state'])
token=await self.platform.tenant_token() token=await self.platform.tenant_token()
@@ -76,6 +76,15 @@ def closed_approval_card(state):
'cancelled':'本次确认已取消,不能再通过这张卡片批准。', 'cancelled':'本次确认已取消,不能再通过这张卡片批准。',
'consumed':'本次许可已交给客户端;是否执行及执行结果请查看任务进度。'} 'consumed':'本次许可已交给客户端;是否执行及执行结果请查看任务进度。'}
if state not in messages:raise ApprovalError('approval_not_closed') if state not in messages:raise ApprovalError('approval_not_closed')
return {'config':{'wide_screen_mode':True,'enable_forward':False}, return {'config':{'wide_screen_mode':True,'enable_forward':False,'update_multi':True},
'header':{'template':'grey','title':{'tag':'plain_text','content':'海诺操作确认已结束'}}, 'header':{'template':'grey','title':{'tag':'plain_text','content':'海诺操作确认已结束'}},
'elements':[{'tag':'div','text':{'tag':'plain_text','content':messages[state]}}]} 'elements':[{'tag':'div','text':{'tag':'plain_text','content':messages[state]}}]}
def decision_response_card(state):
if state=='approved':
return {'config':{'wide_screen_mode':True,'enable_forward':False,'update_multi':True},
'header':{'template':'blue','title':{'tag':'plain_text','content':'海诺操作已允许'}},
'elements':[{'tag':'div','text':{'tag':'plain_text',
'content':'你已允许本次操作,等待客户端继续。执行结果请查看任务进度。'}}]}
return closed_approval_card(state)
+42
View File
@@ -0,0 +1,42 @@
"""Docker-console repair of known CLOSED cards only. No public route or send."""
import argparse
import asyncio
import json
import re
from .config import Settings
from .credential_store import CredentialKeyring
from .approval_worker import ApprovalWorker
from .approval_cards import ApprovalCardSender
from .platform import Feishu
async def repair(task,apply=False):
s=Settings(role='connector')
if not s.work_remote_approvals_enabled:raise ValueError('approvals_disabled')
worker=ApprovalWorker(s,CredentialKeyring.from_file(s.credential_keyring_file))
await worker.start();platform=Feishu(s)
try:
# Dedicated worker serializes SQL. This lookup is constrained to a known
# task plus fixed app/environment; no user SQL or arbitrary message ID.
ids=await worker.call('closed_for_task',task)
if not apply:return {'state':'preview','closed_cards':len(ids)}
sender=ApprovalCardSender(worker,platform);updated=0
for approval_id in ids:
result=await sender.update_closed(approval_id,refresh=True)
updated+=result['state']=='updated'
return {'state':'updated','closed_cards':len(ids),'updated':updated,'new_cards_sent':0}
finally:
await platform.close();await worker.close()
def main():
parser=argparse.ArgumentParser();parser.add_argument('--task',required=True);parser.add_argument('--apply',action='store_true')
args=parser.parse_args()
if not re.fullmatch(r'msg_[a-f0-9]{64}',args.task):raise SystemExit('invalid task reference')
try:print(json.dumps(asyncio.run(repair(args.task,args.apply))))
except Exception as error:
print(json.dumps({'state':'repair_unconfirmed','error_class':type(error).__name__}))
raise SystemExit(1)from None
if __name__=='__main__':main()
+11 -2
View File
@@ -244,14 +244,15 @@ class ApprovalStore:
self._sweep_after=candidate['approval_id'] self._sweep_after=candidate['approval_id']
return closed return closed
def closed_card_receipt(self,approval_id): def closed_card_receipt(self,approval_id,refresh=False):
"""Internal renderer only. Never return action/nonce or imply execution success.""" """Internal renderer only. Never return action/nonce or imply execution success."""
if type(refresh)is not bool:raise ApprovalError('invalid_card_refresh')
with self.db: with self.db:
row=self._row(approval_id);self.state._owner_lock(row['owner']);row=self._expire(self._row(approval_id)) row=self._row(approval_id);self.state._owner_lock(row['owner']);row=self._expire(self._row(approval_id))
if row['state']not in {'rejected','expired','cancelled','consumed'}or not row['card_message_id']: if row['state']not in {'rejected','expired','cancelled','consumed'}or not row['card_message_id']:
return None return None
sent=self.db.execute('SELECT state FROM work_approval_card_outbox_v1 WHERE approval_id=?',(approval_id,)).fetchone() sent=self.db.execute('SELECT state FROM work_approval_card_outbox_v1 WHERE approval_id=?',(approval_id,)).fetchone()
if sent and sent['state']=='closed':return None if sent and sent['state']=='closed'and not refresh:return None
self.db.execute('UPDATE work_approval_card_outbox_v1 SET updated_at=? WHERE approval_id=?', self.db.execute('UPDATE work_approval_card_outbox_v1 SET updated_at=? WHERE approval_id=?',
(self.clock(),approval_id)) (self.clock(),approval_id))
return {'message_id':row['card_message_id'],'state':row['state']} return {'message_id':row['card_message_id'],'state':row['state']}
@@ -279,6 +280,14 @@ class ApprovalStore:
(self.state.environment,self.state.app_id)).fetchall() (self.state.environment,self.state.app_id)).fetchall()
return [row['approval_id']for row in rows] return [row['approval_id']for row in rows]
def closed_for_task(self,task_id):
if not isinstance(task_id,str)or not re.fullmatch(r'msg_[a-f0-9]{64}',task_id):
raise ApprovalError('invalid_task_reference')
rows=self.db.execute('''SELECT approval_id FROM work_approvals_v3 WHERE environment=? AND app_id=?
AND task_id=? AND state IN ('rejected','expired','cancelled','consumed') AND card_message_id<>'' LIMIT 10''',
(self.state.environment,self.state.app_id,task_id)).fetchall()
return [row['approval_id']for row in rows]
def decide(self,decision): def decide(self,decision):
if not isinstance(decision,VerifiedDecision):raise ApprovalError('verified_callback_required') if not isinstance(decision,VerifiedDecision):raise ApprovalError('verified_callback_required')
if decision.choice not in {'allow','deny'}:raise ApprovalError('invalid_approval_choice') if decision.choice not in {'allow','deny'}:raise ApprovalError('invalid_approval_choice')
+1 -1
View File
@@ -45,7 +45,7 @@ class ApprovalWorker:
async def call(self,method,*args): async def call(self,method,*args):
allowed={'create','status','consume','cancel','decide','card_material','claim_card', allowed={'create','status','consume','cancel','decide','card_material','claim_card',
'bind_card','card_send_unknown','close_unavailable','closed_card_receipt', 'bind_card','card_send_unknown','close_unavailable','closed_card_receipt',
'mark_card_closed','cards_to_send','cards_to_close','maintain_retention'} 'mark_card_closed','cards_to_send','cards_to_close','maintain_retention','closed_for_task'}
if method not in allowed:raise ApprovalError('unsupported_approval_operation') if method not in allowed:raise ApprovalError('unsupported_approval_operation')
try:await asyncio.wait_for(self.slots.acquire(),timeout=.05) try:await asyncio.wait_for(self.slots.acquire(),timeout=.05)
except asyncio.TimeoutError:raise ApprovalError('approval_temporarily_unavailable')from None except asyncio.TimeoutError:raise ApprovalError('approval_temporarily_unavailable')from None
+13 -10
View File
@@ -88,7 +88,7 @@ class BindingState:
(self.environment, self.app_id, device["host_id"], generation)) (self.environment, self.app_id, device["host_id"], generation))
self.db.execute("""UPDATE work_tasks_v2 SET status=?,updated_at=? self.db.execute("""UPDATE work_tasks_v2 SET status=?,updated_at=?
WHERE environment=? AND app_id=? AND host_id=? AND binding_generation<=? WHERE environment=? AND app_id=? AND host_id=? AND binding_generation<=?
AND status IN ('inflight','completed','replying','delivery_ready')""", AND status IN ('queued','inflight','completed','replying','delivery_ready')""",
("revoked" if reason == "revoke" else "unbound", time.time(), self.environment, ("revoked" if reason == "revoke" else "unbound", time.time(), self.environment,
self.app_id, device["host_id"], generation)) self.app_id, device["host_id"], generation))
event = uuid.uuid4().hex event = uuid.uuid4().hex
@@ -142,17 +142,20 @@ class BindingState:
and task["deadline"] > time.time()) and task["deadline"] > time.time())
def create_task(self, turn, owner, host, generation, session, worker, deadline, chat_id="", message_id=""): def create_task(self, turn, owner, host, generation, session, worker, deadline, chat_id="", message_id=""):
conversation = hashlib.sha256((self.environment+"\0"+self.app_id+"\0"+owner+"\0"+chat_id+"\0work-dm").encode()).hexdigest()
with self.db: with self.db:
self._owner_lock(owner) self._owner_lock(owner)
device = self.store.device(host) return self.create_task_locked(turn,owner,host,generation,session,worker,deadline,chat_id,message_id)
if not device or device["revoked"] or device["owner"] != owner or device["binding_generation"] != generation:
raise ValueError("binding changed") def create_task_locked(self,turn,owner,host,generation,session,worker,deadline,chat_id,message_id,status='inflight'):
count = self.db.execute("""INSERT INTO work_tasks_v2 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) conversation = hashlib.sha256((self.environment+"\0"+self.app_id+"\0"+owner+"\0"+chat_id+"\0work-dm").encode()).hexdigest()
ON CONFLICT DO NOTHING""", (turn,self.environment,self.app_id,owner,host,generation,session, device = self.store.device(host)
worker,conversation,chat_id,message_id,"inflight",deadline,time.time(),time.time())).rowcount if not device or device["revoked"] or device["owner"] != owner or device["binding_generation"] != generation:
if count != 1: raise ValueError("binding changed")
raise ValueError("task already recorded") count = self.db.execute("""INSERT INTO work_tasks_v2 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
ON CONFLICT DO NOTHING""", (turn,self.environment,self.app_id,owner,host,generation,session,
worker,conversation,chat_id,message_id,status,deadline,time.time(),time.time())).rowcount
if count != 1:
raise ValueError("task already recorded")
return self.task(turn) return self.task(turn)
def transition(self, turn, previous, status): def transition(self, turn, previous, status):
+42 -4
View File
@@ -71,6 +71,7 @@ class Broker:
self.lifecycle = None self.lifecycle = None
self.files = None self.files = None
self.task_cards = None self.task_cards = None
self.dispatch_queue = None
async def replies(self, pub): async def replies(self, pub):
async for message in pub.listen(): async for message in pub.listen():
@@ -156,6 +157,20 @@ class Broker:
return {'status':'materials_receiving','turn_id':turn,'result':'材料仍在接收,尚未执行任务。请等附件接收回执后再发送任务要求。'} return {'status':'materials_receiving','turn_id':turn,'result':'材料仍在接收,尚未执行任务。请等附件接收回执后再发送任务要求。'}
if self.files and self.files.pending_count(owner,host,device['binding_generation'],chat_id) and not file_capable: if self.files and self.files.pending_count(owner,host,device['binding_generation'],chat_id) and not file_capable:
return {'status':'unavailable','turn_id':turn,'result':'材料已保留,但当前客户端尚未支持附件处理;请升级配套客户端后再发任务要求。'} return {'status':'unavailable','turn_id':turn,'result':'材料已保留,但当前客户端尚未支持附件处理;请升级配套客户端后再发任务要求。'}
if (self.dispatch_queue and proof.get('durable_dispatch')=='work-dispatch-v1'
and text.startswith('/助手 ') and chat_id and source_message_id):
if len(text)>8010:
return {'status':'not_dispatched','turn_id':turn,'result':'任务文字超过长度限制,本条未入队。'}
try:
status=self.dispatch_queue.enqueue(owner,device,text,turn,chat_id=chat_id,
source_message_id=source_message_id,file_transfer=file_capable)
except ValueError:
return {'status':'not_dispatched','turn_id':turn,
'result':'材料或绑定状态发生变化,任务未入队。'}
except HTTPException as error:
if error.detail!='device_queue_full':raise
return {'status':'not_dispatched','turn_id':turn,'result':'设备待执行任务已满,本条未入队。'}
return {'status':status,'turn_id':turn,'result':'任务已接收。'}
if not self.store.begin_turn(turn, owner, host): if not self.store.begin_turn(turn, owner, host):
return {"status": "duplicate", "turn_id": turn, "result": "该请求已接收,不会重复执行。"} return {"status": "duplicate", "turn_id": turn, "result": "该请求已接收,不会重复执行。"}
task = None task = None
@@ -256,9 +271,13 @@ def create_app(settings=None, redis=None, platform=None):
lifecycle = DeviceLifecycle(store.lifecycle,r,broker) lifecycle = DeviceLifecycle(store.lifecycle,r,broker)
from .task_delivery import TaskDelivery from .task_delivery import TaskDelivery
deliveries = TaskDelivery(oauth,store.lifecycle,broker,f) deliveries = TaskDelivery(oauth,store.lifecycle,broker,f)
from .task_dispatch import TaskDispatch
broker.dispatch_queue=TaskDispatch(oauth,store.lifecycle,broker)
if s.work_files_enabled: if s.work_files_enabled:
from .work_files import WorkFiles from .work_files import WorkFiles
broker.files=WorkFiles(s,oauth,store.lifecycle,f) broker.files=WorkFiles(s,oauth,store.lifecycle,f)
if deliveries.cards:
deliveries.cards.file_receipts=broker.files.output_receipts
else: else:
oauth = OAuth(s, r, f) oauth = OAuth(s, r, f)
oauth.store = store oauth.store = store
@@ -308,14 +327,28 @@ def create_app(settings=None, redis=None, platform=None):
await asyncio.sleep(5) await asyncio.sleep(5)
try: try:
await lifecycle.maintain() await lifecycle.maintain()
await deliveries.recover_interrupted_sends() broker.dispatch_queue.expire()
if broker.files:await broker.files.flush()
await deliveries.flush()
if approvals:await approvals.maintain() if approvals:await approvals.maintain()
except Exception: except Exception:
# No credentials or raw exception text in background logs. # No credentials or raw exception text in background logs.
pass pass
lifecycle_task = asyncio.create_task(maintenance()) if lifecycle else None lifecycle_task = asyncio.create_task(maintenance()) if lifecycle else None
async def text_delivery_tick():
await deliveries.recover_interrupted_sends()
await deliveries.flush()
async def delivery_loop(tick):
while True:
await asyncio.sleep(5)
# A slow or failing file upload must not stall text delivery.
with contextlib.suppress(Exception):
await tick()
delivery_tasks = []
if lifecycle:
delivery_tasks.append(asyncio.create_task(delivery_loop(text_delivery_tick)))
if broker.files:
delivery_tasks.append(asyncio.create_task(delivery_loop(broker.files.flush)))
async def card_maintenance(): async def card_maintenance():
while True: while True:
await asyncio.sleep(5) await asyncio.sleep(5)
@@ -324,7 +357,7 @@ def create_app(settings=None, redis=None, platform=None):
try: try:
yield yield
finally: finally:
work = [reply_task,sweep_task,*background] + ([lifecycle_task] if lifecycle_task else []) + ([cards_task] if cards_task else []) work = [reply_task,sweep_task,*background,*delivery_tasks] + ([lifecycle_task] if lifecycle_task else []) + ([cards_task] if cards_task else [])
for task in work: for task in work:
task.cancel() task.cancel()
await asyncio.gather(*work, return_exceptions=True) await asyncio.gather(*work, return_exceptions=True)
@@ -348,7 +381,9 @@ def create_app(settings=None, redis=None, platform=None):
app.state.approvals=approvals app.state.approvals=approvals
if lifecycle: if lifecycle:
app.include_router(deliveries.router) app.include_router(deliveries.router)
app.include_router(broker.dispatch_queue.router)
app.state.deliveries=deliveries app.state.deliveries=deliveries
app.state.dispatch_queue=broker.dispatch_queue
if broker.files: if broker.files:
app.include_router(broker.files.router) app.include_router(broker.files.router)
app.state.files=broker.files app.state.files=broker.files
@@ -631,6 +666,9 @@ def create_app(settings=None, redis=None, platform=None):
**({"chat_id":message["chat_id"],"source_message_id":message_id} if lifecycle else {})))["result"] **({"chat_id":message["chat_id"],"source_message_id":message_id} if lifecycle else {})))["result"]
turn = "msg_"+hashlib.sha256(message_id.encode()).hexdigest() turn = "msg_"+hashlib.sha256(message_id.encode()).hexdigest()
task = store.lifecycle.task(turn) if lifecycle else None task = store.lifecycle.task(turn) if lifecycle else None
if task and task['status']=='queued':
store.finish(event_turn,"task_queued")
return
if task and not store.lifecycle.claim_reply(turn,owner,message_id): if task and not store.lifecycle.claim_reply(turn,owner,message_id):
store.finish(event_turn,"result_discarded") store.finish(event_turn,"result_discarded")
return return
+1
View File
@@ -121,6 +121,7 @@ class CredentialAPI:
raise HTTPException(503, "credential_temporarily_unavailable") from None raise HTTPException(503, "credential_temporarily_unavailable") from None
self.require_binding(body.host_id, device["owner"], device["binding_generation"]) self.require_binding(body.host_id, device["owner"], device["binding_generation"])
return no_cache(JSONResponse({"credential_mode": "broker", "protocol_version": 2, return no_cache(JSONResponse({"credential_mode": "broker", "protocol_version": 2,
"dispatch_protocol": "work-dispatch-v1",
"approval_protocol": "work-approval-v1" if self.s.work_remote_approvals_enabled else None, "approval_protocol": "work-approval-v1" if self.s.work_remote_approvals_enabled else None,
"binding_owner": device["owner"], "binding_owner": device["owner"],
"binding_generation": device["binding_generation"], "binding_generation": device["binding_generation"],
+19 -5
View File
@@ -11,6 +11,24 @@ import redis
from .config import Settings from .config import Settings
def safe_card_callback_response(payload):
"""Forward only code-owned terminal cards returned after verified decisions."""
from .approval_cards import decision_response_card
fallback={'toast':{'type':'warning','content':'确认结果待核对,请查看任务状态。'}}
if not isinstance(payload,dict):return fallback
toast=payload.get('toast')
if (not isinstance(toast,dict)or toast.get('type')not in {'info','success','warning','error'}
or not isinstance(toast.get('content'),str)or len(toast['content'])>200):return fallback
response={'toast':{'type':toast['type'],'content':toast['content']}}
card=payload.get('card')
if card is not None:
allowed=[{'type':'raw','data':decision_response_card(state)}for state in
('approved','rejected','expired','cancelled','consumed')]
if card not in allowed:return fallback
response['card']=card
return response
def disable_proxy_environment(): def disable_proxy_environment():
"""This dedicated SDK worker must connect directly, including discovery and WS.""" """This dedicated SDK worker must connect directly, including discovery and WS."""
for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"):
@@ -90,11 +108,7 @@ def main():
future.add_done_callback(settled) future.add_done_callback(settled)
try:payload=future.result(timeout=2.3) try:payload=future.result(timeout=2.3)
except FutureTimeout:return P2CardActionTriggerResponse(fallback) except FutureTimeout:return P2CardActionTriggerResponse(fallback)
toast=payload.get('toast')if isinstance(payload,dict)else None return P2CardActionTriggerResponse(safe_card_callback_response(payload))
if (not isinstance(toast,dict)or toast.get('type')not in {'info','success','warning','error'}
or not isinstance(toast.get('content'),str)or len(toast['content'])>200):
return P2CardActionTriggerResponse(fallback)
return P2CardActionTriggerResponse({'toast':toast})
except Exception:return P2CardActionTriggerResponse(fallback) except Exception:return P2CardActionTriggerResponse(fallback)
builder=builder.register_p2_card_action_trigger(decision) builder=builder.register_p2_card_action_trigger(decision)
handler=builder.build() handler=builder.build()
+18 -4
View File
@@ -7,12 +7,15 @@ import time
EXECUTION={'queued':'排队中','running':'执行中','waiting_for_approval':'等待本人确认', EXECUTION={'queued':'排队中','running':'执行中','waiting_for_approval':'等待本人确认',
'completed':'执行完成','failed':'执行失败','cancelled':'已取消','interrupted':'已中断','unknown':'状态待核对'} 'completed':'执行完成','failed':'执行失败','cancelled':'已取消','interrupted':'已中断','unknown':'状态待核对'}
DELIVERY={None:'尚未接收结果','ready':'已接收结果,等待投递','sending':'正在投递结果', DELIVERY={None:'尚未接收结果','ready':'已接收结果,等待投递','sending':'正在投递结果',
'replied':'结果已发送到当前会话','unknown':'结果投递待核对','discarded':'结果已停止交付'} 'replied':'结果已发送到当前会话','unknown':'结果投递待核对','discarded':'结果已停止交付',
'failed':'结果未能投递'}
def card_content(task_id,execution,delivery,files=None,connection_lost=False,remote_approvals=False): def card_content(task_id,execution,delivery,files=None,connection_lost=False,remote_approvals=False,
attachment_exception=None):
execution=execution if execution in EXECUTION else 'unknown' execution=execution if execution in EXECUTION else 'unknown'
color='green' if execution=='completed' else 'red' if execution in {'failed','interrupted'} else 'orange' if execution in {'waiting_for_approval','unknown'} else 'blue' color='green' if execution=='completed' else 'red' if execution in {'failed','interrupted'} else 'orange' if execution in {'waiting_for_approval','unknown'} else 'blue'
if execution=='cancelled':color='grey'
label=EXECUTION[execution] label=EXECUTION[execution]
if connection_lost and execution not in {'completed','failed','cancelled','interrupted'}: if connection_lost and execution not in {'completed','failed','cancelled','interrupted'}:
color='red';label='客户端失联,任务结果待核对' color='red';label='客户端失联,任务结果待核对'
@@ -25,6 +28,8 @@ def card_content(task_id,execution,delivery,files=None,connection_lost=False,rem
elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':hint}}) elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':hint}})
if execution=='completed' and delivery!='replied': if execution=='completed' and delivery!='replied':
elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':'任务已执行完成,结果交付请看下方状态。'}}) elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':'任务已执行完成,结果交付请看下方状态。'}})
if attachment_exception:
elements.insert(-1,{'tag':'div','text':{'tag':'plain_text','content':attachment_exception}})
return {'config':{'wide_screen_mode':True,'enable_forward':False}, return {'config':{'wide_screen_mode':True,'enable_forward':False},
'header':{'template':color,'title':{'tag':'plain_text','content':'海诺任务进度'}},'elements':elements} 'header':{'template':color,'title':{'tag':'plain_text','content':'海诺任务进度'}},'elements':elements}
@@ -33,6 +38,7 @@ class TaskCards:
def __init__(self,state,platform,worker_id,clock=time.time,files_enabled=False,remote_approvals=False): def __init__(self,state,platform,worker_id,clock=time.time,files_enabled=False,remote_approvals=False):
self.state,self.db,self.platform,self.worker_id,self.clock=state,state.db,platform,worker_id,clock self.state,self.db,self.platform,self.worker_id,self.clock=state,state.db,platform,worker_id,clock
self.files_enabled=files_enabled self.files_enabled=files_enabled
self.file_receipts=None
self.remote_approvals=remote_approvals self.remote_approvals=remote_approvals
with self.db: with self.db:
self.db.execute('''CREATE TABLE IF NOT EXISTS work_task_connection_v3( self.db.execute('''CREATE TABLE IF NOT EXISTS work_task_connection_v3(
@@ -56,12 +62,20 @@ class TaskCards:
def snapshot(self,task): def snapshot(self,task):
row=self.db.execute('SELECT execution_state FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() 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() 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' execution=row['execution_state'] if row else 'queued' if task['status']=='queued' else 'unknown'
if task['status']=='unknown' and execution not in {'completed','failed','cancelled','interrupted'}:execution='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' if task['deadline']<=self.clock() and execution not in {'completed','failed','cancelled','interrupted'}:execution='unknown'
lost=self.db.execute('SELECT reason FROM work_task_connection_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() lost=self.db.execute('SELECT reason FROM work_task_connection_v3 WHERE task_id=?',(task['turn_id'],)).fetchone()
exceptions=[]
if self.file_receipts:
receipts=self.file_receipts(task)
unknown=sum(r['status']=='unknown' for r in receipts)
failed=sum(r['status'] in {'failed','expired','discarded'} for r in receipts)
if unknown:exceptions.append(f'{unknown} 份附件的送达结果待核对。')
if failed:exceptions.append(f'{failed} 份附件未能交付。')
return card_content(task['turn_id'],execution,delivery['status'] if delivery else None, return card_content(task['turn_id'],execution,delivery['status'] if delivery else None,
connection_lost=bool(lost),remote_approvals=self.remote_approvals) connection_lost=bool(lost),remote_approvals=self.remote_approvals,
attachment_exception=''.join(exceptions))
async def flush(self): async def flush(self):
# Bound one maintenance pass; business result delivery remains independent. # Bound one maintenance pass; business result delivery remains independent.
+44 -12
View File
@@ -38,6 +38,7 @@ class TaskDelivery:
status TEXT NOT NULL,updated_at DOUBLE PRECISION NOT NULL)""") status TEXT NOT NULL,updated_at DOUBLE PRECISION NOT NULL)""")
self.router=APIRouter() self.router=APIRouter()
self.router.add_api_route('/work/v2/tasks/state',self.status,methods=['POST']) self.router.add_api_route('/work/v2/tasks/state',self.status,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/delivery',self.delivery_status,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/progress',self.progress,methods=['POST']) self.router.add_api_route('/work/v2/tasks/progress',self.progress,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/result',self.submit,methods=['POST']) self.router.add_api_route('/work/v2/tasks/result',self.submit,methods=['POST'])
self.cards=None self.cards=None
@@ -47,16 +48,25 @@ class TaskDelivery:
remote_approvals=auth.s.work_remote_approvals_enabled) remote_approvals=auth.s.work_remote_approvals_enabled)
broker.task_cards=self.cards broker.task_cards=self.cards
def current(self, body): def current(self, body, *, read_receipt=False, read_queue=False):
self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation)
task=self.state.task(body.task_id) task=self.state.task(body.task_id)
if (not self.state.task_current(task) or if (not task or
not task['source_message_id'] or not task['source_message_id'] or
(task['host_id'],task['owner'],task['binding_generation']) != (task['host_id'],task['owner'],task['binding_generation']) !=
(body.host_id,body.binding_owner,body.binding_generation) or (body.host_id,body.binding_owner,body.binding_generation) or
task['status'] in {'unbound','revoked','result_discarded'}): task['status'] in {'unbound','revoked','result_discarded'}):
raise HTTPException(403,'task_not_recoverable') raise HTTPException(403,'task_not_recoverable')
known=self.db.execute('SELECT task_id FROM work_result_outbox_v2 WHERE task_id=?',(body.task_id,)).fetchone() known=self.db.execute('SELECT task_id FROM work_result_outbox_v2 WHERE task_id=?',(body.task_id,)).fetchone()
if not self.state.task_current(task):
age=time.time()-task['deadline']
files=getattr(self.broker,'files',None)
if (read_receipt and 0<=age<7*86400
and (known or (files and files.output_receipts(task)))):
return task
raise HTTPException(403,'task_not_recoverable')
if read_queue and task['status']=='queued':
return task
if not known and task['status'] not in {'inflight','unknown'}: if not known and task['status'] not in {'inflight','unknown'}:
raise HTTPException(403,'task_not_recoverable') raise HTTPException(403,'task_not_recoverable')
return task return task
@@ -65,20 +75,33 @@ class TaskDelivery:
row=self.db.execute('SELECT status,digest FROM work_result_outbox_v2 WHERE task_id=?', row=self.db.execute('SELECT status,digest FROM work_result_outbox_v2 WHERE task_id=?',
(task['turn_id'],)).fetchone() (task['turn_id'],)).fetchone()
execution=self.db.execute('SELECT execution_state,status_sequence FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() execution=self.db.execute('SELECT execution_state,status_sequence FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone()
file_service=getattr(self.broker,'files',None)
delivery={
'protocol':'work-delivery-v1',
'text':{'status':row['status'] if row else 'not_received',
'platform_sent':bool(row and row['status']=='replied')},
'attachments':file_service.output_receipts(task) if file_service else [],
}
return {'task_id':task['turn_id'],'status':row['status'] if row else task['status'], return {'task_id':task['turn_id'],'status':row['status'] if row else task['status'],
'progress_protocol':'work-progress-v1', 'progress_protocol':'work-progress-v1',
'execution_state':execution['execution_state'] if execution else 'unknown', 'execution_state':execution['execution_state'] if execution else 'queued' if task['status']=='queued' else 'unknown',
'status_sequence':execution['status_sequence'] if execution else 0, 'status_sequence':execution['status_sequence'] if execution else 0,
'result_received':bool(row),'result_digest':row['digest'] if row else None, 'result_received':bool(row),'result_digest':row['digest'] if row else None,
'deadline':task['deadline']} 'deadline':task['deadline'],'delivery':delivery}
async def status(self,body:TaskRequest,request:Request): async def status(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request) await self.auth.authenticate(body,request)
task=self.current(body) task=self.current(body,read_queue=True)
pending=self.broker.pending.get(body.task_id) pending=self.broker.pending.get(body.task_id)
if pending and pending.host==body.host_id:pending.progress.set() if pending and pending.host==body.host_id:pending.progress.set()
return no_cache(JSONResponse(self.receipt(task))) return no_cache(JSONResponse(self.receipt(task)))
async def delivery_status(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request)
task=self.current(body,read_receipt=True)
# Receipt checks never touch the execution watchdog.
return no_cache(JSONResponse({'task_id':body.task_id,'delivery':self.receipt(task)['delivery']}))
async def progress(self,body:StateRequest,request:Request): async def progress(self,body:StateRequest,request:Request):
await self.auth.authenticate(body,request) await self.auth.authenticate(body,request)
with self.db: with self.db:
@@ -155,17 +178,26 @@ class TaskDelivery:
try: try:
result=self.keyring.decrypt(row['key_id'],row['ciphertext'],aad).decode() result=self.keyring.decrypt(row['key_id'],row['ciphertext'],aad).decode()
if hashlib.sha256(result.encode()).hexdigest()!=row['digest']:raise ValueError() if hashlib.sha256(result.encode()).hexdigest()!=row['digest']:raise ValueError()
await self.platform.reply(task['source_message_id'],result) except Exception:
outcome='replied' outcome='failed'
except Exception:pass else:
try:
await self.platform.reply(task['source_message_id'],result)
outcome='replied'
except Exception:pass
with self.db: with self.db:
self.db.execute("UPDATE work_result_outbox_v2 SET status=?,ciphertext=?,updated_at=? WHERE task_id=? AND status='sending'",(outcome,'' if outcome=='replied' else row['ciphertext'],time.time(),row['task_id'])) changed=self.db.execute("UPDATE work_result_outbox_v2 SET status=?,ciphertext=?,updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(outcome,row['ciphertext'] if outcome=='unknown' else '',time.time(),row['task_id'],self.broker.worker_id)).rowcount
self.db.execute("UPDATE work_tasks_v2 SET status=?,updated_at=? WHERE turn_id=? AND status='delivery_ready'", if changed==1:
('replied' if outcome=='replied' else 'reply_unknown',time.time(),row['task_id'])) self.db.execute("UPDATE work_tasks_v2 SET status=?,updated_at=? WHERE turn_id=? AND status='delivery_ready'",
({'replied':'replied','unknown':'reply_unknown','failed':'reply_failed'}[outcome],time.time(),row['task_id']))
async def recover_interrupted_sends(self): async def recover_interrupted_sends(self):
rows=self.db.execute("SELECT task_id,worker_id,updated_at FROM work_result_outbox_v2 WHERE environment=? AND app_id=? AND status='sending'",(self.state.environment,self.state.app_id)).fetchall() rows=self.db.execute("SELECT task_id,worker_id,updated_at FROM work_result_outbox_v2 WHERE environment=? AND app_id=? AND status='sending'",(self.state.environment,self.state.app_id)).fetchall()
for row in rows: for row in rows:
if time.time()-row['updated_at']<60 or await self.auth.r.exists('hn:task-worker:'+row['worker_id']):continue if time.time()-row['updated_at']<60 or await self.auth.r.exists('hn:task-worker:'+row['worker_id']):continue
with self.db: with self.db:
self.db.execute("UPDATE work_result_outbox_v2 SET status='unknown',updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(time.time(),row['task_id'],row['worker_id'])) now=time.time()
changed=self.db.execute("UPDATE work_result_outbox_v2 SET status='unknown',updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(now,row['task_id'],row['worker_id'])).rowcount
if changed==1:
self.db.execute("UPDATE work_tasks_v2 SET status='reply_unknown',updated_at=? WHERE turn_id=? AND status='delivery_ready'",
(now,row['task_id']))
+132
View File
@@ -0,0 +1,132 @@
"""C101 pull queue. No process-local state authorizes execution."""
import hashlib
import time
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import JSONResponse
from pydantic import Field
from .common import no_cache
from .credential_api import DeviceRequest
from .crypto import canonical
from .task_delivery import TaskRequest
PROTOCOL = 'work-dispatch-v1'
class Acceptance(TaskRequest):
digest: str = Field(pattern=r'^[a-f0-9]{64}$')
class TaskDispatch:
def __init__(self, auth, state, broker):
self.auth, self.state, self.broker = auth, state, broker
self.db=state.db
self.keyring=auth.broker.store.keyring
with self.db:
self.db.execute("""CREATE TABLE IF NOT EXISTS work_dispatch_v1 (
task_id TEXT PRIMARY KEY, digest TEXT NOT NULL, key_id TEXT NOT NULL,
ciphertext TEXT NOT NULL, file_transfer INTEGER NOT NULL,
accepted_at DOUBLE PRECISION)""")
self.router=APIRouter()
self.router.add_api_route('/work/v2/tasks/next',self.next_task,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/accept',self.accept,methods=['POST'])
def _aad(self, task, digest, files):
return canonical([PROTOCOL,*[task[k] for k in ('environment','app_id','owner','host_id',
'binding_generation','turn_id','chat_id','source_message_id')],digest,bool(files)])
def enqueue(self, owner, device, text, turn, *, chat_id, source_message_id, file_transfer):
digest=hashlib.sha256(text.encode()).hexdigest()
now=time.time();host=device['host_id'];generation=device['binding_generation']
with self.db:
self.state._owner_lock(owner)
if (self.broker.files and not file_transfer
and self.broker.files.pending_count(owner,host,generation,chat_id)):
raise ValueError('materials_require_file_capability')
inserted=self.db.execute("INSERT INTO turns VALUES(?,?,?,?,?) ON CONFLICT(turn_id) DO NOTHING",
(turn,owner,host,'queued',now)).rowcount
if inserted!=1:return 'duplicate'
count=self.db.execute("""SELECT COUNT(*) AS n FROM work_tasks_v2 WHERE environment=? AND app_id=?
AND host_id=? AND binding_generation=? AND status='queued' AND deadline>?""",
(self.state.environment,self.state.app_id,host,generation,now)).fetchone()['n']
if count>=min(self.broker.s.max_pending,20):
raise HTTPException(503,'device_queue_full')
task=self.state.create_task_locked(turn,owner,host,generation,'',self.broker.worker_id,
now+self.broker.s.task_tracking_timeout,chat_id,source_message_id,status='queued')
if file_transfer:
self.broker.files.claim_locked(task)
key,cipher=self.keyring.encrypt(text.encode(),self._aad(task,digest,file_transfer))
self.db.execute('INSERT INTO work_dispatch_v1 VALUES(?,?,?,?,?,NULL)',
(turn,digest,key,cipher,int(file_transfer)))
return 'queued'
async def next_task(self,body:DeviceRequest,request:Request):
await self.auth.authenticate(body,request)
with self.db:
self.state._owner_lock(body.binding_owner)
self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation)
row=self.db.execute("""SELECT t.*,q.digest,q.key_id,q.ciphertext,q.file_transfer
FROM work_tasks_v2 t JOIN work_dispatch_v1 q ON q.task_id=t.turn_id
WHERE t.environment=? AND t.app_id=? AND t.owner=? AND t.host_id=?
AND t.binding_generation=? AND t.status='queued' AND t.deadline>?
AND q.accepted_at IS NULL
ORDER BY t.created_at,t.turn_id LIMIT 1 """,
(self.state.environment,self.state.app_id,body.binding_owner,body.host_id,
body.binding_generation,time.time())).fetchone()
job=None
if row:
text=self.keyring.decrypt(row['key_id'],row['ciphertext'],
self._aad(row,row['digest'],row['file_transfer'])).decode()
if hashlib.sha256(text.encode()).hexdigest()!=row['digest']:
raise HTTPException(409,'dispatch_integrity_failed')
context={k:row[k] for k in ('environment','app_id','owner','host_id','binding_generation',
'chat_id','source_message_id','conversation_id')}
context.update(task_id=row['turn_id'],channel='work-dm')
job={'context':context,'text':text,'digest':row['digest'],'file_transfer':bool(row['file_transfer'])}
return no_cache(JSONResponse({'protocol':PROTOCOL,'task':job}))
async def accept(self,body:Acceptance,request:Request):
await self.auth.authenticate(body,request)
with self.db:
self.state._owner_lock(body.binding_owner)
self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation)
task=self.state.task(body.task_id)
if (not self.state.task_current(task)
or (task['owner'],task['host_id'],task['binding_generation']) !=
(body.binding_owner,body.host_id,body.binding_generation)
or task['status'] in {'unbound','revoked','expired','result_discarded'}):
raise HTTPException(403,'task_not_recoverable')
row=self.db.execute('SELECT digest,accepted_at FROM work_dispatch_v1 WHERE task_id=?',
(body.task_id,)).fetchone()
if not row:
raise HTTPException(403,'task_not_recoverable')
if row['digest']!=body.digest:
raise HTTPException(409,'dispatch_digest_mismatch')
if row['accepted_at'] is None:
if task['status']!='queued':
raise HTTPException(403,'task_not_recoverable')
now=time.time()
changed=self.db.execute("""UPDATE work_tasks_v2 SET status='inflight',worker_id=?,updated_at=?
WHERE turn_id=? AND status='queued' AND deadline>?""",
(self.broker.worker_id,now,body.task_id,now)).rowcount
if changed!=1:
raise HTTPException(403,'task_not_recoverable')
self.db.execute("UPDATE turns SET status='inflight' WHERE turn_id=?",(body.task_id,))
self.db.execute("UPDATE work_dispatch_v1 SET accepted_at=?,ciphertext='' WHERE task_id=?",
(now,body.task_id))
else:
now=row['accepted_at']
return no_cache(JSONResponse({'protocol':PROTOCOL,'task_id':body.task_id,
'digest':body.digest,'accepted':True,'accepted_at':now}))
def expire(self):
now=time.time()
scope=(self.state.environment,self.state.app_id)
with self.db:
self.db.execute("""UPDATE work_tasks_v2 SET status='expired',updated_at=?
WHERE environment=? AND app_id=? AND status='queued' AND deadline<=?""",(now,*scope,now))
self.db.execute("""UPDATE work_dispatch_v1 SET ciphertext='' WHERE ciphertext<>'' AND task_id IN
(SELECT turn_id FROM work_tasks_v2 WHERE environment=? AND app_id=?
AND status IN ('expired','unbound','revoked'))""",scope)
+36 -11
View File
@@ -55,6 +55,8 @@ class WorkFiles:
key_id TEXT NOT NULL,ciphertext TEXT NOT NULL,status TEXT NOT NULL, key_id TEXT NOT NULL,ciphertext TEXT NOT NULL,status TEXT NOT NULL,
platform_key TEXT NOT NULL,platform_message TEXT NOT NULL, platform_key TEXT NOT NULL,platform_message TEXT NOT NULL,
updated DOUBLE PRECISION NOT NULL,expires DOUBLE PRECISION 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=APIRouter()
self.router.add_api_route('/work/v2/files/list',self.list_files,methods=['POST']) 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']) self.router.add_api_route('/work/v2/files/download',self.download,methods=['POST'])
@@ -129,21 +131,34 @@ class WorkFiles:
def claim(self,task): def claim(self,task):
with self.db: with self.db:
self.state._owner_lock(task['owner']) self.state._owner_lock(task['owner'])
if not self.state.task_current(task):raise ValueError('stale_task') self.claim_locked(task)
if self.pending_count(task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],True):raise ValueError('materials_still_receiving')
self.db.execute("UPDATE work_files_v1 SET task_id=?,status=CASE WHEN status='failed' THEN 'failed_assigned' ELSE 'assigned' END,updated=? WHERE environment=? AND app_id=? AND owner=? AND host_id=? AND binding_generation=? AND chat_id=? AND direction='input' AND status IN ('staged','failed') AND expires>?",(task['turn_id'],time.time(),self.environment,self.app_id,task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],time.time())) def claim_locked(self,task):
if not self.state.task_current(task):raise ValueError('stale_task')
if self.pending_count(task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],True):raise ValueError('materials_still_receiving')
self.db.execute("UPDATE work_files_v1 SET task_id=?,status=CASE WHEN status='failed' THEN 'failed_assigned' ELSE 'assigned' END,updated=? WHERE environment=? AND app_id=? AND owner=? AND host_id=? AND binding_generation=? AND chat_id=? AND direction='input' AND status IN ('staged','failed') AND expires>?",(task['turn_id'],time.time(),self.environment,self.app_id,task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],time.time()))
def current(self,body): def current(self,body):
self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation)
task=self.state.task(body.task_id) task=self.state.task(body.task_id)
if (not self.state.task_current(task)or not task['source_message_id']or if (not self.state.task_current(task)or not task['source_message_id']or
(task['owner'],task['host_id'],task['binding_generation'])!=(body.binding_owner,body.host_id,body.binding_generation) (task['owner'],task['host_id'],task['binding_generation'])!=(body.binding_owner,body.host_id,body.binding_generation)
or task['status']in {'unbound','revoked','result_discarded','offline'}):raise HTTPException(403,'task_not_recoverable') or task['status']in {'queued','expired','unbound','revoked','result_discarded','offline'}):raise HTTPException(403,'task_not_recoverable')
return task return task
def metadata(self,row): def metadata(self,row):
return {k:row[k]for k in ('file_id','direction','name','size','sha256','status')} 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): async def list_files(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request);self.current(body) 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() 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 +196,7 @@ class WorkFiles:
with self.db: with self.db:
self.state._owner_lock(task['owner']);self.current(body) self.state._owner_lock(task['owner']);self.current(body)
old=self.db.execute('SELECT * FROM work_files_v1 WHERE file_id=?',(fid,)).fetchone() 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: 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'] 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') if count>=self.s.work_file_batch_limit:raise HTTPException(413,'artifact_count_limit')
@@ -198,7 +213,10 @@ class WorkFiles:
async def flush(self): async def flush(self):
now=time.time() now=time.time()
with self.db: 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)) 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. # 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)) 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 +224,7 @@ class WorkFiles:
for raw_row in rows: for raw_row in rows:
row=dict(raw_row);task=self.state.task(row['task_id']) row=dict(raw_row);task=self.state.task(row['task_id'])
if not self.state.task_current(task): 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 continue
try:token=await self.platform.tenant_token() try:token=await self.platform.tenant_token()
except Exception:continue except Exception:continue
@@ -214,13 +232,20 @@ class WorkFiles:
self.state._owner_lock(row['owner']) self.state._owner_lock(row['owner'])
if not self.state.task_current(self.state.task(row['task_id'])):continue if not self.state.task_current(self.state.task(row['task_id'])):continue
working='uploading'if row['status']=='ready'else'sending' 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 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: try:
if working=='uploading': if working=='uploading':
content=self.keyring.decrypt(row['key_id'],row['ciphertext'],self._aad(row)) key=await self.platform.upload_file(row['name'],content,mime,token=token)
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)
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'])) 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: else:
response=await self.platform.reply_file(task['source_message_id'],row['platform_key'],hashlib.sha256(row['file_id'].encode()).hexdigest()[:32],token=token) response=await self.platform.reply_file(task['source_message_id'],row['platform_key'],hashlib.sha256(row['file_id'].encode()).hexdigest()[:32],token=token)
+4 -4
View File
@@ -29,7 +29,7 @@ async def test_closed_payload_purge_keeps_replay_tombstone_and_active_payload(pa
e=p['env'];now=__import__('time').time() e=p['env'];now=__import__('time').time()
with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET updated_at=?',(now-31*86400,)) with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET updated_at=?',(now-31*86400,))
api=ApprovalStore(e['store'].lifecycle,e['api'].broker.store.keyring,clock=lambda:now) api=ApprovalStore(e['store'].lifecycle,e['api'].broker.store.keyring,clock=lambda:now)
active=api.create('task-approval','ou_a','a'*32,1,'operation-active',{'kind':'synthetic'},'合成动作','仅测试') active=api.create(('msg_'+'a'*64),'ou_a','a'*32,1,'operation-active',{'kind':'synthetic'},'合成动作','仅测试')
with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET updated_at=? WHERE approval_id=?', with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET updated_at=? WHERE approval_id=?',
(now-32*86400,active['approval_id'])) (now-32*86400,active['approval_id']))
result=api.maintain_retention() result=api.maintain_retention()
@@ -37,11 +37,11 @@ async def test_closed_payload_purge_keeps_replay_tombstone_and_active_payload(pa
saved=e['store'].db.execute('SELECT * FROM work_approvals_v3').fetchone() saved=e['store'].db.execute('SELECT * FROM work_approvals_v3').fetchone()
assert saved['state']=='rejected'and saved['ciphertext']==''and saved['nonce_digest']=='' assert saved['state']=='rejected'and saved['ciphertext']==''and saved['nonce_digest']==''
assert api.maintain_retention()['payloads_purged']==0 assert api.maintain_retention()['payloads_purged']==0
status=api.status(row['approval_id'],'task-approval','ou_a','a'*32,1,row['operation_digest']) status=api.status(row['approval_id'],('msg_'+'a'*64),'ou_a','a'*32,1,row['operation_digest'])
assert status['state']=='rejected' assert status['state']=='rejected'
assert api.consume(row['approval_id'],'task-approval','ou_a','a'*32,1,row['operation_digest'])['execute']is False assert api.consume(row['approval_id'],('msg_'+'a'*64),'ou_a','a'*32,1,row['operation_digest'])['execute']is False
action=json.loads(e['api'].broker.store.keyring.decrypt(row['key_id'],row['ciphertext'],api._aad(row)))['action'] action=json.loads(e['api'].broker.store.keyring.decrypt(row['key_id'],row['ciphertext'],api._aad(row)))['action']
assert api.create('task-approval','ou_a','a'*32,1,'operation-synthetic',action,'同动作','不得重新放行')['state']=='rejected' assert api.create(('msg_'+'a'*64),'ou_a','a'*32,1,'operation-synthetic',action,'同动作','不得重新放行')['state']=='rejected'
# A pre-existing pending approval is not selected even when timestamp is old. # A pre-existing pending approval is not selected even when timestamp is old.
assert api.maintain_retention()['payloads_purged']==0 assert api.maintain_retention()['payloads_purged']==0
assert e['store'].db.execute('SELECT ciphertext FROM work_approvals_v3 WHERE approval_id=?', assert e['store'].db.execute('SELECT ciphertext FROM work_approvals_v3 WHERE approval_id=?',
@@ -0,0 +1,60 @@
import json
import pytest
from test_credential_api import env
from test_approval_integration import approval_env, pair, pc_errors
from relay.approval_cards import decision_response_card
from relay.longconn import safe_card_callback_response
@pytest.mark.parametrize(('choice','state'),[('deny','rejected'),('allow','approved')])
async def test_callback_returns_no_button_terminal_card_to_clicked_view(pair,choice,state):
p=pair
job=p['launch']()
response,_=await p['click'](choice)
assert response.status_code==200
payload=response.json()
assert payload['toast']['type']=='info'
forwarded=safe_card_callback_response(payload)
assert forwarded['card']==payload['card']
assert forwarded['card']=={'type':'raw','data':decision_response_card(state)}
card=forwarded['card']['data']
assert card['config']['update_multi'] is True
assert '"button"' not in json.dumps(card)
if choice=='deny':
with pytest.raises(pc_errors.ApprovalRejected):await job
assert not p['calls']
else:
assert (await job)['status']=='completed'
assert len(p['calls'])==1
def test_callback_proxy_discards_untrusted_card_payload():
result=safe_card_callback_response({'toast':{'type':'info','content':'ok'},
'card':{'type':'raw','data':{'secret':'do-not-forward'}}})
assert result=={'toast':{'type':'warning','content':'确认结果待核对,请查看任务状态。'}}
assert 'do-not-forward' not in json.dumps(result)
async def test_explicit_refresh_repairs_a_known_closed_card_without_new_message(pair):
p=pair
job=p['launch']();row=await p['card']();await p['click']('deny')
with pytest.raises(pc_errors.ApprovalRejected):await job
e=p['env'];sender=e['app'].state.approvals.sender
await sender.update_closed(row['approval_id'])
assert await sender.update_closed(row['approval_id'])=={'state':'no_closed_card'}
assert await sender.update_closed(row['approval_id'],refresh=True)=={'state':'updated'}
assert len(e['platform'].cards)==1
assert e['store'].db.execute('SELECT state FROM work_approvals_v3').fetchone()['state']=='rejected'
assert not p['calls']
async def test_admin_repair_preview_is_scoped_and_never_sends_card(pair):
p=pair
job=p['launch']();row=await p['card']();await p['click']('deny')
with pytest.raises(pc_errors.ApprovalRejected):await job
api=p['env']['app'].state.approvals
before=len(p['env']['platform'].cards)
ids=await api.worker.call('closed_for_task',p['context']['task_id'])
assert ids==[row['approval_id']]
assert len(p['env']['platform'].cards)==before
@@ -101,7 +101,7 @@ async def pair(approval_env,tmp_path,monkeypatch):
if 'business_receipt_lost'in faults:raise httpx.ReadTimeout('synthetic lost business response') if 'business_receipt_lost'in faults:raise httpx.ReadTimeout('synthetic lost business response')
return httpx.Response(200,json={'code':0,'data':{'event':{'event_id':'synthetic-event'}}}) return httpx.Response(200,json={'code':0,'data':{'event':{'event_id':'synthetic-event'}}})
client=pc_broker.BrokerWorkClient(directory,transport=transport,api_transport=httpx.MockTransport(platform)) client=pc_broker.BrokerWorkClient(directory,transport=transport,api_transport=httpx.MockTransport(platform))
task=e['store'].lifecycle.create_task('task-approval','ou_a',host,device['binding_generation'], task=e['store'].lifecycle.create_task(('msg_'+'a'*64),'ou_a',host,device['binding_generation'],
'synthetic-session',e['app'].state.broker.worker_id,time.time()+600,'oc_synthetic','om_source') 'synthetic-session',e['app'].state.broker.worker_id,time.time()+600,'oc_synthetic','om_source')
context={k:task[k]for k in ('environment','app_id','owner','host_id','binding_generation', context={k:task[k]for k in ('environment','app_id','owner','host_id','binding_generation',
'conversation_id','chat_id','source_message_id')} 'conversation_id','chat_id','source_message_id')}
@@ -203,7 +203,7 @@ async def test_stop_binding_terminal_and_expiry_do_not_execute(pair,failure):
(p['directory']/'device.json').write_text(json.dumps(value)) (p['directory']/'device.json').write_text(json.dumps(value))
elif failure=='terminal': elif failure=='terminal':
with e['store'].db:e['store'].db.execute('INSERT INTO work_execution_state_v3 VALUES(?,?,?,?)', with e['store'].db:e['store'].db.execute('INSERT INTO work_execution_state_v3 VALUES(?,?,?,?)',
('task-approval','failed',1,time.time())) (('msg_'+'a'*64),'failed',1,time.time()))
else: else:
with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET expires_at=0') with e['store'].db:e['store'].db.execute('UPDATE work_approvals_v3 SET expires_at=0')
if failure in {'terminal','expired'}:await p['click']() if failure in {'terminal','expired'}:await p['click']()
@@ -240,7 +240,7 @@ async def test_card_send_receipt_loss_never_sends_second_card(pair):
async def test_unsigned_rpc_proof_replay_and_other_task_are_rejected(pair): async def test_unsigned_rpc_proof_replay_and_other_task_are_rejected(pair):
p=pair;job=p['launch']();row=await p['card']();e=p['env'];path='/work/v2/approvals/status' p=pair;job=p['launch']();row=await p['card']();e=p['env'];path='/work/v2/approvals/status'
fields=dict(task_id='task-approval',approval_id=row['approval_id'],operation_digest=row['operation_digest']) fields=dict(task_id=('msg_'+'a'*64),approval_id=row['approval_id'],operation_digest=row['operation_digest'])
unsigned=await e['client'].post(path,json=fields);assert unsigned.status_code==422 unsigned=await e['client'].post(path,json=fields);assert unsigned.status_code==422
signed=wire(e,path,**fields) signed=wire(e,path,**fields)
assert (await e['client'].post(path,json=signed)).status_code==200 assert (await e['client'].post(path,json=signed)).status_code==200
@@ -279,7 +279,7 @@ async def test_conflicting_clicks_and_concurrent_consume_grant_at_most_once(pair
assert response.json()['toast']['type']=='info' assert response.json()['toast']['type']=='info'
assert conflict.json()['toast']['type']=='warning' assert conflict.json()['toast']['type']=='warning'
e=p['env'];path='/work/v2/approvals/consume' e=p['env'];path='/work/v2/approvals/consume'
fields=dict(task_id='task-approval',approval_id=row['approval_id'],operation_digest=row['operation_digest']) fields=dict(task_id=('msg_'+'a'*64),approval_id=row['approval_id'],operation_digest=row['operation_digest'])
responses=await asyncio.gather(*(e['client'].post(path,json=wire(e,path,**fields))for _ in range(2))) responses=await asyncio.gather(*(e['client'].post(path,json=wire(e,path,**fields))for _ in range(2)))
assert sum(r.json().get('execute')is True for r in responses)<=1 assert sum(r.json().get('execute')is True for r in responses)<=1
try:result=await asyncio.wait_for(job,10) try:result=await asyncio.wait_for(job,10)
@@ -22,7 +22,7 @@ async def test_same_intent_cannot_get_new_card_by_changing_operation_id(pair,cho
other='new-operation-id' other='new-operation-id'
action['params']['idempotency_key']=hashlib.sha256(canonical(['ou_a',other])).hexdigest() action['params']['idempotency_key']=hashlib.sha256(canonical(['ou_a',other])).hexdigest()
path='/work/v2/approvals/create' path='/work/v2/approvals/create'
response=await e['client'].post(path,json=wire(e,path,task_id='task-approval',operation_id=other,action=action,ttl=120)) response=await e['client'].post(path,json=wire(e,path,task_id=('msg_'+'a'*64),operation_id=other,action=action,ttl=120))
assert response.status_code==409 assert response.status_code==409
assert e['store'].db.execute('SELECT COUNT(*) n FROM work_approvals_v3').fetchone()['n']==1 assert e['store'].db.execute('SELECT COUNT(*) n FROM work_approvals_v3').fetchone()['n']==1
assert len(p['calls'])==(1 if choice=='allow'else 0) assert len(p['calls'])==(1 if choice=='allow'else 0)
@@ -51,12 +51,12 @@ async def test_changed_action_same_id_rejected_but_distinct_new_action_can_confi
action=json.loads(ledger.keyring.decrypt(row['key_id'],row['ciphertext'],ledger._aad(row)))['action'] action=json.loads(ledger.keyring.decrypt(row['key_id'],row['ciphertext'],ledger._aad(row)))['action']
action['body']['summary']='真正不同的合成动作' action['body']['summary']='真正不同的合成动作'
path='/work/v2/approvals/create' path='/work/v2/approvals/create'
same=await e['client'].post(path,json=wire(e,path,task_id='task-approval', same=await e['client'].post(path,json=wire(e,path,task_id=('msg_'+'a'*64),
operation_id='operation-synthetic',action=action,ttl=120)) operation_id='operation-synthetic',action=action,ttl=120))
assert same.status_code==409 assert same.status_code==409
other='distinct-operation' other='distinct-operation'
action['params']['idempotency_key']=hashlib.sha256(canonical(['ou_a',other])).hexdigest() action['params']['idempotency_key']=hashlib.sha256(canonical(['ou_a',other])).hexdigest()
distinct=await e['client'].post(path,json=wire(e,path,task_id='task-approval', distinct=await e['client'].post(path,json=wire(e,path,task_id=('msg_'+'a'*64),
operation_id=other,action=action,ttl=120)) operation_id=other,action=action,ttl=120))
assert distinct.status_code==200 and distinct.json()['state']=='pending' assert distinct.status_code==200 and distinct.json()['state']=='pending'
assert not p['calls'] assert not p['calls']
+2 -1
View File
@@ -52,7 +52,7 @@ async def routed(env, tmp_path):
await asyncio.wait_for(server_task,5) await asyncio.wait_for(server_task,5)
async def device(env, host="a"*32, *, generation=None, legacy=False, work_files=False): async def device(env, host="a"*32, *, generation=None, legacy=False, work_files=False,durable_dispatch=False):
ws = await connect(env["url"],proxy=None) ws = await connect(env["url"],proxy=None)
env["sessions"].append(ws) env["sessions"].append(ws)
challenge = json.loads(await ws.recv())["challenge"] challenge = json.loads(await ws.recv())["challenge"]
@@ -66,6 +66,7 @@ async def device(env, host="a"*32, *, generation=None, legacy=False, work_files=
app_id=env["settings"].feishu_app_id,binding_owner=row["owner"] or "ou_a", app_id=env["settings"].feishu_app_id,binding_owner=row["owner"] or "ou_a",
binding_generation=row["binding_generation"] if generation is None else generation) binding_generation=row["binding_generation"] if generation is None else generation)
if work_files:plain['work_files']='work-files-v1' if work_files:plain['work_files']='work-files-v1'
if durable_dispatch:plain['durable_dispatch']='work-dispatch-v1'
await ws.send(json.dumps({"host_id":host,"cert":row["cert"],"proof":sign(plain,env["keys"][host])})) await ws.send(json.dumps({"host_id":host,"cert":row["cert"],"proof":sign(plain,env["keys"][host])}))
accepted = json.loads(await asyncio.wait_for(ws.recv(),3)) accepted = json.loads(await asyncio.wait_for(ws.recv(),3))
assert accepted["type"] == "connected" assert accepted["type"] == "connected"
+18
View File
@@ -68,6 +68,24 @@ async def test_result_is_encrypted_durable_and_delivered_once_after_worker_loss(
assert env['store'].db.execute('SELECT ciphertext FROM work_result_outbox_v2').fetchone()['ciphertext']=='' assert env['store'].db.execute('SELECT ciphertext FROM work_result_outbox_v2').fetchone()['ciphertext']==''
async def test_expired_delivery_receipt_is_readable_without_admitting_mutations(env):
task(env)
assert (await upload(env)).status_code==200
await env['app'].state.deliveries.flush()
db=env['store'].db
with db:db.execute("UPDATE work_tasks_v2 SET deadline=? WHERE turn_id=?", (time.time()-1,'task-durable'))
execution_path='/work/v2/tasks/state'
assert (await env['client'].post(execution_path,json=wire(env,execution_path,task_id='task-durable'))).status_code==403
path='/work/v2/tasks/delivery'
result=await env['client'].post(path,json=wire(env,path,task_id='task-durable'))
assert result.status_code==200 and result.json()['delivery']['text']['platform_sent']
assert (await upload(env)).status_code==403
other=await env['client'].post(path,json=wire(env,path,host='b'*32,task_id='task-durable'))
assert other.status_code==403
with db:db.execute("UPDATE work_tasks_v2 SET deadline=? WHERE turn_id=?", (time.time()-8*86400,'task-durable'))
assert (await env['client'].post(path,json=wire(env,path,task_id='task-durable'))).status_code==403
async def test_result_conflict_and_foreign_task_are_rejected(env): async def test_result_conflict_and_foreign_task_are_rejected(env):
task(env) task(env)
assert (await upload(env)).status_code==200 assert (await upload(env)).status_code==200
+100
View File
@@ -0,0 +1,100 @@
import asyncio
import hashlib
import time
import httpx
import pytest
from relay.connector import create_app
from relay.device_lifecycle import DeviceLifecycle
from test_credential_api import env, wire
from test_device_lifecycle import device, routed, event, send_event
async def rpc(client, env, action, host='a'*32, **fields):
path='/work/v2/tasks/'+action
return await client.post(path,json=wire(env,path,host=host,**fields))
async def test_real_ingress_queued_task_survives_connector_reopen_without_receipt(routed):
env=routed
await device(env,durable_dispatch=True)
msg='om-durable-instruction'
text='synthetic restart request'
task_id='msg_'+hashlib.sha256(msg.encode()).hexdigest()
await send_event(env,event(env,msg,text))
for _ in range(200):
if env['store'].lifecycle.task(task_id):break
await asyncio.sleep(.01)
assert env['store'].lifecycle.task(task_id)['status']=='queued'
assert (await rpc(env['client'],env,'state',task_id=task_id)).json()['execution_state']=='queued'
queued=env['app'].state.dispatch_queue
assert queued.enqueue('ou_a',env['store'].device('a'*32),'/助手 '+text,task_id,chat_id='chat-a',
source_message_id=msg,file_transfer=False)=='duplicate'
old=await rpc(env['client'],env,'next')
job=old.json()['task']
assert job['context']['task_id']==task_id and job['text']=='/助手 '+text
assert text not in str(dict(env['store'].db.execute('SELECT * FROM work_dispatch_v1').fetchone()))
assert (await rpc(env['client'],env,'result',task_id=task_id,result='premature')).status_code==403
assert not env['platform'].replies
second=create_app(env['settings'],env['redis'],env['platform'])
try:
assert second.state.broker.worker_id!=env['app'].state.broker.worker_id
await env['redis'].delete('hn:task-worker:'+env['app'].state.broker.worker_id)
await DeviceLifecycle(second.state.store.lifecycle,env['redis'],second.state.broker).maintain()
async with httpx.AsyncClient(transport=httpx.ASGITransport(second),base_url='https://relay.example.test') as client:
assert (await rpc(client,env,'next')).json()['task']==job
assert (await rpc(client,env,'next',host='b'*32)).json()['task'] is None
fields={'task_id':task_id,'digest':job['digest']}
assert (await rpc(client,env,'accept',host='b'*32,**fields)).status_code==403
assert (await rpc(client,env,'accept',task_id=task_id,digest='0'*64)).status_code==409
first=(await rpc(client,env,'accept',**fields)).json()
assert first['accepted'] is True
assert (await rpc(client,env,'next')).json()['task'] is None
# The response may be lost after commit; retry returns the same receipt.
assert (await rpc(env['client'],env,'accept',**fields)).json()==first
assert (await rpc(client,env,'result',task_id=task_id,result='synthetic result')).status_code==200
assert (await rpc(client,env,'accept',**fields)).json()==first
await second.state.deliveries.flush()
await env['app'].state.deliveries.flush()
assert env['platform'].replies==[(msg,'synthetic result')]
assert second.state.store.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']==''
finally:
second.state.store.close()
@pytest.mark.parametrize('invalidated',['expired','unbound'])
async def test_stale_queue_entries_cannot_be_recovered(env,invalidated):
api=env['app'].state.dispatch_queue
assert api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queued-test',
chat_id='chat-a',source_message_id='om-queued',file_transfer=False)=='queued'
if invalidated=='expired':
with api.db:api.db.execute('UPDATE work_tasks_v2 SET deadline=? WHERE turn_id=?',
(time.time()-1,'queued-test'))
assert (await rpc(env['client'],env,'next')).json()['task'] is None
assert (await rpc(env['client'],env,'accept',task_id='queued-test',
digest=hashlib.sha256('/助手 synthetic'.encode()).hexdigest())).status_code==403
else:
env['store'].unbind('ou_a')
assert (await rpc(env['client'],env,'next')).status_code==403
api.expire()
assert env['store'].lifecycle.task('queued-test')['status']==invalidated
assert api.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']==''
@pytest.mark.parametrize('env',[True],indirect=True)
async def test_failed_queue_commit_rolls_back_task_and_material_assignment(env,monkeypatch):
from test_work_files import fake_platform
fake_platform(env,monkeypatch)
files=env['app'].state.files
await files.receive('ou_a','chat-a','om-material',{'file_name':'sample.txt','file_key':'test-file'})
api=env['app'].state.dispatch_queue
def interrupted(*args,**kwargs):raise RuntimeError('synthetic encryption failure')
monkeypatch.setattr(api.keyring,'encrypt',interrupted)
with pytest.raises(RuntimeError):
api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queue-rollback',
chat_id='chat-a',source_message_id='om-queued',file_transfer=True)
assert not env['store'].lifecycle.task('queue-rollback')
assert api.db.execute('SELECT status FROM turns WHERE turn_id=?',('queue-rollback',)).fetchone() is None
assert dict(api.db.execute('SELECT task_id,status FROM work_files_v1').fetchone())=={'task_id':'','status':'staged'}
+140
View File
@@ -83,6 +83,146 @@ async def test_artifact_handoff_encrypted_idempotent_and_replies_to_original_onl
assert env['store'].db.execute("SELECT status,ciphertext FROM work_files_v1").fetchone()['status']=='sent' assert env['store'].db.execute("SELECT status,ciphertext FROM work_files_v1").fetchone()['status']=='sent'
@pytest.mark.parametrize('second_status',['uploaded','sending'])
async def test_restart_recovers_only_confirmed_unsent_attachment(env,monkeypatch,second_status):
import httpx
from relay.connector import create_app
_,calls=fake_platform(env,monkeypatch);create_task(env)
result_path='/work/v2/tasks/result'
response=await env['client'].post(result_path,json=wire(env,result_path,task_id='task-files',result='synthetic result'))
assert response.status_code==200
await env['app'].state.deliveries.flush()
one=await upload(env,name='first.docx',artifact='artifact-01')
assert one.status_code==200
api=env['app'].state.files
await api.flush();await api.flush()
two=await upload(env,name='second.xlsx',artifact='artifact-02',raw=b'second synthetic file')
assert two.status_code==200
await api.flush()
assert [r[0] for r in calls]==['upload','reply_file','upload']
if second_status=='sending':
original_reply=env['platform'].reply_file
accepted=asyncio.Event()
async def accept_without_returning_receipt(*args,**kwargs):
# The fake platform accepts the reply, then the connector exits
# before receiving or persisting the response.
await original_reply(*args,**kwargs)
accepted.set()
await asyncio.Future()
with monkeypatch.context() as patch:
patch.setattr(env['platform'],'reply_file',accept_without_returning_receipt)
interrupted=asyncio.create_task(api.flush())
try:
await asyncio.wait_for(accepted.wait(),timeout=3)
finally:
interrupted.cancel()
with pytest.raises(asyncio.CancelledError):
await interrupted
assert api.db.execute("SELECT status FROM work_files_v1 WHERE file_id=?",
(two.json()['file_id'],)).fetchone()['status']=='sending'
with api.db:
# Advance only the age of the observed claim past recovery grace.
api.db.execute("UPDATE work_files_v1 SET updated=? WHERE file_id=? AND status='sending'",
(time.time()-121,two.json()['file_id']))
second=create_app(env['settings'],env['redis'],env['platform'])
try:
for _ in range(2):
await second.state.files.flush()
await second.state.deliveries.flush()
async with httpx.AsyncClient(transport=httpx.ASGITransport(second),base_url='https://relay.example.test') as http:
path='/work/v2/tasks/delivery'
status=await http.post(path,json=wire(env,path,task_id='task-files'))
assert status.status_code==200
receipt=status.json()['delivery']
assert receipt['text']=={'status':'replied','platform_sent':True}
assert receipt['protocol']=='work-delivery-v1'
files={e['name']:(e['status'],e['platform_sent']) for e in receipt['attachments']}
assert files=={'first.docx':('sent',True),'second.xlsx':
(('sent',True) if second_status=='uploaded' else ('unknown',False))}
from relay.task_cards import TaskCards
cards=TaskCards(second.state.store.lifecycle,env['platform'],'snapshot-test')
cards.file_receipts=second.state.files.output_receipts
rendered=json.dumps(cards.snapshot(second.state.store.lifecycle.task('task-files')),ensure_ascii=False)
assert ('1 份附件的送达结果待核对' in rendered)==(second_status=='sending')
denied=await http.post(path,json=wire(env,path,host='b'*32,task_id='task-files'))
assert denied.status_code==403
finally:
second.state.store.close()
assert env['platform'].replies==[('om-original','synthetic result')]
assert [r[0] for r in calls]==['upload','reply_file','upload','reply_file']
async def test_live_connector_loop_delivers_text_while_attachment_upload_is_blocked(env,monkeypatch):
_,calls=fake_platform(env,monkeypatch);create_task(env)
started=asyncio.Event()
permit_upload=asyncio.Event()
replied=asyncio.Event()
original_upload=env['platform'].upload_file
original_reply=env['platform'].reply
async def blocked_upload(*args,**kwargs):
started.set()
await permit_upload.wait()
return await original_upload(*args,**kwargs)
async def mark_text_reply(*args,**kwargs):
await original_reply(*args,**kwargs)
replied.set()
monkeypatch.setattr(env['platform'],'upload_file',blocked_upload)
monkeypatch.setattr(env['platform'],'reply',mark_text_reply)
assert (await upload(env)).status_code==200
try:
await asyncio.wait_for(started.wait(),timeout=12)
path='/work/v2/tasks/result'
result=await env['client'].post(path,json=wire(env,path,task_id='task-files',result='text while upload is blocked'))
assert result.status_code==200
await asyncio.wait_for(replied.wait(),timeout=12)
path='/work/v2/tasks/delivery'
result=await env['client'].post(path,json=wire(env,path,task_id='task-files'))
assert result.status_code==200
delivery=result.json()['delivery']
assert delivery['text']['platform_sent'] is True
assert delivery['attachments'][0]['status']=='uploading'
assert not calls
finally:
permit_upload.set()
async def test_local_file_integrity_failure_is_not_a_platform_unknown(env,monkeypatch):
_,calls=fake_platform(env,monkeypatch);create_task(env)
result=await upload(env)
assert result.status_code==200
api=env['app'].state.files
with api.db:api.db.execute("UPDATE work_files_v1 SET ciphertext='invalid' WHERE file_id=?",(result.json()['file_id'],))
await api.flush()
await api.flush()
rows=api.output_receipts(env['store'].lifecycle.task('task-files'))
assert rows[0]['status']=='failed' and not rows[0]['platform_sent']
assert not calls
async def test_attachment_expiry_cleans_bytes_without_erasing_uncertain_delivery(env,monkeypatch):
_,calls=fake_platform(env,monkeypatch);task=create_task(env)
first=await upload(env,artifact='artifact-01')
second=await upload(env,artifact='artifact-02',name='ambiguous.txt')
assert first.status_code==second.status_code==200
api=env['app'].state.files
with api.db:
api.db.execute("UPDATE work_files_v1 SET expires=?",(time.time()-1,))
api.db.execute("UPDATE work_files_v1 SET status='sending',platform_key='synthetic' WHERE file_id=?",
(second.json()['file_id'],))
await api.flush()
assert {x['name']:x['status'] for x in api.output_receipts(task)}=={
'result.txt':'expired','ambiguous.txt':'unknown'}
assert all(not r['ciphertext'] and not r['platform_key'] for r in
api.db.execute("SELECT ciphertext,platform_key FROM work_files_v1").fetchall())
assert not calls
async def test_bad_digest_filename_size_and_stale_binding_are_rejected(env,monkeypatch): async def test_bad_digest_filename_size_and_stale_binding_are_rejected(env,monkeypatch):
fake_platform(env,monkeypatch);create_task(env) fake_platform(env,monkeypatch);create_task(env)
assert (await upload(env,sha256='0'*64)).status_code==409 assert (await upload(env,sha256='0'*64)).status_code==409