Fix session cancel and new task routing

This commit is contained in:
wuyang6
2026-06-12 16:35:38 +08:00
parent 0a3e044c9d
commit a2f39e7312
5 changed files with 58 additions and 8 deletions
+25 -1
View File
@@ -927,6 +927,28 @@ class AgentState:
self._run_locks[key] = lock
return lock
def abandon_session_runtime(
self,
account_id: str | None = None,
session_id: str | None = None,
) -> bool:
"""Stop routing future requests through the currently held runtime.
A user cancel can happen while the worker thread is blocked inside a
model HTTP request or a remote runtime call. Python cannot safely
release a Lock owned by another thread, so the correct cancellation
behavior is to abandon that lock object for future turns.
The agent instance is abandoned together with the lock. The old worker
may still mutate its LocalCodingAgent.tool_context during unwind; a new
user turn must not share that object.
"""
key = self._session_key(account_id, session_id)
with self._lock:
removed_lock = self._run_locks.pop(key, None) is not None
removed_agent = self._agents.pop(key, None) is not None
return removed_lock or removed_agent
def update(
self,
*,
@@ -2322,6 +2344,7 @@ def create_app(state: AgentState) -> FastAPI:
if payload.run_id and state.run_manager.cancel_run(payload.run_id):
cancelled_ids.add(payload.run_id)
cancelled_ids.update(state.run_manager.cancel_session(account_key, safe_id))
abandoned_runtime = state.abandon_session_runtime(account_key, safe_id)
cancelled_bg_task_ids = await _bash_bg_manager.cancel_session(
state,
account_key,
@@ -2334,7 +2357,7 @@ def create_app(state: AgentState) -> FastAPI:
stage='用户已取消',
)
cancelled_ids.update(stored_cancelled)
cancelled = bool(cancelled_ids or cancelled_bg_task_ids)
cancelled = bool(cancelled_ids or cancelled_bg_task_ids or abandoned_runtime)
if cancelled:
_mark_session_interrupted(
state.account_paths(payload.account_id)['sessions'],
@@ -2346,6 +2369,7 @@ def create_app(state: AgentState) -> FastAPI:
'cancelled': cancelled,
'cancelled_run_ids': sorted(cancelled_ids),
'cancelled_bg_task_ids': sorted(cancelled_bg_task_ids),
'abandoned_runtime': abandoned_runtime,
}
def _run_chat_payload(