289 lines
14 KiB
Python
289 lines
14 KiB
Python
"""Access snippets: a registry row in, a paste-ready config out.
|
||
|
||
The hub deploys nothing itself — what it hands an operator is the exact block
|
||
that makes one agent dial in (docs/AGENT_REGISTRATION.md §7).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from pathlib import Path
|
||
|
||
from agenthub.deploy import snippets
|
||
from tests.conftest import BASE, add_agent
|
||
|
||
|
||
def plan(client, **body) -> dict:
|
||
response = client.post(f"{BASE}/deploy/plan", json=body)
|
||
assert response.status_code == 200, response.text
|
||
return response.json()
|
||
|
||
|
||
def content_of(plan_body: dict, kind: str) -> str:
|
||
return next(file["content"] for file in plan_body["files"] if file["kind"] == kind)
|
||
|
||
|
||
def test_templates_are_the_access_shapes(hub):
|
||
body = hub.get(f"{BASE}/deploy/templates").json()
|
||
assert [item["name"] for item in body["kinds"]] == ["bridge", "nanobot", "dsh", "claw"]
|
||
assert all(item["filename"] and item["description"] for item in body["kinds"])
|
||
|
||
|
||
def test_bridge_snippet_is_a_runnable_command_carrying_the_credential(hub):
|
||
"""桥接模式:codex/claude/workbuddy 这类无头 CLI 靠一条命令接入,
|
||
片段里就两样东西 —— hub 地址 + 这个 Agent 自己的凭证。"""
|
||
agent = add_agent(
|
||
hub, "bridge-codex", driver="connector", connection_mode="connector", issue_credential=True
|
||
)
|
||
body = plan(
|
||
hub,
|
||
kinds=["bridge"],
|
||
agent_ref="bridge-codex",
|
||
agent_token=agent["agent_token"],
|
||
agent={"cli": "codex", "workdir": "~/code/x", "mode": "write"},
|
||
)
|
||
command = content_of(body, "bridge")
|
||
assert body["files"][0]["filename"] == "bridge.sh"
|
||
assert "deploy/cli-bridge/bridge.py" in command
|
||
assert f"--token {agent['agent_token']}" in command
|
||
assert "--name bridge-codex" in command
|
||
assert "--cli codex" in command and "--workdir ~/code/x" in command and "--mode write" in command
|
||
assert "<agent_token>" not in command, "签过凭证的片段不该再留占位符"
|
||
|
||
|
||
def test_nanobot_snippet_carries_server_and_the_agents_own_credential(hub):
|
||
agent = add_agent(
|
||
hub, "snippet-alpha", driver="nanobot", connection_mode="embedded", issue_credential=True
|
||
)
|
||
body = plan(hub, kinds=["nanobot"], agent_ref="snippet-alpha", agent_token=agent["agent_token"])
|
||
content = content_of(body, "nanobot")
|
||
assert body["files"][0]["filename"] == "nanobot-config.json"
|
||
assert '"channels"' in content and '"agenthub"' in content
|
||
assert agent["agent_token"] in content
|
||
assert '"server"' in content
|
||
assert "agent_id" not in content, "agent id 由 hub 在连接建立时回送,不用人抄"
|
||
|
||
|
||
def test_dsh_snippet_keeps_a_placeholder_until_a_credential_exists(hub):
|
||
"""还没建档签发时也要能先看形状:凭证那一格留占位符,并告诉用户去哪拿。"""
|
||
body = plan(hub, kinds=["dsh"], agent={"name": "beta"})
|
||
content = content_of(body, "dsh")
|
||
assert "cordis.patch.yml" == body["files"][0]["filename"]
|
||
assert "@nex/dsh-agenthub" in content
|
||
assert "agentToken: <agent_token>" in content
|
||
assert "server: http://127.0.0.1:8100" in content # 地址永远都在
|
||
assert "agent_token" in " ".join(body["next_steps"])
|
||
|
||
|
||
def test_dsh_snippet_carries_the_credential_and_the_install_step(hub):
|
||
"""签发凭证那一步的产物要能直接贴:真凭证 + 别忘了插件得先装。"""
|
||
agent = add_agent(
|
||
hub, "dsh-snippet", driver="deepseek_harness", connection_mode="embedded", issue_credential=True
|
||
)
|
||
body = plan(hub, kinds=["dsh"], agent_ref="dsh-snippet", agent_token=agent["agent_token"])
|
||
content = content_of(body, "dsh")
|
||
assert "agentToken: " + agent["agent_token"] in content
|
||
assert "agentId" not in content and "<agent_token>" not in content
|
||
steps = " ".join(body["next_steps"])
|
||
assert "dsh plugin" in steps and "plugins/dsh-agenthub" in steps, "缺了装插件那一步,贴完 config 也起不来"
|
||
assert "<agent_token>" not in steps
|
||
|
||
|
||
def test_dsh_steps_survive_a_profile_that_does_not_exist_yet(hub):
|
||
"""真机踩过两个坑,向导必须把它们写进步骤,否则照着做就是"注册不上来":
|
||
|
||
1. profile 不存在时 `dsh plugin add` 会顺手建一个默认 profile,只有 dsh-base
|
||
—— 一次性进程,没有常驻进程去拨 hub;得用 web 模板建。
|
||
2. 新建 profile 的 cordis.patch.yml 末尾有一行占位 `[]`,片段接在它后面
|
||
YAML 就是两个根节点,profile 起不来。
|
||
"""
|
||
body = plan(hub, kinds=["dsh"], agent={"name": "fresh", "profile": "fresh-prof"})
|
||
steps = " ".join(body["next_steps"])
|
||
assert "dsh --profile fresh-prof --from-default-profile web" in steps, "缺了按 web 模板建 profile"
|
||
assert "~/.dsh/profiles/fresh-prof/cordis.patch.yml" in steps
|
||
assert "[]" in steps, "没提醒删掉那行占位的 [],贴完片段 profile 起不来"
|
||
assert "dsh --profile fresh-prof" in steps, "没有起进程这一步,热重载永远不会发生"
|
||
|
||
|
||
def test_bridge_snippet_names_the_script_it_runs(hub):
|
||
"""这条命令多半在**另一台**机器上跑:路径得是绝对的,还要说清拷哪些文件过去。"""
|
||
agent = add_agent(hub, "bridge-abs", driver="connector", connection_mode="connector")
|
||
body = plan(hub, kinds=["bridge"], agent_ref="bridge-abs", agent_token="ag_x")
|
||
command = content_of(body, "bridge")
|
||
assert "python3 /" in command or "python3 <" in command, command
|
||
steps = " ".join(body["next_steps"])
|
||
assert "adapters" in steps, "没说清换机器要带上 adapters/,脚本会找不到适配器"
|
||
|
||
|
||
def test_a_dsh_row_remembers_which_profile_it_lives_in(hub):
|
||
"""从 Agents 详情页重新生成片段时请求里只有 agent_ref:profile 得能从这一行里拿回来,
|
||
否则片段会指着默认 profile,用户把片段贴进了另一个文件。"""
|
||
add_agent(
|
||
hub,
|
||
"dsh-kept",
|
||
driver="deepseek_harness",
|
||
connection_mode="embedded",
|
||
config={"profile": "my-profile"},
|
||
)
|
||
steps = " ".join(plan(hub, kinds=["dsh"], agent_ref="dsh-kept")["next_steps"])
|
||
assert "dsh --profile my-profile" in steps, steps
|
||
|
||
|
||
def test_a_bridge_row_remembers_how_it_is_launched(hub):
|
||
"""接入页的连接列表只有 agent_ref:桥接的 cli / workdir / mode 也要从这一行拿回来,
|
||
否则「查看配置」还原出来的是默认目录 + readonly,和当初签发的那条不是一回事。"""
|
||
add_agent(
|
||
hub,
|
||
"bridge-kept",
|
||
driver="connector",
|
||
connection_mode="connector",
|
||
config={"cli": "codex", "workdir": "~/code/kept", "mode": "write"},
|
||
)
|
||
command = content_of(plan(hub, kinds=["bridge"], agent_ref="bridge-kept"), "bridge")
|
||
assert "--name bridge-kept" in command
|
||
assert "--cli codex" in command and "--workdir ~/code/kept" in command and "--mode write" in command
|
||
|
||
|
||
def test_claw_snippet_carries_server_and_the_agents_own_credential(hub):
|
||
"""渠道类片段各家键名不同,要填的也就这两格:hub 地址 + 这个 Agent 自己的凭证。"""
|
||
agent = add_agent(
|
||
hub, "snippet-claw", driver="connector", connection_mode="connector", issue_credential=True
|
||
)
|
||
body = plan(hub, kinds=["claw"], agent_ref="snippet-claw", agent_token=agent["agent_token"])
|
||
content = content_of(body, "claw")
|
||
assert body["files"][0]["filename"] == "openclaw-agenthub.json"
|
||
assert '"agenthub"' in content and '"server"' in content
|
||
assert agent["agent_token"] in content and "<agent_token>" not in content
|
||
assert "agent_id" not in content, "agent id 由 hub 在连接建立时回送,不用人抄"
|
||
|
||
|
||
def test_unknown_snippet_kind_is_rejected(hub):
|
||
response = hub.post(f"{BASE}/deploy/plan", json={"kinds": ["docker"]})
|
||
assert response.status_code == 422
|
||
assert "unknown snippet kinds" in response.text
|
||
|
||
|
||
def test_no_access_copy_points_at_a_wizard_step_number(hub):
|
||
"""向导是「一条路 · 三步」,接入相关的文案不许再指名「第 N 步」。
|
||
|
||
步数一改,散在插件 / 桥接 / 渠道报错里那句「回第 3 步签发」就指向一个不存在的格子,
|
||
正是「照着向导做却注册不上来」时最误导人的一句。说清去哪儿(控制台「接入」页)就够。
|
||
"""
|
||
root = Path(__file__).resolve().parents[2]
|
||
sources = [
|
||
"plugins/dsh-agenthub/lib/gateway.js",
|
||
"plugins/dsh-agenthub/lib/client.js",
|
||
"plugins/dsh-agenthub/lib/index.js",
|
||
"deploy/cli-bridge/bridge.py",
|
||
"deploy/nanobot-gateway/channel/agenthub/agenthub_client.py",
|
||
]
|
||
stale = {
|
||
path: re.findall(r"第 ?\d+ ?步", (root / path).read_text(encoding="utf-8"))
|
||
for path in sources
|
||
}
|
||
assert not {path: hits for path, hits in stale.items() if hits}, stale
|
||
|
||
steps = " ".join(plan(hub, kinds=["bridge", "nanobot", "dsh", "claw"], agent={"name": "x"})["next_steps"])
|
||
assert not re.search(r"第 ?\d+ ?步", steps)
|
||
|
||
|
||
def test_docs_do_not_resurrect_a_deleted_access_mode():
|
||
"""接入只剩一条路之后,文档不许再把删掉的机制当"当前做法"教给操作者。
|
||
|
||
README 严格(一个旧字都不提)。docs/ 宽松:`AGENT_REGISTRATION.md` 的兼容读取表、
|
||
故障对照表、变更记录里**必须**留着"旧机制已删、那几条路由必须 404"这类句子——
|
||
它们存在的意义正是拦住想往回加的人。所以 docs/ 只禁那些照抄就能配错的正向写法:
|
||
真实存在的旧令牌前缀、旧环境变量、不存在的 CLI 子命令、旧 SDK 参数名。
|
||
"""
|
||
root = Path(__file__).resolve().parents[2]
|
||
readme = (root / "README.md").read_text(encoding="utf-8")
|
||
for pattern in ("enrollment", "enr_", "hubId", "Hub ID", "hub_id", "自注册", "预注册", "入场"):
|
||
assert pattern not in readme, f"README.md 又提起了已删的机制:{pattern}"
|
||
|
||
stale = {
|
||
"enr_[A-Za-z0-9]": "入场令牌(enr_…)的前缀——它已不存在",
|
||
"AGENTHUB_ENROLLMENT\w*": "已删的环境变量",
|
||
"AGENTHUB_HUB_ID\w*": "已删的环境变量",
|
||
"agenthub token\b": "不存在的 CLI 子命令(签发请用 agenthub agent add --show-token)",
|
||
"hub-identity\.json": "已删的 hub 身份文件",
|
||
"run_task=": "GatewayClient 没这个参数,是 on_task / describe= / command=",
|
||
}
|
||
for path in sorted((root / "docs").glob("*.md")):
|
||
text = path.read_text(encoding="utf-8")
|
||
for pattern, why in stale.items():
|
||
hits = sorted(set(re.findall(pattern, text)))
|
||
assert not hits, f"{path.name} 里还有 {why}:{hits[:3]}"
|
||
|
||
|
||
def test_a_signed_snippet_is_kept_as_an_issuance_record(hub):
|
||
"""「我签过什么」是独立的一份存档:连 token 带当时那段配置一起留着。
|
||
|
||
换一把凭证不会抹掉上一次签的那一份,只把它标成已失效 —— 操作者翻记录时要看到
|
||
历史,不是只看现在活着的那一把。
|
||
"""
|
||
agent = add_agent(
|
||
hub, "iss-bridge", driver="connector", connection_mode="connector", issue_credential=True
|
||
)
|
||
first = agent["agent_token"]
|
||
plan(
|
||
hub,
|
||
kinds=["bridge"],
|
||
agent_ref="iss-bridge",
|
||
agent_token=first,
|
||
agent={"cli": "codex", "workdir": "~/code/keep", "mode": "readonly"},
|
||
record=True,
|
||
)
|
||
|
||
rows = hub.get(f"{BASE}/deploy/issuances").json()
|
||
assert len(rows) == 1
|
||
row = rows[0]
|
||
assert (row["agent_name"], row["kind"], row["active"]) == ("iss-bridge", "bridge", True)
|
||
assert row["agent_token"] == first
|
||
assert f"--token {first}" in row["files"][0]["content"]
|
||
assert "--workdir ~/code/keep" in row["files"][0]["content"]
|
||
|
||
rotated = hub.post(f"{BASE}/agents/iss-bridge/credentials", json={}).json()["agent_token"]
|
||
plan(hub, kinds=["bridge"], agent_ref="iss-bridge", agent_token=rotated, record=True)
|
||
|
||
rows = hub.get(f"{BASE}/deploy/issuances").json()
|
||
assert [row["agent_token"] for row in rows] == [rotated, first]
|
||
assert [row["active"] for row in rows] == [True, False]
|
||
|
||
|
||
def test_records_are_only_written_when_asked(hub):
|
||
"""预览片段(不勾选存档)不该悄悄攒记录 —— 存档是「我按了签发」的那一步。"""
|
||
agent = add_agent(hub, "iss-preview", driver="nanobot", connection_mode="embedded")
|
||
plan(hub, kinds=["nanobot"], agent_ref="iss-preview", agent_token="ag_preview")
|
||
assert hub.get(f"{BASE}/deploy/issuances").json() == []
|
||
|
||
|
||
def test_the_connect_wizard_offers_two_access_types_and_three_steps():
|
||
"""向导的形状本身是产品约束:接入类型只有两类、步数只有三步。
|
||
|
||
这一条存在的意义就是别让人再面对一堆模式名 —— 谁往第 1 步塞进第三种类型
|
||
(尤其把「hub 直连过去」那种分法加回来)、或者把步数改回去,这里先响;
|
||
顺便确认两类各自都有 Agent 可列、每套 Agent 的片段 kind 后端真的渲染得出来。
|
||
"""
|
||
page = (Path(__file__).resolve().parents[2] / "frontend/app/connect/page.tsx").read_text(
|
||
encoding="utf-8"
|
||
)
|
||
|
||
steps = re.search(r"const STEPS = \[([^\]]*)\]", page)
|
||
assert steps, "前端找不到 STEPS"
|
||
assert re.findall(r'"([^"]+)"', steps.group(1)) == ["选择类型", "选择 Agent", "生成凭证"]
|
||
|
||
shape = re.search(r"type AccessType = ([^;]+);", page)
|
||
assert shape, "前端找不到 AccessType"
|
||
types = re.findall(r'"([a-z]+)"', shape.group(1))
|
||
assert types == ["channel", "bridge"], types
|
||
|
||
start = page.index("const TYPES")
|
||
block = page[start : page.index("\n];", start)]
|
||
assert re.findall(r'id: "([a-z]+)"', block) == types, "第 1 步的卡片和 AccessType 对不上"
|
||
|
||
start = page.index("const TARGETS")
|
||
targets = page[start : page.index("\n];", start)]
|
||
assert set(re.findall(r'type: "(\w+)"', targets)) == set(types), "有 Agent 挂在第三种类型下"
|
||
kinds = set(re.findall(r'kind: "(\w+)"', targets))
|
||
assert kinds == set(snippets.KINDS), f"向导列的 Agent 和后端片段种类对不上:{kinds}"
|