From 6174ac850600c89729ab0628bd668e0bd479c766 Mon Sep 17 00:00:00 2001 From: clumsypsc Date: Mon, 28 Sep 2026 15:00:09 +0800 Subject: [PATCH] feat: add Codex-style project workspace and parallel chats --- .env.example | 9 + agent/api/dashboard_routes.py | 515 +++++++----- agent/app.py | 15 + agent/core/model.py | 22 +- agent/core/repository_workspace.py | 24 +- agent/core/run_queue.py | 196 +++++ agent/core/runtime.py | 231 ++++-- agent/sandbox/eval_backend.py | 105 ++- agent/server.py | 59 +- agent/store/migration.py | 31 +- agent/store/postgres_store.py | 395 +++++++++- agent/store/sqlite_store.py | 384 ++++++++- .../MULTI_TASK_HARNESS_IMPLEMENTATION_PLAN.md | 95 +++ tests/unit/test_durable_run_stream.py | 124 +++ tests/unit/test_model_selection.py | 23 +- tests/unit/test_plain_chat.py | 80 ++ tests/unit/test_plan_interactions.py | 2 +- tests/unit/test_projects_and_drafts.py | 162 ++++ tests/unit/test_repository_workspace.py | 68 +- tests/unit/test_run_activity.py | 8 + tests/unit/test_run_queue_store.py | 172 ++++ ui/package.json | 8 +- ui/src/api/client.js | 35 + ui/src/api/sse.js | 46 +- ui/src/components/ActiveTaskStrip.vue | 49 ++ ui/src/components/AgentWorkspace.vue | 154 +++- ui/src/components/ChatComposer.vue | 88 +-- .../components/ConfirmProjectDeleteDialog.vue | 34 + ui/src/components/CreateProjectDialog.vue | 72 ++ ui/src/components/SessionSidebar.test.js | 109 +++ ui/src/components/SessionSidebar.vue | 219 ++++-- ui/src/stores/agent.js | 552 ++++++++----- ui/src/stores/agent.test.js | 75 ++ ui/src/styles/main.css | 228 ++++++ ui/vitest.config.js | 11 + ui/yarn.lock | 743 ++++++++++-------- 36 files changed, 4119 insertions(+), 1024 deletions(-) create mode 100644 agent/core/run_queue.py create mode 100644 docs/MULTI_TASK_HARNESS_IMPLEMENTATION_PLAN.md create mode 100644 tests/unit/test_durable_run_stream.py create mode 100644 tests/unit/test_plain_chat.py create mode 100644 tests/unit/test_projects_and_drafts.py create mode 100644 tests/unit/test_run_queue_store.py create mode 100644 ui/src/components/ActiveTaskStrip.vue create mode 100644 ui/src/components/ConfirmProjectDeleteDialog.vue create mode 100644 ui/src/components/CreateProjectDialog.vue create mode 100644 ui/src/components/SessionSidebar.test.js create mode 100644 ui/src/stores/agent.test.js create mode 100644 ui/vitest.config.js diff --git a/.env.example b/.env.example index d6a6201..01fcea3 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,8 @@ DEEPSEEK_API_KEY=your-deepseek-api-key DEEPSEEK_BASE_URL=https://api.deepseek.com MAIN_MODEL=deepseek-flash +# Comma-separated model allow-list shown in the Dashboard model selector. +AGENT_AVAILABLE_MODELS=deepseek-flash,deepseek-v4-pro GITEE_TOKEN=your-gitee-token GITEE_API_BASE_URL=https://gitee.com/api/v5 @@ -53,6 +55,13 @@ LOCAL_SHELL_WORKSPACE= LOCAL_SHELL_PROJECTS_DIR=projects LOCAL_SHELL_SHARED_PYTHON_VENV= LOCAL_SHELL_ENABLE_COMMAND_GUARD=true + +# Durable multi-task queue and optional per-run OpenSandbox backend. +AGENT_MAX_CONCURRENT_RUNS=2 +OPEN_SANDBOX_DOMAIN=http://127.0.0.1:8080 +OPEN_SANDBOX_IMAGE=python:3.11 +# Keep local until the OpenSandbox registry allows a full-stack image with Node/npm. +CODING_AGENT_RUNTIME_BACKEND=local LOCAL_SHELL_ALLOW_NETWORK=false AGENT_MAX_TOOL_CALLS=100 diff --git a/agent/api/dashboard_routes.py b/agent/api/dashboard_routes.py index c0991d5..4312ed5 100644 --- a/agent/api/dashboard_routes.py +++ b/agent/api/dashboard_routes.py @@ -23,18 +23,17 @@ import asyncio import json import re -import threading import uuid from datetime import datetime from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, HTTPException, Query from fastapi.responses import StreamingResponse from pydantic import BaseModel from agent.core.checkpoint_history import visible_checkpoint_messages from agent.core.graph import get_store -from agent.core.runtime import delete_task, get_task, initialize_task_record, list_tasks, run_agent_task +from agent.core.runtime import delete_task, get_task, initialize_task_record, list_tasks from agent.core.settings import PERSISTENCE_BACKEND from agent.env_utils import get_env from agent.repository import parse_repo_url @@ -85,12 +84,15 @@ def _normalize_dashboard_repo_url( def _normalize_dashboard_model_id(model_id: str | None) -> str: """只允许使用服务端当前暴露给前端的模型,避免接受任意模型名。""" + from agent.core.model import available_agent_models + configured_model = get_env("MAIN_MODEL", "deepseek-v4-pro").strip() selected_model = (model_id or configured_model).strip() - if selected_model != configured_model: + available = available_agent_models() + if selected_model not in available: raise HTTPException( status_code=422, - detail=f"所选模型未启用:{selected_model}。当前可用模型为 {configured_model}。", + detail=f"所选模型未启用:{selected_model}。当前可用模型为 {', '.join(available)}。", ) return selected_model @@ -120,7 +122,21 @@ class DashboardThreadTitleRequest(BaseModel): title: str -def _sse_part(event: str, data: dict[str, Any]) -> str: +class DashboardProjectRequest(BaseModel): + name: str + provider: str + repo: str + + +class DashboardProjectRenameRequest(BaseModel): + name: str + + +class DashboardThreadDraftRequest(BaseModel): + content: str + + +def _sse_part(event: str, data: dict[str, Any], *, event_id: int | None = None) -> str: """输出标准命名 SSE 事件。 新的 POST SSE 主链路采用 `event: xxx` + `data: json`,与 @@ -128,7 +144,8 @@ def _sse_part(event: str, data: dict[str, Any]) -> str: 不再需要把 event 包在 data JSON 里面。 """ - return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False, default=str)}\n\n" + id_line = f"id: {event_id}\n" if event_id is not None else "" + return f"{id_line}event: {event}\ndata: {json.dumps(data, ensure_ascii=False, default=str)}\n\n" def _timestamp_ms(value: str | datetime | None) -> int: @@ -145,12 +162,18 @@ def _timestamp_ms(value: str | datetime | None) -> int: def _status_for_frontend(status: str | None) -> str: """把项目后端状态映射成 open-swe 前端 AgentStatus。""" - if status in {"running", "pushed", "pr_created"}: + if status in {"running", "pushed", "pr_created", "cancelling"}: return "running" + if status == "queued": + return "queued" if status in {"completed", "awaiting_approval"}: return "awaiting_approval" if status == "awaiting_approval" else "finished" if status == "failed": return "error" + if status == "cancelled": + return "cancelled" + if status == "interrupted": + return "interrupted" return "idle" @@ -371,6 +394,8 @@ def _thread_payload(thread: dict[str, Any]) -> dict[str, Any]: }) return { "id": thread["thread_id"], + "projectId": thread.get("project_id"), + "chatOnly": not bool(thread.get("project_id") or thread.get("repo_url")), "title": thread.get("title") or "CODING Task", "repo": repo_full_name, "repoFullName": repo_full_name, @@ -384,6 +409,7 @@ def _thread_payload(thread: dict[str, Any]) -> dict[str, Any]: "status": _status_for_frontend(thread.get("latest_run_status")), "createdAt": _timestamp_ms(thread.get("created_at")), "updatedAt": _timestamp_ms(thread.get("updated_at")), + "draftContent": (getattr(store, "get_thread_draft", lambda _thread_id: None)(thread_id) or {}).get("content", ""), "messages": messages, "pendingIntervention": pending_intervention, "pr": _pr_payload(thread), @@ -430,7 +456,10 @@ def dashboard_options() -> dict[str, Any]: 前端只展示这些选项,真正创建模型对象仍由 `agent.core.model` 负责。 """ + from agent.core.model import available_agent_models + model = get_env("MAIN_MODEL", "deepseek-v4-pro") + models = available_agent_models() return { "default_repo": DEFAULT_REPO_URL, "default_provider": DEFAULT_REPO_PROVIDER, @@ -439,15 +468,11 @@ def dashboard_options() -> dict[str, Any]: {"id": "gitee", "label": "Gitee", "url_placeholder": "https://gitee.com/owner/repo.git"}, ], "repo_placeholder": "https://github.com/owner/repo.git", - "models": [ - { - "id": model, - "label": model, - "efforts": ["default"], - "default_effort": "default", - "supports_images": False, - } - ], + "models": [{ + "id": model_id, "label": model_id, + "efforts": ["default"], "default_effort": "default", + "supports_images": False, + } for model_id in models], "default_agent_model": model, "default_agent_reasoning_effort": "default", "default_agent_subagent_model": model, @@ -466,6 +491,117 @@ def dashboard_threads(limit: int = 50) -> list[dict[str, Any]]: return [_thread_payload(thread) for thread in list_tasks(limit=limit)] +@dashboard_router.get("/projects") +def dashboard_projects() -> list[dict[str, Any]]: + """Return projects with their conversations, grouped for the workspace sidebar.""" + store = get_store() + projects = store.list_projects() + threads = list_tasks(limit=2000) + by_project: dict[str, list[dict[str, Any]]] = {} + for thread in threads: + project_id = thread.get("project_id") + if project_id: + by_project.setdefault(str(project_id), []).append({ + "id": thread["thread_id"], "projectId": project_id, + "title": thread.get("title") or "CODING Task", + "status": _status_for_frontend(thread.get("latest_run_status")), + "updatedAt": _timestamp_ms(thread.get("updated_at")), + "repo": _repo_full_name(thread), + }) + return [{ + "id": project["project_id"], "name": project["name"], + "provider": project.get("provider"), "repo": project.get("repo_url"), + "repoFullName": "/".join(part for part in (project.get("repo_owner"), project.get("repo_name")) if part), + "legacy": bool(project.get("is_legacy")), + "conversations": by_project.get(project["project_id"], []), + } for project in projects] + + +@dashboard_router.post("/projects") +def dashboard_create_project(body: DashboardProjectRequest) -> dict[str, Any]: + name = body.name.strip() + provider = body.provider.strip().lower() + if not name or len(name) > 80: + raise HTTPException(status_code=422, detail="项目名称须为 1 到 80 个字符") + if provider not in {"github", "gitee"}: + raise HTTPException(status_code=422, detail="仅支持 GitHub 和 Gitee") + try: + repository = parse_repo_url(body.repo, provider=provider) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) from exc + store = get_store() + project = store.create_project( + project_id=str(uuid.uuid4()), name=name, provider=repository.provider, + repo_url=repository.clone_url, repo_owner=repository.owner, repo_name=repository.repo, + ) + return { + "id": project["project_id"], "name": project["name"], + "provider": project["provider"], "repo": project["repo_url"], + "repoFullName": repository.full_name, "legacy": False, "conversations": [], + } + + +@dashboard_router.patch("/projects/{project_id}") +def dashboard_rename_project(project_id: str, body: DashboardProjectRenameRequest) -> dict[str, Any]: + name = body.name.strip() + if not name or len(name) > 80: + raise HTTPException(status_code=422, detail="项目名称须为 1 到 80 个字符") + project = get_store().update_project_name(project_id, name) + if not project: + raise HTTPException(status_code=404, detail="project not found") + return {"id": project["project_id"], "name": project["name"]} + + +@dashboard_router.post("/projects/{project_id}/threads") +def dashboard_create_project_thread(project_id: str) -> dict[str, Any]: + thread = get_store().create_thread_for_project(thread_id=str(uuid.uuid4()), project_id=project_id) + if not thread: + if get_store().get_project(project_id) is None: + raise HTTPException(status_code=404, detail="project not found") + raise HTTPException(status_code=409, detail="该历史项目没有可用仓库,不能创建新会话") + return _thread_payload(thread) + + +@dashboard_router.post("/threads") +def dashboard_create_chat_thread() -> dict[str, Any]: + """Create a standalone chat thread that is not bound to a repository project.""" + thread = get_store().create_chat_thread(thread_id=str(uuid.uuid4())) + return _thread_payload(thread) + + +@dashboard_router.delete("/projects/{project_id}", status_code=204) +def dashboard_delete_project(project_id: str) -> None: + """Delete a project and all of its conversation records after UI confirmation.""" + store = get_store() + project = store.get_project(project_id) + if project is None: + raise HTTPException(status_code=404, detail="project not found") + thread_ids = store.list_project_thread_ids(project_id) + active = { + str(run.get("thread_id")) + for run in store.list_active_runs() + if str(run.get("thread_id")) in set(thread_ids) + } + if active: + raise HTTPException(status_code=409, detail="项目中仍有运行中的任务,请先停止或等待任务完成后再删除。") + for thread_id in thread_ids: + if not delete_task(thread_id): + raise HTTPException(status_code=409, detail="部分会话已变化,请刷新后重试删除项目。") + if not store.delete_project(project_id): + raise HTTPException(status_code=409, detail="项目仍有关联会话,请刷新后重试。") + return None + + +@dashboard_router.put("/threads/{thread_id}/draft") +def dashboard_save_thread_draft(thread_id: str, body: DashboardThreadDraftRequest) -> dict[str, Any]: + if len(body.content) > 100_000: + raise HTTPException(status_code=413, detail="草稿不能超过 100 KB") + draft = get_store().save_thread_draft(thread_id=thread_id, content=body.content) + if draft is None: + raise HTTPException(status_code=404, detail="thread not found") + return {"content": draft["content"], "revision": draft["revision"], "updatedAt": draft["updated_at"]} + + @dashboard_router.patch("/threads/{thread_id}") def dashboard_update_thread_title( thread_id: str, @@ -547,6 +683,17 @@ def dashboard_run_activity_events(thread_id: str, run_id: str) -> dict[str, Any] progress_text = detail["text"].strip() if progress_text and progress_text not in final_texts: safe_detail["text"] = progress_text[:12000] + elif ( + event.get("title") in {"任务失败", "技术方案生成失败"} + and event.get("status") == "error" + ): + # Runtime 仅在这里写入经过 mask_token 脱敏的最终异常;普通工具错误 + # 可能包含仓库内容或凭据,继续按默认策略隐藏。 + failure_text = raw_detail.strip() if isinstance(raw_detail, str) else "" + if not failure_text and isinstance(detail.get("text"), str): + failure_text = detail["text"].strip() + if failure_text: + safe_detail["text"] = failure_text[:4000] visible_events.append({ "id": event.get("id"), "kind": event.get("kind"), @@ -560,217 +707,150 @@ def dashboard_run_activity_events(thread_id: str, run_id: str) -> dict[str, Any] def _post_streaming_response( - *, thread_id: str, repo_url: str, content: str, + *, thread_id: str, repo_url: str | None, content: str, model_id: str | None = None, interaction_action: str | None = None, plan_id: str | None = None, intervention_id: str | None = None, ) -> StreamingResponse: - """直接执行本轮 Agent,并把过程事件作为同一个 POST SSE 响应返回。 - - 旧版链路是“POST 创建后台任务 + GET 轮询 run_events”。这种两段式链路在多轮 - 对话里容易出现时序竞争:用户输入由前端本地追加,任务计划来自 run_events, - 历史正文来自 checkpoint,三者不是同一个顺序源。 - - 新链路参考 `finqa_deepagent_observability`:请求体中携带本轮用户输入,后端 - 在同一条 StreamingResponse 中先发送 user_message,再直接运行 Agent。Store - 仍会记录任务摘要、PR、run_events 和仓库记忆,但前端实时正文不再依赖 Store - 轮询。 - """ - - # 先创建或更新 thread 业务记录。 - # 注意:这里不负责把用户消息写入 Store;用户消息展示由 SSE 的 user_message 事件负责, - # 稳定历史恢复由 LangGraph checkpoint 负责。 - initialize_task_record(repo_url=repo_url, prompt=content, thread_id=thread_id) - - # 立即读取刚刚创建或更新后的 thread 摘要,后面要用它生成首个 thread_snapshot 事件。 - initial_task = get_task(thread_id) - - # 如果业务 Store 没有读到 thread,说明初始化失败;此时不能继续建立 SSE,否则前端会拿到残缺状态。 - if initial_task is None: - # 用 HTTP 500 明确告诉前端:不是用户输入问题,而是后端持久化异常。 + """Persist a run first, then stream its durable event log to this client.""" + store = get_store() + if any(run.get("thread_id") == thread_id for run in store.list_active_runs()): + raise HTTPException(status_code=409, detail="此会话已有运行中的任务,请切换会话或等待完成。") + if repo_url is None: + task = store.get_thread(thread_id) + if task is None or task.get("project_id") or task.get("repo_url"): + raise HTTPException(status_code=409, detail="无仓库聊天会话状态已变化,请重新打开会话。") + if task.get("title") in {None, "新聊天", "新会话"}: + store.update_thread_title(thread_id, content.strip().replace("\n", " ")[:80] or "新聊天") + store.add_thread_message( + message_id=f"{thread_id}-user-{uuid.uuid4()}", thread_id=thread_id, + author="user", content=content, metadata={"source": "dashboard_chat"}, + ) + else: + initialize_task_record(repo_url=repo_url, prompt=content, thread_id=thread_id) + task = get_task(thread_id) + if task is None: raise HTTPException(status_code=500, detail="task was not persisted") + run_id = str(uuid.uuid4()) + payload = { + "repo_url": repo_url, + "chat_only": repo_url is None, + "content": content, + "model_id": model_id, + "interaction_action": interaction_action, + "plan_id": plan_id, + "intervention_id": intervention_id, + } + try: + store.enqueue_run(run_id=run_id, thread_id=thread_id, payload=payload) + except ValueError as exc: + raise HTTPException(status_code=409, detail="此会话已有运行中的任务,请切换会话或等待完成。") from exc + store.update_thread_status(thread_id, "queued") + initial = _thread_meta_payload(get_task(thread_id) or task) + initial.update({"thread_id": thread_id, "run_id": run_id, "status": "queued"}) + store.append_run_stream_event(thread_id=thread_id, run_id=run_id, event="thread_snapshot", payload=initial) + store.append_run_stream_event( + thread_id=thread_id, + run_id=run_id, + event="user_message", + payload={ + "thread_id": thread_id, + "run_id": run_id, + "message_id": f"{thread_id}-user-{run_id}", + "author": "user", + "content": content, + }, + ) + startup_message_id = f"{thread_id}-assistant-startup-{run_id}" + store.append_run_stream_event( + thread_id=thread_id, run_id=run_id, event="message_start", + payload={"thread_id": thread_id, "run_id": run_id, "message_id": startup_message_id, "author": "agent"}, + ) + store.append_run_stream_event( + thread_id=thread_id, run_id=run_id, event="text_delta", + payload={"thread_id": thread_id, "run_id": run_id, "message_id": startup_message_id, + "content": "任务已加入队列,等待执行…\n\n", "mode": "append"}, + ) - async def event_iter(): - """StreamingResponse 的异步事件生成器。 - - Agent 本身在工作线程中同步运行;SSE 响应在 asyncio 事件循环中异步发送。 - 二者通过 `asyncio.Queue` 桥接,保证后端边运行边把事件推给前端。 - """ - - # 获取当前 FastAPI 请求所在的 asyncio 事件循环;worker 线程投递事件时需要回到这个 loop。 - loop = asyncio.get_running_loop() - - # 创建本轮 SSE 的内存队列。worker 线程负责生产事件,event_iter 负责消费并 yield 给浏览器。 - queue: asyncio.Queue[tuple[str, dict[str, Any]]] = asyncio.Queue() - - def enqueue(event: str, data: dict[str, Any]) -> None: - """线程安全地把 worker 线程中的事件投递回 asyncio 队列。""" - - # 复制一份事件数据,避免调用方后续修改原 dict 时影响已经进入队列的 payload。 - payload = dict(data) - - # 所有发给前端的事件都补齐 thread_id,前端可以据此判断事件属于哪个会话。 - payload.setdefault("thread_id", thread_id) - - # worker 运行在普通线程,不能直接 await queue.put;必须通过事件循环线程安全投递。 - loop.call_soon_threadsafe(queue.put_nowait, (event, payload)) - - def event_sink(event: str, data: dict[str, Any]) -> None: - """runtime/streaming_runtime 使用的统一实时事件出口。 + async def event_iter(after_seq: int = 0): + cursor = max(0, after_seq) + heartbeat_at = asyncio.get_running_loop().time() + 15 + while True: + rows = store.list_run_stream_events(thread_id=thread_id, run_id=run_id, after_seq=cursor) + for row in rows: + cursor = int(row["seq"]) + yield _sse_part(row["event"], row["payload"], event_id=cursor) + if row["event"] == "done": + return + run = store.get_run(thread_id, run_id) or {} + if run.get("status") in {"completed", "failed", "cancelled", "interrupted"} and not rows: + yield _sse_part("done", {"run_id": run_id, "thread_id": thread_id, "status": run["status"]}) + return + await asyncio.sleep(0.25) + if asyncio.get_running_loop().time() >= heartbeat_at: + yield ": keep-alive\n\n" + heartbeat_at = asyncio.get_running_loop().time() + 15 - `text_delta` 会先过滤空白,避免前端创建没有内容的 assistant 消息; - 其它事件会原样进入 SSE 队列。 - """ + return StreamingResponse( + event_iter(), media_type="text/event-stream", + headers={"Cache-Control": "no-cache, no-transform", "Connection": "keep-alive", "X-Accel-Buffering": "no"}, + ) - # 复制事件数据,避免 streaming_runtime 复用同一个 dict 时产生副作用。 - payload = dict(data) - # 文本增量是用户最敏感的展示内容,需要先做空白过滤和可见文本规整。 - if event == "text_delta": - # 当前实现不再过滤英文/中文,只做统一字符串化,保留模型真实 assistant 输出。 - payload["content"] = _user_visible_stream_text(str(payload.get("content") or "")) +@dashboard_router.get("/threads/{thread_id}/runs/{run_id}/stream") +async def dashboard_resume_run_stream( + thread_id: str, run_id: str, after: int = Query(default=0, ge=0), +) -> StreamingResponse: + store = get_store() + if not store.get_run(thread_id, run_id): + raise HTTPException(status_code=404, detail="运行记录不存在") - # 空字符串或纯空白不推给前端,避免创建空 AIMessage。 - if not payload["content"].strip(): + async def event_iter(): + cursor = after + heartbeat_at = asyncio.get_running_loop().time() + 15 + while True: + rows = store.list_run_stream_events(thread_id=thread_id, run_id=run_id, after_seq=cursor) + for row in rows: + cursor = int(row["seq"]) + yield _sse_part(row["event"], row["payload"], event_id=cursor) + if row["event"] == "done": return + run = store.get_run(thread_id, run_id) or {} + if run.get("status") in {"completed", "failed", "cancelled", "interrupted"} and not rows: + yield _sse_part("done", {"status": run["status"]}) + return + await asyncio.sleep(0.25) + if asyncio.get_running_loop().time() >= heartbeat_at: + yield ": keep-alive\n\n" + heartbeat_at = asyncio.get_running_loop().time() + 15 - # 其它事件,例如 message_start、todo_delta、thread_done,直接进入 SSE 队列。 - enqueue(event, payload) - - def worker() -> None: - """在后台线程中运行一次 Agent 任务。 - - 不能直接在 event_iter 中同步调用 `run_agent_task`,否则 FastAPI 无法边运行边 - yield SSE 数据。worker 结束后发送 `thread_done` 和 `done`,通知前端收尾。 - """ - - # worker 线程内部必须捕获异常,否则线程异常只会写到后端日志,前端收不到失败事件。 - try: - # 真正运行 Agent 的入口。runtime 会做任务分类、方案确认、Agent 构建和事件流消费。 - run_agent_task( - # 本轮任务绑定的 Gitee 仓库地址,已经在外层 API 边界做过规范化。 - repo_url=repo_url, - # 用户本轮真实输入,runtime 会根据任务类型决定是否包装内部执行上下文。 - prompt=content, - # 当前会话 id,用于绑定 Store、checkpoint、SSE 和 Agent config。 - thread_id=thread_id, - # 把 runtime/streaming_runtime 产生的实时事件送回本函数的 SSE 队列。 - event_sink=event_sink, - interaction_action=interaction_action, - plan_id=plan_id, - intervention_id=intervention_id, - model_id=model_id, - ) - - # Agent 正常结束后,重新读取最新 thread 摘要,里面可能已经包含分支、PR、状态等新信息。 - latest = get_task(thread_id) or initial_task - - # 告诉前端本轮任务最终元信息;注意该 payload 不带 messages,不覆盖前端已有正文。 - enqueue("thread_done", _thread_meta_payload(latest)) - - # 发送 done 事件,通知 event_iter 结束 while 循环,也通知前端结束 streaming 状态。 - enqueue("done", {}) - except Exception as exc: - # 失败时也尽量读取最新 thread,保证前端能看到 failed 状态或错误后的元信息。 - latest = get_task(thread_id) or initial_task - - # 把异常转成 SSE error 事件。这里不做复杂格式化,详细堆栈仍然看后端日志。 - enqueue("error", {"message": str(exc), "detail": str(exc)}) - - # 即使失败,也推送最终 thread 元信息,避免前端状态停留在 running。 - enqueue("thread_done", _thread_meta_payload(latest)) - - # 失败路径同样必须发送 done,否则浏览器会一直等待 SSE 结束。 - enqueue("done", {}) - - # 第一个事件只发送 thread 元信息,不发送 messages。 - # 前端当前轮用户输入和 assistant 流式正文必须由后续事件追加,不能被 snapshot 覆盖。 - # 这一步对应“先告诉前端当前会话是谁、状态是什么、仓库是什么”。 - yield _sse_part("thread_snapshot", _thread_meta_payload(initial_task)) - - # 先把用户真实输入立即推给前端。这样即使 Agent 初始化较慢,页面也能立刻看到本轮输入。 - # 前端会用这个正式 user_message 稳定或追加本轮用户气泡。 - yield _sse_part( - "user_message", - { - # 明确事件归属的会话 id。 - "thread_id": thread_id, - # 为本轮用户消息生成稳定 id,避免刷新或后续事件合并时没有主键。 - "message_id": f"{thread_id}-user-{uuid.uuid4()}", - # author=user 表示前端应按用户消息样式渲染。 - "author": "user", - # content 必须是用户真实输入,不能替换成 runtime 内部包装后的 prompt。 - "content": content, - }, - ) + return StreamingResponse( + event_iter(), media_type="text/event-stream", + headers={"Cache-Control": "no-cache, no-transform", "Connection": "keep-alive", "X-Accel-Buffering": "no"}, + ) - # 启动占位 assistant 消息,用于给用户一个明确的“任务已开始”反馈。 - # 后续真正的模型 token 会通过 streaming_runtime.py 继续创建或更新 assistant 消息。 - # 这个启动消息可以降低 Agent 初始化阶段的“页面无响应”感。 - startup_message_id = f"{thread_id}-assistant-startup-{uuid.uuid4()}" - # 先告诉前端创建一条 agent 消息容器。 - yield _sse_part( - "message_start", - { - # message_start 也携带 thread_id,方便前端在多会话状态下做归属判断。 - "thread_id": thread_id, - # 后续启动提示 text_delta 会写入这条 message。 - "message_id": startup_message_id, - # author=agent 表示这是 AI/assistant 侧消息。 - "author": "agent", - }, +@dashboard_router.post("/threads/{thread_id}/runs/{run_id}/cancel") +async def dashboard_cancel_run(thread_id: str, run_id: str) -> dict[str, Any]: + store = get_store() + status = store.request_run_cancel(thread_id=thread_id, run_id=run_id) + if status is None: + raise HTTPException(status_code=409, detail="运行已结束或不存在") + if status == "cancelled": + store.append_run_stream_event( + thread_id=thread_id, run_id=run_id, event="error", + payload={"thread_id": thread_id, "run_id": run_id, "message": "任务已取消"}, ) - - # 再给刚创建的启动消息写入一段简短提示文本。 - yield _sse_part( - "text_delta", - { - # 当前会话 id。 - "thread_id": thread_id, - # 对应上面的启动 assistant message。 - "message_id": startup_message_id, - # 用户可见启动提示,说明后端已经收到任务并正在准备运行上下文。 - "content": "正在理解需求并准备仓库上下文...\n\n", - # append 表示前端把这段文本追加到当前 message。 - "mode": "append", - }, + store.append_run_stream_event( + thread_id=thread_id, run_id=run_id, event="done", payload={"status": "cancelled"}, ) + store.update_thread_status(thread_id, "cancelled") + return {"thread_id": thread_id, "run_id": run_id, "status": status} - # 创建后台线程执行 Agent。线程名带 thread_id,方便从日志或调试工具定位。 - thread = threading.Thread(target=worker, name=f"coding-stream-{thread_id}", daemon=True) - - # 启动 worker 后,Agent 才真正开始运行;event_iter 继续留在 asyncio loop 里发送 SSE。 - thread.start() - - # 持续消费 worker/event_sink 投递到 queue 中的事件。 - while True: - # 持续从队列取事件并写入 SSE 响应。收到 done 后结束本次 HTTP 连接。 - event, data = await queue.get() # 阻塞等待事件。 - # 把内部事件名和 payload 转成标准 SSE 文本块。 - yield _sse_part(event, data) - - # done 是本轮流式响应的终止事件,收到后退出生成器。 - if event == "done": - break - - # 返回 FastAPI StreamingResponse,让浏览器可以边接收边渲染本轮 Agent 输出。 - return StreamingResponse( - # event_iter 是异步生成器,每次 yield 都会向 HTTP 响应体写入一段 SSE。 - event_iter(), - # SSE 必须使用 text/event-stream,前端才会按事件流处理。 - media_type="text/event-stream", - # 这些 header 用来降低代理和浏览器缓冲对实时输出的影响。 - headers={ - # 禁止缓存,并提示代理不要对响应做转换。 - "Cache-Control": "no-cache, no-transform", - # 保持长连接,Agent 未结束前不要主动关闭。 - "Connection": "keep-alive", - # Nginx 识别该 header 后会关闭响应缓冲,让 SSE 更实时。 - "X-Accel-Buffering": "no", - }, - ) +@dashboard_router.get("/runs/active") +async def dashboard_active_runs() -> list[dict[str, Any]]: + return get_store().list_active_runs() @dashboard_router.post("/threads/stream-message") @@ -779,9 +859,11 @@ async def dashboard_stream_new_message(body: DashboardThreadMessageRequest) -> S if body.interaction_action is not None: raise HTTPException(status_code=422, detail="方案与人工介入操作必须来自已有会话。") - repo_url = _normalize_dashboard_repo_url(body.repo, provider=body.provider) model_id = _normalize_dashboard_model_id(body.model_id) + repo_url = _normalize_dashboard_repo_url(body.repo, provider=body.provider) if body.repo else None thread_id = str(uuid.uuid4()) + if repo_url is None: + get_store().create_chat_thread(thread_id=thread_id) return _post_streaming_response( thread_id=thread_id, repo_url=repo_url, content=body.content, model_id=model_id, @@ -801,19 +883,18 @@ async def dashboard_stream_existing_message( """ task = get_task(thread_id) + chat_only = bool(task and not task.get("project_id") and not task.get("repo_url")) model_id = _normalize_dashboard_model_id(body.model_id) - repo_url = _normalize_dashboard_repo_url( - body.repo, - provider=body.provider, - fallback=(task or {}).get("repo_url"), + repo_url = None if chat_only else _normalize_dashboard_repo_url( + body.repo, provider=body.provider, fallback=(task or {}).get("repo_url"), ) existing_repo = (task or {}).get("repo_url") - if existing_repo and _repository_identity(str(existing_repo)) != _repository_identity(repo_url): + if existing_repo and (repo_url is None or _repository_identity(str(existing_repo)) != _repository_identity(repo_url)): raise HTTPException( status_code=409, detail="同一会话不能切换 GitHub/Gitee 仓库;请新建会话后选择目标仓库。", ) - if existing_repo: + if existing_repo and repo_url: # Keep the persisted canonical casing/URL stable for case-insensitive providers. repo_url = parse_repo_url(str(existing_repo)).clone_url store = get_store() diff --git a/agent/app.py b/agent/app.py index 1b8e205..87019d9 100644 --- a/agent/app.py +++ b/agent/app.py @@ -8,6 +8,8 @@ """ from __future__ import annotations +from contextlib import asynccontextmanager + from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware @@ -33,9 +35,22 @@ # --------------------------------------------------------------- # 创建 FastAPI 应用实例 # --------------------------------------------------------------- +@asynccontextmanager +async def lifespan(_app: FastAPI): + from agent.core.run_queue import get_run_worker_pool + + pool = get_run_worker_pool() + pool.start() + try: + yield + finally: + pool.stop() + + app = FastAPI( title="CODING Backend", # 应用名称 version="0.1.0", # 应用版本号 + lifespan=lifespan, ) # --------------------------------------------------------------- diff --git a/agent/core/model.py b/agent/core/model.py index 587aaca..51de872 100644 --- a/agent/core/model.py +++ b/agent/core/model.py @@ -11,12 +11,24 @@ INTENT_MODEL_MAX_TOKENS = 200 +def available_agent_models() -> list[str]: + """Return the allow-listed model IDs offered by the Dashboard. + + DeepSeek model IDs share the configured OpenAI-compatible endpoint and key. + Deployments may narrow or extend the list with AGENT_AVAILABLE_MODELS. + """ + + configured = get_env("MAIN_MODEL", "deepseek-v4-pro").strip() + raw_models = get_env("AGENT_AVAILABLE_MODELS", "deepseek-flash,deepseek-v4-pro") + models = [item.strip() for item in raw_models.split(",") if item.strip()] + return list(dict.fromkeys([configured, *models])) + + def make_main_model(model_id: str | None = None) -> BaseChatModel: """创建编码智能体使用的 DeepSeek 模型。 - 本地部署版只保留一个主模型,默认对齐 open-swe 使用的 `deepseek-v4-pro`。 - 这里不引入多模型 profile、fallback、路由器等生产级能力, - 让开发者先理解“模型配置”和“Agent 编排”之间的关系。 + 默认支持 DeepSeek 当前的 Flash 与 Pro 模型;部署可以通过 + `AGENT_AVAILABLE_MODELS` 限制选择范围。模型 ID 仍由服务端 allow-list 校验。 `thinking: disabled` 与 open-swe 的 DeepSeek 调用方式保持一致, 避免模型输出额外思考内容影响工具调用和最终回复。 @@ -29,8 +41,8 @@ def make_main_model(model_id: str | None = None) -> BaseChatModel: configured_model = get_env("MAIN_MODEL", "deepseek-v4-pro").strip() selected_model = (model_id or configured_model).strip() - if selected_model != configured_model: - raise ValueError(f"请求模型 {selected_model!r} 未在服务端 MAIN_MODEL 配置中启用") + if selected_model not in available_agent_models(): + raise ValueError(f"请求模型 {selected_model!r} 未在服务端 AGENT_AVAILABLE_MODELS 配置中启用") return init_chat_model( model=selected_model, diff --git a/agent/core/repository_workspace.py b/agent/core/repository_workspace.py index 15477a6..76726dc 100644 --- a/agent/core/repository_workspace.py +++ b/agent/core/repository_workspace.py @@ -4,6 +4,7 @@ import logging import re +import time from dataclasses import dataclass from pathlib import Path from typing import Any @@ -12,6 +13,10 @@ from agent.repository import Repository, parse_repo_url logger = logging.getLogger(__name__) +_TRANSIENT_GIT_NETWORK_ERRORS = ( + "failed to receive handshake", "ssl/tls connection", "connection reset", + "connection timed out", "could not resolve host", "early eof", "remote end hung up", +) class RepositoryWorkspaceError(RuntimeError): @@ -34,6 +39,16 @@ def task_branch_name(thread_id: str) -> str: def _run(backend: Any, command: str, *, cwd: str, timeout: int = 300) -> Any: result = backend.run(command, cwd=cwd, timeout=timeout) + if command.startswith("git fetch"): + for attempt in range(1, 4): + detail = f"{result.stderr}\n{result.stdout}".lower() + if result.exit_code == 0 or not any(token in detail for token in _TRANSIENT_GIT_NETWORK_ERRORS): + break + if attempt == 3: + break + logger.warning("Transient Git fetch network failure; retry %s/2 in %s second(s)", attempt, attempt) + time.sleep(attempt) + result = backend.run(command, cwd=cwd, timeout=timeout) combined_output = f"{result.stdout}\n{result.stderr}".lower() if result.exit_code != 0 and command.startswith("git fetch") and "cannot open .git/fetch_head" in combined_output: # Preserve the existing Windows recovery for a stale/locked FETCH_HEAD, @@ -136,6 +151,7 @@ def prepare_repository_workspace( *, thread_id: str | None = None, create_task_branch: bool = False, + workspace_directory: str | None = None, ) -> PreparedRepositoryWorkspace: """Clone or validate the exact selected repository, then select a safe base. @@ -144,13 +160,17 @@ def prepare_repository_workspace( its non-interactive provider credentials and token redaction remain in effect. """ - directory = repo_project_dir(repo).replace("\\", "/") + directory = (workspace_directory or repo_project_dir(repo)).replace("\\", "/").strip("/") + if not directory or any(part in {".", ".."} for part in directory.split("/")): + raise RepositoryWorkspaceError("任务工作区路径不安全") target = backend.workspace.resolve(directory) project_root = backend.projects_dir project_root.mkdir(parents=True, exist_ok=True) if not target.exists(): - clone = backend.run(f"git clone -- {repo.clone_url} {target.name}", cwd="projects", timeout=600) + target.parent.mkdir(parents=True, exist_ok=True) + relative_target = target.relative_to(project_root).as_posix() + clone = backend.run(f"git clone -- {repo.clone_url} {relative_target}", cwd="projects", timeout=600) if clone.exit_code != 0: detail = (clone.stderr or clone.stdout or "克隆失败").strip() raise RepositoryWorkspaceError(f"无法克隆所选 {repo.provider} 仓库 {repo.full_name}:{detail}") diff --git a/agent/core/run_queue.py b/agent/core/run_queue.py new file mode 100644 index 0000000..7668462 --- /dev/null +++ b/agent/core/run_queue.py @@ -0,0 +1,196 @@ +"""Durable, bounded Agent run workers backed by the business store.""" +from __future__ import annotations + +import logging +import os +import threading +import uuid +from typing import Any + +from agent.core.graph import get_store +from agent.core.runtime import run_agent_task, run_plain_chat_task + +logger = logging.getLogger(__name__) + + +class RunCancelled(Exception): + """Raised at an Agent event boundary after a cooperative cancellation request.""" + + +class RunLeaseLost(Exception): + """Raised when a worker can no longer prove ownership of its run.""" + + +class RunWorkerPool: + def __init__(self, *, concurrency: int | None = None, lease_seconds: int = 90) -> None: + self.concurrency = max(1, concurrency or int(os.getenv("AGENT_MAX_CONCURRENT_RUNS", "2"))) + self.lease_seconds = lease_seconds + self._stop = threading.Event() + self._threads: list[threading.Thread] = [] + + def start(self) -> None: + if self._threads: + return + self._stop.clear() + store = get_store() + try: + store.interrupt_stale_runs() + except Exception: + logger.exception("Could not reconcile stale Agent runs at startup") + for index in range(self.concurrency): + thread = threading.Thread( + target=self._worker_loop, + name=f"agent-run-worker-{index + 1}", + daemon=True, + ) + self._threads.append(thread) + thread.start() + reaper = threading.Thread(target=self._reconcile_loop, name="agent-run-reaper", daemon=True) + self._threads.append(reaper) + reaper.start() + logger.info("Agent run worker pool started: concurrency=%s", self.concurrency) + + def stop(self) -> None: + self._stop.set() + for thread in self._threads: + thread.join(timeout=2) + self._threads.clear() + + def _worker_loop(self) -> None: + store = get_store() + worker_id = f"{os.getenv('CODING_WORKER_ID', 'api')}-{uuid.uuid4().hex[:8]}" + poll_seconds = max(0.1, float(os.getenv("AGENT_QUEUE_POLL_SECONDS", "0.5"))) + while not self._stop.is_set(): + try: + item = store.claim_next_run( + worker_id=worker_id, + ttl_seconds=self.lease_seconds, + max_active=self.concurrency, + ) + if item is None: + self._stop.wait(poll_seconds) + continue + self._execute(item, worker_id) + except Exception: + logger.exception("Agent run queue worker failed while polling") + self._stop.wait(min(5, poll_seconds * 4)) + + def _reconcile_loop(self) -> None: + store = get_store() + interval = max(2, int(os.getenv("AGENT_RUN_REAPER_SECONDS", "10"))) + while not self._stop.wait(interval): + try: + store.interrupt_stale_runs() + except Exception: + logger.exception("Could not reconcile expired Agent run leases") + + def _execute(self, item: dict[str, Any], worker_id: str) -> None: + store = get_store() + run_id = str(item["run_id"]) + thread_id = str(item["thread_id"]) + payload = item.get("payload") or {} + heartbeat_stop = threading.Event() + ownership_lost = threading.Event() + + def heartbeat() -> None: + while not heartbeat_stop.wait(max(5, self.lease_seconds // 3)): + try: + if not store.renew_run_lease( + run_id=run_id, worker_id=worker_id, ttl_seconds=self.lease_seconds + ): + logger.warning("Run lease lost: run_id=%s", run_id) + ownership_lost.set() + return + except Exception: + logger.exception("Run lease heartbeat failed: run_id=%s", run_id) + ownership_lost.set() + return + + def emit(event: str, data: dict[str, Any]) -> None: + if event not in {"thread_done", "done"} and store.is_run_cancel_requested(run_id): + raise RunCancelled("Run cancelled by user") + if event not in {"thread_done", "done"} and ownership_lost.is_set(): + raise RunLeaseLost("Run worker lease was lost; task stopped to prevent duplicate execution") + event_payload = dict(data) + event_payload.setdefault("thread_id", thread_id) + event_payload.setdefault("run_id", run_id) + store.append_run_stream_event( + thread_id=thread_id, run_id=run_id, event=event, payload=event_payload + ) + + heartbeat_thread = threading.Thread(target=heartbeat, name=f"run-heartbeat-{run_id[:8]}", daemon=True) + heartbeat_thread.start() + try: + emit("run_status", {"status": "running"}) + if payload.get("chat_only"): + run_plain_chat_task( + thread_id=thread_id, run_id=run_id, + model_id=payload.get("model_id"), event_sink=emit, + ) + else: + run_agent_task( + repo_url=payload["repo_url"], + prompt=payload["content"], + thread_id=thread_id, + run_id=run_id, + event_sink=emit, + interaction_action=payload.get("interaction_action"), + plan_id=payload.get("plan_id"), + intervention_id=payload.get("intervention_id"), + model_id=payload.get("model_id"), + worker_id=worker_id, + ) + if store.is_run_cancel_requested(run_id): + raise RunCancelled("Run cancelled by user") + if ownership_lost.is_set(): + raise RunLeaseLost("Run worker lease was lost; task stopped to prevent duplicate execution") + terminal = store.get_run(thread_id, run_id) or {} + status = terminal.get("status") or "completed" + if status in {"queued", "running", "cancelling"}: + status = "completed" + store.finish_queued_run(thread_id=thread_id, run_id=run_id, status=status) + emit("thread_done", {"id": thread_id, "thread_id": thread_id, "status": status}) + emit("done", {"status": status}) + except RunCancelled as exc: + store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="cancelled", error=str(exc)) + store.update_thread_status(thread_id, "cancelled") + emit_terminal(store, thread_id, run_id, "cancelled", str(exc)) + except RunLeaseLost as exc: + store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="interrupted", error=str(exc)) + store.update_thread_status(thread_id, "interrupted") + emit_terminal(store, thread_id, run_id, "interrupted", str(exc)) + except Exception as exc: + logger.exception("Agent run failed: thread_id=%s run_id=%s", thread_id, run_id) + store.finish_queued_run(thread_id=thread_id, run_id=run_id, status="failed", error=str(exc)) + store.update_thread_status(thread_id, "failed") + emit_terminal(store, thread_id, run_id, "failed", str(exc)) + finally: + heartbeat_stop.set() + heartbeat_thread.join(timeout=1) + + +def emit_terminal(store: Any, thread_id: str, run_id: str, status: str, message: str) -> None: + for event, payload in ( + ("error", {"message": message, "thread_id": thread_id, "run_id": run_id}), + ("thread_done", {"id": thread_id, "thread_id": thread_id, "status": status}), + ("done", {"status": status}), + ): + try: + store.append_run_stream_event(thread_id=thread_id, run_id=run_id, event=event, payload=payload) + except Exception: + logger.exception("Could not persist terminal run event: run_id=%s event=%s", run_id, event) + + +_pool: RunWorkerPool | None = None +_pool_lock = threading.Lock() + + +def get_run_worker_pool() -> RunWorkerPool: + global _pool + with _pool_lock: + if _pool is None: + _pool = RunWorkerPool() + return _pool + + +__all__ = ["RunCancelled", "RunLeaseLost", "RunWorkerPool", "get_run_worker_pool"] diff --git a/agent/core/runtime.py b/agent/core/runtime.py index e30536f..bb943c9 100644 --- a/agent/core/runtime.py +++ b/agent/core/runtime.py @@ -53,6 +53,58 @@ RuntimeEventSink = Callable[[str, dict[str, Any]], None] +def run_plain_chat_task( + *, thread_id: str, run_id: str, model_id: str | None, event_sink: RuntimeEventSink, +) -> dict[str, Any]: + """Run a repository-free, multi-turn chat without tools or workspace access.""" + from langchain_core.messages import AIMessage, HumanMessage, SystemMessage + + from agent.core.model import make_main_model + + store = get_store() + thread = store.get_thread(thread_id) + if thread is None or thread.get("project_id") or thread.get("repo_url"): + raise ValueError("纯聊天会话不能关联项目或代码仓库") + history = store.list_thread_messages(thread_id) + model_messages = [SystemMessage(content=( + "你是 CODING 开发工作台中的通用助手。当前会话未连接代码仓库,也没有文件或命令工具;" + "请基于对话内容直接回答,不要声称已经检查或修改任何本地文件。" + ))] + for item in history[-40:]: + content = str(item.get("content") or "") + if not content: + continue + if item.get("author") == "user": + model_messages.append(HumanMessage(content=content)) + elif item.get("author") == "agent": + model_messages.append(AIMessage(content=content)) + message_id = f"{thread_id}-assistant-{run_id}" + event_sink("message_start", {"message_id": message_id, "author": "agent"}) + response_parts: list[str] = [] + for chunk in make_main_model(model_id).stream(model_messages): + value = chunk.content + if isinstance(value, str): + text = value + elif isinstance(value, list): + text = "".join( + str(part.get("text", "")) for part in value if isinstance(part, dict) and part.get("type") == "text" + ) + else: + text = "" + if text: + response_parts.append(text) + event_sink("text_delta", {"message_id": message_id, "content": text, "mode": "append"}) + response = "".join(response_parts).strip() + if not response: + raise RuntimeError("模型没有返回可显示的文本") + store.add_thread_message( + message_id=message_id, thread_id=thread_id, author="agent", content=response, + run_id=run_id, metadata={"source": "dashboard_chat", "model_id": model_id}, + ) + store.update_thread_status(thread_id, "completed") + return {"thread_id": thread_id, "run_id": run_id, "status": "completed", "content": response} + + def _record_todo_completion_guard(store: Any, *, thread_id: str, run_id: str) -> dict[str, int | bool] | None: """Persist a visible warning when a normal run ends with unfinished todos.""" @@ -84,6 +136,8 @@ def _build_agent_for_runtime( task_kind: str, repo_url: str | None = None, model_id: str | None = None, + workspace_dir: str | None = None, + run_id: str | None = None, ): """为 FastAPI runtime 构造 open-swe 风格的 Agent config。 @@ -111,6 +165,10 @@ def _build_agent_for_runtime( configurable["repo_url"] = repo_url if model_id: configurable["model_id"] = model_id + if workspace_dir: + configurable["workspace_dir"] = workspace_dir + if run_id: + configurable["run_id"] = run_id return get_agent({"configurable": configurable}) @@ -142,12 +200,24 @@ def _prepare_selected_repository( raise RepositoryWorkspaceError("Cannot read the isolated Eval repository branch") branch = branch_result.stdout.strip() or "eval" return PreparedRepositoryWorkspace(directory=directory, default_branch=branch, current_branch=branch) - return prepare_repository_workspace( + # A thread owns a stable checkout. Separate threads never switch branches in + # the same Git directory, so parallel writes cannot race through .git/index. + import hashlib + isolated_directory = ( + f"projects/.tasks/{hashlib.sha256(thread_id.encode('utf-8')).hexdigest()[:20]}/" + f"{repo_project_dir(repo).split('/')[-1]}" + ) + prepared = prepare_repository_workspace( repo, backend, thread_id=thread_id, create_task_branch=create_task_branch, + workspace_directory=isolated_directory, ) + # PreparedRepositoryWorkspace stores a host-relative path ("projects/..."). + # LocalShellBackend accepts only its virtual namespace rooted at "/projects". + backend.set_working_dir("/" + prepared.directory.replace("\\\\", "/").strip("/")) + return prepared def _ensure_repo_memory_for_repo(repo: Any, project_dir: str) -> None: @@ -169,10 +239,10 @@ def _ensure_repo_memory_for_repo(repo: Any, project_dir: str) -> None: logger.info("已初始化仓库记忆:repo=%s/%s", repo.owner, repo.repo) -def _detect_current_branch(repo: Any) -> str | None: +def _detect_current_branch(repo: Any, *, workspace_directory: str | None = None) -> str | None: """读取当前仓库实际工作分支,供 Dashboard 会话元信息展示。""" - project_dir = repo_project_dir(repo) + project_dir = workspace_directory or repo_project_dir(repo) backend = LocalShellBackend(Workspace(WORKSPACE_ROOT), provider=repo.provider) target = backend.workspace.resolve(project_dir) if not (target / ".git").exists(): @@ -323,6 +393,7 @@ def _build_agent_user_content( display_prompt: str | None = None, approved_plan: str | None = None, thread_id: str | None = None, + workspace_directory: str | None = None, ) -> str: """构造发送给 DeepAgent 的用户内容,避免只读任务被误导去创建 PR。 @@ -344,7 +415,7 @@ def _build_agent_user_content( visible_prompt = (display_prompt or prompt).strip() repo = parse_repo_url(repo_url) - repo_working_dir = "/" + repo_project_dir(repo).replace("\\", "/") + repo_working_dir = "/" + (workspace_directory or repo_project_dir(repo)).replace("\\", "/") if task_kind == "coding": branch_instruction = ( f"当前任务分支为 `{task_branch_name(thread_id)}`;请保留该分支,不要切回 main/master。" @@ -360,6 +431,12 @@ def _build_agent_user_content( "禁止访问当前仓库之外的文件。完成后说明改动和真实运行的验证结果。" f"{plan_instruction}" ) + elif get_env("CODING_AGENT_RUNTIME_BACKEND", "local").strip().lower() == "opensandbox": + task_instruction = ( + "本轮在一次性 OpenSandbox 中执行;请只修改当前任务仓库并运行验证。" + "不要提交、push 或创建 Pull Request;沙箱结束后系统会把变更导出到该任务分支供用户审阅。" + f"{branch_instruction}{plan_instruction}" + ) else: task_instruction = ( "这是开发实现任务。请按系统开发流程完成任务,必要时修改代码、验证,并创建或复用 GitHub/Gitee Pull Request。" @@ -391,6 +468,7 @@ def _build_plan_user_content( prompt: str, previous_plan: str | None = None, revision_prompt: str | None = None, + workspace_directory: str | None = None, ) -> str: """构造专门用于生成技术方案的只读任务内容。 @@ -402,7 +480,7 @@ def _build_plan_user_content( """ repo = parse_repo_url(repo_url) - repo_working_dir = "/" + repo_project_dir(repo).replace("\\", "/") + repo_working_dir = "/" + (workspace_directory or repo_project_dir(repo)).replace("\\", "/") workspace_instruction = ( f"所选仓库唯一工作目录:{repo_working_dir};命令默认 cwd 已是此仓库根。请只从该目录读取仓库内容;" "不要把 projects 下其他目录当成本轮仓库,也不要修改 origin。\n\n" @@ -710,7 +788,7 @@ def initialize_task_record( return thread_id -def run_workspace_listing_task(*, repo_url: str, prompt: str, thread_id: str | None = None) -> dict[str, Any]: +def run_workspace_listing_task(*, repo_url: str, prompt: str, thread_id: str | None = None, run_id: str | None = None) -> dict[str, Any]: """直接列出本地工作区项目,不调用模型。 这是一个“直达分支”:用户只是问本地工作区有哪些项目时,没有必要构建 Agent。 @@ -726,7 +804,7 @@ def run_workspace_listing_task(*, repo_url: str, prompt: str, thread_id: str | N ) store = get_store() # run_id 区分同一个 thread 内的多轮运行,前端实时事件依赖它避免跨轮覆盖。 - run_id = str(uuid.uuid4()) + run_id = run_id or str(uuid.uuid4()) store.record_run(run_id=run_id, thread_id=thread_id, status="running") workspace = Workspace(WORKSPACE_ROOT) backend = LocalShellBackend(workspace) @@ -758,7 +836,7 @@ def run_workspace_listing_task(*, repo_url: str, prompt: str, thread_id: str | N raise -def run_pull_only_task(*, repo_url: str, prompt: str, thread_id: str | None = None) -> dict[str, Any]: +def run_pull_only_task(*, repo_url: str, prompt: str, thread_id: str | None = None, run_id: str | None = None) -> dict[str, Any]: """执行只拉取远程代码的轻量任务。 这个分支不调用大模型,也不创建 PR。它只确保 GitHub/Gitee 仓库在本地工作区存在, @@ -776,7 +854,7 @@ def run_pull_only_task(*, repo_url: str, prompt: str, thread_id: str | None = No record_user_message=should_record_user_message, ) store = get_store() - run_id = str(uuid.uuid4()) + run_id = run_id or str(uuid.uuid4()) store.record_run(run_id=run_id, thread_id=thread_id, status="running") repo = parse_repo_url(repo_url) workspace = Workspace(WORKSPACE_ROOT) @@ -825,6 +903,7 @@ def run_plan_response_task( revision_prompt: str | None = None, event_sink: RuntimeEventSink | None = None, model_id: str | None = None, + run_id: str | None = None, ) -> dict[str, Any]: """为编码需求生成技术方案,并把方案作为普通回答直接展示。 @@ -870,7 +949,7 @@ def run_plan_response_task( content=display_prompt, metadata={"source": "dashboard"}, ) - run_id = str(uuid.uuid4()) + run_id = run_id or str(uuid.uuid4()) previous_metadata = _message_metadata(previous_plan_message or {}) previous_proposal = previous_metadata.get("proposal") or {} supersedes_plan_id = previous_metadata.get("plan_id") or previous_proposal.get("plan_id") @@ -893,28 +972,41 @@ def run_plan_response_task( ) record_event(thread_id, "agent", "构建方案生成 Agent", status="in_progress") # 方案任务需要读取仓库结构,因此先确保加载的是用户所选仓库。 - agent = _build_agent_for_runtime( - thread_id=thread_id, task_kind="planning", repo_url=repo.clone_url, model_id=model_id - ) + try: + agent = _build_agent_for_runtime( + thread_id=thread_id, task_kind="planning", repo_url=repo.clone_url, model_id=model_id, + workspace_dir=prepared_workspace.directory, run_id=run_id, + ) + except Exception: + from agent.server import close_runtime_backend + + close_runtime_backend(run_id) + raise record_event(thread_id, "agent", "构建方案生成 Agent", status="completed") # 事件流消费由 streaming_runtime.py 负责。runtime 只关心最终是否成功、 # 以及最终 messages 里是否能提取到一份可确认的技术方案。 - result = run_agent_with_event_stream( - agent=agent, - thread_id=thread_id, - run_id=run_id, - content=_build_plan_user_content( - repo_url=repo.clone_url, - prompt=_plan_source_prompt(previous_plan_message, prompt) - if previous_plan_message is not None - else prompt, - previous_plan=previous_plan_text, - revision_prompt=revision_prompt, - ), - task_kind="planning", - event_sink=event_sink, - model_id=model_id, - ) + try: + result = run_agent_with_event_stream( + agent=agent, + thread_id=thread_id, + run_id=run_id, + content=_build_plan_user_content( + repo_url=repo.clone_url, + prompt=_plan_source_prompt(previous_plan_message, prompt) + if previous_plan_message is not None + else prompt, + previous_plan=previous_plan_text, + revision_prompt=revision_prompt, + workspace_directory=prepared_workspace.directory, + ), + task_kind="planning", + event_sink=event_sink, + model_id=model_id, + ) + finally: + from agent.server import close_runtime_backend + + close_runtime_backend(run_id) _record_todo_completion_guard(store, thread_id=thread_id, run_id=run_id) store.finish_open_run_events(thread_id, status="completed", run_id=run_id) messages = result.get("messages", []) @@ -997,6 +1089,8 @@ def run_agent_task( plan_id: str | None = None, intervention_id: str | None = None, model_id: str | None = None, + run_id: str | None = None, + worker_id: str | None = None, ) -> dict[str, Any]: """运行一次普通 Agent 任务的总入口。 @@ -1015,6 +1109,7 @@ def run_agent_task( # 新任务创建新 thread;继续对话时使用前端已有 thread_id,确保 checkpoint 接上历史。 thread_id = thread_id or str(uuid.uuid4()) + run_id = run_id or str(uuid.uuid4()) store = get_store() existing_thread = store.get_thread(thread_id) get_active_intervention = getattr(store, "get_latest_active_thread_intervention", None) @@ -1027,9 +1122,9 @@ def run_agent_task( # 两个直达分支都不需要 LLM,能显著减少模型调用和等待时间;先检查待处理 HITL, # 避免任何普通消息(包括看似只读的快捷任务)绕过当前中断。 if not interaction_action and is_workspace_listing_task(prompt): - return run_workspace_listing_task(repo_url=repo_url, prompt=prompt, thread_id=thread_id) + return run_workspace_listing_task(repo_url=repo_url, prompt=prompt, thread_id=thread_id, run_id=run_id) if not interaction_action and is_pull_only_task(prompt): - return run_pull_only_task(repo_url=repo_url, prompt=prompt, thread_id=thread_id) + return run_pull_only_task(repo_url=repo_url, prompt=prompt, thread_id=thread_id, run_id=run_id) # 恢复动作不做普通意图分类:“1/确认/继续”等只能作为 checkpoint 的 resume 值, # 不能重新被判为 qa 并启动一轮新任务。 task_kind = ( @@ -1118,6 +1213,7 @@ def run_agent_task( revision_prompt=prompt, event_sink=event_sink, model_id=model_id, + run_id=run_id, ) except Exception: store.transition_thread_plan( @@ -1167,6 +1263,7 @@ def run_agent_task( revision_prompt=prompt, event_sink=event_sink, model_id=model_id, + run_id=run_id, ) if existing_thread and approved_plan_text is None and not interaction_action and _is_approval_prompt(prompt): # 没有可确认的技术方案时,把“确认”当作普通问题处理,避免误执行旧任务。 @@ -1181,7 +1278,8 @@ def run_agent_task( # 这个判断在 runtime 层完成,而不是只写在 Prompt 里,目的是把“先方案、再实施” # 做成确定性的产品流程,降低 Agent 首轮直接误改代码的风险。 return run_plan_response_task( - repo_url=repo_url, prompt=prompt, thread_id=thread_id, event_sink=event_sink, model_id=model_id + repo_url=repo_url, prompt=prompt, thread_id=thread_id, event_sink=event_sink, model_id=model_id, + run_id=run_id, ) # 到这里说明本轮不是直达任务,也不是“未确认的 coding 需求”。 @@ -1210,7 +1308,6 @@ def run_agent_task( metadata={"source": "runtime", "task_kind": task_kind}, ) # 每轮 Agent 执行都有独立 run_id。前端事件列表按 run_id 追加,不能复用上一轮 id。 - run_id = str(uuid.uuid4()) store.record_run(run_id=run_id, thread_id=thread_id, status="running") logger.info("业务 Store 已记录运行:thread_id=%s run_id=%s", thread_id, run_id) try: @@ -1233,33 +1330,51 @@ def run_agent_task( ) record_event(thread_id, "agent", "构建 Agent 运行图", status="in_progress") # Agent 在仓库校验成功后才创建,backend 默认 cwd 已绑定到本轮仓库。 - agent = _build_agent_for_runtime( - thread_id=thread_id, task_kind=task_kind, repo_url=repo.clone_url, model_id=model_id - ) + try: + agent = _build_agent_for_runtime( + thread_id=thread_id, task_kind=task_kind, repo_url=repo.clone_url, model_id=model_id, + workspace_dir=prepared_workspace.directory, run_id=run_id, + ) + except Exception: + from agent.server import close_runtime_backend + + close_runtime_backend(run_id) + raise logger.info("Agent 图已构建:thread_id=%s", thread_id) record_event(thread_id, "agent", "构建 Agent 运行图", status="completed") logger.info("开始通过官方事件流调用 Agent:thread_id=%s", thread_id) # runtime 只负责“决定跑什么”和“最终状态落库”。 # 运行过程中的 text delta、write_todos、tool call、subagent 事件解析, # 统一交给 streaming_runtime.py,避免调度层和事件解析层混在一起。 - with WorkerLeaseManager(store).hold(run_id): - result = run_agent_with_event_stream( - agent=agent, - thread_id=thread_id, - run_id=run_id, - content=_build_agent_user_content( - repo_url=repo.clone_url, - task_kind=task_kind, - prompt=coding_prompt, - display_prompt=display_prompt, - approved_plan=approved_plan_text, - thread_id=thread_id, - ), - task_kind=task_kind, - event_sink=event_sink, - resume_value=resume_value, - model_id=model_id, + try: + lease_manager = ( + WorkerLeaseManager(store, worker_id=worker_id) + if worker_id is not None + else WorkerLeaseManager(store) ) + with lease_manager.hold(run_id): + result = run_agent_with_event_stream( + agent=agent, + thread_id=thread_id, + run_id=run_id, + content=_build_agent_user_content( + repo_url=repo.clone_url, + task_kind=task_kind, + prompt=coding_prompt, + display_prompt=display_prompt, + approved_plan=approved_plan_text, + thread_id=thread_id, + workspace_directory=prepared_workspace.directory, + ), + task_kind=task_kind, + event_sink=event_sink, + resume_value=resume_value, + model_id=model_id, + ) + finally: + from agent.server import close_runtime_backend + + close_runtime_backend(run_id) if interaction_action == "resume_intervention": store.finish_thread_intervention(intervention_id, thread_id=thread_id) interrupts = result.get("interrupts") or [] @@ -1280,14 +1395,14 @@ def run_agent_task( metadata={"source": "human_intervention", "intervention_id": intervention_id}, ) store.finish_open_run_events(thread_id, status="completed", run_id=run_id) - current_branch = _detect_current_branch(repo) + current_branch = _detect_current_branch(repo, workspace_directory=prepared_workspace.directory) store.update_thread_status(thread_id, "awaiting_approval", branch_name=current_branch) store.record_run(run_id=run_id, thread_id=thread_id, status="awaiting_approval", finished=True) record_event(thread_id, "human:intervention", "等待你答复后继续", status="completed") return {"thread_id": thread_id, "run_id": run_id, "status": "awaiting_approval", "interrupts": interrupts} todo_summary = _record_todo_completion_guard(store, thread_id=thread_id, run_id=run_id) store.finish_open_run_events(thread_id, status="completed", run_id=run_id) - current_branch = _detect_current_branch(repo) + current_branch = _detect_current_branch(repo, workspace_directory=prepared_workspace.directory) store.update_thread_status(thread_id, "completed", branch_name=current_branch) store.record_run(run_id=run_id, thread_id=thread_id, status="completed", finished=True) run_title = "任务完成" if not todo_summary or todo_summary["complete"] else "任务运行结束(清单未完成)" @@ -1324,12 +1439,6 @@ def run_agent_task( # 如果漏掉其中任何一项,前端可能会一直停留在“ 运行中”。 store.finish_open_run_events(thread_id, status="error", run_id=run_id) store.update_thread_status(thread_id, "failed") - record_event( - thread_id, - "model", - f"调用 {model_id or get_env('MAIN_MODEL', 'deepseek-v4-pro').strip()}", - status="error", - ) record_event(thread_id, "failed", "任务失败", status="error", detail=mask_token(str(exc))) store.record_run( run_id=run_id, diff --git a/agent/sandbox/eval_backend.py b/agent/sandbox/eval_backend.py index 61de270..a7f36d1 100644 --- a/agent/sandbox/eval_backend.py +++ b/agent/sandbox/eval_backend.py @@ -31,19 +31,32 @@ class OpenSandboxEvalBackend(LocalShellBackend): _sandbox_root = "" - def __init__(self, *args: Any, **kwargs: Any) -> None: + def __init__( + self, *args: Any, runtime_case_repo: str | Path | None = None, + runtime_repo_url: str | None = None, runtime_branch: str | None = None, + **kwargs: Any, + ) -> None: super().__init__(*args, **kwargs) from agent.sandbox.opensandbox_executor import OpenSandboxConfig self.executor = OpenSandboxExecutor(OpenSandboxConfig.from_env()) - self.case_repo = Path(os.environ["EVAL_CASE_REPO"]).expanduser().resolve() - self.repo_url = os.environ["EVAL_REPO_URL"].strip() + self.runtime_mode = runtime_case_repo is not None + if self.runtime_mode: + self.case_repo = Path(runtime_case_repo).expanduser().resolve() + self.repo_url = str(runtime_repo_url or "").strip() + if not self.repo_url: + raise ValueError("OpenSandbox runtime requires a selected repository URL") + self.runtime_branch = runtime_branch or "codex/sandbox-task" + else: + self.case_repo = Path(os.environ["EVAL_CASE_REPO"]).expanduser().resolve() + self.repo_url = os.environ["EVAL_REPO_URL"].strip() + self.runtime_branch = "eval-baseline" self._closed = False self._uploaded_file_count = 0 self._uploaded_bytes = 0 self._execute_injection_remaining = 0 self._pending_execute_recovery: str | None = None - case_config = os.environ.get("EVAL_CASE_CONFIG", "").strip() + case_config = "" if self.runtime_mode else os.environ.get("EVAL_CASE_CONFIG", "").strip() if case_config: try: payload = json.loads(Path(case_config).read_text(encoding="utf-8")) @@ -53,9 +66,25 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: except (OSError, json.JSONDecodeError, AttributeError): pass self._sandbox_id = self.executor.start() - atexit.register(self.close) - self._upload_snapshot() - self._initialize_candidate_repo() + atexit.register(self._close_at_exit) + try: + self._upload_snapshot() + self._initialize_candidate_repo() + except Exception: + self._closed = True + try: + self.executor.close() + except Exception: + pass + raise + + def _close_at_exit(self) -> None: + try: + self.close() + except Exception: + # Explicit runtime close surfaces export/cleanup errors to the worker; + # interpreter shutdown must not emit an unhandled atexit traceback. + pass @property def id(self) -> str: @@ -78,7 +107,21 @@ def _remote_cwd(self, path: str | Path | None) -> str: def _upload_snapshot(self) -> None: from agent.sandbox.opensandbox_executor import collect_safe_workspace_files - files = collect_safe_workspace_files(self.root, max_file_bytes=self.executor.config.max_upload_bytes) + if self.runtime_mode: + roots = [self.case_repo, self.skills_dir, self.policies_dir] + files = [] + for source_root in roots: + if not source_root.is_dir(): + continue + prefix = source_root.resolve().relative_to(self.root.resolve()).as_posix() + files.extend( + type(item)(path=f"{prefix}/{item.path}", data=item.data, mode=item.mode) + for item in collect_safe_workspace_files( + source_root, max_file_bytes=self.executor.config.max_upload_bytes + ) + ) + else: + files = collect_safe_workspace_files(self.root, max_file_bytes=self.executor.config.max_upload_bytes) total_bytes = sum(len(item.data) for item in files) if total_bytes > 32 * 1024 * 1024: raise ValueError("Eval workspace snapshot exceeds the 32 MiB OpenSandbox upload budget") @@ -89,7 +132,7 @@ def _initialize_candidate_repo(self) -> None: remote_repo = self._remote_path(self.working_dir) commands = [ "mkdir -p " + shlex.quote(remote_repo), - "git init -b eval-baseline " + shlex.quote(remote_repo), + "git init -b " + shlex.quote(self.runtime_branch) + " " + shlex.quote(remote_repo), "git -C " + shlex.quote(remote_repo) + " config user.name 'Agent Eval'", "git -C " + shlex.quote(remote_repo) + " config user.email 'agent-eval@localhost'", "git -C " + shlex.quote(remote_repo) + " add -A", @@ -101,7 +144,7 @@ def _initialize_candidate_repo(self) -> None: ) if provision.exit_code != 0: raise RuntimeError("Could not initialize isolated sandbox Git baseline") - tools = self.executor.execute("git --version && python -m pytest --version", cwd=remote_repo) + tools = self.executor.execute("git --version && python --version", cwd=remote_repo) if tools.exit_code != 0: raise RuntimeError("The configured OpenSandbox image must include git and pytest") @@ -126,8 +169,8 @@ def execute(self, command: str, *, timeout: int | None = None) -> ExecuteRespons denied = self._deny_reason(command) if denied: return ExecuteResponse(output=f"命令被拒绝:{denied}", exit_code=126, truncated=False) - if os.environ.get("CODING_AGENT_EVAL_MODE", "").strip() == "1" and self._blocks_git_write(command): - return ExecuteResponse(output="Agent Eval blocks Git write and remote-sync commands", exit_code=126, truncated=False) + if (getattr(self, "runtime_mode", False) or os.environ.get("CODING_AGENT_EVAL_MODE", "").strip() == "1") and self._blocks_git_write(command): + return ExecuteResponse(output="OpenSandbox blocks Git history and remote write commands", exit_code=126, truncated=False) remote_command = self._map_command_paths(command) try: result = self.executor.execute( @@ -373,6 +416,44 @@ def _record(event_type: str, payload: dict[str, Any]) -> None: pass +class OpenSandboxRuntimeBackend(OpenSandboxEvalBackend): + """Per-run remote backend that exports only its checkout patch to the host.""" + + def __init__( + self, *, working_dir: str, case_repo: str | Path, repo_url: str, + branch_name: str, provider: str | None = None, + ) -> None: + super().__init__( + provider=provider, + working_dir=working_dir, + runtime_case_repo=case_repo, + runtime_repo_url=repo_url, + runtime_branch=branch_name, + ) + + def close(self) -> dict[str, Any]: + previous = getattr(self, "_runtime_close_evidence", None) + if previous is not None: + return previous + evidence = super().close() + self._runtime_close_evidence = evidence + if not evidence.get("host_patch_exported") or not evidence.get("cleanup_succeeded"): + raise RuntimeError( + "OpenSandbox runtime could not safely export the task patch or destroy its sandbox: " + + str(evidence.get("error") or evidence.get("cleanup_error") or "unknown failure") + ) + return evidence + + @staticmethod + def _record(event_type: str, payload: dict[str, Any]) -> None: + try: + from agent.evals.telemetry import record_eval_event + + record_eval_event(event_type, payload) + except Exception: + pass + + def close_opensandbox_backends(backends: list[Any]) -> list[dict[str, Any]]: """Export patches and destroy the sandboxes created for one Eval process.""" diff --git a/agent/server.py b/agent/server.py index 327726e..9f061d9 100644 --- a/agent/server.py +++ b/agent/server.py @@ -110,6 +110,8 @@ def ensure_backend_for_thread( *, provider: str | None = None, working_dir: str | None = None, + run_id: str | None = None, + repo_url: str | None = None, ) -> LocalShellBackend: """获取或创建绑定到 thread 的本地 backend。 @@ -120,9 +122,29 @@ def ensure_backend_for_thread( - 只负责复用当前机器上的 `AI_WORKSPACE_ROOT` 工作区。 """ - backend = _BACKENDS.get(thread_id) + runtime_backend = os.environ.get("CODING_AGENT_RUNTIME_BACKEND", "local").strip().lower() + if runtime_backend == "opensandbox" and not run_id: + raise RuntimeError("OpenSandbox runtime requires a run_id so the sandbox is isolated per run") + backend_key = run_id if runtime_backend == "opensandbox" and run_id else thread_id + backend = _BACKENDS.get(backend_key) if backend is None: - if os.environ.get("CODING_AGENT_EVAL_BACKEND", "local").strip().lower() == "opensandbox": + if runtime_backend == "opensandbox" and run_id: + from agent.core.settings import WORKSPACE_ROOT + from agent.sandbox.eval_backend import OpenSandboxRuntimeBackend + from agent.core.repository_workspace import task_branch_name + + if not working_dir or not repo_url: + raise RuntimeError("OpenSandbox runtime requires a prepared task checkout and repository URL") + task_repo_path = (WORKSPACE_ROOT / working_dir.lstrip("/")).resolve() + backend = OpenSandboxRuntimeBackend( + working_dir=working_dir, + case_repo=task_repo_path, + repo_url=repo_url, + branch_name=task_branch_name(thread_id), + provider=provider, + ) + logger.info("为 run 创建 OpenSandboxRuntimeBackend:thread_id=%s run_id=%s", thread_id, run_id) + elif os.environ.get("CODING_AGENT_EVAL_BACKEND", "local").strip().lower() == "opensandbox": if os.environ.get("CODING_AGENT_EVAL_MODE", "").strip() != "1": raise RuntimeError("OpenSandbox Eval backend is only available in isolated Agent Eval runs") from agent.sandbox.eval_backend import OpenSandboxEvalBackend @@ -132,7 +154,7 @@ def ensure_backend_for_thread( else: logger.info("为 thread 创建 LocalShellBackend:%s", thread_id) backend = LocalShellBackend(provider=provider, working_dir=working_dir) - _BACKENDS[thread_id] = backend + _BACKENDS[backend_key] = backend else: logger.info("复用 thread 的 LocalShellBackend:%s", thread_id) if provider: @@ -142,6 +164,13 @@ def ensure_backend_for_thread( return backend +def close_runtime_backend(run_id: str) -> None: + """Export a run's sandbox patch and destroy its isolated runtime.""" + backend = _BACKENDS.pop(run_id, None) + if backend is not None and backend.__class__.__name__ == "OpenSandboxRuntimeBackend": + backend.close() + + def _general_purpose_subagent(model: BaseChatModel) -> SubAgent: """构建 之前项目 风格的通用分析子 Agent。 @@ -321,17 +350,25 @@ def get_agent(config: RunnableConfig): task_kind = _task_kind_from_config(configurable) repo_url = configurable.get("repo_url") + configured_workspace_dir = configurable.get("workspace_dir") + run_id = configurable.get("run_id") repo_provider = None repo_working_dir = None if isinstance(repo_url, str) and repo_url.strip(): repo = parse_repo_url(repo_url) repo_provider = repo.provider - repo_working_dir = "/" + repo_project_dir(repo).replace("\\", "/") + repo_working_dir = ( + "/" + str(configured_workspace_dir).replace("\\", "/").strip("/") + if isinstance(configured_workspace_dir, str) and configured_workspace_dir.strip() + else "/" + repo_project_dir(repo).replace("\\", "/") + ) # backend 按 thread 复用,避免同一个会话内反复初始化 Windows 工作区封装。 backend = ensure_backend_for_thread( thread_id, provider=repo_provider, working_dir=repo_working_dir, + run_id=run_id if isinstance(run_id, str) else None, + repo_url=repo_url if isinstance(repo_url, str) else None, ) langgraph_store = get_langgraph_store() # server.py 在创建 Agent 之前,已经顺手读到了当前仓库记忆内容; @@ -403,6 +440,20 @@ def get_agent(config: RunnableConfig): if configured_tools: eval_safe_tools.intersection_update(configured_tools) tools = [tool for tool in tools if getattr(tool, "name", getattr(tool, "__name__", "")) in eval_safe_tools] + elif os.environ.get("CODING_AGENT_RUNTIME_BACKEND", "local").strip().lower() == "opensandbox" and run_id: + # Sandbox edits are exported only after the Agent turn. External Git/PR + # and issue mutations therefore stay disabled until a verified patch is + # present in the host checkout. + external_write_tools = { + "open_gitee_pull_request", "publish_gitee_pr_comment", "create_gitee_issue", + "publish_gitee_issue_comment", "open_github_pull_request", "publish_github_pr_comment", + "create_github_issue", "publish_github_issue_comment", "rerun_github_actions", + "cancel_github_actions", + } + tools = [ + tool for tool in tools + if getattr(tool, "name", getattr(tool, "__name__", "")) not in external_write_tools + ] system_prompt = get_system_prompt(task_kind) if eval_mode and task_kind == "coding": system_prompt += ( diff --git a/agent/store/migration.py b/agent/store/migration.py index 5dbfd9c..2bb1c16 100644 --- a/agent/store/migration.py +++ b/agent/store/migration.py @@ -47,19 +47,42 @@ def _sqlite_rows(path: Path, table: str) -> list[dict[str, Any]]: def migrate_business_store(source: Path, target: PostgresBusinessStore, report: MigrationReport) -> None: """Idempotently copy platform-owned SQLite tables.""" with target._connection() as conn: # noqa: SLF001 - migration is a storage boundary + for row in _sqlite_rows(source, "projects"): + conn.execute( + """INSERT INTO projects (project_id, tenant_id, user_id, name, provider, repo_url, + repo_owner, repo_name, is_legacy, created_at, updated_at) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT(project_id) DO NOTHING""", + (row["project_id"], target.tenant_id, target.user_id, row["name"], row.get("provider"), + row.get("repo_url"), row.get("repo_owner"), row.get("repo_name"), bool(row.get("is_legacy")), + row["created_at"], row["updated_at"]), + ) + report.tables["projects"] = len(_sqlite_rows(source, "projects")) for row in _sqlite_rows(source, "threads"): conn.execute( """INSERT INTO threads (thread_id, tenant_id, user_id, title, user_prompt, repo_url, repo_owner, - repo_name, branch_name, pr_url, latest_run_status, created_at, updated_at) + repo_name, project_id, branch_name, pr_url, latest_run_status, created_at, updated_at) VALUES (%(thread_id)s, %(tenant_id)s, %(user_id)s, %(title)s, %(user_prompt)s, %(repo_url)s, - %(repo_owner)s, %(repo_name)s, %(branch_name)s, %(pr_url)s, %(status)s, %(created_at)s, %(updated_at)s) + %(repo_owner)s, %(repo_name)s, %(project_id)s, %(branch_name)s, %(pr_url)s, %(status)s, %(created_at)s, %(updated_at)s) ON CONFLICT(thread_id) DO UPDATE SET title=EXCLUDED.title, user_prompt=EXCLUDED.user_prompt, repo_url=EXCLUDED.repo_url, repo_owner=EXCLUDED.repo_owner, repo_name=EXCLUDED.repo_name, - branch_name=EXCLUDED.branch_name, pr_url=EXCLUDED.pr_url, latest_run_status=EXCLUDED.latest_run_status, + project_id=COALESCE(EXCLUDED.project_id, threads.project_id), branch_name=EXCLUDED.branch_name, + pr_url=EXCLUDED.pr_url, latest_run_status=EXCLUDED.latest_run_status, updated_at=EXCLUDED.updated_at""", - {**row, "tenant_id": row.get("tenant_id", target.tenant_id), "user_id": row.get("user_id", target.user_id), "status": row.get("latest_run_status", "pending")}, + {**row, "tenant_id": target.tenant_id, "user_id": target.user_id, + "project_id": row.get("project_id"), "status": row.get("latest_run_status", "pending")}, ) report.tables["threads"] = len(_sqlite_rows(source, "threads")) + target._backfill_legacy_projects(conn) + + for row in _sqlite_rows(source, "thread_drafts"): + conn.execute( + """INSERT INTO thread_drafts (thread_id, tenant_id, user_id, content, revision, updated_at) + VALUES (%s,%s,%s,%s,%s,%s) ON CONFLICT(thread_id) DO UPDATE SET + content=EXCLUDED.content, revision=EXCLUDED.revision, updated_at=EXCLUDED.updated_at""", + (row["thread_id"], target.tenant_id, target.user_id, row.get("content", ""), + row.get("revision", 1), row["updated_at"]), + ) + report.tables["thread_drafts"] = len(_sqlite_rows(source, "thread_drafts")) for row in _sqlite_rows(source, "runs"): conn.execute( diff --git a/agent/store/postgres_store.py b/agent/store/postgres_store.py index 2d6b1c6..b2cccec 100644 --- a/agent/store/postgres_store.py +++ b/agent/store/postgres_store.py @@ -70,6 +70,21 @@ def _decode(value: Any, default: Any = None) -> Any: def _init_schema(self) -> None: statements = [ + """ + CREATE TABLE IF NOT EXISTS projects ( + project_id TEXT PRIMARY KEY, + tenant_id TEXT NOT NULL DEFAULT 'default', + user_id TEXT NOT NULL DEFAULT 'system', + name TEXT NOT NULL, + provider TEXT, + repo_url TEXT, + repo_owner TEXT, + repo_name TEXT, + is_legacy BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL + ) + """, """ CREATE TABLE IF NOT EXISTS threads ( thread_id TEXT PRIMARY KEY, @@ -80,6 +95,7 @@ def _init_schema(self) -> None: repo_url TEXT, repo_owner TEXT, repo_name TEXT, + project_id TEXT, branch_name TEXT, pr_url TEXT, latest_run_status TEXT NOT NULL, @@ -88,6 +104,16 @@ def _init_schema(self) -> None: ) """, """ + CREATE TABLE IF NOT EXISTS thread_drafts ( + thread_id TEXT PRIMARY KEY, + tenant_id TEXT NOT NULL DEFAULT 'default', + user_id TEXT NOT NULL DEFAULT 'system', + content TEXT NOT NULL DEFAULT '', + revision BIGINT NOT NULL DEFAULT 1, + updated_at TIMESTAMPTZ NOT NULL + ) + """, + """ CREATE TABLE IF NOT EXISTS runs ( run_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, @@ -100,9 +126,23 @@ def _init_schema(self) -> None: worker_id TEXT, lease_expires_at TIMESTAMPTZ, heartbeat_at TIMESTAMPTZ, - attempt INTEGER NOT NULL DEFAULT 0 + attempt INTEGER NOT NULL DEFAULT 0, + payload JSONB, + queued_at TIMESTAMPTZ, + cancel_requested BOOLEAN NOT NULL DEFAULT FALSE + ) + """, + """ + CREATE TABLE IF NOT EXISTS run_stream_events ( + seq BIGSERIAL PRIMARY KEY, + thread_id TEXT NOT NULL, + run_id TEXT NOT NULL, + event TEXT NOT NULL, + payload JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) """, + "CREATE INDEX IF NOT EXISTS idx_run_stream_events_run_seq ON run_stream_events (thread_id, run_id, seq)", """ CREATE TABLE IF NOT EXISTS run_events ( id TEXT PRIMARY KEY, @@ -211,6 +251,7 @@ def _init_schema(self) -> None: ) """, "CREATE INDEX IF NOT EXISTS idx_threads_scope_updated ON threads (tenant_id, user_id, updated_at DESC)", + "CREATE INDEX IF NOT EXISTS idx_projects_scope_updated ON projects (tenant_id, user_id, updated_at DESC)", "CREATE INDEX IF NOT EXISTS idx_runs_status_lease ON runs (status, lease_expires_at)", "CREATE INDEX IF NOT EXISTS idx_events_thread_created ON run_events (thread_id, created_at)", "CREATE INDEX IF NOT EXISTS idx_events_run_created ON run_events (thread_id, run_id, created_at)", @@ -224,21 +265,210 @@ def _init_schema(self) -> None: for table, column, definition in ( ("threads", "tenant_id", "TEXT NOT NULL DEFAULT 'default'"), ("threads", "user_id", "TEXT NOT NULL DEFAULT 'system'"), + ("threads", "project_id", "TEXT"), ("runs", "tenant_id", "TEXT NOT NULL DEFAULT 'default'"), ("runs", "user_id", "TEXT NOT NULL DEFAULT 'system'"), ("runs", "worker_id", "TEXT"), ("runs", "lease_expires_at", "TIMESTAMPTZ"), ("runs", "heartbeat_at", "TIMESTAMPTZ"), ("runs", "attempt", "INTEGER NOT NULL DEFAULT 0"), + ("runs", "payload", "JSONB"), + ("runs", "queued_at", "TIMESTAMPTZ"), + ("runs", "cancel_requested", "BOOLEAN NOT NULL DEFAULT FALSE"), ("thread_plans", "version", "INTEGER NOT NULL DEFAULT 1"), ("thread_plans", "supersedes_plan_id", "TEXT"), ("thread_plans", "decision_feedback", "TEXT"), ): conn.execute(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} {definition}") + conn.execute("CREATE INDEX IF NOT EXISTS idx_threads_project_updated ON threads (project_id, updated_at DESC)") + self._backfill_legacy_projects(conn) + conn.execute( + """CREATE INDEX IF NOT EXISTS idx_runs_queue_claim + ON runs (queued_at, run_id) + WHERE status='queued' AND payload IS NOT NULL AND cancel_requested=FALSE""" + ) + + def _backfill_legacy_projects(self, conn: Any | None = None) -> None: + """Group historical threads by repository without changing their history.""" + + if conn is None: + with self._connection() as connection: + self._backfill_legacy_projects(connection) + return + legacy_rows = conn.execute( + """ + SELECT thread_id, tenant_id, user_id, title, repo_url, repo_owner, repo_name, + created_at, updated_at, + CASE WHEN NULLIF(BTRIM(repo_url), '') IS NULL + THEN 'legacy-' || md5(tenant_id || ':' || user_id || ':' || thread_id) + ELSE 'legacy-' || md5(tenant_id || ':' || user_id || ':' || + lower(regexp_replace(rtrim(repo_url, '/'), '\\.git$', '', 'i'))) + END AS legacy_project_id + FROM threads WHERE project_id IS NULL + ORDER BY created_at, thread_id + """ + ).fetchall() + projects: dict[str, dict[str, Any]] = {} + for row in legacy_rows: + project_id = row["legacy_project_id"] + if project_id in projects: + continue + repo_url = row.get("repo_url") + provider = None + if repo_url: + lowered = str(repo_url).lower() + provider = "github" if "github.com/" in lowered else "gitee" if "gitee.com/" in lowered else None + repo_label = "/".join(part for part in (row.get("repo_owner"), row.get("repo_name")) if part) + projects[project_id] = { + "project_id": project_id, + "tenant_id": row["tenant_id"], + "user_id": row["user_id"], + "name": repo_label or ("历史会话 · " + str(row.get("title") or "未命名")[:48]), + "provider": provider, + "repo_url": repo_url, + "repo_owner": row.get("repo_owner"), + "repo_name": row.get("repo_name"), + "created_at": row["created_at"], + "updated_at": row["updated_at"], + } + for project in projects.values(): + conn.execute( + """INSERT INTO projects (project_id, tenant_id, user_id, name, provider, repo_url, + repo_owner, repo_name, is_legacy, created_at, updated_at) + VALUES (%(project_id)s, %(tenant_id)s, %(user_id)s, %(name)s, %(provider)s, + %(repo_url)s, %(repo_owner)s, %(repo_name)s, TRUE, %(created_at)s, %(updated_at)s) + ON CONFLICT(project_id) DO NOTHING""", + project, + ) + for row in legacy_rows: + conn.execute( + "UPDATE threads SET project_id=%s WHERE thread_id=%s AND project_id IS NULL", + (row["legacy_project_id"], row["thread_id"]), + ) def close(self) -> None: self._pool.close() + def create_project( + self, *, project_id: str, name: str, provider: str, repo_url: str, + repo_owner: str, repo_name: str, + ) -> dict[str, Any]: + now = datetime.now(UTC) + with self._connection() as conn: + return conn.execute( + """INSERT INTO projects + (project_id, tenant_id, user_id, name, provider, repo_url, repo_owner, + repo_name, is_legacy, created_at, updated_at) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,FALSE,%s,%s) + RETURNING *""", + (project_id, self.tenant_id, self.user_id, name, provider, repo_url, + repo_owner, repo_name, now, now), + ).fetchone() + + def create_chat_thread(self, *, thread_id: str) -> dict[str, Any]: + """Create a general chat thread without attaching it to a repository project.""" + self.upsert_thread(thread_id=thread_id, title="新聊天", latest_run_status="pending") + return self.get_thread(thread_id) + + def list_project_thread_ids(self, project_id: str) -> list[str]: + with self._connection() as conn: + rows = conn.execute( + """SELECT thread_id FROM threads + WHERE project_id=%s AND tenant_id=%s AND user_id=%s + ORDER BY updated_at DESC""", + (project_id, self.tenant_id, self.user_id), + ).fetchall() + return [str(row["thread_id"]) for row in rows] + + def delete_project(self, project_id: str) -> bool: + with self._connection() as conn: + deleted = conn.execute( + """DELETE FROM projects AS p + WHERE p.project_id=%s AND p.tenant_id=%s AND p.user_id=%s + AND NOT EXISTS ( + SELECT 1 FROM threads AS t WHERE t.project_id=p.project_id + ) + RETURNING project_id""", + (project_id, self.tenant_id, self.user_id), + ).fetchone() + return deleted is not None + + def list_projects(self) -> list[dict[str, Any]]: + with self._connection() as conn: + return list(conn.execute( + """SELECT * FROM projects WHERE tenant_id=%s AND user_id=%s + ORDER BY updated_at DESC, name""", + (self.tenant_id, self.user_id), + ).fetchall()) + + def get_project(self, project_id: str) -> dict[str, Any] | None: + with self._connection() as conn: + return conn.execute( + "SELECT * FROM projects WHERE project_id=%s AND tenant_id=%s AND user_id=%s", + (project_id, self.tenant_id, self.user_id), + ).fetchone() + + def update_project_name(self, project_id: str, name: str) -> dict[str, Any] | None: + with self._connection() as conn: + return conn.execute( + """UPDATE projects SET name=%s, updated_at=%s + WHERE project_id=%s AND tenant_id=%s AND user_id=%s RETURNING *""", + (name, datetime.now(UTC), project_id, self.tenant_id, self.user_id), + ).fetchone() + + def create_thread_for_project(self, *, thread_id: str, project_id: str) -> dict[str, Any] | None: + now = datetime.now(UTC) + with self._connection() as conn: + with conn.transaction(): + project = conn.execute( + """SELECT * FROM projects WHERE project_id=%s AND tenant_id=%s AND user_id=%s + FOR UPDATE""", + (project_id, self.tenant_id, self.user_id), + ).fetchone() + if not project or not project.get("repo_url"): + return None + thread = conn.execute( + """INSERT INTO threads + (thread_id, tenant_id, user_id, title, repo_url, repo_owner, repo_name, + project_id, latest_run_status, created_at, updated_at) + VALUES (%s,%s,%s,'新会话',%s,%s,%s,%s,'pending',%s,%s) + RETURNING *""", + (thread_id, self.tenant_id, self.user_id, project["repo_url"], project["repo_owner"], + project["repo_name"], project_id, now, now), + ).fetchone() + conn.execute( + """INSERT INTO thread_drafts (thread_id, tenant_id, user_id, content, revision, updated_at) + VALUES (%s,%s,%s,'',1,%s)""", + (thread_id, self.tenant_id, self.user_id, now), + ) + return thread + + def get_thread_draft(self, thread_id: str) -> dict[str, Any] | None: + with self._connection() as conn: + thread = conn.execute( + "SELECT 1 FROM threads WHERE thread_id=%s AND tenant_id=%s AND user_id=%s", + (thread_id, self.tenant_id, self.user_id), + ).fetchone() + if not thread: + return None + return conn.execute( + "SELECT content, revision, updated_at FROM thread_drafts WHERE thread_id=%s", + (thread_id,), + ).fetchone() or {"content": "", "revision": 0, "updated_at": None} + + def save_thread_draft(self, *, thread_id: str, content: str) -> dict[str, Any] | None: + now = datetime.now(UTC) + with self._connection() as conn: + return conn.execute( + """INSERT INTO thread_drafts (thread_id, tenant_id, user_id, content, revision, updated_at) + SELECT thread_id, tenant_id, user_id, %s, 1, %s FROM threads + WHERE thread_id=%s AND tenant_id=%s AND user_id=%s + ON CONFLICT(thread_id) DO UPDATE SET content=EXCLUDED.content, + revision=thread_drafts.revision+1, updated_at=EXCLUDED.updated_at + RETURNING content, revision, updated_at""", + (content, now, thread_id, self.tenant_id, self.user_id), + ).fetchone() + def upsert_thread( self, *, @@ -324,6 +554,165 @@ def record_run(self, *, run_id: str, thread_id: str, status: str, error: str | N "status": status, "now": now, "finished_at": now if finished else None, "error": error}, ) + def enqueue_run(self, *, run_id: str, thread_id: str, payload: dict[str, Any]) -> None: + now = datetime.now(UTC) + with self._connection() as conn: + with conn.transaction(): + conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (thread_id,)) + active = conn.execute( + "SELECT 1 FROM runs WHERE thread_id=%s AND status IN ('queued','running','cancelling') LIMIT 1", + (thread_id,), + ).fetchone() + if active: + raise ValueError("this thread already has an active run") + conn.execute( + """INSERT INTO runs (run_id, thread_id, tenant_id, user_id, status, started_at, queued_at, payload) + VALUES (%s,%s,%s,%s,'queued',%s,%s,%s::jsonb)""", + (run_id, thread_id, self.tenant_id, self.user_id, now, now, self._json(payload)), + ) + + def get_run(self, thread_id: str, run_id: str) -> dict[str, Any] | None: + with self._connection() as conn: + row = conn.execute( + "SELECT * FROM runs WHERE thread_id=%s AND run_id=%s", (thread_id, run_id) + ).fetchone() + if row and row.get("payload") is not None: + row["payload"] = self._decode(row["payload"], {}) + return row + + def list_active_runs(self, *, limit: int = 50) -> list[dict[str, Any]]: + with self._connection() as conn: + return list(conn.execute( + """SELECT run_id, thread_id, status, queued_at, started_at FROM runs + WHERE status IN ('queued','running','cancelling') + ORDER BY COALESCE(queued_at, started_at), run_id LIMIT %s""", + (max(1, min(limit, 200)),), + ).fetchall()) + + def claim_next_run( + self, *, worker_id: str, ttl_seconds: int = 300, max_active: int | None = None + ) -> dict[str, Any] | None: + now = datetime.now(UTC) + with self._connection() as conn: + with conn.transaction(): + if max_active is not None: + # Serialize admission checks across API replicas so the + # configured concurrency limit is global, not per process. + conn.execute("SELECT pg_advisory_xact_lock(75486593)") + active = conn.execute( + "SELECT COUNT(*) AS count FROM runs WHERE status IN ('running','cancelling') AND worker_id IS NOT NULL" + ).fetchone() + if int(active["count"]) >= max_active: + return None + row = conn.execute( + """WITH candidate AS ( + SELECT run_id FROM runs + WHERE status='queued' AND payload IS NOT NULL AND cancel_requested=FALSE + ORDER BY queued_at, run_id + FOR UPDATE SKIP LOCKED LIMIT 1 + ) + UPDATE runs AS r SET status='running', worker_id=%s, + lease_expires_at=%s, heartbeat_at=%s, started_at=%s, attempt=r.attempt+1 + FROM candidate WHERE r.run_id=candidate.run_id + RETURNING r.*""", + (worker_id, now + timedelta(seconds=ttl_seconds), now, now), + ).fetchone() + if row and row.get("payload") is not None: + row["payload"] = self._decode(row["payload"], {}) + return row + + def request_run_cancel(self, *, thread_id: str, run_id: str) -> str | None: + with self._connection() as conn: + with conn.transaction(): + row = conn.execute( + """UPDATE runs SET + status=CASE WHEN status='queued' THEN 'cancelled' ELSE 'cancelling' END, + cancel_requested=TRUE, + finished_at=CASE WHEN status='queued' THEN NOW() ELSE finished_at END + WHERE thread_id=%s AND run_id=%s AND status IN ('queued','running','cancelling') + RETURNING status""", + (thread_id, run_id), + ).fetchone() + return row["status"] if row else None + + def is_run_cancel_requested(self, run_id: str) -> bool: + with self._connection() as conn: + row = conn.execute("SELECT cancel_requested FROM runs WHERE run_id=%s", (run_id,)).fetchone() + return bool(row and row["cancel_requested"]) + + def renew_run_lease(self, *, run_id: str, worker_id: str, ttl_seconds: int = 300) -> bool: + now = datetime.now(UTC) + with self._connection() as conn: + row = conn.execute( + """UPDATE runs SET heartbeat_at=%s, lease_expires_at=%s + WHERE run_id=%s AND worker_id=%s AND status IN ('running','cancelling') + RETURNING run_id""", + (now, now + timedelta(seconds=ttl_seconds), run_id, worker_id), + ).fetchone() + return row is not None + + def finish_queued_run(self, *, thread_id: str, run_id: str, status: str, error: str | None = None) -> bool: + if status not in {"completed", "failed", "cancelled", "interrupted"}: + raise ValueError(f"invalid terminal run status: {status}") + with self._connection() as conn: + row = conn.execute( + """UPDATE runs SET status=%s, error=%s, finished_at=NOW(), worker_id=NULL, + lease_expires_at=NULL, heartbeat_at=NULL WHERE thread_id=%s AND run_id=%s RETURNING run_id""", + (status, error, thread_id, run_id), + ).fetchone() + return row is not None + + def append_run_stream_event( + self, *, thread_id: str, run_id: str, event: str, payload: dict[str, Any] + ) -> int: + with self._connection() as conn: + row = conn.execute( + """INSERT INTO run_stream_events (thread_id, run_id, event, payload) + VALUES (%s,%s,%s,%s::jsonb) RETURNING seq""", + (thread_id, run_id, event, self._json(payload)), + ).fetchone() + return int(row["seq"]) + + def list_run_stream_events( + self, *, thread_id: str, run_id: str, after_seq: int = 0, limit: int = 200 + ) -> list[dict[str, Any]]: + with self._connection() as conn: + rows = list(conn.execute( + """SELECT seq, event, payload, created_at FROM run_stream_events + WHERE thread_id=%s AND run_id=%s AND seq>%s ORDER BY seq LIMIT %s""", + (thread_id, run_id, max(0, after_seq), max(1, min(limit, 1000))), + ).fetchall()) + for row in rows: + row["payload"] = self._decode(row.get("payload"), {}) + return rows + + def interrupt_stale_runs(self) -> list[str]: + with self._connection() as conn: + with conn.transaction(): + rows = list(conn.execute( + """UPDATE runs SET status='interrupted', error='Worker lease expired; retry explicitly', + finished_at=NOW(), worker_id=NULL, lease_expires_at=NULL, heartbeat_at=NULL + WHERE status IN ('running','cancelling') AND ( + (lease_expires_at IS NOT NULL AND lease_expires_at < NOW()) OR + (lease_expires_at IS NULL AND started_at < NOW() - INTERVAL '5 minutes') + ) RETURNING run_id, thread_id""" + ).fetchall()) + for row in rows: + conn.execute( + "UPDATE threads SET latest_run_status='interrupted', updated_at=NOW() WHERE thread_id=%s", + (row["thread_id"],), + ) + for row in rows: + self.append_run_stream_event( + thread_id=row["thread_id"], run_id=row["run_id"], event="error", + payload={"message": "Worker lease expired; this run was interrupted. Retry it explicitly."}, + ) + self.append_run_stream_event( + thread_id=row["thread_id"], run_id=row["run_id"], event="done", + payload={"status": "interrupted"}, + ) + return [row["run_id"] for row in rows] + def add_run_event(self, *, event_id: str, thread_id: str, kind: str, title: str, status: str, detail: str | None = None, run_id: str | None = None) -> None: now = datetime.now(UTC) with self._connection() as conn: @@ -446,7 +835,7 @@ def get_thread_intervention(self, intervention_id: str) -> dict[str, Any] | None return row def get_latest_active_thread_intervention(self, thread_id: str) -> dict[str, Any] | None: - """读取会话中最新待答复或正在恢复的人工介入。""" + """Return the newest pending or resuming intervention for a thread.""" with self._connection() as conn: row = conn.execute( @@ -504,7 +893,7 @@ def delete_thread(self, thread_id: str) -> bool: exists = conn.execute("SELECT 1 FROM threads WHERE thread_id=%s", (thread_id,)).fetchone() if not exists: return False - for table in ("review_findings", "thread_plans", "thread_interventions", "thread_messages", "run_events", "runs"): + for table in ("review_findings", "thread_plans", "thread_interventions", "thread_messages", "thread_drafts", "run_events", "run_stream_events", "runs"): conn.execute(f"DELETE FROM {table} WHERE thread_id=%s", (thread_id,)) conn.execute("DELETE FROM audit_events WHERE thread_id=%s", (thread_id,)) conn.execute("DELETE FROM threads WHERE thread_id=%s", (thread_id,)) diff --git a/agent/store/sqlite_store.py b/agent/store/sqlite_store.py index 0592165..f229799 100644 --- a/agent/store/sqlite_store.py +++ b/agent/store/sqlite_store.py @@ -1,9 +1,10 @@ from __future__ import annotations import json +import hashlib import sqlite3 import threading -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -59,6 +60,116 @@ def close(self) -> None: with self._lock: self._conn.close() + def create_project( + self, *, project_id: str, name: str, provider: str, repo_url: str, + repo_owner: str, repo_name: str, + ) -> dict[str, Any]: + now = utc_now() + with self._lock: + self._conn.execute( + """INSERT INTO projects + (project_id, name, provider, repo_url, repo_owner, repo_name, is_legacy, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?)""", + (project_id, name, provider, repo_url, repo_owner, repo_name, now, now), + ) + self._conn.commit() + return self.get_project(project_id) + + def create_chat_thread(self, *, thread_id: str) -> dict[str, Any]: + """Create a general chat thread without attaching it to a repository project.""" + self.upsert_thread(thread_id=thread_id, title="新聊天", latest_run_status="pending") + return self.get_thread(thread_id) + + def list_project_thread_ids(self, project_id: str) -> list[str]: + with self._lock: + rows = self._conn.execute( + "SELECT thread_id FROM threads WHERE project_id=? ORDER BY updated_at DESC", + (project_id,), + ).fetchall() + return [str(row["thread_id"]) for row in rows] + + def delete_project(self, project_id: str) -> bool: + with self._lock: + if self._conn.execute("SELECT 1 FROM projects WHERE project_id=?", (project_id,)).fetchone() is None: + return False + if self._conn.execute("SELECT 1 FROM threads WHERE project_id=? LIMIT 1", (project_id,)).fetchone(): + return False + self._conn.execute("DELETE FROM projects WHERE project_id=?", (project_id,)) + self._conn.commit() + return True + + def list_projects(self) -> list[dict[str, Any]]: + with self._lock: + return [dict(row) for row in self._conn.execute( + "SELECT * FROM projects ORDER BY updated_at DESC, name COLLATE NOCASE" + ).fetchall()] + + def get_project(self, project_id: str) -> dict[str, Any] | None: + with self._lock: + return self._row_to_dict(self._conn.execute( + "SELECT * FROM projects WHERE project_id=?", (project_id,) + ).fetchone()) + + def update_project_name(self, project_id: str, name: str) -> dict[str, Any] | None: + with self._lock: + self._conn.execute( + "UPDATE projects SET name=?, updated_at=? WHERE project_id=?", + (name, utc_now(), project_id), + ) + self._conn.commit() + return self.get_project(project_id) + + def create_thread_for_project(self, *, thread_id: str, project_id: str) -> dict[str, Any] | None: + now = utc_now() + with self._lock: + project = self._conn.execute( + "SELECT * FROM projects WHERE project_id=?", (project_id,) + ).fetchone() + if not project or not project["repo_url"]: + return None + self._conn.execute( + """INSERT INTO threads + (thread_id, title, repo_url, repo_owner, repo_name, project_id, + latest_run_status, created_at, updated_at) + VALUES (?, '新会话', ?, ?, ?, ?, 'pending', ?, ?)""", + (thread_id, project["repo_url"], project["repo_owner"], project["repo_name"], project_id, now, now), + ) + self._conn.execute( + "INSERT INTO thread_drafts (thread_id, content, revision, updated_at) VALUES (?, '', 1, ?)", + (thread_id, now), + ) + self._conn.commit() + return self.get_thread(thread_id) + + def get_thread_draft(self, thread_id: str) -> dict[str, Any] | None: + with self._lock: + exists = self._conn.execute("SELECT 1 FROM threads WHERE thread_id=?", (thread_id,)).fetchone() + if not exists: + return None + return self._row_to_dict(self._conn.execute( + "SELECT content, revision, updated_at FROM thread_drafts WHERE thread_id=?", + (thread_id,), + ).fetchone()) or {"content": "", "revision": 0, "updated_at": None} + + def save_thread_draft(self, *, thread_id: str, content: str) -> dict[str, Any] | None: + now = utc_now() + with self._lock: + exists = self._conn.execute("SELECT 1 FROM threads WHERE thread_id=?", (thread_id,)).fetchone() + if not exists: + return None + self._conn.execute( + """INSERT INTO thread_drafts (thread_id, content, revision, updated_at) + VALUES (?, ?, 1, ?) + ON CONFLICT(thread_id) DO UPDATE SET content=excluded.content, + revision=thread_drafts.revision+1, updated_at=excluded.updated_at""", + (thread_id, content, now), + ) + self._conn.commit() + return self._row_to_dict(self._conn.execute( + "SELECT content, revision, updated_at FROM thread_drafts WHERE thread_id=?", + (thread_id,), + ).fetchone()) + def _init_schema(self) -> None: """初始化业务表。 @@ -69,6 +180,18 @@ def _init_schema(self) -> None: with self._lock: self._conn.executescript( """ + CREATE TABLE IF NOT EXISTS projects ( + project_id TEXT PRIMARY KEY, + name TEXT NOT NULL, + provider TEXT, + repo_url TEXT, + repo_owner TEXT, + repo_name TEXT, + is_legacy INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS threads ( thread_id TEXT PRIMARY KEY, title TEXT NOT NULL, @@ -76,6 +199,7 @@ def _init_schema(self) -> None: repo_url TEXT, repo_owner TEXT, repo_name TEXT, + project_id TEXT, branch_name TEXT, pr_url TEXT, latest_run_status TEXT NOT NULL, @@ -83,6 +207,14 @@ def _init_schema(self) -> None: updated_at TEXT NOT NULL ); + CREATE TABLE IF NOT EXISTS thread_drafts ( + thread_id TEXT PRIMARY KEY, + content TEXT NOT NULL DEFAULT '', + revision INTEGER NOT NULL DEFAULT 1, + updated_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_projects_updated ON projects(updated_at DESC); + CREATE TABLE IF NOT EXISTS runs ( run_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, @@ -90,9 +222,27 @@ def _init_schema(self) -> None: started_at TEXT NOT NULL, finished_at TEXT, error TEXT, + worker_id TEXT, + lease_expires_at TEXT, + heartbeat_at TEXT, + attempt INTEGER NOT NULL DEFAULT 0, + payload TEXT, + queued_at TEXT, + cancel_requested INTEGER NOT NULL DEFAULT 0, FOREIGN KEY(thread_id) REFERENCES threads(thread_id) ); + CREATE TABLE IF NOT EXISTS run_stream_events ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, + thread_id TEXT NOT NULL, + run_id TEXT NOT NULL, + event TEXT NOT NULL, + payload TEXT NOT NULL, + created_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_run_stream_events_run_seq + ON run_stream_events(thread_id, run_id, seq); + CREATE TABLE IF NOT EXISTS run_events ( id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, @@ -167,6 +317,22 @@ def _init_schema(self) -> None: """ ) self._ensure_column("threads", "user_prompt", "TEXT") + self._ensure_column("threads", "project_id", "TEXT") + self._conn.execute( + "CREATE INDEX IF NOT EXISTS idx_threads_project_updated ON threads(project_id, updated_at DESC)" + ) + self._ensure_column("runs", "worker_id", "TEXT") + self._ensure_column("runs", "lease_expires_at", "TEXT") + self._ensure_column("runs", "heartbeat_at", "TEXT") + self._ensure_column("runs", "attempt", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("runs", "payload", "TEXT") + self._ensure_column("runs", "queued_at", "TEXT") + self._ensure_column("runs", "cancel_requested", "INTEGER NOT NULL DEFAULT 0") + self._conn.execute( + """CREATE INDEX IF NOT EXISTS idx_runs_queue_claim + ON runs(queued_at, run_id) + WHERE status='queued' AND payload IS NOT NULL AND cancel_requested=0""" + ) self._ensure_column("run_events", "run_id", "TEXT") self._conn.execute( "CREATE INDEX IF NOT EXISTS idx_run_events_thread_run_created " @@ -175,8 +341,36 @@ def _init_schema(self) -> None: self._ensure_column("thread_plans", "version", "INTEGER NOT NULL DEFAULT 1") self._ensure_column("thread_plans", "supersedes_plan_id", "TEXT") self._ensure_column("thread_plans", "decision_feedback", "TEXT") + self._backfill_legacy_projects() self._conn.commit() + def _backfill_legacy_projects(self) -> None: + rows = self._conn.execute( + """SELECT thread_id, title, repo_url, repo_owner, repo_name, created_at, updated_at + FROM threads WHERE project_id IS NULL ORDER BY created_at, thread_id""" + ).fetchall() + for row in rows: + repo_url = str(row["repo_url"] or "").strip() + if repo_url: + lowered = repo_url.lower().rstrip("/") + provider = "github" if "github.com/" in lowered else "gitee" if "gitee.com/" in lowered else None + identity = f"{provider or 'legacy'}:{lowered.removesuffix('.git')}" + else: + provider = None + identity = f"thread:{row['thread_id']}" + project_id = "legacy-" + hashlib.sha256(identity.encode("utf-8")).hexdigest()[:32] + repo_label = "/".join(part for part in (row["repo_owner"], row["repo_name"]) if part) + project_name = repo_label or f"历史会话 · {str(row['title'] or '未命名')[:48]}" + created_at = row["created_at"] or utc_now() + updated_at = row["updated_at"] or created_at + self._conn.execute( + """INSERT OR IGNORE INTO projects + (project_id, name, provider, repo_url, repo_owner, repo_name, is_legacy, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)""", + (project_id, project_name, provider, repo_url or None, row["repo_owner"], row["repo_name"], created_at, updated_at), + ) + self._conn.execute("UPDATE threads SET project_id=? WHERE thread_id=?", (project_id, row["thread_id"])) + @staticmethod def _row_to_dict(row: sqlite3.Row | None) -> dict[str, Any] | None: return dict(row) if row is not None else None @@ -318,6 +512,192 @@ def record_run( ) self._conn.commit() + def enqueue_run(self, *, run_id: str, thread_id: str, payload: dict[str, Any]) -> None: + now = utc_now() + with self._lock: + self._conn.execute("BEGIN IMMEDIATE") + try: + active = self._conn.execute( + "SELECT 1 FROM runs WHERE thread_id=? AND status IN ('queued','running','cancelling') LIMIT 1", + (thread_id,), + ).fetchone() + if active: + raise ValueError("this thread already has an active run") + self._conn.execute( + """INSERT INTO runs (run_id, thread_id, status, started_at, queued_at, payload) + VALUES (?, ?, 'queued', ?, ?, ?)""", + (run_id, thread_id, now, now, json.dumps(payload, ensure_ascii=False)), + ) + self._conn.commit() + except Exception: + self._conn.rollback() + raise + + def get_run(self, thread_id: str, run_id: str) -> dict[str, Any] | None: + with self._lock: + row = self._conn.execute( + "SELECT * FROM runs WHERE thread_id=? AND run_id=?", (thread_id, run_id) + ).fetchone() + result = dict(row) if row else None + if result and result.get("payload"): + result["payload"] = json.loads(result["payload"]) + return result + + def list_active_runs(self, *, limit: int = 50) -> list[dict[str, Any]]: + with self._lock: + rows = self._conn.execute( + """SELECT run_id, thread_id, status, queued_at, started_at + FROM runs WHERE status IN ('queued','running','cancelling') + ORDER BY COALESCE(queued_at, started_at), run_id LIMIT ?""", + (max(1, min(limit, 200)),), + ).fetchall() + return [dict(row) for row in rows] + + def claim_next_run( + self, *, worker_id: str, ttl_seconds: int = 300, max_active: int | None = None + ) -> dict[str, Any] | None: + now = datetime.now(UTC) + expires = (now + timedelta(seconds=ttl_seconds)).isoformat() + with self._lock: + self._conn.execute("BEGIN IMMEDIATE") + try: + if max_active is not None: + active = self._conn.execute( + "SELECT COUNT(*) FROM runs WHERE status IN ('running','cancelling') AND worker_id IS NOT NULL" + ).fetchone()[0] + if int(active) >= max_active: + self._conn.commit() + return None + row = self._conn.execute( + """SELECT run_id FROM runs WHERE status='queued' AND payload IS NOT NULL + AND cancel_requested=0 ORDER BY queued_at, run_id LIMIT 1""" + ).fetchone() + if row is None: + self._conn.commit() + return None + self._conn.execute( + """UPDATE runs SET status='running', worker_id=?, lease_expires_at=?, + heartbeat_at=?, started_at=?, attempt=attempt+1 WHERE run_id=? AND status='queued'""", + (worker_id, expires, now.isoformat(), now.isoformat(), row["run_id"]), + ) + claimed = self._conn.execute("SELECT * FROM runs WHERE run_id=?", (row["run_id"],)).fetchone() + self._conn.commit() + except Exception: + self._conn.rollback() + raise + result = dict(claimed) + result["payload"] = json.loads(result["payload"]) + return result + + def request_run_cancel(self, *, thread_id: str, run_id: str) -> str | None: + now = utc_now() + with self._lock: + row = self._conn.execute( + "SELECT status FROM runs WHERE thread_id=? AND run_id=?", (thread_id, run_id) + ).fetchone() + if not row or row["status"] not in {"queued", "running", "cancelling"}: + return None + status = "cancelled" if row["status"] == "queued" else "cancelling" + self._conn.execute( + """UPDATE runs SET status=?, cancel_requested=1, + finished_at=CASE WHEN ?='cancelled' THEN ? ELSE finished_at END + WHERE thread_id=? AND run_id=?""", + (status, status, now, thread_id, run_id), + ) + self._conn.commit() + return status + + def is_run_cancel_requested(self, run_id: str) -> bool: + with self._lock: + row = self._conn.execute( + "SELECT cancel_requested FROM runs WHERE run_id=?", (run_id,) + ).fetchone() + return bool(row and row["cancel_requested"]) + + def renew_run_lease(self, *, run_id: str, worker_id: str, ttl_seconds: int = 300) -> bool: + now = datetime.now(UTC) + with self._lock: + cursor = self._conn.execute( + """UPDATE runs SET heartbeat_at=?, lease_expires_at=? + WHERE run_id=? AND worker_id=? AND status IN ('running','cancelling')""", + (now.isoformat(), (now + timedelta(seconds=ttl_seconds)).isoformat(), run_id, worker_id), + ) + self._conn.commit() + return cursor.rowcount == 1 + + def finish_queued_run(self, *, thread_id: str, run_id: str, status: str, error: str | None = None) -> bool: + if status not in {"completed", "failed", "cancelled", "interrupted"}: + raise ValueError(f"invalid terminal run status: {status}") + with self._lock: + cursor = self._conn.execute( + """UPDATE runs SET status=?, error=?, finished_at=?, worker_id=NULL, + lease_expires_at=NULL, heartbeat_at=NULL WHERE thread_id=? AND run_id=?""", + (status, error, utc_now(), thread_id, run_id), + ) + self._conn.commit() + return cursor.rowcount == 1 + + def append_run_stream_event( + self, *, thread_id: str, run_id: str, event: str, payload: dict[str, Any] + ) -> int: + with self._lock: + cursor = self._conn.execute( + """INSERT INTO run_stream_events (thread_id, run_id, event, payload, created_at) + VALUES (?, ?, ?, ?, ?)""", + (thread_id, run_id, event, json.dumps(payload, ensure_ascii=False), utc_now()), + ) + self._conn.commit() + return int(cursor.lastrowid) + + def list_run_stream_events( + self, *, thread_id: str, run_id: str, after_seq: int = 0, limit: int = 200 + ) -> list[dict[str, Any]]: + with self._lock: + rows = self._conn.execute( + """SELECT seq, event, payload, created_at FROM run_stream_events + WHERE thread_id=? AND run_id=? AND seq>? ORDER BY seq LIMIT ?""", + (thread_id, run_id, max(0, after_seq), max(1, min(limit, 1000))), + ).fetchall() + result = [dict(row) for row in rows] + for row in result: + row["payload"] = json.loads(row["payload"]) + return result + + def interrupt_stale_runs(self) -> list[str]: + now = datetime.now(UTC).isoformat() + stale_without_lease_before = (datetime.now(UTC) - timedelta(minutes=5)).isoformat() + with self._lock: + rows = self._conn.execute( + """SELECT run_id, thread_id FROM runs WHERE status IN ('running','cancelling') + AND ((lease_expires_at IS NOT NULL AND lease_expires_at < ?) + OR (lease_expires_at IS NULL AND started_at < ?))""", + (now, stale_without_lease_before), + ).fetchall() + self._conn.execute( + """UPDATE runs SET status='interrupted', error='Worker lease expired; retry explicitly', + finished_at=?, worker_id=NULL, lease_expires_at=NULL, heartbeat_at=NULL + WHERE status IN ('running','cancelling') AND ( + (lease_expires_at IS NOT NULL AND lease_expires_at < ?) + OR (lease_expires_at IS NULL AND started_at < ?) + )""", + (now, now, stale_without_lease_before), + ) + for row in rows: + self._conn.execute( + "UPDATE threads SET latest_run_status='interrupted', updated_at=? WHERE thread_id=?", + (now, row["thread_id"]), + ) + self._conn.commit() + for row in rows: + self.append_run_stream_event( + thread_id=row["thread_id"], run_id=row["run_id"], event="error", + payload={"message": "Worker lease expired; this run was interrupted. Retry it explicitly."}, + ) + self.append_run_stream_event( + thread_id=row["thread_id"], run_id=row["run_id"], event="done", payload={"status": "interrupted"} + ) + return [row["run_id"] for row in rows] + def add_run_event( self, *, @@ -716,7 +1096,9 @@ def delete_thread(self, thread_id: str) -> bool: self._conn.execute("DELETE FROM thread_plans WHERE thread_id = ?", (thread_id,)) self._conn.execute("DELETE FROM thread_interventions WHERE thread_id = ?", (thread_id,)) self._conn.execute("DELETE FROM thread_messages WHERE thread_id = ?", (thread_id,)) + self._conn.execute("DELETE FROM thread_drafts WHERE thread_id = ?", (thread_id,)) self._conn.execute("DELETE FROM run_events WHERE thread_id = ?", (thread_id,)) + self._conn.execute("DELETE FROM run_stream_events WHERE thread_id = ?", (thread_id,)) self._conn.execute("DELETE FROM runs WHERE thread_id = ?", (thread_id,)) self._conn.execute("DELETE FROM threads WHERE thread_id = ?", (thread_id,)) self._conn.commit() diff --git a/docs/MULTI_TASK_HARNESS_IMPLEMENTATION_PLAN.md b/docs/MULTI_TASK_HARNESS_IMPLEMENTATION_PLAN.md new file mode 100644 index 0000000..820f04b --- /dev/null +++ b/docs/MULTI_TASK_HARNESS_IMPLEMENTATION_PLAN.md @@ -0,0 +1,95 @@ +# 多任务并行 Harness 实施方案 + +日期:2026-09-27 + +## 目标 + +在现有 CODING 项目中实现单用户、单机可用的 Codex 式任务管理:用户可以同时提交多个独立任务、在任务间切换,任务在后台继续运行;刷新或短暂断线后能恢复状态和输出;一个任务的文件修改不影响另一个任务。 + +第一阶段以现有 PostgreSQL 和 node2 上的 OpenSandbox 为基础,不额外引入 Redis。队列、运行状态与可续接事件先由 PostgreSQL 承担。运行并发受显式配置限制;以后多 API/Worker 主机或更高吞吐量时,再将队列和事件总线迁移至 Redis Streams 或专用队列。 + +## 当前基线 + +- Dashboard 每个 POST SSE 请求启动一个 API 进程内线程;SSE 通过进程内队列消费。 +- UI 只有一份当前会话和 streaming 状态;切换会话会 abort 请求。 +- 多会话虽有不同 Git 分支名,但使用同一个仓库检出目录,不能安全并行写。 +- 已有业务 PostgreSQL Store、LangGraph PostgreSQL checkpointer、run 事件、worker lease 和 stale-run recovery 原语;lease 当前只标识 run 所属 worker,没有队列调度、全局并发限额或仓库隔离作用。 +- 普通 Agent 运行当前绑定 LocalShellBackend;OpenSandbox 适配器仅用于 Eval。 + +## 目标结构 + +```mermaid +flowchart LR + UI[多任务 Dashboard] -->|提交 / 取消| API[FastAPI] + UI -->|SSE 重连,run_id + cursor| API + API -->|持久化 job 与事件| PG[(PostgreSQL)] + W[有界 Agent Workers] -->|SKIP LOCKED 领取任务| PG + W -->|每次 run 一个执行环境| OS[OpenSandbox] + OS -->|仅该任务的 Git diff / artifacts| W + W -->|事件、状态、checkpoint| PG +``` + +## 实施阶段 + +### 1. 持久任务与事件数据层 + +- 为 run 增加可排队输入、领取/租约、取消请求和 attempt 元数据;保留旧 runs 行并使用增量 schema migration。 +- 增加按 run 单调排序的 `run_stream_events`,保存全部前端事件 payload,使 SSE 可从 cursor 重放。 +- 为 PostgreSQL 实现原子 `claim_next_run`(短事务、`FOR UPDATE SKIP LOCKED`);为 SQLite 提供测试及本地开发实现。 +- 在线程内保持顺序:同一 thread 仅允许运行一个 Agent turn;不同 thread 可并行。 + +### 2. 有界 Worker 与恢复 + +- POST 请求只创建 thread/run、写入 prompt 和 queued 状态,不在 API handler 中跑 Agent。 +- Worker 数由 `AGENT_MAX_CONCURRENT_RUNS` 控制;worker 领取任务后更新心跳,完成、失败、取消均写终态。 +- 进程重启时保留 queued 任务;过期 running lease 标记为 interrupted,由用户显式重试,避免重复执行已有外部副作用。 +- 取消采用协作式信号,在 Agent event/tool 边界检查;queued 任务可立即取消,运行中任务发出取消请求并尽快收敛。 + +### 3. 每任务隔离工作区与 OpenSandbox + +- 为 thread 建立稳定独立 checkout;同一 thread 的连续轮次复用 checkout,不同 thread 永不共享可写目录。 +- 每个 run 建立独立 OpenSandbox,上传当前 thread checkout 和必要的只读 skills/policies;所有 Agent 文件与命令工具都绑定该沙箱。 +- run 结束时导出二进制 diff,在 host 侧对应 thread checkout 内校验并应用;保留可审阅的分支/patch。禁止沙箱访问其他任务目录和宿主凭证。 +- 沙箱创建失败时任务失败并清理,不静默退回宿主机执行。 + +### 4. API 与多任务 UI + +- 保留现有提交入口,增加 run status、按 cursor 续接 SSE、取消 run 的 API。 +- Pinia 状态按 `thread_id`/`run_id` 保存;切换会话只切换视图,不 abort 后台任务。 +- 左侧任务列表展示排队/运行/等待用户/完成/失败状态;增加活跃任务条,方便一键切回任务。 +- 首次加载时读取活跃 runs 并重连 SSE;终态仍可从 thread 历史和 run 事件恢复。 +- 每个 thread 的输入可独立忙碌/取消;新建任务不受其他 thread 正在运行的影响。 + +组件边界:`AgentWorkspace.vue` 继续负责当前会话布局与输入;新增 `ActiveTaskStrip.vue` 只展示活跃 thread 并发出 select 事件;`SessionSidebar.vue` 继续展示全量 thread 与状态,允许运行中切换和新建;Pinia store 按 thread/run 保存消息、游标、控制器与状态。 + +### 5. 验收与风险收敛 + +- SQLite 单测覆盖 schema 兼容、并发领取互斥、run 排序、事件游标重放、取消、lease 恢复和独立任务工作区。 +- node2 PostgreSQL 集成测试使用唯一测试前缀并在结束后删除本轮创建的测试行,不清库、不删现有表。 +- node2 OpenSandbox E2E 创建临时沙箱,验证上传、文件读写、命令执行、diff 回传和资源销毁。 +- 模拟两个不同 thread 同时运行,确认两边可并行、事件互不串流、文件不互相可见;同一 thread 并发提交应被串行或明确拒绝。 +- 前端执行 Vite production build;后端执行相关单测和真实依赖集成验证。 + +## 当前实施结果 + +- 已实现 PostgreSQL/SQLite 持久队列、有界 worker、跨 API 进程全局并发准入、同 thread 单运行、协作取消、心跳和事件游标重放。 +- queued run 在重启后保留;lease 过期的 running run 变成 `interrupted`,等待用户显式重试,避免副作用任务自动重放。 +- Dashboard 支持任务间切换、活跃任务条、取消、后台持续运行和按 SSE cursor 恢复;仓库 clone 路径按 thread 隔离。 +- 已实现可选 `CODING_AGENT_RUNTIME_BACKEND=opensandbox`:每 run 建沙箱,只上传该 thread checkout 与 skills/policies,导出并校验 patch,再销毁沙箱。运行时默认保持 `local`,因为 node2 当前默认镜像缺 Node/npm,尝试使用公开 Python+Node 镜像时被该 OpenSandbox 服务的镜像 allowlist 拒绝;apt 安装在沙箱命令限时内未完成。Python 仓库可单独启用;全栈运行需 node2 管理员将可信的 Python+Node 镜像加入 allowlist,并配置 `OPEN_SANDBOX_IMAGE` 后再启用。 +- node2 OpenSandbox 默认镜像下已验证 sandbox 创建、上传、Python/Git 命令、tracked/untracked patch 导出和销毁;真实 PostgreSQL queue 集成测试结束后删除了所有 probe 行。 +- 回归结果:`tests/unit` 149 项通过;队列/SSE 专项共 7 项通过;`npm run build` 通过。真实 PostgreSQL 队列生命周期通过并清理 probe 行。外部模型服务上的完整 Agent 任务未在回归中自动触发,以免产生真实模型计费或远端 Git/PR 副作用。 + +## 可借鉴实现 + +- [Codex app:并行 threads 与隔离 worktrees](https://openai.com/index/introducing-the-codex-app/);[Codex 长任务:外化状态、计划、观察与修复循环](https://developers.openai.com/blog/run-long-horizon-tasks-with-codex)。 +- [OpenHands Runtime architecture](https://github.com/OpenHands/docs/blob/main/openhands/usage/architecture/runtime.mdx):每个 session 使用隔离 runtime;[Agent Server architecture](https://github.com/OpenHands/docs/blob/main/sdk/arch/agent-server.mdx):应用服务与执行 runtime 分层。 +- [PostgreSQL SELECT / `SKIP LOCKED`](https://www.postgresql.org/docs/current/sql-select.html):适合多个消费者领取队列行;领取事务保持短,不持有长任务锁。 +- [PGMQ](https://github.com/pgmq/pgmq):提供 visibility timeout、ack/archive 等成熟队列概念;当前 node2 未预设 PGMQ extension,因此第一阶段直接使用现有 PostgreSQL 表与 lease,避免引入扩展依赖。 +- 全栈沙箱镜像参考:[Microsoft Dev Containers JavaScript/Node image](https://github.com/devcontainers/images/blob/main/src/javascript-node/README.md);[Python + Node image project](https://github.com/nikolaik/docker-python-nodejs)。部署时使用经审查、固定 tag/digest 且已纳入 OpenSandbox allowlist 的镜像。 + +## 设计约束 + +- 不复用或清空 node2 现有数据库;迁移只做兼容性增列/建表。 +- OpenSandbox 可以按配置成为 Agent 执行路径;健康检查成功不等于容量测试通过,镜像能力也必须匹配项目技术栈。 +- 工作区隔离是正确性的先决条件,不能以 UI 多开窗口替代。 +- 重启恢复不重复提交相同 thread 的 LangGraph turn;只有未开始或明确可重试的任务可以重排。 diff --git a/tests/unit/test_durable_run_stream.py b/tests/unit/test_durable_run_stream.py new file mode 100644 index 0000000..d7a7041 --- /dev/null +++ b/tests/unit/test_durable_run_stream.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import asyncio + +from agent.api import dashboard_routes +from agent.core import run_queue +from agent.store.sqlite_store import LocalSqliteStore + + +def test_post_run_stream_is_durable_and_can_resume_from_event_cursor(tmp_path, monkeypatch): + store = LocalSqliteStore(tmp_path / "stream.sqlite") + + def initialize(*, repo_url, prompt, thread_id, **_kwargs): + store.upsert_thread( + thread_id=thread_id, title=prompt, user_prompt=prompt, repo_url=repo_url, + repo_owner="owner", repo_name="repo", latest_run_status="running", + ) + return thread_id + + monkeypatch.setattr(dashboard_routes, "get_store", lambda: store) + monkeypatch.setattr(dashboard_routes, "initialize_task_record", initialize) + monkeypatch.setattr(dashboard_routes, "get_task", lambda thread_id: store.get_thread(thread_id)) + monkeypatch.setattr( + dashboard_routes, "_thread_meta_payload", + lambda thread: {"id": thread["thread_id"], "title": thread["title"], "status": "queued"}, + ) + monkeypatch.setattr(run_queue, "get_store", lambda: store) + + def fake_run_agent_task(*, repo_url, prompt, thread_id, run_id, event_sink, **_kwargs): + del repo_url + event_sink("message_start", {"message_id": "assistant", "author": "agent"}) + event_sink("text_delta", {"message_id": "assistant", "content": prompt}) + store.record_run(run_id=run_id, thread_id=thread_id, status="completed", finished=True) + store.update_thread_status(thread_id, "completed") + return {"thread_id": thread_id, "run_id": run_id, "status": "completed"} + + monkeypatch.setattr(run_queue, "run_agent_task", fake_run_agent_task) + pool = run_queue.RunWorkerPool(concurrency=1, lease_seconds=30) + thread_id = "durable-stream-probe" + pool.start() + try: + response = dashboard_routes._post_streaming_response( + thread_id=thread_id, repo_url="https://github.com/owner/repo.git", content="persist me" + ) + + async def collect(response): + chunks = [] + async for chunk in response.body_iterator: + chunks.append(chunk.decode() if isinstance(chunk, bytes) else str(chunk)) + return "".join(chunks) + + body = asyncio.run(collect(response)) + # Completed runs are no longer active; derive the run id from its event rows. + rows = store._conn.execute( + "SELECT DISTINCT run_id FROM run_stream_events WHERE thread_id=?", (thread_id,) + ).fetchall() + run_id = rows[0]["run_id"] + assert "event: text_delta" in body and "persist me" in body + assert "id: " in body and body.rstrip().endswith("}") + + resumed = asyncio.run(dashboard_routes.dashboard_resume_run_stream(thread_id, run_id, after=7)) + resumed_body = asyncio.run(collect(resumed)) + assert "event: done" in resumed_body + assert "persist me" not in resumed_body + assert store.get_run(thread_id, run_id)["status"] == "completed" + finally: + pool.stop() + store.close() + + +def test_repository_free_chat_uses_durable_queue_and_persists_reply(tmp_path, monkeypatch): + store = LocalSqliteStore(tmp_path / "plain-chat-stream.sqlite") + monkeypatch.setattr(dashboard_routes, "get_store", lambda: store) + monkeypatch.setattr(run_queue, "get_store", lambda: store) + monkeypatch.setattr(dashboard_routes, "_normalize_dashboard_model_id", lambda value: value or "deepseek-flash") + monkeypatch.setattr(dashboard_routes, "_thread_payload", lambda thread: { + "id": thread["thread_id"], "title": thread["title"], "chatOnly": True, + }) + monkeypatch.setattr(dashboard_routes, "_thread_meta_payload", lambda thread: { + "id": thread["thread_id"], "title": thread["title"], "status": "queued", + }) + monkeypatch.setattr(dashboard_routes, "get_task", lambda thread_id: store.get_thread(thread_id)) + + def fake_chat_task(*, thread_id, run_id, model_id, event_sink): + assert model_id == "deepseek-v4-pro" + event_sink("message_start", {"message_id": f"assistant-{run_id}", "author": "agent"}) + event_sink("text_delta", {"message_id": f"assistant-{run_id}", "content": "无仓库回答"}) + store.add_thread_message( + message_id=f"assistant-{run_id}", thread_id=thread_id, run_id=run_id, + author="agent", content="无仓库回答", metadata={"model_id": model_id}, + ) + store.update_thread_status(thread_id, "completed") + return {"status": "completed"} + + monkeypatch.setattr(run_queue, "run_plain_chat_task", fake_chat_task) + pool = run_queue.RunWorkerPool(concurrency=1, lease_seconds=30) + pool.start() + try: + response = asyncio.run(dashboard_routes.dashboard_stream_new_message( + dashboard_routes.DashboardThreadMessageRequest( + content="请解释异步队列", model_id="deepseek-v4-pro", + ) + )) + + async def collect(): + chunks = [] + async for chunk in response.body_iterator: + chunks.append(chunk.decode() if isinstance(chunk, bytes) else str(chunk)) + return "".join(chunks) + + body = asyncio.run(collect()) + row = store._conn.execute("SELECT thread_id, run_id FROM runs LIMIT 1").fetchone() + run = store.get_run(row["thread_id"], row["run_id"]) + assert run["status"] == "completed" + assert run["payload"]["chat_only"] is True + assert run["payload"]["repo_url"] is None + assert "无仓库回答" in body + assert store.get_thread(row["thread_id"])["project_id"] is None + assert [item["content"] for item in store.list_thread_messages(row["thread_id"])] == [ + "请解释异步队列", "无仓库回答", + ] + finally: + pool.stop() + store.close() diff --git a/tests/unit/test_model_selection.py b/tests/unit/test_model_selection.py index f554e89..6f90093 100644 --- a/tests/unit/test_model_selection.py +++ b/tests/unit/test_model_selection.py @@ -17,6 +17,7 @@ def test_dashboard_model_defaults_to_configured_model(monkeypatch): def test_dashboard_rejects_model_not_exposed_by_configuration(monkeypatch): monkeypatch.setattr(dashboard_routes, "get_env", lambda _name, default: "deepseek-flash") + monkeypatch.setattr(model, "get_env", lambda name, default: "deepseek-flash" if name == "MAIN_MODEL" else "deepseek-flash") with pytest.raises(HTTPException) as exc_info: dashboard_routes._normalize_dashboard_model_id("deepseek-v4-pro") @@ -38,10 +39,30 @@ def test_main_model_factory_rejects_unconfigured_model(monkeypatch): monkeypatch.setattr(model, "get_env", lambda _name, default: "deepseek-flash") monkeypatch.setattr(model, "init_chat_model", lambda **_kwargs: pytest.fail("must not initialize")) - with pytest.raises(ValueError, match="MAIN_MODEL"): + with pytest.raises(ValueError, match="AGENT_AVAILABLE_MODELS"): model.make_main_model("unconfigured-model") +def test_model_allow_list_always_includes_default_and_deduplicates(monkeypatch): + monkeypatch.setattr(model, "get_env", lambda name, default: { + "MAIN_MODEL": "deepseek-flash", "AGENT_AVAILABLE_MODELS": "deepseek-v4-pro, deepseek-flash,deepseek-v4-pro", + }.get(name, default)) + + assert model.available_agent_models() == ["deepseek-flash", "deepseek-v4-pro"] + + +def test_dashboard_options_exposes_server_model_allow_list(monkeypatch): + monkeypatch.setattr(dashboard_routes, "get_env", lambda name, default: "deepseek-flash" if name == "MAIN_MODEL" else default) + monkeypatch.setattr(model, "get_env", lambda name, default: { + "MAIN_MODEL": "deepseek-flash", "AGENT_AVAILABLE_MODELS": "deepseek-v4-pro", + }.get(name, default)) + + options = dashboard_routes.dashboard_options() + + assert [item["id"] for item in options["models"]] == ["deepseek-flash", "deepseek-v4-pro"] + assert options["default_agent_model"] == "deepseek-flash" + + def test_runtime_passes_model_id_to_agent_config(monkeypatch): observed = {} monkeypatch.setattr(runtime, "get_agent", lambda config: observed.update(config) or "agent") diff --git a/tests/unit/test_plain_chat.py b/tests/unit/test_plain_chat.py new file mode 100644 index 0000000..f2bd8af --- /dev/null +++ b/tests/unit/test_plain_chat.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from agent.store.sqlite_store import LocalSqliteStore + + +def test_plain_chat_streams_and_persists_assistant_reply(tmp_path: Path, monkeypatch) -> None: + import agent.core.runtime as runtime + + store = LocalSqliteStore(tmp_path / "chat.sqlite") + thread = store.create_chat_thread(thread_id="chat") + store.add_thread_message(message_id="u1", thread_id="chat", author="user", content="第一轮", run_id="r1") + emitted = [] + + class Chunk: + def __init__(self, content): self.content = content + + class FakeModel: + def stream(self, messages): + assert any(getattr(message, "content", "") == "第一轮" for message in messages) + yield Chunk("并发") + yield Chunk([{"type": "text", "text": "完成"}]) + + monkeypatch.setattr(runtime, "get_store", lambda: store) + monkeypatch.setattr("agent.core.model.make_main_model", lambda _model_id: FakeModel()) + try: + result = runtime.run_plain_chat_task( + thread_id=thread["thread_id"], run_id="run-1", model_id="deepseek-flash", + event_sink=lambda event, payload: emitted.append((event, payload)), + ) + assert result["status"] == "completed" + assert result["content"] == "并发完成" + assert [payload["content"] for event, payload in emitted if event == "text_delta"] == ["并发", "完成"] + persisted = store.list_thread_messages("chat") + assert persisted[-1]["content"] == "并发完成" + assert persisted[-1]["metadata"]["model_id"] == "deepseek-flash" + assert store.get_thread("chat")["latest_run_status"] == "completed" + finally: + store.close() + + +def test_plain_chat_rejects_project_bound_threads(tmp_path: Path, monkeypatch) -> None: + import agent.core.runtime as runtime + + store = LocalSqliteStore(tmp_path / "chat.sqlite") + project = store.create_project( + project_id="p", name="Project", provider="github", repo_url="https://github.com/a/b.git", + repo_owner="a", repo_name="b", + ) + store.create_thread_for_project(thread_id="bound", project_id=project["project_id"]) + monkeypatch.setattr(runtime, "get_store", lambda: store) + try: + with pytest.raises(ValueError, match="不能关联项目"): + runtime.run_plain_chat_task(thread_id="bound", run_id="run", model_id=None, event_sink=lambda *_args: None) + finally: + store.close() + + +def test_plain_chat_fails_when_model_returns_no_text(tmp_path: Path, monkeypatch) -> None: + import agent.core.runtime as runtime + + store = LocalSqliteStore(tmp_path / "chat.sqlite") + store.create_chat_thread(thread_id="chat") + + class Chunk: + content = "" + + class FakeModel: + def stream(self, _messages): return iter([Chunk()]) + + monkeypatch.setattr(runtime, "get_store", lambda: store) + monkeypatch.setattr("agent.core.model.make_main_model", lambda _model_id: FakeModel()) + try: + with pytest.raises(RuntimeError, match="没有返回可显示的文本"): + runtime.run_plain_chat_task(thread_id="chat", run_id="run", model_id=None, event_sink=lambda *_args: None) + finally: + store.close() diff --git a/tests/unit/test_plan_interactions.py b/tests/unit/test_plan_interactions.py index 392fd3a..723c0c6 100644 --- a/tests/unit/test_plan_interactions.py +++ b/tests/unit/test_plan_interactions.py @@ -103,7 +103,7 @@ def hold(self, _run_id): )) monkeypatch.setattr(runtime, "_build_agent_for_runtime", lambda **_kwargs: object()) monkeypatch.setattr(runtime, "WorkerLeaseManager", lambda _store: Lease()) - monkeypatch.setattr(runtime, "_detect_current_branch", lambda _repo: "codex/task") + monkeypatch.setattr(runtime, "_detect_current_branch", lambda _repo, **_kwargs: "codex/task") monkeypatch.setattr(runtime, "run_agent_with_event_stream", lambda **kwargs: ( captured.update(kwargs) or {"messages": [], "interrupts": []} )) diff --git a/tests/unit/test_projects_and_drafts.py b/tests/unit/test_projects_and_drafts.py new file mode 100644 index 0000000..963978a --- /dev/null +++ b/tests/unit/test_projects_and_drafts.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from pathlib import Path +from uuid import uuid4 + +import pytest +from fastapi import HTTPException + +from agent.store.sqlite_store import LocalSqliteStore + + +def test_projects_bind_threads_to_fixed_repositories_and_isolate_drafts(tmp_path: Path) -> None: + store = LocalSqliteStore(tmp_path / "business.sqlite") + try: + first = store.create_project( + project_id="project-a", name="A", provider="github", + repo_url="https://github.com/owner/repo-a.git", repo_owner="owner", repo_name="repo-a", + ) + second = store.create_project( + project_id="project-b", name="B", provider="gitee", + repo_url="https://gitee.com/owner/repo-b.git", repo_owner="owner", repo_name="repo-b", + ) + thread_a1 = store.create_thread_for_project(thread_id="a1", project_id=first["project_id"]) + thread_a2 = store.create_thread_for_project(thread_id="a2", project_id=first["project_id"]) + thread_b = store.create_thread_for_project(thread_id="b1", project_id=second["project_id"]) + + assert thread_a1["repo_url"] == thread_a2["repo_url"] == first["repo_url"] + assert thread_a1["project_id"] == thread_a2["project_id"] == first["project_id"] + assert thread_b["repo_url"] == second["repo_url"] + assert store.save_thread_draft(thread_id="a1", content="draft A") is not None + assert store.save_thread_draft(thread_id="b1", content="draft B") is not None + assert store.get_thread_draft("a1")["content"] == "draft A" + assert store.get_thread_draft("a2")["content"] == "" + assert store.get_thread_draft("b1")["content"] == "draft B" + assert store.save_thread_draft(thread_id="missing", content="ignored") is None + finally: + store.close() + + +def test_standalone_chat_is_not_bound_to_a_project_or_repository_and_project_delete_requires_empty_project(tmp_path: Path) -> None: + store = LocalSqliteStore(tmp_path / "projects.sqlite") + try: + chat = store.create_chat_thread(thread_id="chat-only") + assert chat["repo_url"] is None + assert chat["project_id"] is None + assert chat["title"] == "新聊天" + + project = store.create_project( + project_id="project-delete", name="Delete me", provider="github", + repo_url="https://github.com/owner/repo.git", repo_owner="owner", repo_name="repo", + ) + thread = store.create_thread_for_project(thread_id="project-thread", project_id=project["project_id"]) + assert store.list_project_thread_ids(project["project_id"]) == ["project-thread"] + assert store.delete_project(project["project_id"]) is False + assert store.delete_thread(thread["thread_id"]) is True + assert store.delete_project(project["project_id"]) is True + assert store.get_project(project["project_id"]) is None + finally: + store.close() + + +def test_legacy_threads_are_grouped_by_repository_and_keep_history(tmp_path: Path) -> None: + store = LocalSqliteStore(tmp_path / "legacy.sqlite") + try: + store.upsert_thread( + thread_id="legacy-one", title="First", repo_url="https://github.com/owner/repo.git", + repo_owner="owner", repo_name="repo", latest_run_status="completed", + ) + store.upsert_thread( + thread_id="legacy-two", title="Second", repo_url="https://github.com/owner/repo.git", + repo_owner="owner", repo_name="repo", latest_run_status="failed", + ) + store._backfill_legacy_projects() + rows = [store.get_thread("legacy-one"), store.get_thread("legacy-two")] + assert rows[0]["project_id"] == rows[1]["project_id"] + assert rows[0]["title"] == "First" + assert rows[1]["latest_run_status"] == "failed" + finally: + store.close() + + +def test_project_api_normalizes_provider_and_rejects_mismatch(monkeypatch) -> None: + from agent.api import dashboard_routes + + class FakeStore: + def __init__(self): self.created = None + def create_project(self, **values): + self.created = values + return {**values, "is_legacy": False} + + fake = FakeStore() + monkeypatch.setattr(dashboard_routes, "get_store", lambda: fake) + result = dashboard_routes.dashboard_create_project( + dashboard_routes.DashboardProjectRequest(name=" Demo ", provider="gitee", repo="owner/repo") + ) + assert result["repo"] == "https://gitee.com/owner/repo.git" + assert fake.created["provider"] == "gitee" + + with pytest.raises(HTTPException) as error: + dashboard_routes.dashboard_create_project( + dashboard_routes.DashboardProjectRequest(name="Demo", provider="gitee", repo="https://github.com/owner/repo") + ) + assert error.value.status_code == 422 + + +def test_draft_api_enforces_size_and_thread_existence(monkeypatch) -> None: + from agent.api import dashboard_routes + + class FakeStore: + def save_thread_draft(self, **_values): return None + + monkeypatch.setattr(dashboard_routes, "get_store", lambda: FakeStore()) + with pytest.raises(HTTPException) as missing: + dashboard_routes.dashboard_save_thread_draft("missing", dashboard_routes.DashboardThreadDraftRequest(content="x")) + assert missing.value.status_code == 404 + + with pytest.raises(HTTPException) as too_large: + dashboard_routes.dashboard_save_thread_draft( + "thread", dashboard_routes.DashboardThreadDraftRequest(content="x" * 100_001) + ) + assert too_large.value.status_code == 413 + + +def test_project_delete_endpoint_blocks_active_runs_then_deletes_all_conversations(monkeypatch) -> None: + from agent.api import dashboard_routes + + class FakeStore: + project = {"project_id": "project", "name": "Project"} + active = [{"thread_id": "thread-1"}] + deleted = False + + def get_project(self, project_id): return self.project if project_id == "project" else None + def list_project_thread_ids(self, _project_id): return ["thread-1", "thread-2"] + def list_active_runs(self): return self.active + def delete_project(self, _project_id): self.deleted = True; return True + + fake = FakeStore() + deleted_threads = [] + monkeypatch.setattr(dashboard_routes, "get_store", lambda: fake) + monkeypatch.setattr(dashboard_routes, "delete_task", lambda thread_id: deleted_threads.append(thread_id) or True) + + with pytest.raises(HTTPException) as active_error: + dashboard_routes.dashboard_delete_project("project") + assert active_error.value.status_code == 409 + assert deleted_threads == [] + + fake.active = [] + assert dashboard_routes.dashboard_delete_project("project") is None + assert deleted_threads == ["thread-1", "thread-2"] + assert fake.deleted is True + + +def test_project_delete_endpoint_rejects_missing_project(monkeypatch) -> None: + from agent.api import dashboard_routes + + class FakeStore: + def get_project(self, _project_id): return None + + monkeypatch.setattr(dashboard_routes, "get_store", lambda: FakeStore()) + with pytest.raises(HTTPException) as error: + dashboard_routes.dashboard_delete_project("missing") + assert error.value.status_code == 404 diff --git a/tests/unit/test_repository_workspace.py b/tests/unit/test_repository_workspace.py index 53b3fd9..d3fc145 100644 --- a/tests/unit/test_repository_workspace.py +++ b/tests/unit/test_repository_workspace.py @@ -33,7 +33,7 @@ def run(self, command: str, *, cwd: str = ".", timeout: int = 300): if command.startswith("git clone -- "): _, _, _, url, dirname = command.split(maxsplit=4) target = self.projects_dir / dirname - target.mkdir() + target.mkdir(parents=True) (target / ".git").mkdir() self.remote_url = url self.cloned = True @@ -86,6 +86,44 @@ def test_prepares_selected_github_repo_in_isolated_directory(tmp_path: Path) -> assert not any(command.startswith("git remote set-url") for command in backend.commands) +def test_retries_transient_fetch_tls_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + repo = parse_repo_url("https://github.com/owner/repo") + backend = FakeGitBackend(tmp_path, remote_url=repo.clone_url) + original_run = backend.run + fetch_attempts = 0 + + def flaky_run(command: str, **kwargs): + nonlocal fetch_attempts + if command == "git fetch origin --prune": + fetch_attempts += 1 + if fetch_attempts == 1: + return backend._result(128, stderr="fatal: SSL/TLS connection failed") + return original_run(command, **kwargs) + + monkeypatch.setattr(backend, "run", flaky_run) + monkeypatch.setattr("agent.core.repository_workspace.time.sleep", lambda _seconds: None) + prepare_repository_workspace(repo, backend) + assert fetch_attempts == 2 + + +def test_prepares_same_repository_in_distinct_thread_directories(tmp_path: Path) -> None: + repo = parse_repo_url("https://github.com/owner/repo") + backend = FakeGitBackend(tmp_path) + + first = prepare_repository_workspace( + repo, backend, thread_id="thread-a", workspace_directory="projects/.tasks/a/repo" + ) + backend_two = FakeGitBackend(tmp_path) + second = prepare_repository_workspace( + repo, backend_two, thread_id="thread-b", workspace_directory="projects/.tasks/b/repo" + ) + + assert first.directory == "projects/.tasks/a/repo" + assert second.directory == "projects/.tasks/b/repo" + assert "git clone -- https://github.com/owner/repo.git .tasks/a/repo" in backend.commands + assert "git clone -- https://github.com/owner/repo.git .tasks/b/repo" in backend_two.commands + + def test_uses_remote_default_branch_instead_of_provider_guess(tmp_path: Path) -> None: repo = parse_repo_url("owner/repo", provider="github") backend = FakeGitBackend(tmp_path, default_branch="develop") @@ -157,6 +195,34 @@ def test_local_shell_backend_defaults_to_thread_repository_directory(tmp_path: P assert cwd == tmp_path / "projects" / "github-owner-repo" +def test_selected_repository_binds_isolated_checkout_to_virtual_projects_path( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from agent.core import runtime + + repo = parse_repo_url("https://github.com/owner/repo") + prepared = runtime.PreparedRepositoryWorkspace( + directory="projects/.tasks/thread-hash/repo", default_branch="main", current_branch="main" + ) + target = tmp_path / "projects" / ".tasks" / "thread-hash" / "repo" + target.mkdir(parents=True) + bound_backends: list[LocalShellBackend] = [] + + class CapturingLocalShellBackend(LocalShellBackend): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + bound_backends.append(self) + + monkeypatch.setattr(runtime, "WORKSPACE_ROOT", tmp_path) + monkeypatch.setattr(runtime, "LocalShellBackend", CapturingLocalShellBackend) + monkeypatch.setattr(runtime, "get_env", lambda *_args: "") + monkeypatch.setattr(runtime, "prepare_repository_workspace", lambda *_args, **_kwargs: prepared) + + runtime._prepare_selected_repository(repo, thread_id="thread-id") + + assert bound_backends[0].get_work_dir() == "/projects/.tasks/thread-hash/repo" + + def test_local_shell_backend_rejects_working_directory_traversal(tmp_path: Path) -> None: with pytest.raises(ValueError, match="inside /projects|traversal"): LocalShellBackend(Workspace(tmp_path), working_dir="/projects/../skills") diff --git a/tests/unit/test_run_activity.py b/tests/unit/test_run_activity.py index 6b8e81d..702d236 100644 --- a/tests/unit/test_run_activity.py +++ b/tests/unit/test_run_activity.py @@ -195,6 +195,11 @@ def list_run_events_for_run(self, thread_id, run_id): "created_at": datetime(2026, 9, 25, 8, 0, 3, tzinfo=UTC), "detail": "secret output should not be exposed", }, + { + "id": "run-failure", "kind": "think", "title": "任务失败", "status": "error", + "created_at": datetime(2026, 9, 25, 8, 0, 4, tzinfo=UTC), + "detail": "git clone failed: schannel: failed to receive handshake", + }, ] def list_thread_messages(self, _thread_id): @@ -210,6 +215,9 @@ def list_thread_messages(self, _thread_id): assert result["events"][1]["detail"] == {} assert result["events"][2]["detail"]["complete"] is False assert result["events"][3]["detail"] == {} + assert result["events"][4]["detail"]["text"] == ( + "git clone failed: schannel: failed to receive handshake" + ) def test_run_activity_endpoint_rejects_run_from_another_thread(monkeypatch): diff --git a/tests/unit/test_run_queue_store.py b/tests/unit/test_run_queue_store.py new file mode 100644 index 0000000..f9add5e --- /dev/null +++ b/tests/unit/test_run_queue_store.py @@ -0,0 +1,172 @@ +from __future__ import annotations + +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime, timedelta + +import pytest + +from agent.core import run_queue +from agent.store.sqlite_store import LocalSqliteStore + + +def make_store(tmp_path): + store = LocalSqliteStore(tmp_path / "queue.sqlite") + store.upsert_thread( + thread_id="thread-a", title="A", user_prompt="", repo_url="https://github.com/a/b", + repo_owner="a", repo_name="b", latest_run_status="queued", + ) + store.upsert_thread( + thread_id="thread-b", title="B", user_prompt="", repo_url="https://github.com/a/b", + repo_owner="a", repo_name="b", latest_run_status="queued", + ) + return store + + +def test_enqueue_rejects_second_active_run_for_same_thread(tmp_path): + store = make_store(tmp_path) + try: + store.enqueue_run(run_id="run-1", thread_id="thread-a", payload={"content": "first"}) + with pytest.raises(ValueError, match="already has an active run"): + store.enqueue_run(run_id="run-2", thread_id="thread-a", payload={"content": "second"}) + store.enqueue_run(run_id="run-3", thread_id="thread-b", payload={"content": "parallel"}) + finally: + store.close() + + +def test_competing_workers_claim_a_run_only_once(tmp_path): + store = make_store(tmp_path) + try: + store.enqueue_run(run_id="run-1", thread_id="thread-a", payload={"content": "one"}) + with ThreadPoolExecutor(max_workers=12) as pool: + claims = list(pool.map(lambda index: store.claim_next_run(worker_id=f"worker-{index}"), range(12))) + claimed = [item for item in claims if item] + assert len(claimed) == 1 + assert claimed[0]["run_id"] == "run-1" + assert claimed[0]["payload"] == {"content": "one"} + assert claimed[0]["attempt"] == 1 + finally: + store.close() + + +def test_claim_respects_configured_global_active_limit(tmp_path): + store = make_store(tmp_path) + try: + store.enqueue_run(run_id="run-1", thread_id="thread-a", payload={"content": "one"}) + store.enqueue_run(run_id="run-2", thread_id="thread-b", payload={"content": "two"}) + first = store.claim_next_run(worker_id="worker-a", max_active=1) + second = store.claim_next_run(worker_id="worker-b", max_active=1) + assert first["run_id"] == "run-1" + assert second is None + store.finish_queued_run(thread_id="thread-a", run_id="run-1", status="completed") + assert store.claim_next_run(worker_id="worker-b", max_active=1)["run_id"] == "run-2" + finally: + store.close() + + +def test_event_cursor_cancel_heartbeat_and_stale_recovery(tmp_path): + store = make_store(tmp_path) + try: + store.enqueue_run(run_id="run-1", thread_id="thread-a", payload={"content": "one"}) + assert store.append_run_stream_event( + thread_id="thread-a", run_id="run-1", event="text_delta", payload={"content": "a"} + ) == 1 + assert store.append_run_stream_event( + thread_id="thread-a", run_id="run-1", event="text_delta", payload={"content": "b"} + ) == 2 + assert [event["seq"] for event in store.list_run_stream_events( + thread_id="thread-a", run_id="run-1", after_seq=1 + )] == [2] + assert store.request_run_cancel(thread_id="thread-a", run_id="run-1") == "cancelled" + assert store.get_run("thread-a", "run-1")["status"] == "cancelled" + + store.enqueue_run(run_id="run-2", thread_id="thread-a", payload={"content": "two"}) + claimed = store.claim_next_run(worker_id="worker-a", ttl_seconds=1) + assert claimed["run_id"] == "run-2" + assert store.renew_run_lease(run_id="run-2", worker_id="worker-a", ttl_seconds=30) + with store._lock: + store._conn.execute( + "UPDATE runs SET lease_expires_at=? WHERE run_id=?", + ((datetime.now(UTC) - timedelta(seconds=2)).isoformat(), "run-2"), + ) + store._conn.commit() + assert store.interrupt_stale_runs() == ["run-2"] + assert store.get_run("thread-a", "run-2")["status"] == "interrupted" + assert store.get_thread("thread-a")["latest_run_status"] == "interrupted" + finally: + store.close() + + +def test_stale_running_record_without_worker_lease_is_recovered_but_fresh_one_is_kept(tmp_path): + store = make_store(tmp_path) + try: + store.upsert_thread(thread_id="stale-thread", title="stale", latest_run_status="running") + store.upsert_thread(thread_id="fresh-thread", title="fresh", latest_run_status="running") + store.record_run(run_id="stale-run", thread_id="stale-thread", status="running", finished=False) + store.record_run(run_id="fresh-run", thread_id="fresh-thread", status="running", finished=False) + with store._lock: + store._conn.execute( + "UPDATE runs SET started_at=? WHERE run_id=?", + ((datetime.now(UTC) - timedelta(minutes=10)).isoformat(), "stale-run"), + ) + store._conn.commit() + + assert store.interrupt_stale_runs() == ["stale-run"] + assert store.get_run("stale-thread", "stale-run")["status"] == "interrupted" + assert store.get_run("fresh-thread", "fresh-run")["status"] == "running" + finally: + store.close() + + +def test_delete_thread_removes_durable_run_stream_events(tmp_path): + store = make_store(tmp_path) + try: + store.enqueue_run(run_id="run-1", thread_id="thread-a", payload={"content": "one"}) + store.append_run_stream_event( + thread_id="thread-a", run_id="run-1", event="text_delta", payload={"content": "hello"} + ) + assert store.delete_thread("thread-a") + assert store.list_run_stream_events(thread_id="thread-a", run_id="run-1") == [] + assert store.get_run("thread-a", "run-1") is None + finally: + store.close() + + +def test_worker_pool_runs_independent_threads_concurrently_and_keeps_events_scoped(tmp_path, monkeypatch): + store = make_store(tmp_path) + store.enqueue_run(run_id="run-a", thread_id="thread-a", payload={"repo_url": "https://github.com/a/b", "content": "A"}) + store.enqueue_run(run_id="run-b", thread_id="thread-b", payload={"repo_url": "https://github.com/a/b", "content": "B"}) + both_started = __import__("threading").Barrier(2) + + def fake_run_agent_task(*, repo_url, prompt, thread_id, run_id, event_sink, worker_id, **_kwargs): + del repo_url, worker_id + both_started.wait(timeout=5) + event_sink("text_delta", {"content": prompt, "message_id": f"assistant-{thread_id}"}) + store.update_thread_status(thread_id, "completed") + store.record_run(run_id=run_id, thread_id=thread_id, status="completed", finished=True) + return {"thread_id": thread_id, "run_id": run_id, "status": "completed"} + + monkeypatch.setattr(run_queue, "get_store", lambda: store) + monkeypatch.setattr(run_queue, "run_agent_task", fake_run_agent_task) + pool = run_queue.RunWorkerPool(concurrency=2, lease_seconds=30) + pool.start() + try: + import time + + deadline = time.monotonic() + 6 + while time.monotonic() < deadline: + statuses = [store.get_run(thread_id, run_id)["status"] for thread_id, run_id in ( + ("thread-a", "run-a"), ("thread-b", "run-b") + )] + if statuses == ["completed", "completed"]: + break + time.sleep(0.05) + assert statuses == ["completed", "completed"] + for thread_id, run_id, expected in ( + ("thread-a", "run-a", "A"), ("thread-b", "run-b", "B") + ): + events = store.list_run_stream_events(thread_id=thread_id, run_id=run_id) + assert any(row["event"] == "text_delta" and row["payload"]["content"] == expected for row in events) + assert events[-1]["event"] == "done" + finally: + pool.stop() + store.close() diff --git a/ui/package.json b/ui/package.json index 722fd70..8bfc307 100644 --- a/ui/package.json +++ b/ui/package.json @@ -6,6 +6,8 @@ "scripts": { "dev": "vite --host 127.0.0.1 --port 3000", "build": "vite build", + "test": "vitest run", + "test:watch": "vitest", "preview": "vite preview --host 127.0.0.1 --port 3000" }, "dependencies": { @@ -17,5 +19,9 @@ "vite": "^7.0.0", "vue": "^3.5.13" }, - "devDependencies": {} + "devDependencies": { + "@vue/test-utils": "^2.5.1", + "happy-dom": "^20.14.5", + "vitest": "^5.0.2" + } } diff --git a/ui/src/api/client.js b/ui/src/api/client.js index 8a28702..02a1477 100644 --- a/ui/src/api/client.js +++ b/ui/src/api/client.js @@ -18,6 +18,37 @@ export const dashboardApi = { const { data } = await http.get('/threads') return data }, + async listProjects() { + const { data } = await http.get('/projects') + return data + }, + async createProject(payload) { + const { data } = await http.post('/projects', payload) + return data + }, + async renameProject(projectId, name) { + const { data } = await http.patch(`/projects/${projectId}`, { name }) + return data + }, + async deleteProject(projectId) { + await http.delete(`/projects/${projectId}`) + }, + async createChatThread() { + const { data } = await http.post('/threads') + return data + }, + async createProjectThread(projectId) { + const { data } = await http.post(`/projects/${projectId}/threads`) + return data + }, + async saveDraft(threadId, content) { + const { data } = await http.put(`/threads/${threadId}/draft`, { content }) + return data + }, + async listActiveRuns() { + const { data } = await http.get('/runs/active') + return data + }, async getThread(threadId) { const { data } = await http.get(`/threads/${threadId}`) return data @@ -26,6 +57,10 @@ export const dashboardApi = { const { data } = await http.get(`/threads/${threadId}/runs/${runId}/events`) return data }, + async cancelRun(threadId, runId) { + const { data } = await http.post(`/threads/${threadId}/runs/${runId}/cancel`) + return data + }, async deleteThread(threadId) { await http.delete(`/threads/${threadId}`) }, diff --git a/ui/src/api/sse.js b/ui/src/api/sse.js index 336ea2a..20ab2fb 100644 --- a/ui/src/api/sse.js +++ b/ui/src/api/sse.js @@ -1,10 +1,13 @@ function parseBlock(block) { const dataLines = [] let eventName = 'message' + let eventId = null for (const line of block.split(/\r?\n/)) { if (line.startsWith('event:')) { eventName = line.slice(6).trim() + } else if (line.startsWith('id:')) { + eventId = line.slice(3).trim() } else if (line.startsWith('data:')) { dataLines.push(line.slice(5).trimStart()) } @@ -17,31 +20,18 @@ function parseBlock(block) { return { event: payload.event, data: payload.data || {}, + id: eventId, } } return { event: eventName, data: payload || {}, + id: eventId, } } -export async function streamAgentMessage(threadId, payload, { signal, onEvent }) { - const url = threadId - ? `/dashboard/api/threads/${encodeURIComponent(threadId)}/stream-message` - : '/dashboard/api/threads/stream-message' - - const response = await fetch(url, { - method: 'POST', - credentials: 'include', - headers: { - Accept: 'text/event-stream', - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payload), - signal, - }) - +async function consumeResponse(response, signal, onEvent) { if (!response.ok) { const body = await response.json().catch(() => ({})) throw new Error(body.detail || `SSE 请求失败:HTTP ${response.status}`) @@ -62,7 +52,7 @@ export async function streamAgentMessage(threadId, payload, { signal, onEvent }) buffer = blocks.pop() || '' for (const block of blocks) { const parsed = parseBlock(block) - if (parsed) onEvent(parsed.event, parsed.data) + if (parsed) onEvent(parsed.event, parsed.data, parsed.id) } if (done) break @@ -70,6 +60,26 @@ export async function streamAgentMessage(threadId, payload, { signal, onEvent }) if (buffer.trim()) { const parsed = parseBlock(buffer) - if (parsed) onEvent(parsed.event, parsed.data) + if (parsed) onEvent(parsed.event, parsed.data, parsed.id) } } + +export async function streamAgentMessage(threadId, payload, { signal, onEvent }) { + const url = threadId + ? `/dashboard/api/threads/${encodeURIComponent(threadId)}/stream-message` + : '/dashboard/api/threads/stream-message' + const response = await fetch(url, { + method: 'POST', credentials: 'include', + headers: { Accept: 'text/event-stream', 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), signal, + }) + return consumeResponse(response, signal, onEvent) +} + +export async function resumeAgentRun(threadId, runId, { signal, after = 0, onEvent }) { + const url = `/dashboard/api/threads/${encodeURIComponent(threadId)}/runs/${encodeURIComponent(runId)}/stream?after=${encodeURIComponent(after)}` + const response = await fetch(url, { + method: 'GET', credentials: 'include', headers: { Accept: 'text/event-stream' }, signal, + }) + return consumeResponse(response, signal, onEvent) +} diff --git a/ui/src/components/ActiveTaskStrip.vue b/ui/src/components/ActiveTaskStrip.vue new file mode 100644 index 0000000..ef5172b --- /dev/null +++ b/ui/src/components/ActiveTaskStrip.vue @@ -0,0 +1,49 @@ + + + + + diff --git a/ui/src/components/AgentWorkspace.vue b/ui/src/components/AgentWorkspace.vue index 3ec6509..b3f8867 100644 --- a/ui/src/components/AgentWorkspace.vue +++ b/ui/src/components/AgentWorkspace.vue @@ -1,21 +1,33 @@ diff --git a/ui/src/components/ChatComposer.vue b/ui/src/components/ChatComposer.vue index 768481b..f9bd493 100644 --- a/ui/src/components/ChatComposer.vue +++ b/ui/src/components/ChatComposer.vue @@ -6,10 +6,13 @@ const props = defineProps({ type: Boolean, default: false, }, + draft: { type: String, default: '' }, model: { type: String, default: '', }, + models: { type: Array, default: () => [] }, + chatOnly: { type: Boolean, default: false }, effort: { type: String, default: 'default', @@ -22,10 +25,6 @@ const props = defineProps({ type: String, default: 'github', }, - providers: { - type: Array, - default: () => [], - }, locked: { type: Boolean, default: false, @@ -40,35 +39,14 @@ const props = defineProps({ }, }) -const emit = defineEmits(['send', 'stop', 'cancel-interaction', 'update:repo', 'update:provider']) -const draft = shallowRef('') +const emit = defineEmits(['send', 'stop', 'cancel-interaction', 'update:draft', 'update:model']) const inputRef = shallowRef(null) +const draft = computed({ get: () => props.draft, set: (value) => emit('update:draft', value) }) -const modelLabel = computed(() => props.model || 'deepseek-v4-pro') const effortLabel = computed(() => props.effort || 'default') const canSend = computed(() => !props.disabled && !props.locked && Boolean(draft.value.trim())) -const githubUrlPattern = /^https?:\/\/(?:www\.)?github\.com\/[\w.-]+\/[\w.-]+(?:\.git)?\/?$/i -const giteeUrlPattern = /^https?:\/\/(?:www\.)?gitee\.com\/[\w.-]+\/[\w.-]+(?:\.git)?\/?$/i -const shortRepoPattern = /^[\w.-]+\/[\w.-]+$/ - -const providerLabel = computed(() => { - const selected = props.providers.find((item) => item.id === props.provider) - return selected?.label || (props.provider === 'gitee' ? 'Gitee' : 'GitHub') -}) -const repoPlaceholder = computed(() => { - const selected = props.providers.find((item) => item.id === props.provider) - return selected?.url_placeholder || `${props.provider === 'gitee' ? 'https://gitee.com' : 'https://github.com'}/owner/repo` -}) - -const repoStatus = computed(() => { - const value = props.repo.trim() - if (!value) return { label: '待填写', className: 'empty' } - if (githubUrlPattern.test(value) || giteeUrlPattern.test(value) || shortRepoPattern.test(value)) { - return { label: '已识别', className: 'ready' } - } - return { label: '检查地址', className: 'warning' } -}) +const providerLabel = computed(() => props.provider === 'gitee' ? 'Gitee' : 'GitHub') function resizeTextarea() { const element = inputRef.value @@ -80,7 +58,6 @@ function resizeTextarea() { function send() { const content = draft.value.trim() if (!content || props.disabled || props.locked) return - draft.value = '' nextTick(resizeTextarea) emit('send', content) } @@ -101,16 +78,6 @@ function stop() { emit('stop') } -function changeProvider(event) { - const nextProvider = event.target.value - emit('update:provider', nextProvider) - const current = props.repo.trim().toLowerCase() - const isGithubUrl = current.includes('github.com/') - const isGiteeUrl = current.includes('gitee.com/') - if ((nextProvider === 'github' && isGiteeUrl) || (nextProvider === 'gitee' && isGithubUrl)) { - emit('update:repo', '') - } -}