Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,15 @@
durable_json(file, value)
return cancelled

def has_queued(self, project_id: UUID) -> bool:
"""Whether a message is still waiting after the project became idle."""
directory = self.path(project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
if not file.exists():
return False
value = read_json(file)
return any(item.get('status') == 'queued' for item in value.get('messages', []))

def list(self, project_id: UUID) -> dict:
directory = self.path(project_id)
file = child(child(directory, 'agent-runs'), 'conversation.json')
Expand Down Expand Up @@ -614,7 +623,7 @@
config = await asyncio.to_thread(configs.resolve, message['modelConfigId'], 'agent')
except Exception:
logger.warning('agent.queue.model_missing project_id=%s message_id=%s',
project_id, message.get('id'))

Check warning

Code scanning / CodeQL

Log Injection Medium

This log entry depends on a
user-provided value
.
available = await skills(projects.local.repository, directory) if spec.supportsSkills else []
model_selections = dict(message.get('modelSelections') or {})
return {'session': session, 'directory': directory, 'config': config, 'available': available,
Expand Down Expand Up @@ -864,6 +873,13 @@
if project_id in active:
raise ProjectError('当前工程已有回复正在执行。', 409)
plan = await prepare(project_id, value, session, accept_language)
if await asyncio.to_thread(conversations.has_queued, project_id):
# Keep submission order: accept the message behind work that is
# already waiting, and leave the queue paused for an explicit retry.
await asyncio.to_thread(conversations.queue, project_id, session,
plan['message'], value.conversationId)
raise ProjectError(
'还有更早提交、尚未执行的排队消息。新消息已排入队列,请先继续这些消息后再执行。', 409)
run_session = str(uuid4())
try:
plan['start'] = await asyncio.to_thread(conversations.update, project_id, session,
Expand Down Expand Up @@ -902,7 +918,12 @@
check = revalidate(plan)
if check is not None:
await asyncio.to_thread(check)
await asyncio.to_thread(conversations.queue, project_id, session, plan['message'], value.conversationId)
pending = await asyncio.to_thread(conversations.has_queued, project_id)
queued = await asyncio.to_thread(conversations.queue, project_id, session, plan['message'], value.conversationId)
if pending:
# A leftover queue after a failure or restart must not start just
# because a later message arrived; keep FIFO until explicit retry.
return JSONResponse({'queued': queued, 'chainId': None, 'turnId': None}, status_code=202)
start_session = str(uuid4())
dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session, start_session)
if dispatched is None:
Expand All @@ -912,4 +933,27 @@
started['run_session'] = start_session
return launch(project_id, started, UUID(dispatched['conversation']['conversationId']))

@router.post('/queue/dispatch')
async def dispatch_queue(project_id: UUID, x_opendirector_session: UUID = Header(),
accept_language: str | None = Header(default=None, alias='Accept-Language')):
"""Start the oldest queued message when nothing is running.

A failed or interrupted turn, or a process restart, leaves later
messages waiting. This continues them in submission order, and only
when the user asks.
"""
session = str(x_opendirector_session)
async with admission.setdefault(project_id, asyncio.Lock()):
if project_id in active:
raise ProjectError('当前工程已有回复正在执行。', 409)
run_session = str(uuid4())
dispatched = await asyncio.to_thread(
conversations.dispatch, project_id, session, run_session)
if dispatched is None:
raise ProjectError('没有等待执行的排队消息。', 409)
started = await plan_for(project_id, dispatched['message'], session, accept_language)
started['start'] = dispatched['conversation']
started['run_session'] = run_session
return launch(project_id, started, UUID(dispatched['conversation']['conversationId']))

return router
2 changes: 1 addition & 1 deletion docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ Default 将模型配置中的输入模态传入 bundled OpenCode。外部 harnes

Search citations keep their native markers in the original reply and trace. Completed Codex MCP web-search results supply validated source IDs, HTTP(S) URLs and titles through `sources` events; the conversation retains this metadata with the reply. The UI splits tool activities using raw text offsets before formatting prose citations as source links, and uses the same formatting for copying. Code examples remain literal. Missing sources and incomplete final markers have a localized fallback. For saved Codex replies without source metadata, queries derive it from the matching turn's project-local trace without rewriting the conversation; a bounded metadata cache is invalidated by trace modification time and size. Reading a trace never requests a model call.

同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=<seq>` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/<turn-id>.<runtime>.jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。
同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲且没有遗留排队消息时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮成功结束后依次运行。一轮失败或中断、以及进程重启后,已排队消息保持等待,不会自动续跑;此时新的直接提交(`/turns` 或空闲时的 `/messages`)只能排在既有队列后面,由 `POST /assistant/queue/dispatch` 按提交顺序显式继续。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=<seq>` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/<turn-id>.<runtime>.jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。

Default 的模型网关在 `agent-runs/<turn-id>.model.jsonl` 记录实际转发的请求体,包括生效的系统消息、会话上下文、工具 Schema 与模型参数。请求 ID 关联上游 HTTP 状态、响应头等待耗时和传输错误。该文件仅供本地调试,创建权限为 `0600`,不记录 HTTP 鉴权头。回复片段、工具结果和 token 用量仍见原生轨迹。

Expand Down
243 changes: 243 additions & 0 deletions tests/test_assistant_queue_admission.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
"""A failed chain must not let a later message overtake older queued work.

#521: when a turn fails, later queued messages stay waiting for an explicit
retry. A new direct submission must not run ahead of them, and the queue must
not start on its own after a failure or a process restart.
"""
import asyncio
from concurrent.futures import ThreadPoolExecutor
import json
import threading
from uuid import uuid4

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: ')]


def statuses(client, path):
return [item['status'] for item in client.get(path).json()['messages']]


def texts(contexts):
return [context[-1]['content'] for context in contexts]


async def empty_skills(*args):
return []


@pytest.fixture
def assistant(tmp_path, monkeypatch):
"""A project whose turns can be released or failed by the test."""
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, **kwargs: 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
try:
yield client, root + '/assistant', contexts, gate, tmp_path
finally:
gate['release'].set()


def fail_first_turn_with_queued(assistant, queued_texts):
"""Run one turn that fails, leaving the given messages queued behind it."""
client, path, contexts, gate, _ = assistant
cid = client.get(path).json()['conversationId']
first = str(uuid4())
queued_ids = [str(uuid4()) for _ in queued_texts]
gate['fail'].set()
gate['started'].clear()
gate['release'].clear()
with ThreadPoolExecutor() as pool:
running = pool.submit(client.post, path + '/turns', json={
'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '一'})
assert gate['started'].wait(5)
for message_id, text in zip(queued_ids, queued_texts):
sent = client.post(path + '/messages', json={
'id': message_id, 'runtime': 'default', 'conversationId': cid, 'text': text})
assert sent.status_code == 202, sent.text
gate['release'].set()
events = frames(running.result(timeout=10))
assert events[-1]['error'] is not None
assert texts(contexts) == ['一']
return cid, first, queued_ids


def test_a_new_direct_turn_does_not_run_ahead_of_a_stranded_queue(assistant):
"""A later /turns submission must not execute before the older queued message."""
client, path, contexts, gate, _ = assistant
cid, _, [second] = fail_first_turn_with_queued(assistant, ['二'])
assert statuses(client, path) == ['complete', 'interrupted', 'queued']

gate['fail'].clear()
gate['started'].clear()
gate['release'].clear()
third = str(uuid4())
# The UI still starts a new message with /turns when the project looks idle.
jumped = client.post(path + '/turns', json={
'id': third, 'runtime': 'default', 'conversationId': cid, 'text': '三'})
assert jumped.status_code == 409, jumped.text
assert statuses(client, path) == ['complete', 'interrupted', 'queued', 'queued']
assert [item['text'] for item in client.get(path).json()['messages'] if item['role'] == 'user'] == [
'一', '二', '三']
assert texts(contexts) == ['一']
assert 'activeTurnId' not in client.get(path).json()

gate['release'].set()
continued = client.post(path + '/queue/dispatch')
assert continued.status_code == 200, continued.text
ending = [event for event in frames(continued) if event['type'] == 'end']
assert [event['turnId'] for event in ending] == [second, third]
assert ending[-1]['error'] is None
# Context bounding for a dispatched turn is #518; this issue only pins order.
assert len(contexts) == 3
messages = ending[-1]['conversation']['messages']
assert [item['id'] for item in messages if item['role'] == 'user'] == [
client.get(path).json()['messages'][0]['id'], second, third]
assert [item['status'] for item in messages if item['role'] == 'user'] == [
'complete', 'complete', 'complete']
assert 'activeTurnId' not in client.get(path).json()


def test_idle_message_endpoint_appends_behind_a_stranded_queue_without_starting(assistant):
client, path, contexts, gate, _ = assistant
cid, _, [second] = fail_first_turn_with_queued(assistant, ['二'])
gate['fail'].clear()
third = str(uuid4())
sent = client.post(path + '/messages', json={
'id': third, 'runtime': 'default', 'conversationId': cid, 'text': '三'})
assert sent.status_code == 202, sent.text
assert sent.json()['queued']['id'] == third
assert statuses(client, path) == ['complete', 'interrupted', 'queued', 'queued']
assert texts(contexts) == ['一']

continued = client.post(path + '/queue/dispatch')
assert continued.status_code == 200, continued.text
ending = [event for event in frames(continued) if event['type'] == 'end']
assert [event['turnId'] for event in ending] == [second, third]
assert len(contexts) == 3
assert statuses(client, path)[-4:] == ['complete', 'complete', 'complete', 'complete']


def test_explicit_retry_runs_multiple_queued_messages_in_submission_order(assistant):
client, path, contexts, gate, _ = assistant
cid, _, [second, third] = fail_first_turn_with_queued(assistant, ['二', '三'])
fourth = str(uuid4())
assert client.post(path + '/turns', json={
'id': fourth, 'runtime': 'default', 'conversationId': cid, 'text': '四'}).status_code == 409
gate['fail'].clear()
continued = client.post(path + '/queue/dispatch')
assert continued.status_code == 200, continued.text
ending = [event for event in frames(continued) if event['type'] == 'end']
assert [event['turnId'] for event in ending] == [second, third, fourth]
assert len(contexts) == 4
assert [item['status'] for item in ending[-1]['conversation']['messages'] if item['role'] == 'user'] == [
'complete', 'complete', 'complete', 'complete']
assert client.post(path + '/queue/dispatch').status_code == 409


def test_restart_does_not_replay_a_stranded_queue(assistant, monkeypatch):
client, path, _, _, root = assistant
fail_first_turn_with_queued(assistant, ['二'])
assert statuses(client, path) == ['complete', 'interrupted', 'queued']
# A new process sees the same files but must not start the leftover queue.
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, **kwargs: dict(config))
restarted_contexts = []

async def stream(self, run):
restarted_contexts.append(run.messages)
yield {'type': 'delta', 'text': '重启:' + run.messages[-1]['content']}

monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream)
with TestClient(create_app(LocalProjects(root)), headers={
'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as restarted:
assert statuses(restarted, path) == ['complete', 'interrupted', 'queued']
assert restarted_contexts == []
assert 'activeTurnId' not in restarted.get(path).json()


def test_stop_still_cancels_the_queue_and_does_not_block_a_later_turn(assistant):
client, path, contexts, gate, _ = assistant
cid = client.get(path).json()['conversationId']
first, second, third = str(uuid4()), 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
assert client.post(path + f'/turns/{first}/stop').status_code == 200
frames(running.result(timeout=10))
assert statuses(client, path) == ['complete', 'stopped', 'cancelled']
assert client.post(path + '/queue/dispatch').status_code == 409
gate['started'].clear()
gate['release'].clear()
with ThreadPoolExecutor() as pool:
started = pool.submit(client.post, path + '/turns', json={
'id': third, 'runtime': 'default', 'conversationId': cid, 'text': '重新说'})
assert gate['started'].wait(5)
gate['release'].set()
assert started.result(timeout=10).status_code == 200
assert texts(contexts) == ['做到一半', '重新说']


def test_duplicate_message_ids_stay_idempotent_on_a_stranded_queue(assistant):
client, path, contexts, _, _ = assistant
cid, _, [second] = fail_first_turn_with_queued(assistant, ['二'])
duplicate = client.post(path + '/turns', json={
'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '二'})
assert duplicate.status_code == 409
assert statuses(client, path) == ['complete', 'interrupted', 'queued']
again = client.post(path + '/messages', json={
'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '二'})
assert again.status_code == 409
assert texts(contexts) == ['一']


def test_dispatch_is_refused_while_a_turn_is_running(assistant):
client, path, _, 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)
assert client.post(path + '/queue/dispatch').status_code == 409
gate['release'].set()
frames(running.result(timeout=10))
assert client.post(path + '/queue/dispatch').status_code == 409
Loading