diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index e049f80c5..88d3d6ce5 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -248,6 +248,29 @@ def cancel_queued(self, project_id: UUID, session: str | None = None) -> list[di durable_json(file, value) return cancelled + def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict: + """Take a message back while it is still waiting in the queue. + + A message that already started belongs to the conversation now: it can + be stopped, but removing it would leave the reply it produced without + the words that asked for it. + """ + with self.projects.local.transaction() as db: + self.projects._recover() + directory, _, _ = self.projects._load(db, project_id) + self.projects._lease(db, project_id, directory, session) + file = child(child(directory, 'agent-runs'), 'conversation.json') + value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + found = next((item for item in value['messages'] if item['id'] == str(message_id)), None) + if found is None: + raise ProjectError('这条消息不在当前对话里,请重新加载。', 404) + if found.get('status') != 'queued': + raise ProjectError('这条消息已经开始执行,停止回复后才能撤回。', 409) + value['messages'] = [item for item in value['messages'] if item['id'] != str(message_id)] + durable_json(file, value) + result = public_conversation(value) + return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)} + def list(self, project_id: UUID) -> dict: directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') @@ -912,4 +935,39 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = started['run_session'] = start_session return launch(project_id, started, UUID(dispatched['conversation']['conversationId'])) + @router.delete('/messages/{message_id}') + async def retract(project_id: UUID, message_id: UUID, x_opendirector_session: UUID = Header()): + """Take back a message that has not started yet. + + Retracting under the admission lock is what keeps it from being picked + up in the same instant: the message is either still waiting and goes + away, or it has started and the caller is told to stop it instead. + """ + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + result = await asyncio.to_thread(conversations.retract, project_id, session, message_id) + chain = active.get(project_id) + if chain is not None: + chain.events.put({'type': 'retracted', 'messageId': str(message_id)}) + return result + + @router.post('/queue/dispatch') + async def dispatch(project_id: UUID, x_opendirector_session: UUID = Header(), + accept_language: str | None = Header(default=None, alias='Accept-Language')): + """Continue the queue when nothing is running. + + Messages outlive a restart, and a turn that failed leaves them waiting; + this starts the oldest one so the user does not have to retype it. + """ + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + if project_id in active: + raise ProjectError('当前工程已有回复正在执行。', 409) + dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session) + if dispatched is None: + raise ProjectError('没有等待执行的排队消息。', 409) + plan = await plan_for(project_id, dispatched['message'], session, accept_language) + plan['start'] = dispatched['conversation'] + return launch(project_id, plan, UUID(dispatched['conversation']['conversationId'])) + return router diff --git a/tests/test_assistant_retract.py b/tests/test_assistant_retract.py new file mode 100644 index 000000000..e19d627c9 --- /dev/null +++ b/tests/test_assistant_retract.py @@ -0,0 +1,135 @@ +"""A waiting message can be taken back, and a stalled queue can be continued. + +#379: a supplementary message waits for the active turn. These cases pin what +happens around that wait: a message that has not started can be withdrawn, a +message that has started cannot, and a queue left behind by a failed turn waits +for the user instead of running on its own and then can be continued by hand. +""" +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import threading +from uuid import UUID, uuid4, uuid5 + +from fastapi.testclient import TestClient +import pytest + +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector_api.main import create_app +from opendirector_api import agent + + +def frames(response): + return [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')] + + +async def empty_skills(*args): + return [] + + +@pytest.fixture +def assistant(tmp_path, monkeypatch): + """A project whose turns block until the test lets them finish.""" + contexts = [] + gate = {'started': threading.Event(), 'release': threading.Event(), 'fail': threading.Event()} + + async def stream(self, run): + contexts.append(run.messages) + gate['started'].set() + yield {'type': 'delta', 'text': '收到:' + run.messages[-1]['content']} + await asyncio.to_thread(gate['release'].wait, 10) + if gate['fail'].is_set(): + raise RuntimeError('provider down') + yield {'type': 'delta', 'text': '|完'} + + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + monkeypatch.setattr(agent, 'runtime_available', lambda _: True) + monkeypatch.setattr(agent, 'skills', empty_skills) + from opendirector.infrastructure.model_configs import ModelConfigs + config = {'id': str(uuid4()), 'modelId': 'test-model', 'kind': 'agent', 'url': 'http://models.test/v1', + 'connectionType': 'api', 'protocol': 'openai', 'authMode': 'none', 'apiKey': ''} + monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: dict(config)) + with TestClient(create_app(LocalProjects(tmp_path)), headers={ + 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client: + pid = str(uuid4()) + root = f'/api/creation/projects/{pid}' + assert client.post(root + '/commands', json={'type': 'project.create', 'projectId': pid, + 'commandId': str(uuid4()), 'payload': {'name': '撤回'}}).status_code == 200 + assert client.post(root + '/open').status_code == 200 + yield client, root + '/assistant', contexts, gate + + +def test_a_queued_message_can_be_taken_back_before_it_runs(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first, second = str(uuid4()), str(uuid4()) + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '先做这个'}) + assert gate['started'].wait(5) + assert client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '再补一句'}).status_code == 202 + taken = client.delete(path + f'/messages/{second}') + assert taken.status_code == 200, taken.text + assert taken.json()['retracted'] == second + # The message is gone from the thread the user is reading, while the + # turn that is still running keeps its own reply in place. + assert [item['id'] for item in taken.json()['conversation']['messages']] == [ + first, str(uuid5(UUID(first), 'assistant'))] + gate['release'].set() + events = frames(running.result(timeout=10)) + + # The turn that was already running is not disturbed, and nothing runs after it. + assert [event['turnId'] for event in events if event['type'] == 'end'] == [first] + assert [context[-1]['content'] for context in contexts] == ['先做这个'] + assert [item['status'] for item in client.get(path).json()['messages']] == ['complete', 'complete'] + + +def test_a_message_that_already_started_is_stopped_not_removed(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first = str(uuid4()) + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '做到一半'}) + assert gate['started'].wait(5) + started = client.delete(path + f'/messages/{first}') + assert started.status_code == 409 and '已经开始执行' in started.json()['detail'] + unknown = client.delete(path + f'/messages/{uuid4()}') + assert unknown.status_code == 404 and '不在当前对话里' in unknown.json()['detail'] + gate['release'].set() + frames(running.result(timeout=10)) + + # A message that has begun is part of the record: it stays, with its reply. + assert [item['status'] for item in client.get(path).json()['messages']] == ['complete', 'complete'] + assert len(contexts) == 1 + + +def test_a_failed_turn_leaves_the_queue_to_be_continued_by_hand(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first, second = str(uuid4()), str(uuid4()) + gate['fail'].set() + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '先做这个'}) + assert gate['started'].wait(5) + assert client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '补一句'}).status_code == 202 + gate['release'].set() + events = frames(running.result(timeout=10)) + + assert events[-1]['error'] is not None + # A failure does not spend the queue by itself, and it is not silent about it. + assert [item['status'] for item in client.get(path).json()['messages']] == [ + 'complete', 'interrupted', 'queued'] + assert [context[-1]['content'] for context in contexts] == ['先做这个'] + + gate['fail'].clear() + continued = client.post(path + '/queue/dispatch') + assert continued.status_code == 200, continued.text + tail = frames(continued) + assert tail[-1]['conversation']['messages'][-1]['text'] == '收到:补一句|完' + # Nothing is left waiting, so continuing again has nothing to start. + assert client.post(path + '/queue/dispatch').status_code == 409 + assert 'activeTurnId' not in client.get(path).json()