代码修改

This commit is contained in:
董宏凯 committed 2026-07-23 15:08:00 +08:00
1 parent b60d9ed09e
commit 1d07025f74
9 files changed
+337 -53

No files matched your search

@@ -403,12 +403,23 @@ and direct-agent node indexes in `position_roundtable_nodes` (migration
`20260721_01`). Message history remains in the established LangGraph thread
store; a node completion unlocks its next chain stage and a later upstream
revision marks downstream records `stale` for refresh.
`POST /api/position-roundtable/sessions/{id}/nodes/{node_key}/reject` uses the
same cascade: its reason is intentionally optional, the selected node becomes
`rejected`, and downstream material becomes `stale` (or `locked` when no
material exists) with `invalidated_by` set. Clients must replace their complete
session snapshot from this response so the flow, delivery list, and active
node state stay consistent. A rejected/stale node returns to `done` only after
a fresh Markdown delivery is recorded.
For direct-agent handoff, the router resolves artifact paths only inside the
completed upstream node's own thread, then includes bounded UTF-8 excerpts for
text outputs; binary artifacts stay as metadata-only references.
`POST /sessions/{id}/archive` turns a session into a read-only historical
record: task/intent updates, node binding, hidden-context construction, and
turn completion are rejected, while read endpoints remain available.
Built-in summary and action-plan completion also preserves a visible report
answer when the model misses its final `write_file` call: the router writes
that exact answer as the required Markdown artifact in the owning thread's
`outputs/` directory, so users receive both chat text and a downloadable file.
### 岗位 (Position) Subscription System
+1 -1
View File
@@ -124,7 +124,7 @@ FastAPI application providing REST endpoints for frontend integration:
| `GET/POST /api/agents` | List visible agents or create a user-owned agent |
| `GET/PUT/DELETE /api/agents/{id}` | Read, update, or delete an id-addressed agent |
| `GET/POST/PUT/DELETE /api/roundtable-chains` | Manage user-owned roundtable business chains; each seat may optionally carry `position_id` for the separate position-collaboration workspace (the original roundtable ignores it) |
| `GET/POST/PUT /api/position-roundtable/sessions` | Standalone position-collaboration sessions: freeze task/intent/chain snapshots, index one direct-agent node per seat, build upstream handoff context (including bounded UTF-8 excerpts of text artifacts), and make archived sessions read-only without invoking the original roundtable coordinator or jobs |
| `GET/POST/PUT /api/position-roundtable/sessions` | Standalone position-collaboration sessions: freeze task/intent/chain snapshots, index one direct-agent node per seat, build upstream handoff context (including bounded UTF-8 excerpts of text artifacts), and make archived sessions read-only without invoking the original roundtable coordinator or jobs. Built-in summary/action-plan completion mirrors visible report text into a Markdown artifact when a model omits its final `write_file` call. `POST /sessions/{id}/nodes/{nodeKey}/reject` accepts an optional reason, marks the rejected delivery for rework, and invalidates affected downstream deliveries so they are regenerated in order. |
| `GET /api/memory` | Retrieve memory data |
| `POST /api/memory/reload` | Force memory reload |
| `GET /api/memory/config` | Memory configuration |
@@ -28,6 +28,10 @@ _MAX_INLINE_ARTIFACT_CHARS = 1_800
_BUILTIN_MATERIAL_BUDGET = 24_000
SUMMARY_AGENT_ID = "roundtable-summary"
ACTION_PLAN_AGENT_ID = "position-action-planner"
_BUILTIN_MARKDOWN_OUTPUTS = {
"summary": "mnt/user-data/outputs/岗位会商方案总结报告.md",
"action_plan": "mnt/user-data/outputs/岗位会商行动规划.md",
}
_TEXT_ARTIFACT_SUFFIXES = {
".csv",
".json",
@@ -113,8 +117,11 @@ class CompleteTurnRequest(BaseModel):
class RejectNodeRequest(BaseModel):
title: str = Field(min_length=1, max_length=120)
reason: str = Field(min_length=1, max_length=5_000)
# The UI only asks for an optional rejection reason. Keep ``title`` for
# compatible clients and for the audit record, but provide a stable
# default so neither field turns a valid rejection into a 422/400.
title: str = Field(default="产物驳回", max_length=120)
reason: str = Field(default="", max_length=5_000)
class PrepareBuiltinRunRequest(BaseModel):
@@ -731,6 +738,45 @@ def _artifact_manifest_refs(artifacts: list[dict[str, Any]]) -> list[dict[str, A
return refs
async def _write_builtin_markdown_fallback(
*, thread_id: str, kind: str, content: str
) -> dict[str, Any]:
"""Materialize a built-in agent's visible answer when it skipped ``write_file``.
Position roundtable runs are direct chat streams. A model can therefore
finish with a complete visible report but still omit its required artifact
tool call. Keep the chat answer as the source of truth and mirror it into
the owning thread's outputs directory so the report remains previewable and
downloadable after the stream has ended.
"""
virtual_path = _BUILTIN_MARKDOWN_OUTPUTS.get(kind)
report = content.strip()
if virtual_path is None:
raise HTTPException(status_code=400, detail=f"Unknown built-in delivery kind: {kind}")
if not report:
raise HTTPException(status_code=422, detail="内置智能体未返回可保存为报告的正文")
try:
output_path = await aresolve_thread_virtual_path(thread_id, virtual_path)
await asyncio.to_thread(output_path.parent.mkdir, parents=True, exist_ok=True)
await asyncio.to_thread(
output_path.write_text,
report if report.endswith("\n") else f"{report}\n",
encoding="utf-8",
)
stat = await asyncio.to_thread(output_path.stat)
except OSError as error:
raise HTTPException(status_code=500, detail="无法保存内置智能体 Markdown 报告") from error
return {
"name": output_path.name,
"path": virtual_path,
"mime_type": "text/markdown",
"modified_at": datetime.fromtimestamp(stat.st_mtime, tz=UTC).isoformat(),
"size_bytes": stat.st_size,
}
async def _effective_delivery_material(
session: dict[str, Any], nodes: list[dict[str, Any]]
) -> str:
@@ -1109,10 +1155,8 @@ async def complete_node_turn(
async def reject_node(
request: Request, session_id: str, node_key: str, body: RejectNodeRequest
) -> SessionDetailResponse:
title = body.title.strip()
title = body.title.strip() or "产物驳回"
reason = body.reason.strip()
if not title or not reason:
raise HTTPException(status_code=400, detail="驳回标题和理由不能为空")
store, user_id, _ = await _require_writable_session(request, session_id)
current = await store.get_node(session_id, node_key, user_id)
if current is None:
@@ -1199,7 +1243,17 @@ async def _complete_builtin_run(
artifacts = _artifact_manifest_refs(body.artifact_manifest)
markdown = [artifact for artifact in artifacts if _is_markdown_artifact(artifact)]
if not markdown:
raise HTTPException(status_code=422, detail="内置智能体必须交付 outputs 目录下的一份 Markdown 报告文档")
# The report text is already visible in the chat stream. Do not lose
# that successful result just because the model skipped its final
# write_file call: mirror the exact response into the thread outputs
# directory and persist it as the normal report artifact.
fallback_markdown = await _write_builtin_markdown_fallback(
thread_id=body.thread_id,
kind=kind,
content=body.content,
)
artifacts.append(fallback_markdown)
markdown = [fallback_markdown]
if kind == "action_plan" and not any(_is_json_artifact(artifact) for artifact in artifacts):
raise HTTPException(status_code=422, detail="行动规划智能体还需交付 action-plan-subtasks.json 子任务清单")
@@ -27,6 +27,14 @@ async def store(tmp_path):
return PositionRoundtableRepository(async_sessionmaker(engine, expire_on_commit=False))
def test_reject_node_request_allows_an_optional_reason():
"""A rejection must work even when the reviewer leaves the reason blank."""
request = position_roundtable_router.RejectNodeRequest()
assert request.title == "产物驳回"
assert request.reason == ""
@pytest.mark.asyncio
async def test_session_activation_freezes_chain_and_creates_nodes_once(store):
created = await store.create_session(
@@ -186,6 +194,122 @@ def test_all_nodes_delivered_requires_markdown_for_non_intent_nodes():
)
@pytest.mark.asyncio
async def test_builtin_markdown_fallback_writes_visible_summary_to_thread_outputs(tmp_path, monkeypatch):
target = tmp_path / "outputs" / "岗位会商方案总结报告.md"
async def resolve(thread_id: str, path: str):
assert thread_id == "summary-thread"
assert path == "mnt/user-data/outputs/岗位会商方案总结报告.md"
return target
monkeypatch.setattr(position_roundtable_router, "aresolve_thread_virtual_path", resolve)
artifact = await position_roundtable_router._write_builtin_markdown_fallback(
thread_id="summary-thread",
kind="summary",
content="# 岗位会商方案总结报告\n\n这是对话中生成的完整报告正文。",
)
assert target.read_text(encoding="utf-8") == "# 岗位会商方案总结报告\n\n这是对话中生成的完整报告正文。\n"
assert artifact["name"] == "岗位会商方案总结报告.md"
assert artifact["path"] == "mnt/user-data/outputs/岗位会商方案总结报告.md"
assert artifact["mime_type"] == "text/markdown"
assert artifact["size_bytes"] == target.stat().st_size
@pytest.mark.asyncio
async def test_builtin_summary_completion_persists_fallback_markdown_when_agent_skips_write_file(monkeypatch):
node = {
"id": "node-1",
"session_id": "session-a",
"node_key": "intent-node",
"stage_index": 0,
"seat_index": 0,
"agent_id": "intent-agent",
"position_id": "intelligence",
"thread_id": "intent-thread",
"status": "done",
"latest_answer": "已确认任务意图",
"artifact_manifest": [],
"revision": 1,
"upstream_revision": None,
"rejection_count": 0,
"last_rejection": None,
"invalidated_by": None,
}
session = {
"id": "session-a",
"status": "active",
"task_snapshot": {},
"chain_id": "chain-a",
"chain_snapshot": {},
"intent_thread_id": "intent-thread",
"intent_snapshot": {"objective": "形成方案", "constraints": []},
"summary_thread_id": None,
"summary_snapshot": None,
"action_plan_thread_id": None,
"action_plan_snapshot": None,
}
class StubStore:
updates: dict | None = None
async def get_session(self, session_id, user_id):
assert (session_id, user_id) == ("session-a", "user-a")
return session
async def list_nodes(self, session_id, user_id):
assert (session_id, user_id) == ("session-a", "user-a")
return [node]
async def update_session(self, session_id, user_id, **updates):
assert (session_id, user_id) == ("session-a", "user-a")
self.updates = updates
return {**session, **updates}
store = StubStore()
async def write_fallback(**kwargs):
assert kwargs["thread_id"] == "summary-thread"
assert kwargs["kind"] == "summary"
assert kwargs["content"] == "# 方案总结\n\n完整报告正文"
return {
"name": "岗位会商方案总结报告.md",
"path": "mnt/user-data/outputs/岗位会商方案总结报告.md",
"mime_type": "text/markdown",
"modified_at": "2026-07-23T00:00:00+00:00",
"size_bytes": 42,
}
monkeypatch.setattr(position_roundtable_router, "_write_builtin_markdown_fallback", write_fallback)
request = SimpleNamespace(
app=SimpleNamespace(state=SimpleNamespace(position_roundtable_store=store)),
state=SimpleNamespace(user=SimpleNamespace(id="user-a")),
)
body = position_roundtable_router.CompleteBuiltinRunRequest(
thread_id="summary-thread",
content="# 方案总结\n\n完整报告正文",
artifact_manifest=[],
source_revisions={"intent-node": 1},
)
result = await position_roundtable_router._complete_builtin_run(
request,
"session-a",
kind="summary",
body=body,
)
assert store.updates is not None
snapshot = store.updates["summary_snapshot"]
assert snapshot["content"] == "# 方案总结\n\n完整报告正文"
assert snapshot["primary_artifact"]["name"] == "岗位会商方案总结报告.md"
assert result.summary_snapshot["primary_artifact"]["path"] == (
"mnt/user-data/outputs/岗位会商方案总结报告.md"
)
@pytest.mark.asyncio
async def test_node_updates_are_user_scoped_and_keep_thread_out_of_messages(store):
created = await store.create_session("user-a", external_task_id=None, task_snapshot={})