From b418c0d951af9a1ab404d8cbdbe100d6408605ae Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Mon, 28 Sep 2026 02:42:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9C=80=E7=BB=88=E9=AA=8C=E6=94=B6=EF=BC=9A14?= =?UTF-8?q?8=20=E9=A1=B9=E9=80=90=E6=9D=A1=E5=A4=8D=E6=A0=B8=EF=BC=88?= =?UTF-8?q?=E5=8E=9F=E5=AE=A1=E6=9F=A5=20142=20=E6=9D=A1=20+=20=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E9=97=AE=E9=A2=98=206=20=E6=9D=A1=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E8=BF=94=E5=B7=A5=E5=90=8E=20145=20=E9=A1=B9=E8=A7=A3=E5=86=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 四组验收员拿审查原文在沙箱里逐条复现:133 项已解决、15 项部分解决、没有未解决或回退的; 另发现 10 个新问题。按归属返工后,剩 3 项低严重度:MCP / 自定义工具的危险标记(待用户拍板)、 选中环与运行态同色(需跨三处协调改)、「接着跑」这个说法是否更换(多处引用原文,暂留)。 这次返工改了 - 右栏:老运行没有 active_ms 时执行时长改按航迹算,不再显示最后一段的「22 ms」;循环出口行不再差一; 取消在一轮中途时泳道脚注不写「0 ms」;分支、循环出口显示 case 的说明而不是 key; 展开已完成轮次不再误报「N 条新进展」;旧数据里已完成的模型调用不再一律标成「已取消」 - 后端:跳过事件带节点名和类型;restore 版本时把已发布 / 受管退回草稿;只是打开旧会话不再把它顶到最前、 标成「刚刚」;协作团队全程没有成员交付成果、调度者却判完成时按失败或降档处理,不再当成功交付 - 画布:循环体有「循环体 · 最多 N 轮」的底框,出口标签不再被自己的走线穿过;运行中校验角标退让; 768 宽下工具栏不溢出;运行被拦时点名是哪个节点;正式运行弹层写明以谁的名义发起 - 问数据:离线时能力条不把「没取回来」说成 0;窄屏下会话列表收起;check-chat 在零点前后不再误报 - 公共层:FastAPI 422 校验错误翻成中文,不再把英文原文透给用户 验证(沙箱):tsc 干净,pytest 878 passed(两遍),check-all 15 项检查全绿。 --- backend/app/api/conversations.py | 10 +- backend/app/api/workflows.py | 3 + backend/app/engine/compiler.py | 3 +- backend/app/engine/nodes/multi.py | 33 +++- backend/app/engine/review.py | 2 + backend/tests/test_conversation_status.py | 75 +++++++- backend/tests/test_markup_leak.py | 2 + backend/tests/test_run_timing.py | 20 +++ backend/tests/test_team_exhausted.py | 67 +++++++ backend/tests/test_workflow_restore.py | 62 +++++++ frontend/src/api/client.ts | 26 ++- frontend/src/canvas/FlowCanvas.tsx | 61 ++++++- frontend/src/canvas/Inspector.tsx | 19 +- frontend/src/canvas/NodeCard.tsx | 21 ++- frontend/src/canvas/loops.ts | 194 ++++++++++++++++++++ frontend/src/canvas/routing.ts | 89 +++++++++- frontend/src/canvas/surface.css | 81 +++++++++ frontend/src/dev/preview.tsx | 27 +++ frontend/src/dev/ui-harness.tsx | 7 +- frontend/src/lib/errors.ts | 6 + frontend/src/lib/validation.ts | 183 +++++++++++++++++++ frontend/src/pages/ChatPage.tsx | 30 +++- frontend/src/pages/ConversationList.tsx | 78 +++++--- frontend/src/pages/StudioPage.tsx | 178 +++++++++++++++---- frontend/src/pages/runs/RunDetailView.tsx | 9 +- frontend/src/run/AssistantPanel.tsx | 46 ++++- frontend/src/run/AssistantStream.tsx | 39 ++-- frontend/src/run/Composer.tsx | 2 +- frontend/src/run/RunControl.tsx | 34 +++- frontend/src/run/decode.ts | 86 ++++++++- scripts/check-canvas-fx.mjs | 207 +++++++++++++++++++--- scripts/check-canvas-layout.mjs | 74 ++++++++ scripts/check-chat.mjs | 76 +++++++- scripts/check-decode.mjs | 121 +++++++++++++ scripts/check-manage.mjs | 25 +++ scripts/check-run-states.mjs | 129 +++++++++++++- scripts/check-stream.mjs | 58 ++++++ scripts/check-studio.mjs | 189 +++++++++++++++++++- scripts/check-ui-kit.mjs | 107 +++++++++++ 39 files changed, 2308 insertions(+), 171 deletions(-) create mode 100644 backend/tests/test_workflow_restore.py create mode 100644 frontend/src/canvas/loops.ts create mode 100644 frontend/src/lib/validation.ts diff --git a/backend/app/api/conversations.py b/backend/app/api/conversations.py index a92381b5..293e966b 100644 --- a/backend/app/api/conversations.py +++ b/backend/app/api/conversations.py @@ -412,9 +412,13 @@ async def patch_turn( if value is not None: setattr(turn, field, value) - conversation = await session.get(Conversation, conversation_id) - if conversation: - conversation.last_active_at = utcnow() + # 活跃时间只认人在这里开始做事:改问题、按下运行、重试(状态回到 running)。 + # 打开会话时前端的回源核对也走这里——补全截断的答案、记下运行已删、把断掉的 + # 建图写回 error、补交付错过的结果——这些不算,否则旧会话一打开就顶到列表最上面 + if payload.question is not None or payload.run_id is not None or payload.status == "running": + conversation = await session.get(Conversation, conversation_id) + if conversation: + conversation.last_active_at = utcnow() await session.commit() await session.refresh(turn) return _turn_out(turn) diff --git a/backend/app/api/workflows.py b/backend/app/api/workflows.py index ef8f6720..6b3e78d1 100644 --- a/backend/app/api/workflows.py +++ b/backend/app/api/workflows.py @@ -271,6 +271,9 @@ async def restore_version( note=f"回滚到 v{version}", ) ) + # 恢复旧版也是改图,和 PATCH 同一条规矩:旧图没过这次的闸,不能挂着受管 / 已发布 + if workflow.status in ("published", "governed"): + workflow.status = "draft" await session.commit() await session.refresh(workflow) return workflow diff --git a/backend/app/engine/compiler.py b/backend/app/engine/compiler.py index 46ae78e4..719dd3a6 100644 --- a/backend/app/engine/compiler.py +++ b/backend/app/engine/compiler.py @@ -63,7 +63,8 @@ def _wrap( from app.engine.state import template_context if eval_condition(skip_if, template_context(state)): - ctx.emit(EventType.NODE_SKIPPED, reason=f"skip_if 成立:{skip_if}") + ctx.emit(EventType.NODE_SKIPPED, node_type=str(node.type), label=node.title, + reason=f"skip_if 成立:{skip_if}") return {"nodes": {node.id: {"skipped": True}}} retries = int(node.config.get("retries", 0) or 0) diff --git a/backend/app/engine/nodes/multi.py b/backend/app/engine/nodes/multi.py index 786df515..1b1b198a 100644 --- a/backend/app/engine/nodes/multi.py +++ b/backend/app/engine/nodes/multi.py @@ -441,6 +441,9 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: progress_lines: list[str] = [] final_text = "" + #: 成功交回来的产出(成员, 原话)。调度者说完成时,成果取最后一份成功的: + #: 失败说明是写给调度者看的,不是结论 + delivered: list[tuple[str, str]] = [] rounds_meta: list[dict[str, Any]] = [] #: 调度者最后一轮给的理由,以及派过活的成员。轮数用完时报错要说清卡在哪、谁从没上过场 last_reason = "" @@ -457,7 +460,6 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: batch = _batch_of(decision) if bool(decision.get("done")) or not batch: - final_text = progress_lines[-1].split("】", 1)[-1] if progress_lines else "" finished = True break @@ -494,6 +496,8 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: "duration_ms": each_ms} ) final_text = outcome["text"] + if not outcome.get("failed"): + delivered.append((name, outcome["text"])) rounds_meta.append({ "round": round_no, "agents": [n for n, _ in batch], @@ -505,15 +509,36 @@ async def run_supervisor(state: GraphState, ctx: NodeContext) -> dict[str, Any]: _accumulate(judged.get("usage") or _usage(None, sup_model_id)) last_reason = str(judged.get("reason") or "") or last_reason if judged.get("done"): - final_text = progress_lines[-1].split("】", 1)[-1] finished = True exhausted: dict[str, Any] = {} - if not finished: + failed = [t for t in transcript if t.get("failed")] + never = [n for n in names if n not in dispatched] + if finished and delivered: + final_text = delivered[-1][1] + if transcript[-1].get("failed"): + # 调度者认可了收工,可最后派出去的人没交回东西:成果取最后一份成功的产出, + # 并说清楚——下游拿到的是它,不是本该定稿的那个人的 + late = "、".join(dict.fromkeys(t["agent"] for t in failed + if t["round"] == transcript[-1]["round"])) + ctx.emit(EventType.LOG, level="warn", code="team_last_failed", + message=f"{late} 最后一轮没有交回结果,团队成果取自{delivered[-1][0]}的产出") + elif finished and transcript: + # 调度者说完成了,派出去的成员却一个都没交回结果,手上只有失败说明。以前最后 + # 那段失败说明就被当成团队的结论交出去:一条数据都没查到,运行照样是已完成。 + # 不看 on_exhausted:那是「用完轮数时」的收场方式,降档交的是成员原话;这里 + # 连原话都没有,交下去的只能是失败说明,界面还会把它说成「用完 N 轮」 + why = ";".join(f"{who}:{err[:200]}" for who, err in dict.fromkeys( + (t["agent"], t.get("error") or "没有说明原因") for t in failed)) + summary = (f"协作团队没有交出结论:派出去的成员都没能交回结果,调度者仍判定完成" + f"({last_reason or '没有给出理由'})。{why}") + if never: + summary += f"。一次都没被派到的成员:{'、'.join(never)}" + raise NodeError(ctx.node.id, f"{summary}。按各成员的失败原因改好配置,再运行") + elif not finished: # 轮数用完,调度者一次都没说「完成」。这时手上只有最后一个成员的原话—— # 以前它就被当作团队的结论交了出去:真实运行里是一段没执行的工具调用标记, # 而负责定稿的成员一次都没被派到 - never = [n for n in names if n not in dispatched] summary = (f"协作团队用完 {max_rounds} 轮仍未完成:" f"{last_reason or '调度者没有给出理由'}") if never: diff --git a/backend/app/engine/review.py b/backend/app/engine/review.py index dc6b5fb7..1ce54d71 100644 --- a/backend/app/engine/review.py +++ b/backend/app/engine/review.py @@ -76,6 +76,8 @@ WARN_CODES: dict[str, tuple[str, str]] = { "tool_markup_leak": ("tool_markup_leak", DEGRADED), # 协作团队用完轮数、按降档交付:交来的是成员原话,不是调度者认可的结论 "team_exhausted": ("team_exhausted", BROKEN), + # 调度者收了工,但最后派出去的成员失败了,成果取自更早的那份:有缺口,不是断裂 + "team_last_failed": ("team_last_failed", DEGRADED), # 校验节点的修复编出了原文没有的值,这次修复被作废 "repair_invented": ("repair_invented", DEGRADED), } diff --git a/backend/tests/test_conversation_status.py b/backend/tests/test_conversation_status.py index dc673b30..1a9fe345 100644 --- a/backend/tests/test_conversation_status.py +++ b/backend/tests/test_conversation_status.py @@ -15,7 +15,7 @@ import pytest from httpx import ASGITransport, AsyncClient from app.db.base import SessionLocal, utcnow -from app.db.models import Approval, ConversationTurn, Run +from app.db.models import Approval, Conversation, ConversationTurn, Run from app.main import app @@ -240,3 +240,76 @@ async def test_turns_carry_updated_at_for_the_same_staleness_clock(client): assert turn.get("updated_at"), turn detail = (await client.get(f"/api/conversations/{conv}")).json() assert detail["turns"][0]["updated_at"] + + +# -------------------------------------------------------------------------- +# 活跃时间:只是打开一个旧会话,不算在这里做了事 +# -------------------------------------------------------------------------- + + +async def _age(conv_id: str, days: int) -> None: + async with SessionLocal() as session: + row = await session.get(Conversation, conv_id) + row.last_active_at = utcnow() - timedelta(days=days) + await session.commit() + + +async def _order(client, *ids: str) -> list[str]: + r = await client.get("/api/conversations") + return [c["id"] for c in r.json() if c["id"] in ids] + + +async def test_catching_up_on_open_does_not_bump_the_conversation(client): + """打开会话时前端会回源核对:补全截断的答案、记下运行已删、把断掉的建图写回 + error、补交付错过的结果。这些都不是人在这里做了事——以前每一次都把 + last_active_at 改成现在,旧会话一打开就跳到列表最上面、写着「刚刚」。""" + old = await _conversation(client, "上周的") + turn = await _turn(client, old, run_id=await _run("succeeded"), status="done", answer="十二") + recent = await _conversation(client, "昨天的") + await _turn(client, recent) + await _age(old, 7) + await _age(recent, 1) + before = (await _listed(client))[old]["last_active_at"] + assert await _order(client, old, recent) == [recent, old] + + url = f"/api/conversations/{old}/turns/{turn['id']}" + for body in ( + {"meta": {"v": 1, "clipped": "lost"}, "review": {}}, # 运行删了、答案补不回来 + {"answer": "十二(完整版)", "meta": {"v": 1}, "review": {}}, # 截断的答案换成完整的 + {"status": "error", "error": "上次没有跑完", "meta": {"v": 1}, "review": {}}, + {"status": "done", "answer": "补交付", "meta": {"v": 1}, "review": {}}, + ): + r = await client.patch(url, json=body) + assert r.status_code == 200, r.text + assert (await _listed(client))[old]["last_active_at"] == before, body + assert await _order(client, old, recent) == [recent, old] + + +@pytest.mark.parametrize("body", [ + {"run_id": "RUN", "status": "running"}, # 按下运行 + {"status": "running", "error": "", "answer": ""}, # 重试这一轮 + {"question": "换个问法"}, +]) +async def test_starting_something_in_a_turn_still_bumps_it(client, body): + old = await _conversation(client, "上周的") + turn = await _turn(client, old) + recent = await _conversation(client, "昨天的") + await _turn(client, recent) + await _age(old, 7) + await _age(recent, 1) + if body.get("run_id") == "RUN": + body = {**body, "run_id": await _run("running")} + r = await client.patch(f"/api/conversations/{old}/turns/{turn['id']}", json=body) + assert r.status_code == 200, r.text + assert await _order(client, old, recent) == [old, recent] + + +async def test_a_new_turn_bumps_it(client): + old = await _conversation(client, "上周的") + await _turn(client, old) + recent = await _conversation(client, "昨天的") + await _turn(client, recent) + await _age(old, 7) + await _age(recent, 1) + await _turn(client, old, "接着问") + assert await _order(client, old, recent) == [old, recent] diff --git a/backend/tests/test_markup_leak.py b/backend/tests/test_markup_leak.py index 3d1aea45..d79f435d 100644 --- a/backend/tests/test_markup_leak.py +++ b/backend/tests/test_markup_leak.py @@ -161,6 +161,8 @@ async def test_a_team_member_writing_markup_fails_its_step_and_the_coordinator_i routes = [batch[1] for batch in seen if batch and batch[0] == "route"] assert len(routes) == 2 and "原始标记" in routes[1], routes assert "<||DSML" not in json.dumps(row.output, ensure_ascii=False) + # 调度者读完失败说明判了完成,可一条数据都没查到:不能把失败说明当成果、记为已完成 + assert row.status == "failed" and "工具调用的原始标记" in (row.error or ""), (row.status, row.output) async def test_markup_in_the_settle_round_keeps_what_the_agent_found(monkeypatch): diff --git a/backend/tests/test_run_timing.py b/backend/tests/test_run_timing.py index c7ae9384..179d8bb1 100644 --- a/backend/tests/test_run_timing.py +++ b/backend/tests/test_run_timing.py @@ -251,3 +251,23 @@ async def test_node_started_says_which_iteration_and_whether_it_was_a_replay(slo assert gate[1].get("resumed") is True, "恢复后重放的那一次要标出来" out = [e.data for e in events if e.type == "node.started" and e.node_id == "out"] assert not out[0].get("resumed"), "恢复之后新走到的节点不是重放" + + +async def test_node_skipped_says_which_node_by_name_not_just_id(): + """被 skip_if 跳过的节点也得带上名称和类型:界面按名字写「跳过「整理结果」」, + 以前只带 reason,右栏只能退回写节点 id。""" + graph = chain( + node("start", "input", fields=[{"name": "question"}]), + {"id": "bg", "type": "transform", "position": {"x": 0, "y": 0}, + "data": {"label": "整理结果", + "config": {"mode": "template", "template": "x", "skip_if": "true"}}}, + node("out", "output", fields=[{"name": "结果", "value": "ok"}]), + ) + run = await run_manager.start(graph=graph, input_payload={"question": "q"}) + done = await _wait(run.id, ("succeeded", "failed")) + assert done.status == "succeeded", done.error + [skipped] = [e for e in await _events(run.id) if e.type == "node.skipped"] + assert skipped.node_id == "bg" + assert skipped.data.get("label") == "整理结果" + assert skipped.data.get("node_type") == "transform" + assert "skip_if 成立" in skipped.data.get("reason", "") diff --git a/backend/tests/test_team_exhausted.py b/backend/tests/test_team_exhausted.py index 9fc5137d..0a31e293 100644 --- a/backend/tests/test_team_exhausted.py +++ b/backend/tests/test_team_exhausted.py @@ -212,3 +212,70 @@ async def test_continuing_a_failed_team_does_not_replay_its_rounds(monkeypatch): assert tally(after_events) == before, "接着跑把前几轮的调度和成员又发了一遍" # 前几轮取自断点,用量不能跟着丢:成员的调用也要算进去 assert row.usage["calls"] == before["llm.end"], (row.usage, before) + + +# -------------------------------------------------------------------------- +# 调度者说完成了,可派出去的成员一个都没交回结果 +# -------------------------------------------------------------------------- + +DSML = ('<||DSML|| calls>\n<||DSML|| invoke name="db_query__shop">\n' + '<||DSML|| parameter name="sql">SELECT COUNT(*) FROM orders\n' + '\n') + + +def _gives_up_after(monkeypatch, *plan: str, writes: dict[str, str]) -> None: + """调度者按 plan 依次派人,派完就判完成;成员按 system 认人,照 writes 回话。""" + from app.providers import mock_model + + routed = {"n": 0} + + def _decide(self, messages): + if self.response_format: + routed["n"] += 1 + if routed["n"] <= len(plan): + who = plan[routed["n"] - 1] + decision = {"assignments": [{"agent": who, "instruction": "做你那部分"}], + "done": False, "reason": f"交给{who}"} + else: + decision = {"assignments": [], "done": True, "reason": "查不到了,先这样"} + return AIMessage(content=json.dumps(decision, ensure_ascii=False)) + role = str(messages[0].content) + return AIMessage(content=next(v for k, v in writes.items() if k in role)) + + monkeypatch.setattr(mock_model.MockChatModel, "_decide", _decide) + + +async def test_nobody_delivering_is_not_a_finished_team(monkeypatch): + """验收时的一次:成员没绑工具,两次都把工具调用写成文字;调度者读到失败说明, + 判定完成。团队把「(<成员> 这一步失败:…)」当成果交了出去,运行 succeeded, + 画布头部是绿色的已完成——一条数据都没查到。""" + _gives_up_after(monkeypatch, "核对员", writes={"复核": DSML, "结论": "不该轮到我"}) + row, events = await _finish(_graph()) + assert row.status == "failed", f"失败说明被当成了成果:{row.output}" + assert row.error_node_id == "team" + assert "没有交出结论" in row.error and "查不到了,先这样" in row.error, row.error + # 失败的原因一起带上:界面照它说「模型没有真正调用工具」、指到画布上去绑工具 + assert "工具调用的原始标记" in row.error, row.error + assert "撰稿员" in row.error, "从没被派过的成员要点出来" + + +async def test_nobody_delivering_fails_even_when_set_to_degrade(monkeypatch): + """「用完轮数时 · 降档交付」交的是成员原话。没人交回结果时手上只有失败说明, + 交下去不是降档、是冒充:照样判失败,也不借用「用完 N 轮」的说法。""" + _gives_up_after(monkeypatch, "核对员", writes={"复核": DSML, "结论": "不该轮到我"}) + row, events = await _finish(_graph(on_exhausted="degrade")) + assert row.status == "failed", f"失败说明被当成了成果:{row.output}" + assert "没有交出结论" in row.error and "用完" not in row.error, row.error + assert not [e for e in events if e.data.get("code") == "team_exhausted"] + + +async def test_a_failed_last_step_is_not_handed_over_as_the_result(monkeypatch): + """核对员查到了,撰稿员失败,调度者判完成:成果是核对员查到的,不是撰稿员的失败说明。""" + _gives_up_after(monkeypatch, "核对员", "撰稿员", writes={"复核": "一共 1 条。", "结论": DSML}) + row, events = await _finish(_graph()) + assert row.status == "succeeded", row.error + assert row.output["r"] == "一共 1 条。", row.output + warn = [e.data for e in events if e.type == "log" and e.data.get("code") == "team_last_failed"] + assert warn and "撰稿员" in warn[0]["message"] and "核对员" in warn[0]["message"], warn + signals = review.scan(events, row.output) + assert any(s.kind == "team_last_failed" for s in signals), signals diff --git a/backend/tests/test_workflow_restore.py b/backend/tests/test_workflow_restore.py new file mode 100644 index 00000000..848cf054 --- /dev/null +++ b/backend/tests/test_workflow_restore.py @@ -0,0 +1,62 @@ +"""恢复旧版本也是改图:受管 / 已发布得退回草稿。 + +status 说的是**当前画布**的状态。PATCH 改图时早就这么退了,restore 接口却只换图、 +升版本、留快照,状态原样挂着——一张受管工作流恢复成从没过闸的旧图,工具栏照样 +写「受管」。前端的版本历史为此绕开了它,但接口还对外开着,谁直接调都会中招。 +已发布的那一版仍由 published_version 指着,正式运行不受影响。 +""" + +from __future__ import annotations + +import pytest +from httpx import ASGITransport, AsyncClient + +from app.db.base import SessionLocal +from app.db.models import Workflow +from app.main import app + + +def _graph(label: str) -> dict: + return { + "nodes": [ + {"id": "start", "type": "input", "position": {"x": 0, "y": 0}, + "data": {"label": "输入", "config": {"fields": [{"name": "q"}]}}}, + {"id": "out", "type": "output", "position": {"x": 300, "y": 0}, + "data": {"label": label, "config": {"fields": [{"name": "r", "value": "{{ input.q }}"}]}}}, + ], + "edges": [{"source": "start", "target": "out"}], + } + + +@pytest.fixture +async def client(): + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as c: + yield c + + +@pytest.mark.parametrize("level", ["published", "governed"]) +async def test_restoring_an_old_version_drops_back_to_draft(client, level): + old, new = _graph("旧出口"), _graph("新出口") + workflow_id = (await client.post("/api/workflows", json={"name": "恢复", "graph": old})).json()["id"] + assert (await client.patch(f"/api/workflows/{workflow_id}", json={"graph": new})).status_code == 200 + # 受管要过治理 lint,这里只关心恢复之后的状态,直接把 v2 立成发布版 + async with SessionLocal() as session: + row = await session.get(Workflow, workflow_id) + row.status, row.published_version = level, 2 + await session.commit() + + r = await client.post(f"/api/workflows/{workflow_id}/versions/1/restore") + assert r.status_code == 200, r.text + body = r.json() + assert body["graph"] == old and body["version"] == 3 + assert body["status"] == "draft", f"恢复成 v1 之后仍显示 {body['status']}" + assert body["published_version"] == 2, "发布的那一版不受影响" + assert (await client.get(f"/api/workflows/{workflow_id}")).json()["status"] == "draft" + + +async def test_restoring_a_draft_stays_a_draft(client): + workflow_id = (await client.post("/api/workflows", json={"name": "恢复", "graph": _graph("a")})).json()["id"] + await client.patch(f"/api/workflows/{workflow_id}", json={"graph": _graph("b")}) + body = (await client.post(f"/api/workflows/{workflow_id}/versions/1/restore")).json() + assert body["status"] == "draft" and body["published_version"] is None diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index a21ec818..89c55f52 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -4,6 +4,7 @@ import type { ValidationIssue, VarIssue, Variable, Workflow, WorkflowVersion, } from '../types' import { localActor } from '../lib/actor' +import { VALIDATION_TITLE, describeValidation } from '../lib/validation' const BASE = '/api' @@ -69,16 +70,13 @@ function actorHeader(): Record { return actor ? { 'X-Actor': encodeURIComponent(actor) } : {} } -/** FastAPI 的 422 是 [{loc, msg, type}] 数组,直接 String() 会变成 [object Object] */ -function describeDetail(detail: unknown): string { +/** + * FastAPI 的 422 是 [{loc, msg, type}] 数组:直接 String() 是 [object Object],照拼 msg + * 又是 pydantic 的英文原文。按 type 翻成中文(lib/validation),path 用来查表单上的叫法 + */ +function describeDetail(detail: unknown, path?: string): string { if (typeof detail === 'string') return detail - if (Array.isArray(detail)) { - const parts = detail.map((d: any) => { - const loc = Array.isArray(d?.loc) ? d.loc.filter((x: unknown) => x !== 'body' && x !== 'query').join('.') : '' - return loc ? `${loc}:${d?.msg ?? ''}` : String(d?.msg ?? JSON.stringify(d)) - }) - return `提交的内容不符合要求:${parts.join(';')}` - } + if (Array.isArray(detail)) return `${VALIDATION_TITLE}:${describeValidation(detail, path).join(';')}` try { return JSON.stringify(detail) } catch { return String(detail) } } @@ -132,7 +130,7 @@ async function request(path: string, init?: RequestInit & { timeoutMs?: numbe } finally { if (timer) clearTimeout(timer) } - if (!res.ok) throw failure(res.status, res.statusText, await res.text().catch(() => '')) + if (!res.ok) throw failure(res.status, res.statusText, await res.text().catch(() => ''), path) report(true) if (res.status === 204) return undefined as T return res.json() @@ -145,7 +143,7 @@ const codeOf = (body: unknown): string | undefined => { } /** 非 2xx 的响应 → ApiError,顺带报告连接状态。fetch 和 XHR 两条路共用 */ -function failure(status: number, statusText: string, text: string): ApiError { +function failure(status: number, statusText: string, text: string, path?: string): ApiError { let body: any let isJson = false try { body = JSON.parse(text); isJson = true } catch { /* 响应体不是 JSON */ } @@ -159,7 +157,7 @@ function failure(status: number, statusText: string, text: string): ApiError { report(true) if (isJson) { const detail = body?.detail ?? body - return new ApiError(status, describeDetail(detail), { + return new ApiError(status, describeDetail(detail, path), { detail, raw: typeof body?.raw === 'string' ? body.raw : `${status} ${text.slice(0, 2000)}`, code: codeOf(body), }) @@ -214,7 +212,7 @@ function upload(path: string, form: FormData, opts?: UploadOptions): Promise< xhr.onload = () => { cleanup() if (xhr.status < 200 || xhr.status >= 300) { - reject(failure(xhr.status, xhr.statusText, xhr.responseText ?? '')) + reject(failure(xhr.status, xhr.statusText, xhr.responseText ?? '', path)) return } report(true) @@ -761,7 +759,7 @@ export function streamCopilot( return } report(true) - onEnd(isJson ? describeDetail(body?.detail ?? body) + onEnd(isJson ? describeDetail(body?.detail ?? body, '/copilot/generate-stream') : res.status >= 500 ? `后端出错了(${res.status}),详情看服务日志` : `请求没有成功(${res.status} ${res.statusText})`, { status: res.status, code: isJson ? codeOf(body) : undefined }) return diff --git a/frontend/src/canvas/FlowCanvas.tsx b/frontend/src/canvas/FlowCanvas.tsx index 56c1ce8b..06956f44 100644 --- a/frontend/src/canvas/FlowCanvas.tsx +++ b/frontend/src/canvas/FlowCanvas.tsx @@ -12,6 +12,7 @@ import { FlowEdge, MomentContext, RoutingContext, type EdgeRunState, type EdgeVi import { openInspector, stepsFirst, useSheet } from './InspectorSheet' import { NodeCard } from './NodeCard' import { NODE_CATEGORIES, NODE_DEFS, type NodeDef } from './nodeDefs' +import { loopFrames } from './loops' import { buildRoutes, NODE_WIDTH } from './routing' import { RunTimeline, useDock } from './RunTimeline' import { isComposing, toast } from '../components/ui' @@ -285,6 +286,44 @@ function useRemovedGhosts(): { seq: number; items: Ghost[] } | null { return ghosts } +// ------------------------------------------------------------------------- +// 循环体底框:垫在边和卡片下面,只画不接指针 +// ------------------------------------------------------------------------- + +/** + * 每个循环一块淡色区域,左上角写「循环体 · 最多 N 轮」;在跑的循环再补一句「第 k 轮」, + * 回放时是游标那一刻的轮次。几何只跟着节点、连线重算,事件进来只换标签上的轮次 + */ +const LoopFrames = memo(function LoopFrames({ nodes, edges, trace }: { + nodes: FlowNode[] + edges: Edge[] + trace: Trace +}) { + const frames = useMemo(() => loopFrames(nodes, edges), [nodes, edges]) + if (!frames.length) return null + return ( + +
+ + {frames.map((f) => )} + + {frames.map((f) => { + const n = trace.nodes[f.id] + const round = n?.state === 'running' && n.iteration ? n.iteration : null + return ( +
+ ↻ + 循环体 · 最多 {f.max} 轮 + {round && 第 {round} 轮} +
+ ) + })} +
+
+ ) +}) + // ------------------------------------------------------------------------- // 双击空白处快速添加:在光标处搜类型、回车放下。和节点库读同一份节点定义 // ------------------------------------------------------------------------- @@ -420,6 +459,18 @@ function CanvasInner() { // 走线方案整张图算一次。节点尺寸要等 React Flow 量完才有,量到之后 // nodes 会变,这里跟着重算,端口和车道就落到实测尺寸上。 const routes = useMemo(() => buildRoutes(nodes, edges), [nodes, edges]) + // 走廊挪不出地方的出口标签:节点 → 出口 → 最多多宽。卡片按它截短,不伸进拐弯 + const exitRooms = useMemo(() => { + const out = new Map>() + for (const e of edges) { + const exit = routes.get(e.id)?.exit + if (!exit) continue + const rooms = out.get(e.source) ?? {} + rooms[exit.handle] = Math.min(rooms[exit.handle] ?? Infinity, exit.room) + out.set(e.source, rooms) + } + return out + }, [routes, edges]) // ---- 此刻(实时或回放游标那一刻)的航迹 ---- // graph 直接用 store 里的 nodes / edges 数组:卡片那边按同样的引用取,缓存才对得上 @@ -498,24 +549,25 @@ function CanvasInner() { }) }, [edges, edgeStates, topo, view.trace, replayAt, hasRun, selectedId, pathView]) - // ---- 节点:注入拓扑层级(一次性时刻按它错开),只看执行路径时压暗没走的 ---- + // ---- 节点:注入拓扑层级(一次性时刻按它错开)和出口标签的宽度上限,只看执行路径时压暗没走的 ---- // 按原节点对象缓存:拖一个节点只换那一个的副本,其余卡片的 data 引用不变,memo 生效 const nodeCache = useRef(new WeakMap()) const flowNodes = useMemo(() => nodes.map((n) => { const rank = topo.rank[n.id] ?? 0 const off = pathView && !visited.has(n.id) - const key = `${rank}|${off ? 1 : 0}` + const exitRoom = exitRooms.get(n.id) + const key = `${rank}|${off ? 1 : 0}|${exitRoom ? JSON.stringify(exitRoom) : ''}` const hit = nodeCache.current.get(n) if (hit && hit.key === key) return hit.out const out: FlowNode = { ...n, className: clsx(n.className, off && 'sf-offpath') || undefined, style: { ...n.style, '--rank': rank } as CSSProperties, - data: { ...n.data, rank } as FlowNode['data'], + data: { ...n.data, rank, ...(exitRoom ? { exitRoom } : {}) } as FlowNode['data'], } nodeCache.current.set(n, { key, out }) return out - }), [nodes, topo, pathView, visited]) + }), [nodes, topo, pathView, visited, exitRooms]) // ---- 小地图的状态表 ---- // 小地图按节点和视口的并集缩进 150×100。这里只按节点算(视口一动就重算不值得), @@ -956,6 +1008,7 @@ function CanvasInner() { style={{ width: 150, height: 100 }} ariaLabel={hasRun ? '小地图(按运行状态着色)' : '小地图'} /> + {ghosts && ( {ghosts.items.map((g) => ( diff --git a/frontend/src/canvas/Inspector.tsx b/frontend/src/canvas/Inspector.tsx index b8e27d7b..18befb35 100644 --- a/frontend/src/canvas/Inspector.tsx +++ b/frontend/src/canvas/Inspector.tsx @@ -1,5 +1,6 @@ import { useEffect, useId, useMemo, useState } from 'react' import { createPortal } from 'react-dom' +import { Link } from 'react-router-dom' import { AlertTriangle, ChevronLeft, Copy, Lock, Maximize2, Plus, Trash2, X, XCircle } from 'lucide-react' import clsx from 'clsx' import { NODE_DEFS, syntaxOf, type FieldDef, type FieldSyntax } from './nodeDefs' @@ -503,7 +504,9 @@ function FieldInput({ field, id, nodeId, syntax, value, config, invalid, describ options={skills.filter((s) => s.enabled).map((s) => ({ value: s.name, label: s.name, hint: s.description }))} value={Array.isArray(value) ? value : []} onChange={onChange} - empty="还没有 Skill,去「方法论」页创建" + addLabel="添加 Skill" + empty={<>还没有可用的 Skill。 + 去「知识 → 方法论 Skill」创建} /> ) @@ -627,9 +630,11 @@ function SubgraphPicker({ id, value, version, invalid, describedBy, onChange }: // 复合编辑器 // ------------------------------------------------------------------------- -function MultiPick({ options, value, onChange, empty }: { +function MultiPick({ options, value, onChange, empty, addLabel = '添加工具' }: { options: { value: string; label: string; hint?: string; danger?: boolean; group?: string }[] - value: string[]; onChange: (v: string[]) => void; empty: string + value: string[]; onChange: (v: string[]) => void; empty: React.ReactNode + /** 展开按钮上写添加的是什么:只写「添加」时,一个检查器里有两个多选就分不清 */ + addLabel?: string }) { const [open, setOpen] = useState(false) const [query, setQuery] = useState('') @@ -658,14 +663,18 @@ function MultiPick({ options, value, onChange, empty }: { {/* 定位(revealField)把光标放在这儿,不放在前面那排芯片的 × 上 */} {open && (
setQuery(e.target.value)} autoFocus />
- {!filtered.length &&
{empty}
} + {!filtered.length && ( +
+ {options.length ? `没有匹配「${query.trim()}」的` : empty} +
+ )} {filtered.map((o) => (
)} - {/* 校验问题的角标:error 和 warning 同样醒目,谁也不挡谁 */} - {(hasErrors || hasWarnings) && ( + {/* 校验问题的角标:error 和 warning 同样醒目,谁也不挡谁。只在编辑时挂——运行中、 + 结果还留在画布上时,卡片上要读的是状态:实心琥珀的「! 1」和等待审批同一个色相, + 远景里又跟状态牌一样大,满屏的「没指定模型」会把真正的异常淹掉。问题清单照样在 + 工具栏的 chip 和问题面板里 */} + {editing && (hasErrors || hasWarnings) && (
{hasErrors && ✕ {errCount}} {hasWarnings && ! {warnCount}} @@ -1074,7 +1080,10 @@ function NodeCardImpl({ id, data, selected, isConnectable }: NodeProps {handle.label && ( {handle.label} diff --git a/frontend/src/canvas/loops.ts b/frontend/src/canvas/loops.ts new file mode 100644 index 00000000..93762ca6 --- /dev/null +++ b/frontend/src/canvas/loops.ts @@ -0,0 +1,194 @@ +/** + * 循环体底框:循环节点和它的循环体圈在一块淡色区域里,左上角写「循环体 · 最多 N 轮」。 + * + * 回边有了虚线和 ↺,读得出「从哪回到循环头」;可哪些节点每轮都要跑一遍、最多跑几轮, + * 以前只能顺着回边一个个倒推。嵌套循环框套框,外层留得宽一圈。 + * + * 框不是一个大矩形:循环体旁边常有同列、却不在循环里的节点(循环结束后才跑的那一支), + * 包围盒会把它们也圈进去。这里按列各圈各的,列与列之间用它们纵向重叠的那一段接起来, + * 得到一块阶梯形的区域。 + */ +import type { NodeType } from '../types' +import { NODE_WIDTH } from './routing' + +export interface LoopNodeLike { + id: string + position: { x: number; y: number } + measured?: { width?: number; height?: number } + data: { nodeType: NodeType; config: Record } +} + +export interface LoopEdgeLike { + source: string + target: string + sourceHandle?: string | null +} + +export interface LoopFrame { + /** 循环节点的 id */ + id: string + /** 轮廓,画布坐标 */ + path: string + /** 标签落点:轮廓左上角那条上边 */ + labelX: number + labelY: number + /** 每进来一次最多几轮(后端 control.run_loop 的 max_iterations,缺省 10) */ + max: number + /** 圈在里面的节点,含循环节点本身 */ + members: string[] +} + +/** 最内层的框离卡片留多宽;每多包一层再外扩这么多 */ +const PAD = 16 +const NEST = 14 +/** 两列的 x 差在这以内算同一列(和 routing 的 COLUMN_TOLERANCE 一致) */ +const COLUMN_TOLERANCE = 60 +/** 相邻两列纵向不重叠时,接起来的那一段至少伸进两边这么多 */ +const BRIDGE = 24 +const RADIUS = 10 + +/** + * 每个循环节点的循环体(不含它自己),和后端 schema.loop_bodies 同一个口径: + * 从非 done 出口出发、不经过循环节点能走到,又能绕回它的那些节点 + */ +export function loopBodies(nodes: LoopNodeLike[], edges: LoopEdgeLike[]): Map> { + const out = new Map>() + const loops = nodes.filter((n) => n.data.nodeType === 'loop') + if (!loops.length) return out + const succ = new Map() + const pred = new Map() + for (const e of edges) { + succ.set(e.source, [...(succ.get(e.source) ?? []), e.target]) + pred.set(e.target, [...(pred.get(e.target) ?? []), e.source]) + } + const reach = (starts: string[], step: Map, avoid: string): Set => { + const seen = new Set() + const stack = starts.filter((s) => s !== avoid) + while (stack.length) { + const id = stack.pop()! + if (seen.has(id)) continue + seen.add(id) + for (const x of step.get(id) ?? []) if (x !== avoid) stack.push(x) + } + return seen + } + for (const loop of loops) { + const entries = edges.filter((e) => e.source === loop.id && e.sourceHandle !== 'done').map((e) => e.target) + const forward = reach(entries, succ, loop.id) + const back = reach(pred.get(loop.id) ?? [], pred, loop.id) + out.set(loop.id, new Set([...forward].filter((id) => back.has(id)))) + } + return out +} + +interface Rect { l: number; r: number; t: number; b: number } + +/** 闭合折线画成带圆角的路径 */ +function closedRounded(points: { x: number; y: number }[]): string { + const n = points.length + let d = '' + for (let i = 0; i < n; i++) { + const prev = points[(i - 1 + n) % n] + const cur = points[i] + const next = points[(i + 1) % n] + const inLen = Math.hypot(cur.x - prev.x, cur.y - prev.y) + const outLen = Math.hypot(next.x - cur.x, next.y - cur.y) + const r = Math.min(RADIUS, inLen / 2, outLen / 2) + const a = { x: cur.x - ((cur.x - prev.x) / inLen) * r, y: cur.y - ((cur.y - prev.y) / inLen) * r } + const b = { x: cur.x + ((next.x - cur.x) / outLen) * r, y: cur.y + ((next.y - cur.y) / outLen) * r } + d += `${i ? 'L' : 'M'}${a.x} ${a.y}Q${cur.x} ${cur.y} ${b.x} ${b.y}` + } + return `${d}Z` +} + +/** 一组矩形(按 x 排好、相邻的已经接上)的并集轮廓。每个竖直切片里只有一段 */ +function outline(rects: Rect[]): { path: string; x: number; y: number } | null { + const xs = [...new Set(rects.flatMap((r) => [r.l, r.r]))].sort((a, b) => a - b) + const slabs: Rect[] = [] + for (let i = 0; i + 1 < xs.length; i++) { + const l = xs[i] + const r = xs[i + 1] + const over = rects.filter((x) => x.l <= l + 0.01 && x.r >= r - 0.01) + if (!over.length) continue + const t = Math.min(...over.map((x) => x.t)) + const b = Math.max(...over.map((x) => x.b)) + const last = slabs[slabs.length - 1] + if (last && Math.abs(last.r - l) < 0.01 && Math.abs(last.t - t) < 0.01 && Math.abs(last.b - b) < 0.01) last.r = r + else slabs.push({ l, r, t, b }) + } + if (!slabs.length) return null + const pts: { x: number; y: number }[] = [] + for (const s of slabs) pts.push({ x: s.l, y: s.t }, { x: s.r, y: s.t }) + for (let i = slabs.length - 1; i >= 0; i--) pts.push({ x: slabs[i].r, y: slabs[i].b }, { x: slabs[i].l, y: slabs[i].b }) + // 去掉重合点和共线的中间点,圆角才算得对 + const clean: { x: number; y: number }[] = [] + for (const p of pts) { + const last = clean[clean.length - 1] + if (!last || Math.abs(last.x - p.x) > 0.01 || Math.abs(last.y - p.y) > 0.01) clean.push(p) + } + if (clean.length > 1 && Math.abs(clean[0].x - clean[clean.length - 1].x) < 0.01 + && Math.abs(clean[0].y - clean[clean.length - 1].y) < 0.01) clean.pop() + const corners = clean.filter((p, i) => { + const a = clean[(i - 1 + clean.length) % clean.length] + const b = clean[(i + 1) % clean.length] + return !((Math.abs(a.x - p.x) < 0.01 && Math.abs(b.x - p.x) < 0.01) || (Math.abs(a.y - p.y) < 0.01 && Math.abs(b.y - p.y) < 0.01)) + }) + if (corners.length < 4) return null + return { path: closedRounded(corners), x: slabs[0].l, y: slabs[0].t } +} + +export function loopFrames(nodes: LoopNodeLike[], edges: LoopEdgeLike[]): LoopFrame[] { + const bodies = loopBodies(nodes, edges) + if (!bodies.size) return [] + const byId = new Map(nodes.map((n) => [n.id, n])) + // 每个循环里面还包着几层循环:外层按它往外扩,框套框不贴在一起 + const inner = new Map() + const depthOf = (id: string, seen: Set): number => { + if (inner.has(id)) return inner.get(id)! + let d = 0 + for (const m of bodies.get(id) ?? []) { + if (m !== id && bodies.has(m) && !seen.has(m)) d = Math.max(d, depthOf(m, new Set([...seen, id])) + 1) + } + inner.set(id, d) + return d + } + const frames: LoopFrame[] = [] + for (const [id, body] of bodies) { + if (!body.size) continue + const loop = byId.get(id) + if (!loop) continue + const pad = PAD + depthOf(id, new Set()) * NEST + const members = [id, ...body].map((m) => byId.get(m)).filter((n): n is LoopNodeLike => !!n) + // 按列圈:同一列的上下合成一段 + const cols: Rect[] = [] + for (const n of [...members].sort((a, b) => a.position.x - b.position.x)) { + const w = n.measured?.width || NODE_WIDTH + const h = n.measured?.height || 80 + const box = { l: n.position.x, r: n.position.x + w, t: n.position.y, b: n.position.y + h } + const last = cols[cols.length - 1] + if (last && box.l - last.l < COLUMN_TOLERANCE) { + last.r = Math.max(last.r, box.r) + last.t = Math.min(last.t, box.t) + last.b = Math.max(last.b, box.b) + } else cols.push(box) + } + const boxes: Rect[] = cols.map((c) => ({ l: c.l - pad, r: c.r + pad, t: c.t - pad, b: c.b + pad })) + // 相邻两列之间接一段:纵向有重叠就取重叠那段,没有就跨过缺口、两头各伸进去一点 + const bridges: Rect[] = [] + for (let i = 0; i + 1 < boxes.length; i++) { + const a = boxes[i] + const b = boxes[i + 1] + const t = Math.max(a.t, b.t) + const bottom = Math.min(a.b, b.b) + bridges.push(t < bottom + ? { l: a.r, r: b.l, t, b: bottom } + : { l: a.r, r: b.l, t: Math.min(a.b, b.b) - BRIDGE, b: Math.max(a.t, b.t) + BRIDGE }) + } + const shape = outline([...boxes, ...bridges.filter((r) => r.r > r.l)]) + if (!shape) continue + const max = Number(loop.data.config?.max_iterations) || 10 + frames.push({ id, path: shape.path, labelX: shape.x + 12, labelY: shape.y, max, members: members.map((m) => m.id) }) + } + // 外层先画:里层的框叠在上面 + return frames.sort((a, b) => b.members.length - a.members.length) +} diff --git a/frontend/src/canvas/routing.ts b/frontend/src/canvas/routing.ts index 7dca25e6..9ad9a5bd 100644 --- a/frontend/src/canvas/routing.ts +++ b/frontend/src/canvas/routing.ts @@ -41,6 +41,14 @@ const LANE_TOLERANCE = 6 const BAND_PAD = 12 /** 两列的中心距离小于它就算同一列。用户手拖过的节点不至于被拆成两列。 */ const COLUMN_TOLERANCE = 60 +/** 出口标签的左缘在卡片右边外这么远,和 index.css 的 .nc-exit(left: 100% + 8px)一致 */ +const EXIT_LABEL_DX = 8 +/** 标签右缘和拐上去的那道弯之间至少留的空。比圆角半径小一点:弯刚起头时还贴着水平线 */ +const EXIT_LABEL_GAP = 6 +/** 竖直车道离目标卡片至少这么远:末段水平线要放得下圆角和箭头 */ +const TARGET_ROOM = 26 +/** 出口多到这个数,标签改成骑在自己那条线上(NodeCard 的 nc-exits-dense) */ +export const DENSE_EXITS = 5 export interface Point { x: number @@ -54,6 +62,22 @@ export interface Route { /** 路径长度。边上的流光按它定速度——短线走得快、长线走得慢, * 视觉速度才是一致的;否则长边上的光点会慢得像卡住了 */ length: number + /** + * 这条线离开带标签的出口后往标签那一侧拐、走廊又挪不出地方时:那个出口的标签最多 + * 能占多宽(含内边距),超出的由卡片截短。放得下就没有这一项 + */ + exit?: { handle: string; room: number } +} + +/** + * 出口标签的宽度估算:9.5px 的字(出口密时 9px),中日韩字符按一个字宽、其余按 0.62 个, + * 加左右各 3px 内边距。宁可估宽一点:估窄了拐弯照样压字 + */ +export function exitLabelWidth(label: string, dense: boolean): number { + const size = dense ? 9 : 9.5 + let width = 6 + for (const ch of label) width += /[\u2e80-\uffff]/.test(ch) ? size : size * 0.62 + return Math.ceil(width) } /** buildRoutes 需要的节点信息,结构上就是 store 里的 FlowNode。 */ @@ -194,14 +218,24 @@ function assignLanes(segments: Segment[]): number { return lanes.length } -/** 车道在走廊里的 x。整束车道居中,走廊窄的时候自动压缩间距。 */ -function laneX(column: Column, next: Column, lane: number, total: number): number { +/** + * 车道在走廊里的 x。整束车道居中,走廊窄的时候自动压缩间距。 + * + * floor:走廊左侧有出口标签、线又往标签那一侧拐时,第一条车道至少要在这儿以右—— + * 居中的车道正好落在「快速模式」四个字的尾巴上,拐弯从字里穿过去。整束往右挪, + * 挪不下先压间距,再不够就挪到能挪的最右(剩下的由卡片截短标签) + */ +function laneX(column: Column, next: Column, lane: number, total: number, floor = 0): number { const left = column.right const avail = Math.max(0, next.left - left) - if (total <= 1) return left + avail / 2 - const gap = Math.max(6, Math.min(LANE, (avail - STUB * 2) / (total - 1))) - const span = gap * (total - 1) - return left + (avail - span) / 2 + lane * gap + let gap = total <= 1 ? 0 : Math.max(6, Math.min(LANE, (avail - STUB * 2) / (total - 1))) + let start = left + (avail - gap * (total - 1)) / 2 + if (floor > start) { + const right = next.left - TARGET_ROOM + if (total > 1 && floor + gap * (total - 1) > right) gap = Math.max(6, (right - floor) / (total - 1)) + start = Math.max(start, Math.min(floor, right - gap * (total - 1))) + } + return start + lane * gap } /** @@ -385,6 +419,23 @@ export function buildRoutes( tx: number ty: number band: number + /** 从哪个出口出来(没标出口的按第一个算) */ + handle: string + /** 那个出口的标签左缘 */ + labelLeft: number + /** 第一道弯至少要在这个 x 以右才不压标签;0 表示不用让 */ + floor: number + } + /** + * 第一道弯会不会压到出口标签。标签平时画在出线上方,只有往上拐的弯会穿过它; + * 出口密时标签骑在线上,往哪边拐都会。turnTo 是第一段竖线的另一头 + */ + const labelFloor = (node: Geometry, handleId: string, sy: number, turnTo: number): number => { + const label = node.handles.find((h) => h.id === handleId)?.label + if (!label) return 0 + const dense = node.handles.length >= DENSE_EXITS + const crosses = dense ? Math.abs(turnTo - sy) > 0.5 : turnTo < sy - 0.5 + return crosses ? node.right + EXIT_LABEL_DX + exitLabelWidth(label, dense) + EXIT_LABEL_GAP : 0 } const plans: Plan[] = [] const usedBands: number[] = [] @@ -418,11 +469,16 @@ export function buildRoutes( band = freeBand(columns, from, to, ideal, usedBands) usedBands.push(band) } + const handle = resolveHandleId(source, e.sourceHandle) + const turnTo = kind === 'short' ? ty : kind === 'self' ? source.bottom + 34 : band plans.push({ edge: e, kind, colS, colT, sx: source.right + SOURCE_PORT_DX, sy, tx: target.left + TARGET_PORT_DX, ty, band, + handle, + labelLeft: source.right + EXIT_LABEL_DX, + floor: labelFloor(source, handle, sy, turnTo), }) } @@ -450,11 +506,19 @@ export function buildRoutes( corridorLanes.set(corridor, total) for (const seg of segments) laneOf.set(`${seg.edgeId}\u0000${corridor}`, seg.lane) } + // 走廊左侧有出口标签要让:整条走廊的车道一起往右挪,谁的竖线都不从标签里穿过 + const corridorFloor = new Map() + for (const plan of plans) { + if (plan.floor && plan.kind !== 'self') { + corridorFloor.set(plan.colS, Math.max(corridorFloor.get(plan.colS) ?? 0, plan.floor)) + } + } const laneAt = (corridor: number, edgeId: string): number | null => { if (corridor < 0 || corridor >= columns.length - 1) return null const lane = laneOf.get(`${edgeId}\u0000${corridor}`) ?? 0 - return laneX(columns[corridor], columns[corridor + 1], lane, corridorLanes.get(corridor) ?? 1) + return laneX(columns[corridor], columns[corridor + 1], lane, corridorLanes.get(corridor) ?? 1, + corridorFloor.get(corridor)) } // ---- 4. 出路径 ---- @@ -471,7 +535,8 @@ export function buildRoutes( } else if (plan.kind === 'long' || plan.kind === 'back') { const outX = laneAt(plan.colS, plan.edge.id) const inX = laneAt(plan.colT - 1, plan.edge.id) - const startX = outX ?? plan.sx + STUB + // 源在最右一列、右边没有走廊:拐弯点不受车道约束,直接让过标签 + const startX = outX ?? Math.max(plan.sx + STUB, plan.floor) const endX = inX ?? plan.tx - 26 points = [ { x: plan.sx, y: plan.sy }, @@ -484,7 +549,7 @@ export function buildRoutes( } else { // 自环:贴着卡片右边出去,从下面兜回来 const node = byId.get(plan.edge.source)! - const outX = node.right + 26 + const outX = Math.max(node.right + 26, plan.floor) const inX = node.left - 26 const band = node.bottom + 34 points = [ @@ -497,11 +562,17 @@ export function buildRoutes( ] } const { mid, length } = polylineMidpoint(points) + // 车道挪到头也没让开标签:告诉卡片这个出口的标签最多能多宽 + const bend = points[1].x + const exit = plan.floor && bend < plan.floor + ? { handle: plan.handle, room: Math.max(0, Math.floor(bend - EXIT_LABEL_GAP - plan.labelLeft)) } + : undefined routes.set(plan.edge.id, { path: roundedPath(points), labelX: mid.x, labelY: mid.y, length, + ...(exit ? { exit } : {}), }) } diff --git a/frontend/src/canvas/surface.css b/frontend/src/canvas/surface.css index d207f81b..f010c52d 100644 --- a/frontend/src/canvas/surface.css +++ b/frontend/src/canvas/surface.css @@ -45,6 +45,11 @@ .sf-canvas[data-lod='signal'] .sf-loop-badge { visibility: hidden; } +/* 校验角标在信号档只留 error:它会拦住运行,远景里也要找得到。warning 多半是「没指定 + 模型」这类提示,每个模型节点一枚,反向放大之后比卡片还显眼 */ +.sf-canvas[data-lod='signal'] .nc-issue .is-warning { + display: none; +} /* 选中的边(编辑态) */ .sf-canvas .react-flow__edge.selected .react-flow__edge-path { @@ -348,6 +353,61 @@ text-overflow: ellipsis; } +/* 循环体底框:垫在边和卡片下面(视口里的层叠上下文里排最底),不接指针,平移、框选、 + 点空白处都照常。线宽不随缩放变,远景里仍是一道 1px 的细线;颜色用循环的类型色, + 不用状态色——框本身不表达运行态,只有标签上的「第 k 轮」是 */ +.sf-loops { + position: absolute; + top: 0; + left: 0; + z-index: -1; + pointer-events: none; +} +.sf-loops-svg { + position: absolute; + top: 0; + left: 0; + width: 1px; + height: 1px; + overflow: visible; +} +.sf-loop-frame { + fill: color-mix(in srgb, var(--nt-loop) 5%, transparent); + stroke: color-mix(in srgb, var(--nt-loop) 40%, transparent); + stroke-width: 1px; + vector-effect: non-scaling-stroke; +} +.sf-loop-tag { + position: absolute; + top: 0; + left: 0; + display: flex; + align-items: center; + gap: 0.4em; + padding: 0 0.55em; + border: 1px solid color-mix(in srgb, var(--nt-loop) 40%, transparent); + border-radius: 999px; + background: var(--bg); + color: var(--text-dim); + /* 和删除虚线框的标签同一条规矩:精简档里也不小于 11px,远景档不画 */ + font-size: calc(11px / min(max(var(--zoom, 1), 0.35), 1)); + line-height: 1.5; + white-space: nowrap; +} +.sf-loop-glyph { + color: var(--nt-loop); +} +.sf-loop-tag b { + color: var(--st-running); + font-weight: 600; +} +.sf-canvas[data-lod='signal'] .sf-loop-tag { + visibility: hidden; +} +.sf-canvas[data-path-only] .sf-loops { + opacity: 0.45; +} + /* Copilot 这一轮删掉的节点:原地一道虚线框,停一下再淡出(时长和 FlowCanvas 的 GHOST_MS 一致)。框在画布坐标里,跟着平移缩放;标签的字按缩放补回来,精简档里 (窄画布打开就是 0.4)也不小于 11px,到远景档才跟着缩小。长名字由 max-width 截成省略号 */ @@ -632,6 +692,27 @@ border-color: var(--border-strong); font-weight: 600; } +/* 以谁的名义发起:正式运行要留痕。没署名用等待色说出来,和审批卡、发布弹窗同一个说法 */ +.sf-pop-sign { + margin-bottom: 8px; + color: var(--text-dim); + font-size: var(--text-2xs); + line-height: 1.55; +} +.sf-pop-sign b { + color: var(--text); + font-weight: 600; +} +.sf-pop-sign.is-unsigned { + color: var(--st-waiting); +} +.sf-pop-sign a { + text-decoration: underline; + text-underline-offset: 2px; +} +.sf-pop-sign a:hover { + color: var(--text); +} /* 「去审批」落到右栏那张审批卡上时描一圈,1.6 秒后撤掉。静态的,不做动画 */ .sf-flash { diff --git a/frontend/src/dev/preview.tsx b/frontend/src/dev/preview.tsx index 70c9d865..81a7c9b8 100644 --- a/frontend/src/dev/preview.tsx +++ b/frontend/src/dev/preview.tsx @@ -212,6 +212,15 @@ function synthetic(name: string): StreamTurn[] { return [{ id: 'team-live', question: '比较三家供应商的交期风险', phase: 'running', status: '运行中', steps: decodeRun(ev), runId: 'syn-team-live' }] } + case 'team-cancelled': { + // 第 1 轮三人都还在跑时被取消:那一轮不知道本来要多久 + const ev = rebase(teamRun('members').filter((e) => + !(e.data?.agent === '物流员' && (e.type === 'agent.step.end' || e.type === 'llm.end')))) + const last = ev[ev.length - 1] + ev.push({ seq: last.seq + 1, type: 'run.cancelled', node_id: null, ts: last.ts + 1, data: {} }) + return [{ id: 'team-cancelled', question: '比较三家供应商的交期风险', phase: 'done', statusCode: 'cancelled', + steps: decodeRun(ev), runId: 'syn-team-cancelled' }] + } case 'team-routing': { const ev = rebase(teamRun('routing')) return [{ id: 'team-routing', question: '比较三家供应商的交期风险', phase: 'running', status: '运行中', @@ -378,6 +387,23 @@ function Growing({ dense }: { dense: boolean }) { ) } +/** + * 几轮已经完成的对话,执行过程按需取回:window.__expand(i) 给第 i 轮填上步骤,和问数据页点 + * 「看执行过程」一样。check-stream 用它验证取回的历史步骤不算「新进展」、也不把人拽走 + */ +function Expanding({ dense, n }: { dense: boolean; n: number }) { + const [open, setOpen] = useState([]) + useEffect(() => { + ;(window as any).__expand = (i: number) => setOpen((x) => [...x, i]) + }, []) + const turns: StreamTurn[] = Array.from({ length: n }, (_, i) => ({ + id: `past-${i}`, question: `第 ${i + 1} 个问题:把这批报表各查一遍`, phase: 'done', status: '已完成', + steps: open.includes(i) ? decodeRun(pipelineRun(12), { status: 'succeeded' }) : [], + output: { result: longReport() }, runId: `syn-past-${i}`, + })) + return +} + /** 审批卡的上下文:等了多久、挂在哪个节点、将以谁的名义签批 */ const APPROVAL = { id: 'ap-1', run_id: 'syn-mixed', node_id: 'review', mode: 'approve' as const, @@ -418,6 +444,7 @@ function Preview() { if (md) return
if (params.get('grow') === '1') return + if (params.get('expand')) return if (params.get('approval') === '1') { return (
diff --git a/frontend/src/dev/ui-harness.tsx b/frontend/src/dev/ui-harness.tsx index e5c6ad82..d241cf60 100644 --- a/frontend/src/dev/ui-harness.tsx +++ b/frontend/src/dev/ui-harness.tsx @@ -8,7 +8,7 @@ import { SectionBar, Skeleton, StatusBadge, StatusPill, Tabs, TabPanel, ToastHost, confirmDialog, deferDelete, promptDialog, toast, useRadioGroup, withoutDeferred, } from '../components/ui' -import { ApiError, api } from '../api/client' +import { ApiError, api, streamCopilot } from '../api/client' import { useCatalog, useDatasources, useOnReconnect } from '../store/catalog' import { STATUS } from '../lib/status' import { formatClock, formatCost, formatDateTime, formatDuration, formatTime, formatTokens } from '../lib/format' @@ -20,6 +20,7 @@ import * as errors from '../lib/errors' import * as explain from '../lib/explain' import * as health from '../lib/health' import * as actor from '../lib/actor' +import * as validation from '../lib/validation' import '../index.css' /** @@ -426,10 +427,10 @@ function Harness() { } ;(window as any).__ui = { - toast, confirmDialog, promptDialog, useCatalog, ApiError, api, + toast, confirmDialog, promptDialog, useCatalog, ApiError, api, streamCopilot, mountDatasources: (n: number) => setDatasourceConsumers(n), // 检查脚本直接拿应用同一份模块实例测 lib:instanceof ApiError 才靠得住 - lib: { format, status, keys, terms, errors, explain, health, actor }, + lib: { format, status, keys, terms, errors, explain, health, actor, validation }, } createRoot(document.getElementById('root')!).render( diff --git a/frontend/src/lib/errors.ts b/frontend/src/lib/errors.ts index 730db9a3..1082a67e 100644 --- a/frontend/src/lib/errors.ts +++ b/frontend/src/lib/errors.ts @@ -9,6 +9,7 @@ */ import { ApiError } from '../api/client' +import { VALIDATION_TITLE } from './validation' export interface HumanError { /** 一句人话:发生了什么 */ @@ -45,6 +46,11 @@ const CJK_RE = /[一-鿿]/ function fromText(text: string, { network = true }: { network?: boolean } = {}): Omit & { kind?: HumanError['kind'] } { const raw = text.trim() if (!raw) return { title: '出错了,但没有给出原因', raw } + // 422:client 已经把 pydantic 的原文逐条翻好了(lib/validation)。标题固定、逐条进原因, + // 不交给 splitSentence——那边会在第一个「;」处把第二条切成原因、第一条挂在标题上 + if (raw.startsWith(`${VALIDATION_TITLE}:`)) { + return { title: VALIDATION_TITLE, reason: raw.slice(VALIDATION_TITLE.length + 1), action: '按提示改好再提交。' } + } if (network && NETWORK_RE.test(raw)) return { ...NETWORK_ERROR, raw } if (/exit (?:code )?undefined|exit_code.*none/i.test(raw)) { return { title: '请求没到沙箱', reason: '沙箱没有返回退出码,可能没启动或者中途被中断。', action: '看一眼设置里的沙箱状态,再重试。', raw } diff --git a/frontend/src/lib/validation.ts b/frontend/src/lib/validation.ts new file mode 100644 index 00000000..b21a2834 --- /dev/null +++ b/frontend/src/lib/validation.ts @@ -0,0 +1,183 @@ +/** + * FastAPI 的 422(请求没过 pydantic 校验)翻成人话。 + * + * 422 的 detail 是 [{type, loc, msg, input, ctx}]:msg 是 pydantic 的英文原文,loc 是 + * 请求体里的内部键名。原样拼出来就是「name:Field required」——表单大多先在前端 + * 校验过,但 Copilot、画布这类只靠后端校验的路径会直接撞上。 + * + * 这里按 type 翻成中文,loc 换成表单上的叫法;查不到叫法就写字段路径,没见过的 + * type 写笼统说法。英文原文不丢:ApiError 的 detail 和 raw 里都在,界面收进「详情」。 + * 输入值(input)一律不回显:密码、密钥也可能在里面。 + */ + +export const VALIDATION_TITLE = '提交的内容不符合要求' + +export interface ValidationItem { + type?: string + loc?: (string | number)[] + msg?: string + ctx?: Record +} + +/** 多数表单上一样的叫法 */ +const COMMON_LABELS: Record = { + name: '名称', + description: '说明', + kind: '类型', + enabled: '启用', + title: '标题', + content: '内容', + tags: '标签', +} + +/** + * 按接口覆盖:同一个键在不同表单上叫法不同(数据源的 name 是「标识」, + * 自定义工具的 description 是「描述」)。和页面上 的写法保持一致, + * 先匹配到的算数,所以更具体的路径写在前面 + */ +const LABELS_BY_PATH: [RegExp, Record][] = [ + [/^\/(settings\/)?providers/, { base_url: 'Base URL', api_key: 'API Key', default_model: '默认模型', models: '可选模型' }], + [/^\/datasources\/upload/, { name: '数据源名', header_row: '表头在第几行', file: '文件' }], + [/^\/datasources/, { + name: '标识', host: '主机', port: '端口', database: '数据库', username: '用户名', password: '密码', + readonly: '只读', options: '高级参数', + }], + [/^\/custom-tools/, { description: '描述', parameters: '参数 JSON Schema', config: '配置' }], + [/^\/mcp/, { transport: '传输方式', command: '命令', args: '参数', env: '环境变量', url: 'URL' }], + [/^\/tools\//, { args: '参数', sandbox_session: '沙箱会话' }], + [/^\/memory/, { importance: '重要度', scope: '作用域' }], + [/^\/kb/, { collection: '知识库', file: '文件' }], + [/^\/skills/, { description: '一句话说明', instructions: '指令内容', examples: '示例', suggested_tools: '建议工具' }], + [/^\/workflows/, { graph: '工作流', note: '版本说明', level: '发布级别', version: '版本' }], + [/^\/copilot/, { instruction: '输入的内容', base_graph: '当前工作流', datasource_ids: '圈定的数据源', question: '问题' }], + [/^\/runs/, { + input: '输入', run_class: '运行类别', version: '版本', memory_scope: '记忆作用域', collection: '知识库', + workflow_id: '工作流', graph: '工作流', + }], + [/^\/conversations/, { question: '问题', archived: '归档' }], + [/^\/settings/, { values: '设置项' }], +] + +function labelOf(key: string, path?: string): string | undefined { + const own = path ? LABELS_BY_PATH.find(([re]) => re.test(path))?.[1] : undefined + return own?.[key] ?? COMMON_LABELS[key] +} + +/** + * loc → 「字段」。每一段都查得到叫法才换(数组下标写成「第 N 项」),有一段查不到 + * 就整条写字段路径:半中半英的「工作流 › nodes › type」比路径还难认 + */ +function fieldOf(loc: (string | number)[], path?: string): string { + const [where, ...rest] = loc + const segs = where === 'body' || where === 'query' || where === 'path' || where === 'header' || where === 'cookie' + ? rest : loc + if (!segs.length) return '' + const names = segs.map((s) => (typeof s === 'number' ? `第 ${s + 1} 项` : labelOf(s, path))) + const field = names.every(Boolean) && typeof segs[0] === 'string' + ? `「${names[0]}」${names.slice(1).join('')}` + : `「${segs.join('.')}」` + if (where === 'query') return `参数${field}` + if (where === 'path') return `地址里的${field}` + return field +} + +const num = (v: unknown) => (typeof v === 'number' ? String(v) : String(v ?? '')) + +/** ctx.expected:「'a', 'b' or 'c'」或「1, 2 or 3」→ ['a', 'b', 'c'] */ +function choicesOf(expected: unknown): string[] { + if (typeof expected !== 'string' || !expected.trim()) return [] + const quoted = [...expected.matchAll(/'((?:[^'\\]|\\.)*)'/g)].map((m) => m[1]) + return quoted.length ? quoted : expected.split(/,\s*|\s+or\s+/).map((s) => s.trim()).filter(Boolean) +} + +const joinChoices = (xs: string[]) => (xs.length > 1 ? `${xs.slice(0, -1).join('、')} 或 ${xs[xs.length - 1]}` : xs[0]) + +/** 自定义校验器(value_error / assertion_error)的话是后端写的:写的是中文就照用 */ +function customMessage(msg: string | undefined): string | undefined { + const text = (msg ?? '').replace(/^(?:Value error|Assertion failed),\s*/, '').trim() + return /[一-鿿]/.test(text) ? text : undefined +} + +/** 一条:「字段」+ 怎么了。field 为空(整个请求体)时各自单说 */ +function describeOne(d: ValidationItem, path?: string): string { + const type = d.type ?? '' + const ctx = d.ctx ?? {} + if (type === 'json_invalid') return '提交的内容不是合法的 JSON' + const field = fieldOf(Array.isArray(d.loc) ? d.loc : [], path) + if (!field && type === 'missing') return '没有收到提交的内容' + const f = field || '提交的内容' + switch (type) { + case 'missing': + return `${f}没有填` + case 'string_too_short': + return Number(ctx.min_length) <= 1 ? `${f}不能为空` : `${f}太短,至少 ${num(ctx.min_length)} 个字符` + case 'string_too_long': + return `${f}太长,最多 ${num(ctx.max_length)} 个字符` + case 'too_short': + return `${f}至少要 ${num(ctx.min_length)} 项` + case 'too_long': + return `${f}最多 ${num(ctx.max_length)} 项` + case 'string_pattern_mismatch': + return `${f}格式不对` + case 'string_type': + return `${f}要填文字` + case 'int_parsing': + case 'int_type': + case 'int_from_float': + return `${f}要填整数` + case 'float_parsing': + case 'float_type': + case 'decimal_parsing': + case 'decimal_type': + return `${f}要填数字` + case 'bool_parsing': + case 'bool_type': + return `${f}只能是「是」或「否」` + case 'greater_than': + return `${f}要大于 ${num(ctx.gt)}` + case 'greater_than_equal': + return `${f}不能小于 ${num(ctx.ge)}` + case 'less_than': + return `${f}要小于 ${num(ctx.lt)}` + case 'less_than_equal': + return `${f}不能大于 ${num(ctx.le)}` + case 'literal_error': + case 'enum': { + const xs = choicesOf(ctx.expected) + // 列太长就不列了:一长串内部枚举值对填表的人没有帮助 + return xs.length && xs.length <= 6 ? `${f}只能取 ${joinChoices(xs)}` : `${f}不在允许的取值里` + } + case 'list_type': + case 'tuple_type': + case 'set_type': + return `${f}要是一个列表` + case 'dict_type': + case 'model_type': + case 'model_attributes_type': + return `${f}格式不对,要是一组键值` + case 'url_parsing': + case 'url_type': + case 'url_scheme': + return `${f}不是合法的网址` + case 'date_parsing': + case 'date_type': + case 'datetime_parsing': + case 'datetime_type': + case 'time_parsing': + return `${f}不是合法的日期或时间` + case 'extra_forbidden': + return `${f}是多余的,后端不认识这一项` + case 'value_error': + case 'assertion_error': { + const said = customMessage(d.msg) + return said ? (field ? `${field}:${said}` : said) : `${f}取值不对` + } + default: + return `${f}不符合要求` + } +} + +/** 422 的 detail 数组 → 一条条中文。path 是请求路径(不带 /api),用来查表单叫法 */ +export function describeValidation(items: unknown[], path?: string): string[] { + return items.map((d) => (d && typeof d === 'object' ? describeOne(d as ValidationItem, path) : '有一项不符合要求')) +} diff --git a/frontend/src/pages/ChatPage.tsx b/frontend/src/pages/ChatPage.tsx index c60d357d..9f35f2ed 100644 --- a/frontend/src/pages/ChatPage.tsx +++ b/frontend/src/pages/ChatPage.tsx @@ -9,13 +9,14 @@ import { ApiError, api } from '../api/client' import { ApprovalCard } from '../run/RunPanel' import { AssistantStream, type StreamTurn, type TurnFailure } from '../run/AssistantStream' import { PromptBox } from '../run/Composer' -import { decodeCopilot, decodeRun } from '../run/decode' +import { decodeCopilot, decodeRun, exitLabels } from '../run/decode' +import { sourceHandles } from '../canvas/nodeDefs' import { isComposing, PageHeader, Skeleton, Spinner, StatusBadge, TechDetails, toast } from '../components/ui' import { humanizeError } from '../lib/errors' import { explainRunError } from '../lib/explain' import { canLeave, leavePass } from '../lib/leave' import { formatNumber, formatTime } from '../lib/format' -import { useCatalog, useDatasources, useOnReconnect } from '../store/catalog' +import { useCatalog, useCatalogListState, useDatasources, useOnReconnect, type CatalogListState } from '../store/catalog' import { agentSteps, busyTurn, isBusy, stepsVisible, useChat, type Attempt, type ChatTurn, type Failure, type ScopeSource, } from '../store/chat' @@ -316,7 +317,8 @@ export function ChatPage() { } return ( -
+ // relative:窄屏上会话列表是浮在正文上面的抽屉,按这一层定位 +
} title="问数据" @@ -384,7 +386,12 @@ function toStreamTurn(turn: ChatTurn): StreamTurn { : undefined, // 从库里恢复、还没点开「执行过程」的轮次只有问题和答案;点开后又收起的, // 步骤留在内存里但不画 - steps: stepsVisible(turn) ? [...decodeCopilot(turn.ops), ...decodeRun(turn.events, turn.final)] : [], + steps: stepsVisible(turn) ? [...decodeCopilot(turn.ops), ...decodeRun(turn.events, turn.final, { + // 分支、循环那一行写这一轮工作流里出口的说明,不写 case 的 key + exitLabelOf: turn.graph?.nodes?.length + ? exitLabels(turn.graph.nodes.map((n) => ({ id: n.id, type: n.type, config: n.data?.config })), sourceHandles) + : undefined, + })] : [], thinking: turn.thinking, output: turn.output, error: turn.phase === 'error' && f ? streamError(turn, f) : turn.error || undefined, @@ -864,6 +871,8 @@ function ChatHero({ sources, usable, scope, onScope, picker, inputRef, draft, se }) { const collections = useCatalog((s) => s.collections) const tools = useCatalog((s) => s.tools) + const collectionsState = useCatalogListState('collections') + const toolsState = useCatalogListState('tools') const byConversation = useChat((s) => s.byConversation) const list = sources.list // 停用的库 Copilot 看不见,拿它造句等于教人问一个答不了的问题 @@ -904,8 +913,8 @@ function ChatHero({ sources, usable, scope, onScope, picker, inputRef, draft, se : list.length ? `${list.length} 个数据源` : '还没有数据源'} /> } - text={`知识库 ${collections.length} 个`} /> - } text={`工具 ${tools.length} 个`} /> + text={countLine('知识库', collections.length, collectionsState)} /> + } text={countLine('工具', tools.length, toolsState)} />
{/* 库名本身就是开关:点一下这一问只查它。以前它只是一行说明文字,想换个库问 @@ -1067,6 +1076,15 @@ function ScopePicker({ sources, scope, onChange, unconfirmed }: { ) } +/** + * 能力条上的「知识库 N 个」。没取回来(后端断着、请求出错)时手上的空列表不是「0 个」, + * 和数据源那一项一样说没取回来;还在路上写「—」 + */ +function countLine(what: string, n: number, state: CatalogListState): string { + if (state === 'ok') return `${what} ${n} 个` + return state === 'loading' ? `${what} —` : `${what}没取回来` +} + function Capability({ to, icon, text }: { to: string; icon: ReactNode; text: string }) { return ( diff --git a/frontend/src/pages/ConversationList.tsx b/frontend/src/pages/ConversationList.tsx index 7bc6cd20..264b6d2d 100644 --- a/frontend/src/pages/ConversationList.tsx +++ b/frontend/src/pages/ConversationList.tsx @@ -38,9 +38,19 @@ export function ConversationList() { // 相对时间和分组一分钟重算一次就够:「刚刚」「3 分钟前」不需要更细 const now = useTicker(60_000) + const narrow = useNarrow() + const [collapsed, setCollapsed] = useState(narrow) + // 跨过断点时跟着变;窄屏上挑了一个对话(或新建、从回收站点开)就把抽屉收回去 + useEffect(() => { setCollapsed(narrow) }, [narrow]) + useEffect(() => { if (narrow) setCollapsed(true) }, [currentId, narrow]) + // 切会话 = 换地址,不是改 store。store 那个 currentId 是 URL 的派生缓存, // 在这里直接 set 的话,地址栏不动、刷新就跳回旧的那个,前进后退也全失效 - const open = (id: string) => navigate(`/chat/${id}`) + const open = (id: string) => { + navigate(`/chat/${id}`) + // 窄屏上点的就是当前这个时地址不变,抽屉也得收 + if (narrow) setCollapsed(true) + } const startNew = async () => { try { @@ -79,7 +89,6 @@ export function ConversationList() { }, }) } - const [collapsed, setCollapsed] = useState(false) const [editing, setEditing] = useState(null) const [query, setQuery] = useState('') @@ -100,26 +109,7 @@ export function ConversationList() { : list), [list, needle]) const groups = useMemo(() => groupByDay(shown, now), [shown, now]) - if (collapsed) { - return ( -
- - -
- ) - } - - if (showTrash) { - // 相对时间跟着这一层每分钟重渲染 - return setShowTrash(false)} /> - } - - return ( + const listPanel = ( ) + + const strip = ( +
+ + +
+ ) + if (collapsed) return strip + + // 相对时间跟着这一层每分钟重渲染 + const panel = showTrash + ? setShowTrash(false)} /> + : listPanel + if (!narrow) return panel + // 窄屏上 240px 的列表和正文抢宽度,正文被挤成一字一行、整页横向溢出:列表改成浮在 + // 正文上面的抽屉,收起条留在原处占位,开合时正文不跟着跳 + return ( + <> + {strip} +
setCollapsed(true)} /> +
+ {panel} +
+ + ) +} + +/** 窄于 768px 算窄屏:会话列表默认收起,展开时是抽屉 */ +function useNarrow(): boolean { + const query = '(max-width: 767px)' + const [narrow, setNarrow] = useState(() => typeof matchMedia === 'function' && matchMedia(query).matches) + useEffect(() => { + if (typeof matchMedia !== 'function') return + const mq = matchMedia(query) + const on = () => setNarrow(mq.matches) + mq.addEventListener('change', on) + return () => mq.removeEventListener('change', on) + }, []) + return narrow } /** 行尾的浮层按钮:悬停或键盘聚焦到这一行才出现,渐隐背景盖住标题尾巴而不挤占宽度 */ diff --git a/frontend/src/pages/StudioPage.tsx b/frontend/src/pages/StudioPage.tsx index 863cefd4..4d0137cd 100644 --- a/frontend/src/pages/StudioPage.tsx +++ b/frontend/src/pages/StudioPage.tsx @@ -1,7 +1,7 @@ -import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react' import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom' import { - AlertTriangle, Check, ChevronDown, History, LayoutGrid, PanelRightClose, PanelRightOpen, Plus, + AlertTriangle, Check, ChevronDown, History, LayoutGrid, MoreHorizontal, PanelRightClose, PanelRightOpen, Plus, Redo2, RotateCw, Save, ShieldCheck, Square, Undo2, Variable, Wand2, XCircle, } from 'lucide-react' import clsx from 'clsx' @@ -15,7 +15,7 @@ import { VersionsSheet } from '../canvas/VersionsSheet' import { PublishDialog } from '../canvas/PublishDialog' import { WorkflowPicker, confirmDiscard, createWorkflow, takeDiscarded } from '../canvas/WorkflowPicker' import { problemsOf, type Problem } from '../canvas/issues' -import { STUDIO_SHORTCUTS, hintOf, type StudioShortcutId } from '../canvas/shortcuts' +import { STUDIO_SHORTCUTS, hintOf, studioShortcut, type StudioShortcutId } from '../canvas/shortcuts' import { AssistantPanel } from '../run/AssistantPanel' import { RunControl } from '../run/RunControl' import { useRunClock } from '../run/useRunClock' @@ -27,13 +27,15 @@ import { } from '../components/ui' import { isNetworkError } from '../lib/errors' import { formatClock } from '../lib/format' -import { isTypingTarget, matchShortcut } from '../lib/keys' +import { formatShortcut, isTypingTarget, matchShortcut } from '../lib/keys' import { WORKFLOW_STATUS_LABEL } from '../lib/terms' import type { Workflow } from '../types' // 三栏的收起状态存在这台浏览器里。读写都可能抛(隐私模式、存储被禁),抛了就用默认值 const PALETTE_KEY = 'agentlab.studio.palette' const ASSISTANT_KEY = 'agentlab.studio.assistant' +/** 窄屏上助手栏的开合单独记:宽屏上一直开着,不等于在 1024 的笔记本上也要它压掉半张画布 */ +const ASSISTANT_NARROW_KEY = 'agentlab.studio.assistant.narrow' const readPref = (key: string): 'open' | 'closed' | null => { try { const v = localStorage.getItem(key) @@ -45,8 +47,12 @@ const readPref = (key: string): 'open' | 'closed' | null => { const writePref = (key: string, open: boolean) => { try { localStorage.setItem(key, open ? 'open' : 'closed') } catch { /* 下次用默认值 */ } } -/** 窄于这个宽度默认收起节点库:1024 宽时三栏固定占掉 624px,画布只剩约 400px */ +/** + * 窄于这个宽度:节点库默认收成图标轨,助手栏默认收起、展开时浮在画布上而不是挤它。 + * 1024 宽时三栏固定占掉 624px,画布只剩约 400px;768 宽时 8 个节点只看得见 3 个 + */ const NARROW = 1280 +const isNarrow = () => window.innerWidth < NARROW /** 助手栏可拖宽:长 prompt、成员 system 在 360px 里没法编辑;再宽画布就不够了 */ const ASIDE_KEY = 'agentlab.studio.assistantWidth' const ASIDE_MIN = 300 @@ -133,7 +139,20 @@ export function StudioPage() { const pref = readPref(PALETTE_KEY) return pref ? pref === 'open' : window.innerWidth >= NARROW }) - const [assistantOpen, setAssistantOpen] = useState(() => readPref(ASSISTANT_KEY) !== 'closed') + // 窗口拖过门槛时只换摆法(占位 / 浮层),不替人开合:正开着的栏不会因为拖窄一点就没了 + const [narrow, setNarrow] = useState(isNarrow) + useEffect(() => { + const mq = matchMedia(`(max-width: ${NARROW - 0.02}px)`) + const sync = () => setNarrow(mq.matches) + mq.addEventListener('change', sync) + return () => mq.removeEventListener('change', sync) + }, []) + const narrowRef = useRef(narrow) + narrowRef.current = narrow + const [assistantOpen, setAssistantOpen] = useState(() => { + const pref = readPref(isNarrow() ? ASSISTANT_NARROW_KEY : ASSISTANT_KEY) + return pref ? pref === 'open' : !isNarrow() + }) const [asideWidth, setAsideWidth] = useState(readAsideWidth) const togglePalette = useCallback((open?: boolean) => { @@ -147,7 +166,7 @@ export function StudioPage() { const toggleAssistant = useCallback((open?: boolean) => { const next = open ?? !assistantRef.current assistantRef.current = next - writePref(ASSISTANT_KEY, next) + writePref(narrowRef.current ? ASSISTANT_NARROW_KEY : ASSISTANT_KEY, next) setAssistantOpen(next) // 属性面板和版本历史都叠在这一栏里:栏收起了它们也跟着收,别在看不见的地方开着 if (!next) { @@ -371,6 +390,13 @@ export function StudioPage() { toggleAssistant(true) select(null) }, [toggleAssistant, select]) + const openCopilot = useCallback(() => { + select(null) // 属性面板盖着的话先让开 + setHistory(false) + toggleAssistant(true) + requestAnimationFrame(() => window.dispatchEvent(new Event('agentlab:focus-copilot'))) + }, [select, toggleAssistant]) + const toggleVariables = useCallback(() => setDock((d) => (d === 'variables' ? null : 'variables')), []) useEffect(() => { const run = (id: StudioShortcutId): boolean => { @@ -472,8 +498,10 @@ export function StudioPage() {
{/* 生成期间这一排全部锁住(停止在画布上方的条和助手栏里):这时候保存会存下 - 半张图,运行跑的也是半张图,排版会被它的最终结果覆盖 */} -
+ 半张图,运行跑的也是半张图,排版会被它的最终结果覆盖。 + 这一排不许被压得比内容窄:以前压窄了子项互相叠着画,768 宽时「运行」盖住了 + 收起助手栏。放不下时让左边的工作流名先截短,次要按钮收进「更多操作」 */} +
} /> void relayout()} icon={} /> - @@ -531,7 +566,7 @@ export function StudioPage() {
{/* 三栏 */} -
+
@@ -553,9 +588,12 @@ export function StudioPage() { {/* 助手常驻,属性和版本历史是盖在它上面的一层。做成 tab 的话它们就互斥了, 而这几件事在时间上并不互斥——跑图跑到一半点开节点看配置,整条执行过程 会从眼前消失,切回来滚动位置和输入草稿也没了。 - 收起时只是藏起来不卸载:输入框里打了一半的字、滚动位置都留着 */} -