Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(studio): add VikingBot conversations and Feishu onboarding (#5109)

yufengca777889c6aa
diff --git a/bot/tests/test_studio.py b/bot/tests/test_studio.py
new file mode 100644
index 000000000..0ee48025e
--- /dev/null
+++ b/bot/tests/test_studio.py
@@ -0,0 +1,534 @@
+"""Studio channel persistence, isolation and real delivery boundaries."""
+
+import asyncio
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import HTTPException
+from vikingbot.bus.events import OutboundMessage
+from vikingbot.bus.queue import MessageBus
+from vikingbot.config.schema import FeishuChannelConfig, SessionKey
+from vikingbot.studio.providers.feishu.channel import StudioFeishuChannel
+from vikingbot.studio.providers.registry import get_provider
+from vikingbot.studio.service import StudioService
+from vikingbot.studio.store import StudioStore
+
+
+def record():
+ return {
+ "id": "connection",
+ "account": "a",
+ "app_id": "cli_test",
+ "app_secret": "secret",
+ "bot_name": "Bot",
+ "bot_open_id": "ou_bot",
+ "enabled": True,
+ "revision": 1,
+ "step": 2,
+ "identity": {"user_id": "group-user", "api_key": "private", "role": "user"},
+ }
+
+
+def test_store_survives_restart_deduplicates_and_paginates(tmp_path):
+ path = tmp_path / "studio.db"
+ store = StudioStore(path)
+ store.save(record())
+ for i in range(105):
+ store.append(
+ "connection",
+ "group",
+ str(i),
+ {
+ "content": str(i),
+ "title": "Team",
+ "chat_type": "group",
+ },
+ )
+ store.append("connection", "group", "0", {"content": "duplicate"})
+ reloaded = StudioStore(path)
+ assert reloaded.connections("b") == []
+ assert reloaded.connections("a")[0]["id"] == "connection"
+ page = reloaded.history("connection", "group")
+ assert len(page) == 101
+ assert page[0]["content"] == "104"
+ assert len(reloaded.history("connection", "group", page[99]["id"])) == 5
+ assert reloaded.conversations("connection")[0]["title"] == "0"
+ assert reloaded.conversations("connection")[0]["group_name"] == "Team"
+ store.append(
+ "connection",
+ "group#topic",
+ "topic",
+ {
+ "role": "user",
+ "content": "First question",
+ "chat_type": "group",
+ "title": "Team / First question",
+ "topic_title": "Release plan",
+ },
+ )
+ topic = reloaded.conversations("connection")[0]
+ assert topic["title"] == "Release plan"
+ assert topic["group_name"] == "Team"
+ assert path.stat().st_mode & 0o777 == 0o600
+
+
+def channel(tmp_path):
+ result = StudioFeishuChannel(
+ FeishuChannelConfig(app_id="cli_test", bot_name="Old name"),
+ MessageBus(),
+ record=record(),
+ store=StudioStore(tmp_path / "s.db"),
+ )
+ result._running = True
+ return result
+
+
+def test_mentions_use_identity_even_after_rename(channel):
+ assert channel._is_bot_mention(
+ SimpleNamespace(id=SimpleNamespace(open_id="ou_bot"), name="New")
+ )
+ assert not channel._is_bot_mention(
+ SimpleNamespace(id=SimpleNamespace(open_id="ou_other"), name="Old name")
+ )
+
+
+async def test_fixed_verification_bypasses_model_and_requires_actual_send(channel, monkeypatch):
+ channel.verification = {
+ "code": "ABC123",
+ "expires_at": time.time() + 60,
+ "received": False,
+ "sent": False,
+ }
+ monkeypatch.setattr(channel, "send", AsyncMock(return_value=False))
+ await channel._handle_message(
+ "sender",
+ "group",
+ "VikingBot connection test ABC123",
+ metadata={"chat_type": "group", "message_id": "m1"},
+ )
+ assert channel.verification["received"]
+ assert not channel.verification["sent"]
+ assert channel.store.history("connection") == []
+ with pytest.raises(TimeoutError):
+ await asyncio.wait_for(channel.bus.consume_inbound(), 0.01)
+
+
+async def test_group_identity_and_peer_are_separate_from_installer(channel):
+ await channel._handle_message(
+ "sender",
+ "group",
+ "hello",
+ sender_name="Alice",
+ metadata={"chat_type": "group", "message_id": "m1"},
+ )
+ event = await channel.bus.consume_inbound()
+ assert event.openviking_connection["user_id"] == "group-user"
+ assert event.actor_peer_id.startswith("feishu-")
+ assert event.actor_peer_id != "sender"
+ assert channel.store.history("connection")[0]["sender"] == "Alice"
+
+
+async def test_pause_drops_new_inbound_messages(channel):
+ await channel.stop()
+ await channel._handle_message("sender", "group", "hello")
+ assert channel.store.history("connection") == []
+
+
+async def test_delivery_failure_is_not_reported_as_sent(channel, monkeypatch):
+ from vikingbot.channels.feishu import FeishuChannel
+
+ monkeypatch.setattr(FeishuChannel, "send", AsyncMock(return_value=False))
+ result = await channel.send(
+ OutboundMessage(
+ SessionKey(type="feishu", channel_id="cli_test", chat_id="studio:connection:group"),
+ "answer",
+ )
+ )
+ assert not result
+ assert channel.last_sent is None
+ assert channel.store.history("connection")[0]["status"] == "send_failed"
+
+
+def test_public_config_never_returns_credentials_and_filters_accounts(tmp_path):
+ manager = SimpleNamespace(channels={})
+ config = SimpleNamespace(bot_data_path=tmp_path)
+ service = StudioService(config, manager)
+ service.store.save(record())
+ public = service.public(record())
+ assert "secret" not in str(public)
+ assert "private" not in str(public)
+ with pytest.raises(HTTPException) as error:
+ service.get("other-account", "connection")
+ assert error.value.status_code == 404
+
+
+async def test_revision_conflict_does_not_mutate_config(tmp_path):
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ service.store.save(record())
+ with pytest.raises(HTTPException) as error:
+ await service.update("a", "connection", {"revision": 0, "action": "pause"})
+ assert error.value.status_code == 409
+ assert service.get("a", "connection")["enabled"]
+
+
+async def test_private_gateway_rejects_loopback_without_secret(tmp_path, monkeypatch):
+ import httpx
+ from fastapi import FastAPI
+ from vikingbot.studio.router import create_router
+
+ monkeypatch.delenv("OPENVIKING_BOT_STUDIO_TOKEN", raising=False)
+ channel = SimpleNamespace(
+ _gateway_token=lambda: "internal", _is_loopback_request=lambda r: True
+ )
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ app = FastAPI()
+ app.include_router(create_router(channel, service))
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ for token in ["", "wrong"]:
+ response = await client.post(
+ "/studio/dispatch",
+ headers={"X-Gateway-Token": token},
+ json={"account": "a", "action": "list"},
+ )
+ assert response.status_code == 403
+ response = await client.post(
+ "/studio/dispatch",
+ headers={"X-Gateway-Token": "internal"},
+ json={"account": "a", "action": "list"},
+ )
+ assert response.status_code == 200
+
+
+async def test_duplicate_message_does_not_rerun_agent(channel):
+ for _ in range(2):
+ await channel._handle_message("s", "group", "hello", metadata={"message_id": "same"})
+ await channel.bus.consume_inbound()
+ with pytest.raises(TimeoutError):
+ await asyncio.wait_for(channel.bus.consume_inbound(), 0.01)
+
+
+async def test_failed_secret_rotation_preserves_old_connection(tmp_path, monkeypatch):
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ service.store.save(record())
+ monkeypatch.setattr(
+ get_provider({}), "validate_app", AsyncMock(side_effect=HTTPException(400, "Invalid"))
+ )
+ with pytest.raises(HTTPException):
+ await service.update(
+ "a", "connection", {"revision": 1, "action": "credentials", "app_secret": "wrong"}
+ )
+ assert service.get("a", "connection")["app_secret"] == "secret"
+ assert service.get("a", "connection")["enabled"]
+
+
+async def test_obsolete_setup_step_action_is_rejected(tmp_path):
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ service.store.save(record())
+ with pytest.raises(HTTPException) as exc:
+ await service.update("a", "connection", {"revision": 1, "action": "step", "step": 5})
+ assert exc.value.status_code == 400
+
+
+def test_managed_group_tools_deny_local_and_unregistered_capabilities():
+ from vikingbot.studio.policy import disabled_group_tools
+
+ assert disabled_group_tools(
+ ["openviking_search", "exec", "read_file", "mcp_admin", "spawn"]
+ ) == ["exec", "read_file", "mcp_admin", "spawn"]
+
+
+def test_provider_registry_preserves_legacy_and_rejects_unknown():
+ assert get_provider({}).type == "feishu"
+ assert get_provider({"type": "feishu"}).type == "feishu"
+ with pytest.raises(HTTPException) as error:
+ get_provider({"type": "slack"})
+ assert error.value.status_code == 400
+
+
+async def test_delete_connection_stops_runtime_and_cleans_owned_data(tmp_path):
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ item = record()
+ service.store.save(item)
+ service.store.save({**item, "id": "other", "account": "b"})
+ service.store.append(item["id"], "group", "event", {"content": "hello"})
+ runtime = SimpleNamespace(stop=AsyncMock())
+ key = get_provider(item).runtime_key(item)
+ service.manager.channels[key] = runtime
+ with pytest.raises(HTTPException) as error:
+ await service.update("b", item["id"], {"action": "delete", "revision": 1})
+ assert error.value.status_code == 404
+ with pytest.raises(HTTPException) as error:
+ await service.update("a", item["id"], {"action": "delete", "revision": 0})
+ assert error.value.status_code == 409
+ runtime.stop.assert_not_awaited()
+ assert await service.update("a", item["id"], {"action": "delete", "revision": 1}) == {
+ "deleted": True
+ }
+ runtime.stop.assert_awaited_once()
+ assert key not in service.manager.channels
+ assert service.store.connections("a") == []
+ assert len(service.store.connections("b")) == 1
+ assert service.store.history(item["id"]) == []
+
+
+def test_conversations_show_latest_preview_and_time(tmp_path):
+ store = StudioStore(tmp_path / "preview.db")
+ store.append("bot", "group", "1", {"title": "Team", "content": "first"})
+ store.append(
+ "bot",
+ "group",
+ "2",
+ {
+ "content": "latest reply",
+ "time": "2026-09-16T12:00:00+00:00",
+ },
+ )
+ item = store.conversations("bot")[0]
+ assert item["title"] == "first"
+ assert item["preview"] == "latest reply"
+ assert item["time"] == "2026-09-16T12:00:00+00:00"
+ assert store.conversations("another") == []
+
+
+def test_conversation_title_keeps_first_message_when_group_name_resolves(tmp_path):
+ store = StudioStore(tmp_path / "titles.db")
+ store.append("bot", "group", "1", {"title": "", "content": "介绍一下 OpenViking"})
+ assert store.conversations("bot")[0]["title"] == "介绍一下 OpenViking"
+ store.append("bot", "group", "2", {"title": "开发讨论", "content": "继续"})
+ assert store.conversations("bot")[0]["title"] == "介绍一下 OpenViking"
+
+
+async def test_history_backfills_names_only_when_sender_identity_is_known(channel, monkeypatch):
+ channel.store.append(
+ "connection",
+ "group",
+ "known",
+ {
+ "role": "user",
+ "sender": "",
+ "sender_id": "ou_person",
+ "content": "hello",
+ },
+ )
+ channel.store.append(
+ "connection",
+ "group",
+ "legacy",
+ {
+ "role": "user",
+ "sender": "",
+ "content": "old",
+ },
+ )
+ lookup = AsyncMock(return_value="张三")
+ monkeypatch.setattr(channel, "_get_group_member_name", lookup)
+ messages = await channel.history_with_names("group")
+ assert messages[1]["sender"] == "张三"
+ assert messages[0]["sender"] == ""
+ assert channel.store.history("connection", "group")[1]["sender"] == "张三"
+ lookup.assert_awaited_once_with("group", "ou_person")
+
+
+async def test_history_name_lookup_failure_keeps_messages(channel, monkeypatch):
+ channel.store.append(
+ "connection",
+ "group",
+ "known",
+ {
+ "role": "user",
+ "sender": "",
+ "sender_id": "ou_person",
+ "content": "hello",
+ },
+ )
+ monkeypatch.setattr(channel, "_get_group_member_name", AsyncMock(side_effect=RuntimeError()))
+ messages = await channel.history_with_names("group")
+ assert messages[0]["content"] == "hello"
+ assert messages[0]["sender"] == ""
+
+
+async def test_platform_provider_receives_generic_credentials(tmp_path, monkeypatch):
+ from vikingbot.studio.providers.registry import PROVIDERS
+
+ class FutureProvider:
+ type = "future-platform"
+
+ async def prepare(self, credentials):
+ assert credentials == {"client_id": "app", "client_secret": "secret"}
+ return {"client_id": credentials["client_id"]}
+
+ def runtime_key(self, record):
+ return self.type + record["client_id"]
+
+ def install(self, service, record):
+ channel = SimpleNamespace(start=AsyncMock())
+ service.manager.channels[self.runtime_key(record)] = channel
+ return channel
+
+ def public_fields(self, record):
+ return {"client_id": record["client_id"]}
+
+ monkeypatch.setitem(PROVIDERS, "future-platform", FutureProvider())
+ service = StudioService(SimpleNamespace(bot_data_path=tmp_path), SimpleNamespace(channels={}))
+ result = await service.create(
+ "a",
+ {
+ "type": "future-platform",
+ "credentials": {"client_id": "app", "client_secret": "secret"},
+ },
+ {"user_id": "bot"},
+ )
+ await asyncio.gather(*service.tasks.values())
+ assert result["type"] == "future-platform"
+ assert result["client_id"] == "app"
+ assert "secret" not in str(result)
+ assert service.get("a", result["id"])["account"] == "a"
+
+
[email protected]("value", ["false", 0, None, {"unexpected": True}])
+def test_feishu_settings_reject_invalid_values(value):
+ provider = get_provider({"type": "feishu"})
+ with pytest.raises(HTTPException):
+ provider.validate_settings(
+ value if isinstance(value, dict) else {"thread_require_mention": value}
+ )
+
+
+async def test_reply_settings_persist_apply_immediately_and_keep_revision_guard(
+ tmp_path, channel, monkeypatch
+):
+ provider = get_provider({"type": "feishu"})
+ service = StudioService(
+ SimpleNamespace(
+ bot_data_path=tmp_path, channels=[{"type": "feishu", "app_id": "cli_test"}]
+ ),
+ SimpleNamespace(channels={provider.runtime_key(record()): channel}),
+ )
+ service.store.save(record())
+ assert service.public(record())["settings"] == {"thread_require_mention": True}
+ monkeypatch.setattr(channel, "_get_chat_mode", AsyncMock(return_value="group"))
+ assert not await channel._check_should_process("group", "g", SimpleNamespace(), False)
+ updated = await service.update(
+ "a",
+ "connection",
+ {
+ "revision": 1,
+ "action": "settings",
+ "settings": {"thread_require_mention": False},
+ },
+ )
+ assert updated["revision"] == 2
+ assert await channel._check_should_process("group", "g", SimpleNamespace(), False)
+ assert service.config.channels[0]["thread_require_mention"] is False
+ persisted = StudioStore(tmp_path / "studio.sqlite3").connections("a")[0]
+ assert persisted["settings"] == {"thread_require_mention": False}
+ with pytest.raises(HTTPException) as error:
+ await service.update(
+ "a", "connection", {"revision": 1, "action": "settings", "settings": {}}
+ )
+ assert error.value.status_code == 409
+ assert channel.config.thread_require_mention is False
+ captured = []
+
+ def restored(config, *args, **kwargs):
+ captured.append(config.thread_require_mention)
+ return SimpleNamespace()
+
+ monkeypatch.setattr("vikingbot.studio.providers.feishu.channel.StudioFeishuChannel", restored)
+ service.manager.bus = None
+ service.manager.add_channel = lambda channel: None
+ service.config.workspace_path = tmp_path
+ provider.install(service, persisted)
+ assert captured == [False]
+
+
[email protected]("endpoint", ["token", "bot"])
[email protected]("status", [429, 503])
+async def test_feishu_upstream_failure_is_not_a_credentials_error(monkeypatch, endpoint, status):
+ import httpx
+ from vikingbot.studio.providers.feishu import provider
+
+ def respond(request):
+ if endpoint == "bot" and request.method == "POST":
+ return httpx.Response(200, json={"code": 0, "tenant_access_token": "token"})
+ return httpx.Response(status, json={"code": 99991400, "msg": "unavailable"})
+
+ client = httpx.AsyncClient(transport=httpx.MockTransport(respond))
+ monkeypatch.setattr(provider.httpx, "AsyncClient", lambda **kwargs: client)
+ with pytest.raises(HTTPException) as error:
+ await provider.FeishuProvider().validate_app("cli_test", "secret")
+ assert error.value.status_code == 502
+ assert error.value.detail == "Cannot reach Feishu; retry the connection check"
+
+
+async def test_recreated_connection_isolates_sessions_and_rejects_old_replies(
+ tmp_path, monkeypatch
+):
+ from vikingbot.channels.feishu import FeishuChannel
+ from vikingbot.channels.manager import ChannelManager
+ from vikingbot.session.manager import SessionManager
+
+ async def start(channel):
+ channel._running = True
+
+ provider = get_provider({"type": "feishu"})
+ monkeypatch.setattr(provider, "validate_app", AsyncMock(return_value={"open_id": "ou_bot"}))
+ monkeypatch.setattr(StudioFeishuChannel, "start", start)
+ delivery = AsyncMock(return_value=True)
+ monkeypatch.setattr(FeishuChannel, "send", delivery)
+ bus = MessageBus()
+ service = StudioService(
+ SimpleNamespace(bot_data_path=tmp_path, workspace_path=tmp_path, channels=[]),
+ ChannelManager(bus),
+ )
+
+ async def connect(account):
+ result = await service.create(
+ account,
+ {"type": "feishu", "credentials": {"app_id": "cli_test", "app_secret": "secret"}},
+ {"account_id": account, "user_id": "bot-user", "role": "user"},
+ )
+ await asyncio.gather(*service.tasks.values())
+ channel = service.runtime(service.get(account, result["id"]))
+ await channel._handle_message(
+ "sender", "oc_group#topic", "hello", metadata={"message_id": account}
+ )
+ return result, channel, await bus.consume_inbound()
+
+ old, _, old_event = await connect("a")
+ sessions = SessionManager(tmp_path)
+ old_session = sessions.get_or_create(old_event.session_key)
+ old_session.add_message("assistant", "account A private result")
+ await sessions.save(old_session)
+ await service.update("a", old["id"], {"action": "delete", "revision": old["revision"]})
+ new, channel, event = await connect("b")
+ assert event.openviking_connection["account_id"] == "b"
+ assert sessions.get_or_create(event.session_key).get_history() == []
+ assert SessionManager(tmp_path).get_or_create(event.session_key).get_history() == []
+ assert service.store.history(old["id"]) == []
+
+ assert not await channel.send(OutboundMessage(old_event.session_key, "late old reply"))
+ delivery.assert_not_awaited()
+ assert await channel.send(OutboundMessage(event.session_key, "new reply"))
+ assert delivery.await_args.args[0].session_key.chat_id == "oc_group#topic"
+ assert event.session_key.channel_key() in service.manager.channels
+ assert service.store.history(new["id"], "oc_group#topic")[0]["content"] == "new reply"
+
+ # Restarting the same connection must retain its scoped session.
+ current_session = sessions.get_or_create(event.session_key)
+ current_session.add_message("assistant", "account B result")
+ await sessions.save(current_session)
+ service.install(service.get("b", new["id"]))
+ restored = service.runtime(service.get("b", new["id"]))
+ await restored.start()
+ await restored._handle_message("sender", "oc_group#topic", "again")
+ restored_event = await bus.consume_inbound()
+ assert restored_event.session_key == event.session_key
+ assert SessionManager(tmp_path).get_or_create(restored_event.session_key).get_history() == [
+ {"role": "assistant", "content": "account B result"}
+ ]
diff --git a/bot/tests/test_studio_onboarding.py b/bot/tests/test_studio_onboarding.py
new file mode 100644
index 000000000..44b805ce2
--- /dev/null
+++ b/bot/tests/test_studio_onboarding.py
@@ -0,0 +1,500 @@
+"""Contract and recovery tests; no live Feishu account or app is used."""
+
+import json
+import uuid
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from fastapi import HTTPException
+from vikingbot.studio.onboarding import OnboardingJobs
+from vikingbot.studio.providers.feishu import console, onboarding
+from vikingbot.studio.providers.feishu.web_session import FeishuWebSession, SetupError, allowed_url
+from vikingbot.studio.store import StudioStore
+
+
+def make_jobs(tmp_path):
+ return OnboardingJobs(SimpleNamespace(store=StudioStore(tmp_path / "studio.sqlite3")))
+
+
+def run_record(**extra):
+ return {
+ "id": "run",
+ "account": "a",
+ "type": "feishu",
+ "name": "VikingBot",
+ "identity": {"user_id": "bot", "api_key": "private-key"},
+ "state": "creating",
+ "request_id": str(uuid.uuid4()),
+ **extra,
+ }
+
+
+async def test_start_is_idempotent_and_scoped(tmp_path, monkeypatch):
+ jobs = make_jobs(tmp_path)
+ launches = []
+
+ def launch(run):
+ jobs.service.store.save_onboarding(run)
+ launches.append(run)
+
+ monkeypatch.setattr(jobs, "launch", launch)
+ body = {"type": "feishu", "request_id": str(uuid.uuid4())}
+ identity = {"user_id": "bot", "api_key": "private-key"}
+ first = await jobs.start("a", body, identity)
+ second = await jobs.start("a", body, identity)
+ third = await jobs.start("a", {**body, "request_id": str(uuid.uuid4())}, identity)
+ assert first["id"] == second["id"] == third["id"]
+ assert len(launches) == 1
+ with pytest.raises(HTTPException) as error:
+ jobs.get("other-account", first["id"])
+ assert error.value.status_code == 404
+ assert "private-key" not in json.dumps(first)
+ assert jobs.current("other-account", "feishu") is None
+
+
+def test_restart_keeps_checkpoints_but_not_fake_live_qr(tmp_path):
+ jobs = make_jobs(tmp_path)
+ run = run_record(app_id="cli_existing", create_started=True, state="configuring")
+ jobs.service.store.save_onboarding(run)
+ restarted = OnboardingJobs(jobs.service)
+ restored = restarted.get("a", "run")
+ assert restored["app_id"] == "cli_existing"
+ assert restored["state"] == "interrupted"
+ public = restarted.public(restored)
+ assert public["can_retry"]
+ assert "qr" not in public and "identity" not in public
+
+
+async def test_unknown_creation_result_cannot_retry(tmp_path):
+ jobs = make_jobs(tmp_path)
+ run = run_record(create_started=True, state="failed")
+ jobs.service.store.save_onboarding(run)
+ assert not jobs.public(run)["can_retry"]
+ with pytest.raises(HTTPException):
+ await jobs.update("a", "run", "retry")
+ session = SimpleNamespace(post=AsyncMock())
+ with pytest.raises(SetupError, match="creation_uncertain"):
+ await console.create_app(session, run, lambda **kwargs: None)
+ session.post.assert_not_called()
+
+
+async def test_creation_checkpoint_precedes_uncertain_network_call():
+ run = run_record()
+
+ async def post(path, *args, **kwargs):
+ if path.endswith("upload/image"):
+ return {"data": {"url": "avatar"}}
+ assert run["create_started"]
+ raise httpx.ReadTimeout("possibly committed")
+
+ with pytest.raises(httpx.ReadTimeout):
+ await console.create_app(SimpleNamespace(post=post), run, lambda **kw: run.update(kw))
+ assert run["create_started"] and "app_id" not in run
+
+
+async def test_retries_only_read_an_already_submitted_version():
+ run = run_record(app_id="cli_existing", version_id="version", publish_started=True)
+ session = SimpleNamespace(
+ post=AsyncMock(
+ return_value={
+ "data": {
+ "versions": [
+ {"versionId": "version", "versionStatus": 1},
+ ]
+ }
+ }
+ )
+ )
+ assert (
+ await console.publish_app(session, run, lambda **kw: run.update(kw)) == "awaiting_approval"
+ )
+ assert session.post.await_args.args[0] == "/developers/v1/app_version/list/cli_existing"
+ assert session.post.await_count == 1
+ session.post.return_value = {
+ "data": {"versions": [{"versionId": "version", "versionStatus": 2}]}
+ }
+ assert await console.publish_app(session, run, lambda **kw: run.update(kw)) == "published"
+
+
+async def test_committed_response_is_not_publication_proof():
+ run = run_record(app_id="cli_existing", version_id="version", publish_started=True)
+ session = SimpleNamespace(
+ post=AsyncMock(
+ return_value={
+ "data": {
+ "versions": [
+ {"versionId": "version", "versionStatus": 0},
+ ]
+ }
+ }
+ )
+ )
+ with pytest.raises(SetupError, match="publication_uncertain"):
+ await console.publication_status(session, run)
+
+
+async def test_cannot_cancel_once_app_mutation_started(tmp_path):
+ jobs = make_jobs(tmp_path)
+ jobs.service.store.save_onboarding(run_record())
+ with pytest.raises(HTTPException) as error:
+ await jobs.update("a", "run", "cancel")
+ assert error.value.status_code == 409
+
+
+def test_permission_mapping_does_not_take_user_scopes():
+ entries = [{"scopeName": name, "id": name + "-tenant"} for name in console.SCOPES]
+ result = console.scope_ids(
+ {
+ "data": {
+ "appScopes": entries,
+ "userScopes": [
+ {"scopeName": name, "id": name + "-user"} for name in console.SCOPES
+ ],
+ }
+ }
+ )
+ assert set(result) == console.SCOPES
+ assert all(value.endswith("-tenant") for value in result.values())
+
+
+async def test_event_write_success_requires_readback():
+ async def post(path, *args):
+ if "/scope/all/" in path:
+ return {"data": {"appScopes": [{"name": name, "id": name} for name in console.SCOPES]}}
+ if path == "/developers/v1/event/cli_test":
+ return {"data": {"eventMode": 4, "appEvents": []}}
+ return {"code": 0}
+
+ with pytest.raises(SetupError, match="events_not_ready"):
+ await console.configure_app(SimpleNamespace(post=post), "cli_test")
+
+
+async def test_qr_session_follows_cookie_scopes_and_rejects_unsafe_redirect():
+ async def handler(request):
+ if request.url.path.endswith("/init"):
+ return httpx.Response(
+ 200,
+ headers={"x-flow-key": "flow", "set-cookie": "login=secret; Path=/; Secure"},
+ json={"code": 0, "data": {"step_info": {"token": "qr-token"}}},
+ )
+ assert request.headers["x-flow-key"] == "flow"
+ assert request.headers["cookie"] == "login=secret"
+ return httpx.Response(
+ 200,
+ json={
+ "code": 0,
+ "data": {
+ "next_step": "enter_app",
+ "step_info": {"cross_login_uri": "http://127.0.0.1/private"},
+ },
+ },
+ )
+
+ session = FeishuWebSession(httpx.AsyncClient(transport=httpx.MockTransport(handler)))
+ assert json.loads(await session.begin()) == {"qrlogin": {"token": "qr-token"}}
+ with pytest.raises(SetupError, match="untrusted_redirect"):
+ await session.poll()
+ await session.close()
+ assert not session.client.cookies
+
+
+ "url",
+ [
+ "https://feishu.cn.evil.test",
+ "http://open.feishu.cn",
+ "https://[email protected]",
+ "https://open.feishu.cn:999/app",
+ ],
+)
+def test_redirect_allowlist(url):
+ assert not allowed_url(url)
+
+
+async def test_resume_with_wrong_owner_never_mutates_app(tmp_path, monkeypatch):
+ jobs = make_jobs(tmp_path)
+ run = run_record(owner={"user_id": "original", "tenant_id": "tenant"})
+ jobs.live["run"] = {}
+ session = SimpleNamespace(
+ begin=AsyncMock(return_value="qr"),
+ poll=AsyncMock(return_value="authorized"),
+ identity=AsyncMock(return_value={"user_id": "other", "tenant_id": "tenant"}),
+ close=AsyncMock(),
+ )
+ monkeypatch.setattr(onboarding, "FeishuWebSession", lambda: session)
+ create = AsyncMock()
+ monkeypatch.setattr(onboarding, "create_app", create)
+ await onboarding.run_onboarding(jobs, run)
+ assert run["state"] == "failed" and run["error"] == "identity_changed"
+ create.assert_not_called()
+ session.close.assert_awaited_once()
+
+
+async def test_job_failure_never_returns_upstream_secrets(tmp_path, monkeypatch):
+ jobs = make_jobs(tmp_path)
+ run = run_record()
+ jobs.live["run"] = {}
+ session = SimpleNamespace(
+ begin=AsyncMock(side_effect=RuntimeError("cookie=secret client_secret=private")),
+ close=AsyncMock(),
+ )
+ monkeypatch.setattr(onboarding, "FeishuWebSession", lambda: session)
+ await onboarding.run_onboarding(jobs, run)
+ assert run["error"] == "setup_failed"
+ assert "secret" not in json.dumps(jobs.public(run))
+ session.close.assert_awaited_once()
+
+
[email protected]("require_mention", [True, False])
+async def test_complete_scan_configure_publish_flow(tmp_path, monkeypatch, require_mention):
+ jobs = make_jobs(tmp_path)
+ run = run_record(state="initializing")
+ run["settings"] = {"thread_require_mention": require_mention}
+ jobs.live["run"] = {}
+ owner = {"user_id": "owner", "tenant_id": "tenant", "user_name": "User", "tenant_name": "Team"}
+ session = SimpleNamespace(
+ begin=AsyncMock(return_value="qr"),
+ poll=AsyncMock(return_value="authorized"),
+ identity=AsyncMock(return_value=owner),
+ close=AsyncMock(),
+ )
+ monkeypatch.setattr(onboarding, "FeishuWebSession", lambda: session)
+
+ async def create(session, run, checkpoint):
+ checkpoint(app_id="cli_new")
+ return "cli_new"
+
+ monkeypatch.setattr(onboarding, "create_app", create)
+ monkeypatch.setattr(onboarding, "prepare_app", AsyncMock(return_value="secret"))
+ configure = AsyncMock()
+ monkeypatch.setattr(onboarding, "configure_app", configure)
+ monkeypatch.setattr(onboarding, "publish_app", AsyncMock(return_value="published"))
+ record = {
+ "id": "connection",
+ "account": "a",
+ "type": "feishu",
+ "app_id": "cli_new",
+ "revision": 1,
+ }
+
+ async def install(account, body, identity):
+ assert body["app_secret"] == "secret" and identity["user_id"] == "bot"
+ assert body["settings"] == {"thread_require_mention": require_mention}
+ jobs.service.store.save(record)
+ return record
+
+ jobs.service.create = install
+ jobs.service.get = lambda *_: record
+ jobs.service.runtime = lambda _: SimpleNamespace(status=lambda: {"state": "connected"})
+ await onboarding.run_onboarding(jobs, run)
+ assert run["state"] == "ready" and run["configured"]
+ assert run["connection_id"] == "connection"
+ assert record["setup_mode"] == "qr" and record["step"] == 4
+ assert "qr" not in jobs.public(run)
+ configure.assert_awaited_once_with(session, "cli_new", require_mention=require_mention)
+ session.close.assert_awaited_once()
+
+
+async def test_manual_recovery_releases_current_job_without_forgetting_app(tmp_path):
+ jobs = make_jobs(tmp_path)
+ run = run_record(state="failed", app_id="cli_saved")
+ jobs.service.store.save_onboarding(run)
+ await jobs.update("a", "run", "manual")
+ assert jobs.current("a", "feishu") is None
+ assert jobs.get("a", "run")["app_id"] == "cli_saved"
+
+
+async def test_lost_publish_response_reconciles_without_replaying(monkeypatch):
+ run = run_record(app_id="cli_saved", version_id="v1", publish_started=True)
+ publish = AsyncMock(side_effect=httpx.ReadTimeout("response lost"))
+ read = AsyncMock(side_effect=[SetupError("publication_uncertain"), "published"])
+ monkeypatch.setattr(onboarding, "publish_app", publish)
+ monkeypatch.setattr(onboarding, "publication_status", read)
+ monkeypatch.setattr(onboarding.asyncio, "sleep", AsyncMock())
+ result = await onboarding.publish_and_wait(None, run, lambda **kw: run.update(kw))
+ assert result == "published"
+ publish.assert_awaited_once()
+ assert read.await_count == 2
+
+
+async def test_retry_waits_for_previous_session_cleanup(tmp_path, monkeypatch):
+ jobs = make_jobs(tmp_path)
+ run = run_record(state="expired")
+ jobs.service.store.save_onboarding(run)
+ closed = []
+
+ async def finish_cleanup():
+ closed.append(True)
+
+ import asyncio
+
+ jobs.tasks["run"] = asyncio.create_task(finish_cleanup())
+
+ def launch(restarted):
+ assert closed == [True]
+ restarted["state"] = "initializing"
+
+ monkeypatch.setattr(jobs, "launch", launch)
+ result = await jobs.update("a", "run", "retry")
+ assert result["state"] == "initializing"
+
+
+async def test_numeric_permission_ids_are_sent_as_strings():
+ scopes = sorted(console.SCOPES)
+ calls = []
+
+ async def post(path, body=None):
+ calls.append((path, body))
+ if "/scope/all/" in path:
+ return {
+ "data": {
+ "appScopeList": [
+ {"name": name, "id": index + 101} for index, name in enumerate(scopes)
+ ],
+ "userScopeList": [
+ {"name": name, "id": index + 201} for index, name in enumerate(scopes)
+ ],
+ }
+ }
+ if path == "/developers/v1/event/cli_test":
+ return {"data": {"eventMode": 4, "appEvents": [console.EVENT]}}
+ return {"code": 0}
+
+ await console.configure_app(SimpleNamespace(post=post), "cli_test")
+ update = next(body for path, body in calls if "/scope/update/" in path)
+ assert update["appScopeIDs"] == ["101", "102", "103", "104"]
+ assert update["userScopeIDs"] == []
+
+
+def test_invalid_permission_ids_are_not_accepted():
+ for value in (True, False, None, {}, []):
+ assert console.scope_ids({"name": next(iter(console.SCOPES)), "id": value}) == {}
+
+
+async def test_current_feishu_catalog_uses_chat_read_permission():
+ calls = []
+
+ async def post(path, body=None):
+ calls.append((path, body))
+ if "/scope/all/" in path:
+ return {
+ "data": {
+ "appScopeList": [
+ {"name": "im:message.group_at_msg:readonly", "id": 101},
+ {"name": "im:message:send_as_bot", "id": 102},
+ {"name": "im:chat:read", "id": 103},
+ {"name": "im:chat.members:read", "id": 104},
+ ]
+ }
+ }
+ if path == "/developers/v1/event/cli_test":
+ return {"data": {"eventMode": 4, "appEvents": ["im.message.receive_v1"]}}
+ return {"code": 0}
+
+ await console.configure_app(SimpleNamespace(post=post), "cli_test")
+ body = next(body for path, body in calls if "/scope/update/" in path)
+ assert set(body["appScopeIDs"]) == {"101", "102", "103", "104"}
+ assert body["userScopeIDs"] == []
+
+
+async def test_new_app_uses_agent_template_and_persists_request_identity():
+ run = run_record()
+ calls = []
+
+ async def post(path, body, **kwargs):
+ calls.append(path)
+ if path.endswith("upload/image"):
+ return {"data": {"url": "avatar"}}
+ assert path == "/developers/v1/manifest/upsert_by_template"
+ assert body["appManifestTemplateID"] == "developer_console"
+ assert body["cid"] == run["template_request_id"]
+ assert run["create_started"]
+ assert body["createAppUserCustomField"]["i18n"]["zh_cn"]["name"] == run["name"]
+ return {"data": {"ClientID": "cli_agent"}}
+
+ assert (
+ await console.create_app(SimpleNamespace(post=post), run, lambda **kw: run.update(kw))
+ == "cli_agent"
+ )
+ assert run["app_id"] == "cli_agent"
+ assert "/developers/v1/app/create" not in calls
+
+
+async def test_existing_app_is_preserved_without_attempting_template_conversion():
+ session = SimpleNamespace(post=AsyncMock())
+ run = run_record(app_id="cli_existing")
+ assert await console.create_app(session, run, lambda **kw: run.update(kw)) == "cli_existing"
+ session.post.assert_not_called()
+
+
+async def test_rejected_agent_template_never_falls_back_to_ordinary_bot():
+ session = SimpleNamespace(
+ post=AsyncMock(
+ side_effect=[
+ {"data": {"url": "avatar"}},
+ SetupError("platform_rejected"),
+ ]
+ )
+ )
+ run = run_record()
+ with pytest.raises(SetupError, match="platform_rejected"):
+ await console.create_app(session, run, lambda **kw: run.update(kw))
+ assert session.post.call_count == 2
+ assert run["create_started"]
+
+
+async def test_onboarding_idempotency_is_scoped_to_platform(tmp_path, monkeypatch):
+ from vikingbot.studio.providers.registry import PROVIDERS
+
+ monkeypatch.setitem(
+ PROVIDERS,
+ "future-platform",
+ SimpleNamespace(
+ type="future-platform",
+ run_onboarding=AsyncMock(),
+ ),
+ )
+ jobs = make_jobs(tmp_path)
+ monkeypatch.setattr(jobs, "launch", jobs.service.store.save_onboarding)
+ request_id = str(uuid.uuid4())
+ identity = {"user_id": "bot"}
+ feishu = await jobs.start("a", {"type": "feishu", "request_id": request_id}, identity)
+ other = await jobs.start("a", {"type": "future-platform", "request_id": request_id}, identity)
+ assert feishu["id"] != other["id"]
+ assert jobs.current("a", "feishu")["id"] == feishu["id"]
+ assert jobs.current("a", "future-platform")["id"] == other["id"]
+
+
+async def test_setup_preserves_reply_settings(tmp_path, monkeypatch):
+ jobs = make_jobs(tmp_path)
+ monkeypatch.setattr(jobs, "launch", jobs.service.store.save_onboarding)
+ run = await jobs.start(
+ "a",
+ {
+ "type": "feishu",
+ "request_id": str(uuid.uuid4()),
+ "settings": {"thread_require_mention": False},
+ },
+ {"user_id": "bot"},
+ )
+ assert jobs.get("a", run["id"])["settings"] == {"thread_require_mention": False}
+
+
[email protected]("require_mention", [True, False])
+async def test_setup_requests_all_group_messages_only_when_selected(require_mention):
+ all_scopes = console.SCOPES | {"im:message.group_msg"}
+ calls = []
+
+ async def post(path, body=None):
+ calls.append((path, body))
+ if "/scope/all/" in path:
+ return [{"name": name, "id": name} for name in all_scopes]
+ return {"eventMode": 4, "appEvents": [console.EVENT]}
+
+ await console.configure_app(
+ SimpleNamespace(post=post), "cli_test", require_mention=require_mention
+ )
+ requested = next(body["appScopeIDs"] for path, body in calls if "/scope/update/" in path)
+ assert ("im:message.group_msg" in requested) is (not require_mention)
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index 24842a15e..817558a5c 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -2034,6 +2034,10 @@ class AgentLoop:
disabled_tools = msg.metadata.get("disabled_tools", []) if msg.metadata else []
if not isinstance(disabled_tools, list):
disabled_tools = []
+ if msg.metadata.get("studio_managed"):
+ from vikingbot.studio.policy import disabled_group_tools
+
+ disabled_tools = list(set(disabled_tools) | set(disabled_group_tools(self.tools.tool_names)))
openviking_connection = getattr(msg, "openviking_connection", None)
if not isinstance(openviking_connection, dict):
openviking_connection = None
diff --git a/bot/vikingbot/channels/feishu.py b/bot/vikingbot/channels/feishu.py
index 75acfe750..9ff6a6272 100644
--- a/bot/vikingbot/channels/feishu.py
+++ b/bot/vikingbot/channels/feishu.py
@@ -307,6 +307,12 @@ class FeishuChannel(BaseChannel):
return "group" # 失败默认普通群
+ def _is_bot_mention(self, mention) -> bool:
+ bot_id = getattr(self, "bot_open_id", None)
+ if bot_id:
+ return getattr(getattr(mention, "id", None), "open_id", None) == bot_id
+ return bool(self.config.bot_name and getattr(mention, "name", "") == self.config.bot_name)
+
async def start(self) -> None:
"""Start the Feishu bot with WebSocket long connection."""
if not FEISHU_AVAILABLE:
@@ -531,19 +537,19 @@ class FeishuChannel(BaseChannel):
return elements or [{"tag": "markdown", "content": content}]
- async def send(self, msg: OutboundMessage) -> None:
+ async def send(self, msg: OutboundMessage) -> bool:
"""Send a message through Feishu."""
# 先调用基类处理通用动作
if await super().send(msg):
- return
+ return False
if not self._client:
logger.warning("Feishu client not initialized")
- return
+ return False
# Only send normal response messages, skip thinking/tool_call/etc.
if not msg.is_normal_message:
- return
+ return False
try:
# logger.info(f"Sending message {msg}")
@@ -554,7 +560,7 @@ class FeishuChannel(BaseChannel):
logger.warning(
f"Skipping Feishu message without reply_to metadata: session={msg.session_key}"
)
- return
+ return False
if reply_to.startswith("oc_"):
receive_id_type = "chat_id"
else:
@@ -659,8 +665,11 @@ class FeishuChannel(BaseChannel):
f"msg={response.msg}, log_id={response.get_log_id()}"
)
+ return response.success()
+
except Exception as e:
logger.exception(f"Error sending Feishu message: {e}")
+ return False
@staticmethod
def _reply_to_message_id_from_metadata(metadata: dict[str, Any] | None) -> str | None:
@@ -997,10 +1006,9 @@ class FeishuChannel(BaseChannel):
# 5. 检查是否被@
is_mentioned = False
- bot_name = self.config.bot_name
- if hasattr(message, "mentions") and message.mentions and bot_name:
+ if hasattr(message, "mentions") and message.mentions:
for mention in message.mentions:
- if hasattr(mention, "name") and mention.name == bot_name:
+ if self._is_bot_mention(mention):
is_mentioned = True
break
@@ -1023,7 +1031,7 @@ class FeishuChannel(BaseChannel):
if placeholder not in content:
continue
mention_name = getattr(mention, "name", "")
- if bot_name and mention_name == bot_name:
+ if self._is_bot_mention(mention):
content = content.replace(placeholder, "")
continue
if hasattr(mention, "id") and mention.id:
@@ -1059,6 +1067,13 @@ class FeishuChannel(BaseChannel):
message.root_id = message.message_id
final_chat_id = f"{reply_to}#{message.root_id}"
+ topic_title = ""
+ if chat_mode == "thread" and message.root_id == message_id and msg_type == "post":
+ try:
+ topic_title = json.loads(message.content).get("title", "")
+ except (json.JSONDecodeError, AttributeError):
+ pass
+
# 10. 转发到消息总线
logger.info(f"Received message from Feishu: {content}")
await self._handle_message(
@@ -1075,6 +1090,7 @@ class FeishuChannel(BaseChannel):
"msg_type": msg_type,
"root_id": message.root_id,
"chat_mode": chat_mode,
+ "topic_title": topic_title if isinstance(topic_title, str) else "",
"sender_id": sender_id,
},
)
diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.py
index 3033aadcf..c0dd73cab 100644
--- a/bot/vikingbot/channels/openapi.py
+++ b/bot/vikingbot/channels/openapi.py
@@ -364,6 +364,11 @@ class OpenAPIChannel(BaseChannel):
"""Verify gateway access and resolve caller OpenViking identity when needed."""
return await channel._verify_gateway_request(http_request, x_gateway_token)
+ if getattr(channel, "_studio_service", None) is not None:
+ from vikingbot.studio.router import create_router
+
+ router.include_router(create_router(channel, channel._studio_service))
+
@router.get("/health", response_model=HealthResponse)
async def health_check(
auth: GatewayRequestAuth = Depends(verify_gateway_request),
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index 0c30b99dc..b7fc57888 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -691,6 +691,9 @@ def prepare_channel(
global_config=config,
compile_service=compile_service,
)
+ from vikingbot.studio.service import StudioService
+
+ openapi_channel._studio_service = StudioService(config, channels)
channels.add_channel(openapi_channel)
logger.info(f"OpenAPI channel enabled on port {openapi_port}")
diff --git a/bot/vikingbot/studio/__init__.py b/bot/vikingbot/studio/__init__.py
new file mode 100644
index 000000000..8d7a6d583
--- /dev/null
+++ b/bot/vikingbot/studio/__init__.py
@@ -0,0 +1 @@
+"""Studio-managed channel configuration and read-only IM history."""
diff --git a/bot/vikingbot/studio/onboarding.py b/bot/vikingbot/studio/onboarding.py
new file mode 100644
index 000000000..97adf2acf
--- /dev/null
+++ b/bot/vikingbot/studio/onboarding.py
@@ -0,0 +1,175 @@
+"""Account-scoped onboarding jobs with durable mutation checkpoints.
+
+Live authorization sessions belong to the selected provider and stay in memory.
+"""
+
+import asyncio
+import time
+import uuid
+from contextlib import suppress
+
+from fastapi import HTTPException
+
+from .providers.registry import get_provider, validate_settings
+
+TERMINAL = {"ready", "cancelled", "failed", "expired", "interrupted"}
+
+
+class OnboardingJobs:
+ def __init__(self, service):
+ self.service = service
+ self.tasks = {}
+ self.live = {}
+ self.lock = asyncio.Lock()
+ for run in service.store.onboarding_runs():
+ if run["state"] not in TERMINAL:
+ run.update(state="interrupted", error="interrupted")
+ service.store.save_onboarding(run)
+
+ def get(self, account, identifier):
+ run = next(
+ (r for r in self.service.store.onboarding_runs(account) if r["id"] == identifier), None
+ )
+ if run is None:
+ raise HTTPException(404, "Onboarding not found")
+ return run
+
+ def public(self, run):
+ result = {
+ key: run.get(key)
+ for key in (
+ "id",
+ "type",
+ "state",
+ "name",
+ "expires_at",
+ "error",
+ "app_id",
+ "connection_id",
+ )
+ }
+ result["user_id"] = run["identity"]["user_id"]
+ owner = run.get("owner")
+ if owner:
+ result["owner"] = {k: owner[k] for k in ("user_name", "tenant_name")}
+ if run["state"] in ("waiting_for_scan", "scanned"):
+ result["qr"] = self.live.get(run["id"], {}).get("qr")
+ result["can_retry"] = run["state"] in ("failed", "expired", "interrupted") and not (
+ (run.get("create_started") and not run.get("app_id"))
+ or (run.get("version_started") and not run.get("version_id"))
+ )
+ return result
+
+ def current(self, account, platform):
+ get_provider({"type": platform})
+ runs = self.service.store.onboarding_runs(account)
+ run = next(
+ (
+ r
+ for r in reversed(runs)
+ if r["type"] == platform
+ and not r.get("archived")
+ and r["state"] not in {"ready", "cancelled"}
+ ),
+ None,
+ )
+ return self.public(run) if run else None
+
+ async def start(self, account, body, identity):
+ provider = get_provider(body)
+ if not hasattr(provider, "run_onboarding"):
+ raise HTTPException(400, "Automatic onboarding is unavailable for this platform")
+ settings = validate_settings(provider, body.get("settings", {}))
+ request_id = body.get("request_id")
+ try:
+ uuid.UUID(request_id)
+ except (ValueError, TypeError, AttributeError) as exc:
+ raise HTTPException(400, "A valid request ID is required") from exc
+ async with self.lock:
+ existing = next(
+ (
+ r
+ for r in self.service.store.onboarding_runs(account)
+ if r["request_id"] == request_id and r["type"] == provider.type
+ ),
+ None,
+ )
+ if existing:
+ return self.public(existing)
+ current = self.current(account, provider.type)
+ if current:
+ return current
+ name = str(body.get("name", "VikingBot")).strip()
+ if not name or len(name) > 50:
+ raise HTTPException(400, "Bot name must contain 1–50 characters")
+ run = {
+ "id": str(uuid.uuid4()),
+ "request_id": request_id,
+ "account": account,
+ "type": provider.type,
+ "identity": identity,
+ "settings": settings,
+ "name": name,
+ "state": "initializing",
+ }
+ self.launch(run)
+ return self.public(run)
+
+ def launch(self, run):
+ run.update(state="initializing", error=None, expires_at=time.time() + 120)
+ self.service.store.save_onboarding(run)
+ self.live[run["id"]] = {}
+ self.tasks[run["id"]] = asyncio.create_task(self.execute(run))
+
+ async def execute(self, run):
+ try:
+ await get_provider(run).run_onboarding(self, run)
+ finally:
+ self.live.pop(run["id"], None)
+ self.tasks.pop(run["id"], None)
+
+ def checkpoint(self, run, **values):
+ run.update(values)
+ self.service.store.save_onboarding(run)
+
+ async def update(self, account, identifier, action):
+ async with self.lock:
+ run = self.get(account, identifier)
+ if action == "cancel":
+ if run["state"] not in {"initializing", "waiting_for_scan", "scanned", "expired"}:
+ raise HTTPException(
+ 409, "Application setup has started; close and resume later"
+ )
+ task = self.tasks.get(identifier)
+ if task:
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self.tasks.pop(identifier, None)
+ self.live.pop(identifier, None)
+ self.checkpoint(run, state="cancelled")
+ elif action == "manual":
+ if run["state"] not in {"failed", "expired", "interrupted"}:
+ raise HTTPException(409, "Wait for automatic setup to finish")
+ if run.get("connection_id"):
+ record = self.service.get(account, run["connection_id"])
+ record.update(setup_mode="manual", revision=record["revision"] + 1)
+ self.service.store.save(record)
+ self.checkpoint(run, archived=True)
+ elif action == "retry":
+ if not self.public(run)["can_retry"]:
+ raise HTTPException(
+ 409, "Check the application on its platform before continuing"
+ )
+ previous = self.tasks.get(identifier)
+ if previous:
+ # Terminal state can be persisted before its HTTP session
+ # finishes closing. Do not let old cleanup erase a new run.
+ with suppress(asyncio.CancelledError, Exception):
+ await previous
+ self.launch(run)
+ else:
+ raise HTTPException(400, "Unknown onboarding action")
+ return self.public(run)
diff --git a/bot/vikingbot/studio/policy.py b/bot/vikingbot/studio/policy.py
new file mode 100644
index 000000000..d1ec0370f
--- /dev/null
+++ b/bot/vikingbot/studio/policy.py
@@ -0,0 +1,17 @@
+"""Tools permitted for externally reachable Studio-managed group conversations."""
+
+GROUP_TOOLS = frozenset(
+ {
+ "openviking_list",
+ "openviking_search",
+ "openviking_grep",
+ "openviking_glob",
+ "openviking_multi_read",
+ "openviking_memory_commit",
+ }
+)
+
+
+def disabled_group_tools(tool_names):
+ # Deny by default, including installed MCP tools and local filesystem/Shell.
+ return [name for name in tool_names if name not in GROUP_TOOLS]
diff --git a/bot/vikingbot/studio/providers/__init__.py b/bot/vikingbot/studio/providers/__init__.py
new file mode 100644
index 000000000..a1d86221c
--- /dev/null
+++ b/bot/vikingbot/studio/providers/__init__.py
@@ -0,0 +1 @@
+"""Platform adapters for Studio-managed IM connections."""
diff --git a/bot/vikingbot/studio/providers/feishu/__init__.py b/bot/vikingbot/studio/providers/feishu/__init__.py
new file mode 100644
index 000000000..7d87406a8
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/__init__.py
@@ -0,0 +1 @@
+"""Feishu connection and onboarding implementation."""
diff --git a/bot/vikingbot/studio/providers/feishu/channel.py b/bot/vikingbot/studio/providers/feishu/channel.py
new file mode 100644
index 000000000..7b380a503
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/channel.py
@@ -0,0 +1,233 @@
+"""Feishu channel with persisted delivery evidence and a dedicated OV identity."""
+
+import asyncio
+import hashlib
+import time
+import uuid
+from dataclasses import replace
+from datetime import datetime, timezone
+
+from vikingbot.bus.events import InboundMessage, OutboundMessage
+from vikingbot.channels.feishu import FeishuChannel
+from vikingbot.config.schema import SessionKey
+
+
+def now():
+ return datetime.now(timezone.utc).isoformat()
+
+
+class StudioFeishuChannel(FeishuChannel):
+ def __init__(self, config, bus, *, record, store, **kwargs):
+ super().__init__(config, bus, **kwargs)
+ self.record = record
+ self._session_prefix = f"studio:{record['id']}:"
+ self.store = store
+ self.verification = None
+ self.last_received = None
+ self.last_sent = None
+ self.bot_open_id = record["bot_open_id"]
+ self.last_error = None
+ self.chat_names = {}
+
+ async def start(self):
+ from vikingbot.studio.providers.feishu.transport import run_connection
+
+ await run_connection(self)
+
+ async def _handle_message(
+ self,
+ sender_id,
+ chat_id,
+ content,
+ sender_name=None,
+ need_reply=True,
+ media=None,
+ metadata=None,
+ ):
+ if not self._running or not self.is_allowed(sender_id):
+ return
+ metadata = dict(metadata or {})
+ metadata["studio_managed"] = True
+ self.last_received = now()
+ key = SessionKey(
+ type="feishu", channel_id=self.channel_id, chat_id=self._session_prefix + chat_id
+ )
+ token = self.verification
+ if (
+ token
+ and token["expires_at"] > time.time()
+ and not token.get("received")
+ and token["code"] in content
+ and metadata.get("chat_type") == "group"
+ and need_reply
+ ):
+ token["received"] = True
+ token["conversation"] = chat_id
+ token["sent"] = bool(
+ await self.send(
+ OutboundMessage(
+ session_key=key,
+ content="VikingBot 已连接,可以 @我开始对话。",
+ metadata={**metadata, "studio_verification": True},
+ )
+ )
+ )
+ return
+ # Expired/replayed onboarding messages must never invoke the agent.
+ if "VikingBot connection test" in content:
+ return
+ event_id = metadata.get("message_id", str(uuid.uuid4()))
+ inserted = self.store.append(
+ self.record["id"],
+ chat_id,
+ event_id,
+ {
+ "role": "user",
+ "content": content,
+ "sender": sender_name or "",
+ "sender_id": sender_id,
+ "time": now(),
+ "status": "received",
+ "chat_type": metadata.get("chat_type"),
+ "topic_title": metadata.get("topic_title", ""),
+ "title": await self.chat_title(chat_id, content, metadata),
+ "group_name": self.chat_names.get(
+ metadata.get("reply_to", chat_id).split("#")[0], ""
+ )
+ if metadata.get("chat_type") == "group"
+ else "",
+ },
+ )
+ if not inserted:
+ return
+ connection = dict(self.record["identity"])
+ # Partition peer memory by group/topic, never by the installing administrator.
+ peer = "feishu-" + hashlib.sha256(chat_id.encode()).hexdigest()[:24]
+ await self.bus.publish_inbound(
+ InboundMessage(
+ sender_id=sender_id,
+ sender_name=sender_name,
+ session_key=key,
+ actor_peer_id=peer,
+ content=content,
+ need_reply=need_reply,
+ media=media or [],
+ metadata=metadata,
+ openviking_connection=connection,
+ )
+ )
+
+ async def history_with_names(self, conversation, before=0):
+ messages = self.store.history(self.record["id"], conversation, before)
+ for message in messages:
+ sender_id = message.get("sender_id")
+ if message.get("role") != "user" or message.get("sender") or not sender_id:
+ continue
+ group = message.get("conversation", "").split("#")[0]
+ try:
+ name = await asyncio.wait_for(
+ self._get_group_member_name(group, sender_id), timeout=3
+ )
+ except Exception:
+ break
+ if name:
+ message["sender"] = name
+ self.store.update_sender(self.record["id"], message["id"], name)
+ return messages
+
+ async def chat_title(self, chat_id, content, metadata):
+ group_id = metadata.get("reply_to", chat_id).split("#")[0]
+ if metadata.get("chat_type") != "group":
+ return metadata.get("sender_name") or ""
+ if group_id not in self.chat_names and self._client:
+ from lark_oapi.api.im.v1 import GetChatRequest
+
+ try:
+ request = GetChatRequest.builder().chat_id(group_id).build()
+ response = await asyncio.to_thread(self._client.im.v1.chat.get, request)
+ if response.success():
+ self.chat_names[group_id] = response.data.name
+ except Exception:
+ pass
+ name = self.chat_names.get(group_id, "")
+ if "#" in chat_id and name:
+ return name + " / " + content[:40]
+ return name
+
+ async def _download_viking_image(self, uri, msg):
+ from openviking.utils.media_limits import MAX_INLINE_TOOL_RESULT_MEDIA_BYTES
+ from vikingbot.openviking_mount.ov_server import VikingClient
+ from vikingbot.utils.image_format import sniff_image_format
+
+ if not msg:
+ raise ValueError("Missing message scope")
+ peer = "feishu-" + hashlib.sha256(msg.session_key.chat_id.encode()).hexdigest()[:24]
+ client = await VikingClient.create(
+ connection=self.record["identity"],
+ actor_peer_id=peer,
+ config=self._bot_config,
+ )
+ try:
+ info = await client.stat(uri)
+ size = info.get("size")
+ if (
+ isinstance(size, bool)
+ or not isinstance(size, int)
+ or not 0 < size <= MAX_INLINE_TOOL_RESULT_MEDIA_BYTES
+ ):
+ raise ValueError("Image exceeds delivery limit")
+ data = await client.download_bytes(uri)
+ if len(data) > size or sniff_image_format(data) is None:
+ raise ValueError("Unsupported image")
+ return data
+ finally:
+ await client.close()
+
+ async def send(self, msg):
+ # A replaced connection must never deliver an old in-flight response.
+ if not msg.session_key.chat_id.startswith(self._session_prefix):
+ return False
+ # Only the Agent session is scoped; Feishu delivery and captured history
+ # continue using the original group/topic identifier.
+ msg = replace(
+ msg,
+ session_key=msg.session_key.model_copy(
+ update={"chat_id": msg.session_key.chat_id.removeprefix(self._session_prefix)}
+ ),
+ )
+ accepted = await super().send(msg)
+ if msg.is_normal_message:
+ if accepted:
+ self.last_sent = now()
+ if not msg.metadata.get("studio_verification"):
+ self.store.append(
+ self.record["id"],
+ msg.session_key.chat_id,
+ msg.response_id or str(uuid.uuid4()),
+ {
+ "role": "assistant",
+ "content": msg.content,
+ "sender": self.config.bot_name,
+ "time": now(),
+ "status": "sent" if accepted else "send_failed",
+ },
+ )
+ return accepted
+
+ async def stop(self):
+ self._running = False
+ socket = getattr(self._ws_client, "_conn", None)
+ if socket:
+ await socket.close()
+
+ def status(self):
+ # Socket evidence, never infer connection from the channel's start flag.
+ socket = getattr(self._ws_client, "_conn", None)
+ connected = socket is not None and not getattr(socket, "closed", False)
+ return {
+ "state": "connected" if connected and self._running else "connecting",
+ "last_received": self.last_received,
+ "last_sent": self.last_sent,
+ "verification": self.verification,
+ "last_error": self.last_error,
+ }
diff --git a/bot/vikingbot/studio/providers/feishu/console.py b/bot/vikingbot/studio/providers/feishu/console.py
new file mode 100644
index 000000000..0a41c43cf
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/console.py
@@ -0,0 +1,208 @@
+"""Minimal console automation for newly created VikingBot apps only.
+
+Uses the Feishu developer-console agent template for new apps. No automatic replay
+of non-idempotent create/publish calls. Checkpoints are saved before every such call.
+"""
+
+from pathlib import Path
+from uuid import uuid4
+
+from loguru import logger
+
+from .web_session import SetupError, data, field
+
+SCOPES = {
+ "im:message.group_at_msg:readonly",
+ "im:message:send_as_bot",
+ "im:chat:read",
+ "im:chat.members:read",
+}
+EVENT = "im.message.receive_v1"
+
+
+def scope_ids(value, bucket=None, required=SCOPES):
+ found = {}
+ if isinstance(value, list):
+ for item in value:
+ found.update(scope_ids(item, bucket, required))
+ elif isinstance(value, dict):
+ name = field(value, "scope_name", "scopeName", "name", "key", "scopeKey")
+ identifier = None
+ for key in ("id", "scope_id", "scopeId", "scopeID"):
+ raw = value.get(key)
+ if isinstance(raw, str) and raw:
+ identifier = raw
+ break
+ if isinstance(raw, int) and not isinstance(raw, bool):
+ identifier = str(raw)
+ break
+ if name in required and identifier and bucket != "user":
+ found[name] = identifier
+ for key, child in value.items():
+ next_bucket = "user" if "user" in key.lower() else bucket
+ if any(word in key.lower() for word in ("app", "tenant", "client")):
+ next_bucket = "tenant"
+ if isinstance(child, (dict, list)):
+ found.update(scope_ids(child, next_bucket, required))
+ return found
+
+
+def event_ids(value):
+ if isinstance(value, str):
+ return {value}
+ if isinstance(value, list):
+ return set().union(*(event_ids(item) for item in value))
+ if isinstance(value, dict):
+ return event_ids(value.get("id", [])) | event_ids(value.get("items", []))
+ return set()
+
+
+async def create_app(session, run, checkpoint):
+ if run.get("app_id"):
+ return run["app_id"]
+ if run.get("create_started"):
+ raise SetupError("creation_uncertain")
+ icon = Path(__file__).with_name("icon.png").read_bytes()
+ uploaded = await session.post(
+ "/developers/v1/app/upload/image",
+ {"uploadType": "4", "isIsv": "false", "scale": '{"width":512,"height":512}'},
+ files={"file": ("vikingbot.png", icon, "image/png")},
+ )
+ avatar = field(uploaded, "url")
+ if not avatar:
+ raise SetupError("icon_upload_failed")
+ # Persist the request identity before creation; an uncertain result must never
+ # fall back to app/create and silently create a second, ordinary bot.
+ request_id = run.get("template_request_id") or str(uuid4())
+ checkpoint(create_started=True, template_request_id=request_id)
+ created = await session.post(
+ "/developers/v1/manifest/upsert_by_template",
+ {
+ "appManifestTemplateID": "developer_console",
+ "createAppUserCustomField": {
+ "i18n": {
+ "zh_cn": {
+ "name": run["name"],
+ "description": "OpenViking AI assistant",
+ }
+ },
+ "avatar": avatar,
+ "primaryLang": "zh_cn",
+ },
+ "cid": request_id,
+ "HTTPHead": {},
+ },
+ )
+ app_id = field(created, "ClientID", "clientID", "clientId", "appId")
+ if not app_id or not app_id.startswith("cli_"):
+ raise SetupError("creation_uncertain")
+ checkpoint(app_id=app_id)
+ return app_id
+
+
+async def prepare_app(session, app_id):
+ await session.post(
+ f"/developers/v1/robot/switch/{app_id}", {"clientId": app_id, "enable": True}
+ )
+ await session.post(
+ f"/developers/v1/event/switch/{app_id}", {"clientId": app_id, "eventMode": 4}
+ )
+ secret = field(await session.post(f"/developers/v1/secret/{app_id}"), "secret")
+ if not secret:
+ raise SetupError("credentials_unavailable")
+ return secret
+
+
+async def configure_app(session, app_id, require_mention=True):
+ required = SCOPES if require_mention else SCOPES | {"im:message.group_msg"}
+ catalog = scope_ids(await session.post(f"/developers/v1/scope/all/{app_id}"), required=required)
+ if missing := required - catalog.keys():
+ logger.warning(
+ "Feishu permission catalog missing required scope names: {}", sorted(missing)
+ )
+ raise SetupError("permissions_unavailable")
+ await session.post(
+ f"/developers/v1/scope/update/{app_id}",
+ {
+ "clientId": app_id,
+ "appScopeIDs": list(catalog.values()),
+ "userScopeIDs": [],
+ "scopeIds": [],
+ "operation": "add",
+ "isDeveloperPanel": True,
+ },
+ )
+ await session.post(
+ f"/developers/v1/event/update/{app_id}",
+ {
+ "clientId": app_id,
+ "eventMode": 4,
+ "operation": "add",
+ "events": [],
+ "appEvents": [EVENT],
+ "userEvents": [],
+ },
+ )
+ state = data(await session.post(f"/developers/v1/event/{app_id}"))
+ events = set().union(
+ *(
+ event_ids(state.get(key, []))
+ for key in (
+ "events",
+ "appEvents",
+ "appEventDetails",
+ "eventDetails",
+ )
+ )
+ )
+ if state.get("eventMode") != 4 or EVENT not in events:
+ raise SetupError("events_not_ready")
+
+
+async def publish_app(session, run, checkpoint):
+ app_id = run["app_id"]
+ if not run.get("version_id"):
+ if run.get("version_started"):
+ raise SetupError("publication_uncertain")
+ checkpoint(version_started=True)
+ visible = {
+ "departments": [],
+ "members": [run["owner"]["user_id"]],
+ "groups": [],
+ "isAll": 0,
+ }
+ created = await session.post(
+ f"/developers/v1/app_version/create/{app_id}",
+ {
+ "appVersion": "1.0.0",
+ "mobileDefaultAbility": "bot",
+ "pcDefaultAbility": "bot",
+ "changeLog": "Initial VikingBot release.",
+ "visibleSuggest": visible,
+ "blackVisibleSuggest": {**visible, "members": []},
+ },
+ )
+ version_id = field(created, "versionId", "version_id", "id") or field(
+ data(created).get("appVersion", {}), "versionId", "version_id", "id"
+ )
+ if not version_id:
+ raise SetupError("publication_uncertain")
+ checkpoint(version_id=version_id)
+ if not run.get("publish_started"):
+ checkpoint(publish_started=True)
+ await session.post(
+ f"/developers/v1/publish/commit/{app_id}/{run['version_id']}", {"clientId": app_id}
+ )
+ return await publication_status(session, run)
+
+
+async def publication_status(session, run):
+ versions = data(await session.post(f"/developers/v1/app_version/list/{run['app_id']}"))
+ for version in versions.get("versions", []):
+ if field(version, "versionId", "version_id", "id") == run["version_id"]:
+ status = version.get("versionStatus")
+ if status == 2:
+ return "published"
+ if status == 1:
+ return "awaiting_approval"
+ raise SetupError("publication_uncertain")
diff --git a/bot/vikingbot/studio/providers/feishu/icon.png b/bot/vikingbot/studio/providers/feishu/icon.png
new file mode 100644
index 000000000..fb9ea3329
Binary files /dev/null and b/bot/vikingbot/studio/providers/feishu/icon.png differ
diff --git a/bot/vikingbot/studio/providers/feishu/onboarding.py b/bot/vikingbot/studio/providers/feishu/onboarding.py
new file mode 100644
index 000000000..a10408b6c
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/onboarding.py
@@ -0,0 +1,126 @@
+"""One QR session creates, configures and publishes a group-chat application."""
+
+import asyncio
+import time
+
+import httpx
+
+from .console import configure_app, create_app, prepare_app, publication_status, publish_app
+from .web_session import FeishuWebSession, SetupError
+
+
+async def run_onboarding(jobs, run):
+ session = FeishuWebSession()
+ service = jobs.service
+
+ def checkpoint(**values):
+ jobs.checkpoint(run, **values)
+
+ try:
+ qr = await session.begin()
+ jobs.live[run["id"]]["qr"] = qr
+ checkpoint(state="waiting_for_scan", expires_at=time.time() + 120)
+ while time.time() < run["expires_at"]:
+ state = await session.poll()
+ if state == "authorized":
+ break
+ if state == "expired":
+ checkpoint(state="expired", error="expired")
+ return
+ if run["state"] != state:
+ checkpoint(state=state)
+ await asyncio.sleep(1.5)
+ else:
+ checkpoint(state="expired", error="expired")
+ return
+ jobs.live[run["id"]].clear()
+ owner = await session.identity()
+ if run.get("owner") and any(owner[k] != run["owner"][k] for k in ("user_id", "tenant_id")):
+ raise SetupError("identity_changed")
+ checkpoint(owner=owner, state="creating")
+ app_id = await create_app(session, run, checkpoint)
+ if not run.get("configured"):
+ checkpoint(state="configuring")
+ secret = await prepare_app(session, app_id)
+ if not run.get("connection_id"):
+ # A crash after create() persisted a connection must not create it a second time.
+ existing = next(
+ (
+ r
+ for r in service.store.connections(run["account"])
+ if r.get("type", "feishu") == "feishu" and r.get("app_id") == app_id
+ ),
+ None,
+ )
+ if existing:
+ connection = service.public(existing)
+ else:
+ connection = await service.create(
+ run["account"],
+ {
+ "type": "feishu",
+ "settings": run.get("settings", {}),
+ "app_id": app_id,
+ "app_secret": secret,
+ },
+ run["identity"],
+ )
+ record = service.get(run["account"], connection["id"])
+ record.update(onboarding_id=run["id"], setup_mode="qr")
+ service.store.save(record)
+ checkpoint(connection_id=connection["id"])
+ record = service.get(run["account"], run["connection_id"])
+ runtime = service.runtime(record)
+ for _ in range(30):
+ if runtime and runtime.status()["state"] == "connected":
+ break
+ await asyncio.sleep(1)
+ else:
+ raise SetupError("connection_unavailable")
+ await configure_app(
+ session,
+ app_id,
+ require_mention=run.get("settings", {}).get("thread_require_mention", True),
+ )
+ checkpoint(configured=True)
+ checkpoint(state="publishing")
+ await publish_and_wait(session, run, checkpoint)
+ record = service.get(run["account"], run["connection_id"])
+ # Keep optimistic concurrency intact when a paused connection was changed.
+ record.update(step=4, revision=record["revision"] + 1)
+ service.store.save(record)
+ checkpoint(state="ready", error=None)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ # HTTP/SDK exceptions may contain URLs, cookies and credentials. Never
+ # expose or log the upstream exception text in the onboarding API.
+ checkpoint(
+ state="failed", error=str(exc) if isinstance(exc, SetupError) else "setup_failed"
+ )
+ finally:
+ await session.close()
+
+
+async def publish_and_wait(session, run, checkpoint):
+ try:
+ state = await publish_app(session, run, checkpoint)
+ except (SetupError, httpx.HTTPError):
+ if not run.get("publish_started"):
+ raise
+ # A dropped commit response is ambiguous. Reconcile by reading, never
+ # replay the publish request. Console reads can lag behind the write.
+ state = "publishing"
+ deadline = time.time() + 600
+ reconcile_deadline = time.time() + 45
+ while state != "published":
+ checkpoint(state=state)
+ if time.time() > deadline:
+ raise SetupError("approval_pending")
+ await asyncio.sleep(3 if state == "publishing" else 10)
+ try:
+ state = await publication_status(session, run)
+ except SetupError:
+ if time.time() > reconcile_deadline:
+ raise
+ return state
diff --git a/bot/vikingbot/studio/providers/feishu/provider.py b/bot/vikingbot/studio/providers/feishu/provider.py
new file mode 100644
index 000000000..4fd3f42e2
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/provider.py
@@ -0,0 +1,145 @@
+"""Feishu-specific credentials, channel configuration and onboarding actions."""
+
+import secrets
+import time
+
+import httpx
+from fastapi import HTTPException
+
+from vikingbot.config.schema import FeishuChannelConfig
+
+
+class FeishuProvider:
+ type = "feishu"
+
+ def validate_settings(self, value):
+ if not isinstance(value, dict) or set(value) - {"thread_require_mention"}:
+ raise HTTPException(400, "Unsupported Feishu settings")
+ required = value.get("thread_require_mention", True)
+ if type(required) is not bool:
+ raise HTTPException(400, "thread_require_mention must be boolean")
+ return {"thread_require_mention": required}
+
+ def apply_settings(self, service, record):
+ required = self.validate_settings(record.get("settings", {}))["thread_require_mention"]
+ runtime = service.runtime(record)
+ if runtime:
+ runtime.config.thread_require_mention = required
+ for config in service.config.channels:
+ if (
+ isinstance(config, dict)
+ and config.get("type", "feishu") == "feishu"
+ and config.get("app_id") == record["app_id"]
+ ):
+ config["thread_require_mention"] = required
+
+ async def run_onboarding(self, jobs, run):
+ from .onboarding import run_onboarding
+
+ await run_onboarding(jobs, run)
+
+ def runtime_key(self, record):
+ return "feishu__" + record["app_id"]
+
+ def validate_input(self, body):
+ app_id = str(body.get("app_id", "")).strip()
+ secret = str(body.get("app_secret", "")).strip()
+ if not app_id.startswith("cli_") or not secret or len(secret) > 4096:
+ raise HTTPException(400, "App ID and App Secret are required")
+ return app_id, secret
+
+ async def prepare(self, body):
+ app_id, secret = self.validate_input(body)
+ info = await self.validate_app(app_id, secret)
+ return {
+ "app_id": app_id,
+ "app_secret": secret,
+ "bot_name": info.get("app_name") or "VikingBot",
+ "bot_open_id": info["open_id"],
+ "step": 2,
+ }
+
+ async def credentials(self, record, body):
+ secret = str(body.get("app_secret") or record["app_secret"]).strip()
+ info = await self.validate_app(record["app_id"], secret)
+ if info["open_id"] != record["bot_open_id"]:
+ raise HTTPException(409, "Robot identity changed")
+ return {**record, "app_secret": secret}
+
+ def public_fields(self, record):
+ return {
+ key: record.get(key) for key in ("app_id", "step", "setup_mode", "onboarding_id")
+ } | {"settings": self.validate_settings(record.get("settings", {}))}
+
+ def install(self, service, record):
+ from vikingbot.studio.providers.feishu.channel import StudioFeishuChannel
+
+ channel_config = FeishuChannelConfig(
+ app_id=record["app_id"],
+ app_secret=record["app_secret"],
+ bot_name=record["bot_name"],
+ thread_require_mention=self.validate_settings(record.get("settings", {}))[
+ "thread_require_mention"
+ ],
+ memory_peer=[],
+ memory_user=[],
+ )
+ channel = StudioFeishuChannel(
+ channel_config,
+ service.manager.bus,
+ record=record,
+ store=service.store,
+ workspace_path=service.config.workspace_path,
+ bot_config=service.config,
+ )
+ service.manager.add_channel(channel)
+ # Agent configuration is the same object; keep runtime channel policy in sync.
+ service.config.channels = [
+ c
+ for c in service.config.channels
+ if not (
+ isinstance(c, dict)
+ and c.get("type", "feishu") == "feishu"
+ and c.get("app_id") == record["app_id"]
+ )
+ ]
+ service.config.channels.append(channel_config.model_dump(mode="json"))
+ return channel
+
+ async def validate_app(self, app_id, secret):
+ try:
+ async with httpx.AsyncClient(timeout=15) as client:
+ auth_response = await client.post(
+ "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
+ json={"app_id": app_id, "app_secret": secret},
+ )
+ auth_response.raise_for_status()
+ auth = auth_response.json()
+ if auth.get("code") != 0 or not auth.get("tenant_access_token"):
+ raise HTTPException(400, "Feishu rejected the application credentials")
+ bot_response = await client.get(
+ "https://open.feishu.cn/open-apis/bot/v3/info",
+ headers={"Authorization": "Bearer " + auth["tenant_access_token"]},
+ )
+ bot_response.raise_for_status()
+ bot = bot_response.json()
+ except (httpx.HTTPError, ValueError) as exc:
+ raise HTTPException(502, "Cannot reach Feishu; retry the connection check") from exc
+ info = bot.get("bot", {})
+ if bot.get("code") != 0 or not info.get("open_id"):
+ raise HTTPException(400, "Enable the application's bot capability first")
+ return info
+
+ def onboarding(self, record, runtime, body):
+ action = body.get("action")
+ if action == "verify":
+ if not record["enabled"] or not runtime:
+ raise HTTPException(409, "Resume the connection first")
+ runtime.verification = {
+ "code": secrets.token_hex(3).upper(),
+ "expires_at": time.time() + 600,
+ "received": False,
+ "sent": False,
+ }
+ else:
+ raise HTTPException(400, "Unknown action")
diff --git a/bot/vikingbot/studio/providers/feishu/transport.py b/bot/vikingbot/studio/providers/feishu/transport.py
new file mode 100644
index 000000000..be00376f1
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/transport.py
@@ -0,0 +1,76 @@
+"""Cancellable Feishu transport, using the SDK only for its wire protocol.
+
+The SDK's public start() owns a module-global event loop and cannot run multiple
+managed connections or be stopped independently. Keep its protocol calls here.
+"""
+
+import asyncio
+from contextlib import suppress
+from urllib.parse import parse_qs, urlsplit
+
+import httpx
+import lark_oapi as lark
+import websockets
+from lark_oapi.ws.model import ClientConfig
+
+
+async def run_connection(channel):
+ channel._running = True
+ channel._loop = asyncio.get_running_loop()
+ channel._client = (
+ lark.Client.builder()
+ .app_id(channel.config.app_id)
+ .app_secret(channel.config.app_secret)
+ .build()
+ )
+ handler = (
+ lark.EventDispatcherHandler.builder("", "")
+ .register_p2_im_message_receive_v1(channel._on_message_sync)
+ .build()
+ )
+ client = lark.ws.Client(
+ channel.config.app_id,
+ channel.config.app_secret,
+ event_handler=handler,
+ auto_reconnect=False,
+ )
+ channel._ws_client = client
+ while channel._running:
+ ping = None
+ try:
+ async with httpx.AsyncClient(timeout=15) as http:
+ response = await http.post(
+ "https://open.feishu.cn/callback/ws/endpoint",
+ json={"AppID": channel.config.app_id, "AppSecret": channel.config.app_secret},
+ )
+ response.raise_for_status()
+ endpoint = response.json()
+ if endpoint.get("code") != 0:
+ raise ValueError("Feishu rejected the long connection")
+ data = endpoint["data"]
+ url = data["URL"]
+ query = parse_qs(urlsplit(url).query)
+ client._service_id = query["service_id"][0]
+ if data.get("ClientConfig"):
+ client._configure(ClientConfig(data["ClientConfig"]))
+ async with websockets.connect(url) as socket:
+ client._conn = socket
+ channel.last_error = None
+ ping = asyncio.create_task(client._ping_loop())
+ async for frame in socket:
+ if not channel._running:
+ break
+ await client._handle_message(frame)
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ # No endpoint URL or credentials in public diagnostics.
+ channel.last_error = type(exc).__name__
+ finally:
+ client._conn = None
+ if ping:
+ ping.cancel()
+ with suppress(asyncio.CancelledError):
+ await ping
+ if channel._running:
+ await asyncio.sleep(5)
diff --git a/bot/vikingbot/studio/providers/feishu/web_session.py b/bot/vikingbot/studio/providers/feishu/web_session.py
new file mode 100644
index 000000000..50d2c5db9
--- /dev/null
+++ b/bot/vikingbot/studio/providers/feishu/web_session.py
@@ -0,0 +1,155 @@
+"""Short-lived Feishu console sessions. No cookies or login tokens are persisted.
+
+The console login contract is isolated here because it is not a public OAuth API.
+"""
+
+import json
+import re
+from urllib.parse import urljoin, urlparse
+
+import httpx
+
+
+class SetupError(Exception):
+ """Safe error code suitable for the Studio API; never contains upstream bodies."""
+
+
+ACCOUNTS = "https://accounts.feishu.cn"
+REDIRECT = "https://ask.feishu.cn/"
+HEADERS = {
+ "x-app-id": "12",
+ "x-api-version": "1.0.28",
+ "x-device-info": "device_id=0;device_name=Chrome;device_os=Mac;device_model=Chrome;"
+ "lark_version=;channel=Release;package_name=feishu;tt_app_id=1658;"
+ "is_dpop_support=true;is_iframe=false",
+ "x-locale": "zh-CN",
+ "x-terminal-type": "2",
+}
+
+
+def allowed_url(url):
+ parsed = urlparse(url)
+ return (
+ parsed.scheme == "https"
+ and parsed.port in (None, 443)
+ and not parsed.username
+ and not parsed.password
+ and any(
+ parsed.hostname == domain or (parsed.hostname or "").endswith("." + domain)
+ for domain in ("feishu.cn", "larkoffice.com")
+ )
+ )
+
+
+def payload(response):
+ try:
+ response.raise_for_status()
+ value = response.json()
+ except (httpx.HTTPError, ValueError) as exc:
+ raise SetupError("platform_request_failed") from exc
+ if not isinstance(value, dict) or value.get("code", 0) != 0:
+ raise SetupError("platform_rejected")
+ return value
+
+
+def data(value):
+ return value.get("data", value)
+
+
+def field(value, *names):
+ for container in (value, data(value)):
+ for name in names:
+ if isinstance(container.get(name), str) and container[name]:
+ return container[name]
+ return None
+
+
+class FeishuWebSession:
+ def __init__(self, client=None):
+ self.client = client or httpx.AsyncClient(timeout=20, follow_redirects=False)
+ self.origin = "https://open.feishu.cn"
+ self.csrf = None
+ self.flow_key = None
+
+ async def close(self):
+ self.client.cookies.clear()
+ self.csrf = self.flow_key = None
+ await self.client.aclose()
+
+ async def request(self, method, url, **kwargs):
+ # Follow only trusted HTTPS redirects, without forwarding CSRF to another origin.
+ for _ in range(10):
+ if not allowed_url(url):
+ raise SetupError("untrusted_redirect")
+ response = await self.client.request(method, url, **kwargs)
+ if not response.is_redirect:
+ return response
+ url = urljoin(str(response.url), response.headers.get("location", ""))
+ if method != "GET":
+ raise SetupError("session_expired")
+ raise SetupError("session_expired")
+
+ async def begin(self):
+ response = await self.request(
+ "POST",
+ ACCOUNTS + "/accounts/qrlogin/init",
+ headers=HEADERS,
+ json={"biz_type": None, "redirect_uri": REDIRECT},
+ )
+ token = data(payload(response)).get("step_info", {}).get("token")
+ self.flow_key = response.headers.get("x-flow-key")
+ if not isinstance(token, str) or not self.flow_key:
+ raise SetupError("login_unavailable")
+ return json.dumps({"qrlogin": {"token": token}}, separators=(",", ":"))
+
+ async def poll(self):
+ response = await self.request(
+ "POST",
+ ACCOUNTS + "/accounts/qrlogin/polling",
+ headers={**HEADERS, "x-flow-key": self.flow_key},
+ json={"biz_type": None},
+ )
+ result = data(payload(response))
+ step = result.get("step_info", {})
+ if result.get("next_step") == "enter_app":
+ if step.get("cross_login_uri"):
+ await self.request("GET", step["cross_login_uri"])
+ await self.request("GET", REDIRECT)
+ return "authorized"
+ return {2: "scanned", 5: "expired"}.get(step.get("status"), "waiting_for_scan")
+
+ async def identity(self):
+ page = await self.request("GET", "https://open.feishu.cn/app")
+ page.raise_for_status()
+ match = re.search(r"\b(?:window\.csrfToken\s*=|csrfToken\s*:)\s*['\"]([^'\"]+)", page.text)
+ user_match = re.search(r"\bwindow\.user\s*=\s*", page.text)
+ if not match or not user_match:
+ raise SetupError("session_expired")
+ try:
+ user, _ = json.JSONDecoder().raw_decode(page.text[user_match.end() :])
+ except ValueError as exc:
+ raise SetupError("identity_unavailable") from exc
+ identity = {
+ "user_id": field(user, "id", "userId", "user_id"),
+ "tenant_id": field(user, "tenantId", "tenant_id"),
+ "user_name": field(user, "name", "userName", "user_name")
+ or user.get("displayName", {}).get("value"),
+ "tenant_name": field(user, "tenantName", "tenant_name")
+ or user.get("tenantDisplayName", {}).get("value"),
+ }
+ if not all(identity.values()):
+ raise SetupError("identity_unavailable")
+ self.origin = str(page.url).split("/app")[0]
+ if self.origin not in ("https://open.feishu.cn", "https://open.larkoffice.com"):
+ raise SetupError("untrusted_redirect")
+ self.csrf = match[1]
+ return identity
+
+ async def post(self, path, body=None, files=None):
+ headers = {
+ "origin": self.origin,
+ "referer": self.origin + "/app",
+ "x-csrf-token": self.csrf,
+ }
+ kwargs = {"files": files, "data": body} if files else {"json": body or {}}
+ return payload(await self.request("POST", self.origin + path, headers=headers, **kwargs))
diff --git a/bot/vikingbot/studio/providers/registry.py b/bot/vikingbot/studio/providers/registry.py
new file mode 100644
index 000000000..58e71f65e
--- /dev/null
+++ b/bot/vikingbot/studio/providers/registry.py
@@ -0,0 +1,23 @@
+"""Explicit platform registration. Unknown types never fall back to Feishu."""
+
+from fastapi import HTTPException
+
+from vikingbot.studio.providers.feishu.provider import FeishuProvider
+
+PROVIDERS = {"feishu": FeishuProvider()}
+
+
+def get_provider(record):
+ # Records written before platform support were all Feishu connections.
+ platform = record.get("type", "feishu")
+ if platform not in PROVIDERS:
+ raise HTTPException(400, "Unsupported IM type")
+ return PROVIDERS[platform]
+
+
+def validate_settings(provider, value):
+ if hasattr(provider, "validate_settings"):
+ return provider.validate_settings(value)
+ if value:
+ raise HTTPException(400, "Settings are unavailable for this platform")
+ return {}
diff --git a/bot/vikingbot/studio/router.py b/bot/vikingbot/studio/router.py
new file mode 100644
index 000000000..723c31048
--- /dev/null
+++ b/bot/vikingbot/studio/router.py
@@ -0,0 +1,54 @@
+"""Private gateway endpoints, callable only by the authenticated server proxy."""
+
+import os
+import secrets
+
+from fastapi import APIRouter, Depends, Header, HTTPException, Request
+
+
+def create_router(channel, service):
+ async def authorize(request: Request, x_gateway_token: str = Header(default="")):
+ token = os.environ.get("OPENVIKING_BOT_STUDIO_TOKEN") or channel._gateway_token()
+ if not (
+ token
+ and secrets.compare_digest(token, x_gateway_token)
+ and channel._is_loopback_request(request)
+ ):
+ raise HTTPException(403, "Studio management requires the internal gateway token")
+
+ router = APIRouter(prefix="/studio", dependencies=[Depends(authorize)], include_in_schema=False)
+
+ @router.post("/dispatch")
+ async def dispatch(request: Request):
+ body = await request.json()
+ account = body["account"]
+ action = body["action"]
+ payload = body.get("payload", {})
+ if action == "onboarding_start":
+ return await service.onboarding.start(account, payload, body["identity"])
+ if action == "onboarding_current":
+ return service.onboarding.current(account, payload.get("type", "feishu"))
+ if action == "onboarding_get":
+ return service.onboarding.public(service.onboarding.get(account, payload.get("id")))
+ if action == "onboarding_update":
+ return await service.onboarding.update(
+ account, payload.get("id"), payload.get("action")
+ )
+ if action == "list":
+ return [service.public(r) for r in service.store.connections(account)]
+ if action == "create":
+ return await service.create(account, payload, body["identity"])
+ record = service.get(account, body.get("connection_id"))
+ if action == "update":
+ return await service.update(account, record["id"], payload)
+ if action == "conversations":
+ return service.store.conversations(record["id"])
+ if action == "messages":
+ before = max(0, int(payload.get("before", 0)))
+ runtime = service.runtime(record)
+ if runtime and hasattr(runtime, "history_with_names"):
+ return await runtime.history_with_names(payload.get("conversation", ""), before)
+ return service.store.history(record["id"], payload.get("conversation", ""), before)
+ raise HTTPException(400, "Unknown operation")
+
+ return router
diff --git a/bot/vikingbot/studio/service.py b/bot/vikingbot/studio/service.py
new file mode 100644
index 000000000..fcede4d34
--- /dev/null
+++ b/bot/vikingbot/studio/service.py
@@ -0,0 +1,152 @@
+"""Lifecycle of Studio-owned IM connections. Secrets never leave this service."""
+
+import asyncio
+import uuid
+
+from fastapi import HTTPException
+
+from vikingbot.studio.providers.registry import get_provider, validate_settings
+from vikingbot.studio.store import StudioStore
+
+
+class StudioService:
+ def __init__(self, config, manager):
+ self.config = config
+ self.manager = manager
+ self.store = StudioStore(config.bot_data_path / "studio.sqlite3")
+ self.tasks = {}
+ self.lock = asyncio.Lock()
+ from vikingbot.studio.onboarding import OnboardingJobs
+
+ self.onboarding = OnboardingJobs(self)
+ for record in self.store.connections():
+ if record.get("enabled"):
+ self.install(record)
+
+ def get(self, account, connection_id):
+ for record in self.store.connections(account):
+ if record["id"] == connection_id:
+ return record
+ raise HTTPException(404, "Connection not found")
+
+ def runtime(self, record):
+ return self.manager.channels.get(get_provider(record).runtime_key(record))
+
+ def public(self, record):
+ runtime = self.runtime(record)
+ status = (
+ runtime.status()
+ if record["enabled"] and runtime and hasattr(runtime, "status")
+ else {"state": "paused"}
+ )
+ return (
+ {key: record.get(key) for key in ("id", "bot_name", "enabled", "revision")}
+ | get_provider(record).public_fields(record)
+ | {
+ "type": get_provider(record).type,
+ "status": status,
+ "identity_user": record["identity"]["user_id"],
+ }
+ )
+
+ def install(self, record):
+ return get_provider(record).install(self, record)
+
+ async def create(self, account, body, identity):
+ provider = get_provider(body)
+ settings = validate_settings(provider, body.get("settings", {}))
+ async with self.lock:
+ fields = await provider.prepare(body.get("credentials", body))
+ candidate = {**fields, "type": provider.type}
+ key = provider.runtime_key(candidate)
+ if (
+ any(get_provider(r).runtime_key(r) == key for r in self.store.connections())
+ or key in self.manager.channels
+ ):
+ raise HTTPException(409, "This app is already configured")
+ record = {
+ "id": str(uuid.uuid4()),
+ "account": account,
+ **candidate,
+ "identity": identity,
+ "settings": settings,
+ "enabled": True,
+ "revision": 1,
+ }
+ channel = self.install(record)
+ self.store.save(record)
+ self.tasks[record["id"]] = asyncio.create_task(channel.start())
+ return self.public(record)
+
+ async def update(self, account, connection_id, body):
+ async with self.lock:
+ record = self.get(account, connection_id)
+ if body.get("revision") != record["revision"]:
+ raise HTTPException(409, "Configuration changed; refresh before saving")
+ action = body.get("action")
+ runtime = self.runtime(record)
+ if action == "delete":
+ if any(
+ run.get("connection_id") == connection_id and run["id"] in self.onboarding.tasks
+ for run in self.store.onboarding_runs(account)
+ ):
+ raise HTTPException(
+ 409, "Setup is running; finish or cancel it before deleting"
+ )
+ if runtime:
+ await runtime.stop()
+ task = self.tasks.pop(connection_id, None)
+ if task:
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ self.manager.channels.pop(get_provider(record).runtime_key(record), None)
+ self.store.delete_connection(record)
+ return {"deleted": True}
+ if action == "settings":
+ provider = get_provider(record)
+ if not hasattr(provider, "apply_settings"):
+ raise HTTPException(400, "Settings are unavailable for this platform")
+ record["settings"] = validate_settings(provider, body["settings"])
+ record["revision"] += 1
+ self.store.save(record)
+ provider.apply_settings(self, record)
+ return self.public(record)
+ if action == "pause":
+ if runtime:
+ await runtime.stop()
+ task = self.tasks.pop(connection_id, None)
+ if task:
+ task.cancel()
+ record["enabled"] = False
+ elif action == "resume":
+ if not record["enabled"]:
+ runtime = self.install(record)
+ self.tasks[connection_id] = asyncio.create_task(runtime.start())
+ record["enabled"] = True
+ elif action == "credentials":
+ candidate = await get_provider(record).credentials(
+ record, body.get("credentials", body)
+ )
+ if body.get("identity"):
+ if body["identity"]["user_id"] != record["identity"]["user_id"]:
+ raise HTTPException(409, "Rotate the key for the same Bot user")
+ candidate["identity"] = body["identity"]
+ # Persist before replacing runtime. Validation failure preserves the old connection.
+ self.store.save(candidate)
+ if runtime:
+ await runtime.stop()
+ old_task = self.tasks.pop(connection_id, None)
+ if old_task:
+ old_task.cancel()
+ record = candidate
+ if record["enabled"]:
+ runtime = self.install(record)
+ self.tasks[connection_id] = asyncio.create_task(runtime.start())
+ else:
+ get_provider(record).onboarding(record, runtime, body)
+ record["revision"] += 1
+ self.store.save(record)
+ result = self.public(record)
+ if not record["enabled"]:
+ result["status"] = {"state": "paused"}
+ return result
diff --git a/bot/vikingbot/studio/store.py b/bot/vikingbot/studio/store.py
new file mode 100644
index 000000000..1d534141e
--- /dev/null
+++ b/bot/vikingbot/studio/store.py
@@ -0,0 +1,152 @@
+"""Small durable index for managed connections and platform delivery history."""
+
+import json
+import os
+import sqlite3
+from pathlib import Path
+
+
+class StudioStore:
+ def __init__(self, path: Path):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o600)
+ os.close(fd)
+ self.db = sqlite3.connect(path)
+ os.chmod(path, 0o600)
+ self.db.row_factory = sqlite3.Row
+ self.db.executescript("""
+ CREATE TABLE IF NOT EXISTS onboarding (
+ id TEXT PRIMARY KEY, account TEXT NOT NULL, value TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS connections (
+ id TEXT PRIMARY KEY, account TEXT NOT NULL, value TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT, connection_id TEXT NOT NULL,
+ conversation TEXT NOT NULL, event_id TEXT NOT NULL, value TEXT NOT NULL,
+ UNIQUE(connection_id, event_id));
+ """)
+
+ def connections(self, account: str | None = None):
+ rows = self.db.execute(
+ "SELECT value FROM connections" + (" WHERE account=?" if account else ""),
+ (account,) if account else (),
+ )
+ return [json.loads(row[0]) for row in rows]
+
+ def save(self, record: dict):
+ with self.db:
+ self.db.execute(
+ "INSERT OR REPLACE INTO connections VALUES (?, ?, ?)",
+ (record["id"], record["account"], json.dumps(record)),
+ )
+
+ def delete_connection(self, record):
+ with self.db:
+ self.db.execute("DELETE FROM messages WHERE connection_id=?", (record["id"],))
+ for run in self.onboarding_runs(record["account"]):
+ if run.get("connection_id") == record["id"]:
+ self.db.execute("DELETE FROM onboarding WHERE id=?", (run["id"],))
+ self.db.execute(
+ "DELETE FROM connections WHERE id=? AND account=?",
+ (record["id"], record["account"]),
+ )
+
+ def append(self, connection: str, conversation: str, event_id: str, value: dict):
+ with self.db:
+ cursor = self.db.execute(
+ "INSERT OR IGNORE INTO messages(connection_id, conversation, event_id, value) "
+ "VALUES (?, ?, ?, ?)",
+ (connection, conversation, event_id, json.dumps(value)),
+ )
+
+ return cursor.rowcount == 1
+
+ def history(self, connection: str, conversation: str = "", before: int = 0):
+ query = "SELECT id, conversation, value FROM messages WHERE connection_id=?"
+ args: list = [connection]
+ if conversation:
+ query += " AND conversation=?"
+ args.append(conversation)
+ if before:
+ query += " AND id<?"
+ args.append(before)
+ rows = self.db.execute(query + " ORDER BY id DESC LIMIT 101", args).fetchall()
+ return [
+ dict(json.loads(row["value"]), id=row["id"], conversation=row["conversation"])
+ for row in rows
+ ]
+
+ def update_sender(self, connection, message_id, name):
+ with self.db:
+ self.db.execute(
+ "UPDATE messages SET value=json_set(value, '$.sender', ?) "
+ "WHERE connection_id=? AND id=?",
+ (name, connection, message_id),
+ )
+
+ def conversations(self, connection: str):
+ rows = self.db.execute(
+ "SELECT conversation, MAX(id) AS latest FROM messages WHERE connection_id=? "
+ "GROUP BY conversation ORDER BY latest DESC LIMIT 200",
+ (connection,),
+ ).fetchall()
+ result = []
+ for row in rows:
+ first = self.db.execute(
+ "SELECT value FROM messages WHERE connection_id=? AND conversation=? "
+ "ORDER BY id LIMIT 1",
+ (connection, row["conversation"]),
+ ).fetchone()
+ last = self.db.execute(
+ "SELECT value FROM messages WHERE id=?", (row["latest"],)
+ ).fetchone()
+ message = json.loads(last[0])
+ user = self.db.execute(
+ "SELECT value FROM messages WHERE connection_id=? AND conversation=? "
+ "AND json_extract(value, '$.role')='user' "
+ "AND TRIM(COALESCE(json_extract(value, '$.content'), '')) != '' "
+ "ORDER BY id LIMIT 1",
+ (connection, row["conversation"]),
+ ).fetchone()
+ first_message = json.loads(user[0] if user else first[0])
+ title = " ".join(
+ str(first_message.get("topic_title") or first_message.get("content", "")).split()
+ )[:60]
+ named = self.db.execute(
+ "SELECT value FROM messages WHERE connection_id=? AND conversation=? "
+ "AND json_extract(value, '$.chat_type')='group' "
+ "AND TRIM(COALESCE(json_extract(value, '$.title'), '')) != '' "
+ "ORDER BY id DESC LIMIT 1",
+ (connection, row["conversation"]),
+ ).fetchone()
+ group_name = ""
+ if named:
+ source = json.loads(named[0])
+ group_name = source.get("group_name") or source["title"]
+ if not source.get("group_name") and "#" in row["conversation"]:
+ group_name = group_name.removesuffix(" / " + source.get("content", "")[:40])
+ result.append(
+ dict(row)
+ | {
+ "title": title,
+ "group_name": group_name,
+ "preview": str(message.get("content", ""))[:160],
+ "time": message.get("time", ""),
+ }
+ )
+ return result
+
+ def onboarding_runs(self, account=None):
+ rows = self.db.execute(
+ "SELECT value FROM onboarding"
+ + (" WHERE account=?" if account else "")
+ + " ORDER BY rowid",
+ (account,) if account else (),
+ )
+ return [json.loads(row[0]) for row in rows]
+
+ def save_onboarding(self, run):
+ with self.db:
+ self.db.execute(
+ "INSERT INTO onboarding VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET value=excluded.value",
+ (run["id"], run["account"], json.dumps(run)),
+ )
diff --git a/docs/design/web-studio-vikingbot.md b/docs/design/web-studio-vikingbot.md
new file mode 100644
index 000000000..c3d2c81f0
--- /dev/null
+++ b/docs/design/web-studio-vikingbot.md
@@ -0,0 +1,304 @@
+# Web Studio VikingBot 产品与实现方案
+
+状态:设计与首期实现说明。首期支持网页对话与飞书接入,其他 IM 在 Studio 中标注“开发中”。
+
+## 当前分支实现说明
+
+- 页面入口 `/vikingbot`;新增管理接口集中在 `/api/v1/admin`,网页聊天继续复用原有接口。
+- 飞书连接和收发时间线持久化到 Bot 数据目录的 `studio.sqlite3`,文件权限 0600。它含应用与专用用户凭证,备份需按服务端配置处理。
+- Studio 管理的飞书会话仅开放带绑定身份的 OpenViking 查询与记忆工具;Shell、本地文件、定时任务及未显式批准的 MCP 工具默认不可用。
+- 首期仅服务管理员可管理渠道;按当前 account 隔离连接及飞书历史。接入时选择同账户普通用户,由服务端绑定现有凭证;浏览器无需接收或输入用户 API Key。管理员身份不可选,仅存储哈希而无法自动绑定凭证的用户显示不可用。
+- 受管启动时自动为父子进程生成内部管理令牌,不写回配置文件。独立 Gateway 需要额外的管理部署支持。
+- 默认使用三步扫码接入:选择运行用户 → 飞书扫码自动建应用、配权限事件并提交发布 → 添加到群验证。保留单表单手动配置作为已有应用和故障恢复入口。支持凭证更新、暂停/恢复、重启恢复连接、群内短期验证码与独立收发验证。
+- 飞书时间线展示 Studio 连接建立后捕获的消息,不自动接管原 ov.conf 渠道或补录它们的旧历史。既有渠道的迁移需要后续显式绑定与身份确认。
+- 支持暂停连接并保留历史,也支持确认后删除连接及其本地收发记录。删除不会删除飞书应用或飞书中的消息。飞书会话首期只读。
+- 受管 Agent 会话以连接 ID 隔离;删除重建后不继承旧连接上下文,也不发送旧连接未完成的回复。同一连接暂停恢复或重启后仍可续接。此前未按连接隔离的 Agent 历史不自动迁移,Studio 已捕获的只读消息记录不受影响。
+- 自动化和模拟接口浏览器验证不等同真实飞书群验收;真实收发仍需部署后使用应用凭证与测试群验证。
+
+
+## 接口范围与复用依据
+
+路由遵循仓库管理接口约定:`/api/v1/admin` 为管理前缀,账号在 URL 中指定,router 自身声明 prefix/tags,并由 `routers/__init__.py` 导出、`app.py` 统一挂载。业务管理仍仅允许 ROOT,不能因挂入 admin 前缀而放宽为账号 ADMIN。
+
+以下表格用 `B` 代表 `/api/v1/admin/accounts/{account_id}/bot`:
+
+| HTTP 路由 | 调用场景与契约 |
+| --- | --- |
+| `GET /api/v1/admin/bot/capabilities` | 判断 Bot 启用及 ROOT 管理能力;与运行健康检查职责不同。 |
+| `GET /api/v1/admin/accounts/{account_id}/users?role=user&include_credentials=false` | **复用现有接口**。返回 `user_id`、`role`、`api_key_available`,不返回密钥或前缀。默认参数保持原有接口行为。 |
+| `GET B/connections` | 渠道列表、混合会话来源、扫码完成后加载连接。 |
+| `POST B/connections` | 手动连接;请求包含 `type`、`user_id`、平台自有的 `credentials` 对象。 |
+| `PATCH B/connections/{id}` | 更新 `enabled`;提交 `revision` 保留并发保护。 |
+| `DELETE B/connections/{id}?revision=N` | 删除连接及其本地记录;不删除外部平台应用。 |
+| `POST B/connections/{id}/credentials` | 更新平台凭证,包含 `credentials`、`user_id`、`revision`;服务端重新绑定身份。 |
+| `POST B/connections/{id}/verifications` | 发起可选群验证,提交 `revision`。 |
+| `GET B/connections/{id}/conversations` | 连接下的收发会话列表。 |
+| `GET B/connections/{id}/messages?conversation=...&before=...` | 捕获消息及发送状态;平台会话标识保留在查询参数中。 |
+| `POST B/onboarding-runs` | 创建自动接入任务,显式传 `type`、`user_id`、`request_id` 和可选 `name`。 |
+| `GET B/onboarding-runs/current?type=...` | 查询指定平台当前未完成任务;没有任务时返回 null。不是全量任务列表。 |
+| `GET B/onboarding-runs/{id}` | 轮询指定任务。 |
+| `POST B/onboarding-runs/{id}/actions` | 请求体 `action` 严格限定为 `retry`、`cancel`、`manual`,保留各操作的状态校验。 |
+
+浏览器管理接口共 13 个,加上复用的用户列表接口。扫码任务的重试、取消和转手动共用一个 actions 接口,连接生命周期保持独立方法。Studio 管理路由及 Gateway 内部 dispatch 均不进入 OpenAPI schema;接口仍正常注册并保留原鉴权。旧的 `PATCH {action: ...}` 和 `X-OpenViking-Studio-Account` 已移除。该变更调整当前未发布 PR 内的接口,前后端需一起更新;不为旧的临时浏览器接口保留兼容入口。
+
+网页会话创建、列表、历史、删除、Bot 聊天流式响应和健康状态继续复用既有 API。平台收发记录按连接归属并保存发送状态,不能直接替换为 OpenViking 上下文会话历史。
+
+`POST /bot/v1/studio/dispatch` 仅在 Bot Gateway 内部保留,用内部令牌及 loopback 限制服务端调用。浏览器不直接调用;账号和绑定用户仍在 OpenViking 服务端校验。
+
+### 后续接入钉钉等平台
+
+- URL 按连接和接入任务组织,不含飞书或钉钉名称。平台由显式 `type` 决定;未知平台由 provider registry 拒绝,不能默认为飞书。
+- 平台凭证放入 `credentials` 对象,例如飞书使用 `app_id/app_secret`,后续平台可以使用自己的字段。具体校验、连接运行、凭证更新及公开配置字段由 provider 负责;浏览器不能借凭证字段替换服务端身份。
+- 暂停、恢复、删除、收发记录和任务查询共享资源接口。各平台的授权实现与前端表单放入 provider 目录;平台特有能力不应直接加入全局路径或假设所有平台支持扫码/群验证。
+- 当前仍只注册飞书 provider。新增钉钉需要实现它的鉴权、连接、消息转换和 UI,并验证其接入状态流;通用路由不是钉钉功能已完成的证明。
+
+未使用的定时任务接口及 UI、旧独立飞书会话列表、旧 `step` 操作已删除,既有 CLI/Agent 定时任务功能不受影响。
+
+## 1. 用户目标与首期范围
+
+用户可以在 Web Studio 中直接与 VikingBot 对话、查阅历史,并通过完整引导将同一个 Bot 接入飞书群。网页和各个群的对话上下文独立;共用 Bot 不代表共享所有会话或个人记忆。
+
+首期交付:
+
+- 一级导航新增 **VikingBot**,包含“对话”和“渠道”两个页面。
+- 网页新建对话、流式回复、停止生成、继续历史对话。
+- 查看有权限访问的网页、飞书单聊、普通群、话题群历史。
+- 飞书接入向导、连接检查、群内验证、暂停和恢复连接。
+- Slack、钉钉、Discord、Telegram 等展示“开发中”,无配置表单、无可点击的接入按钮。文案说明“Studio 接入管理开发中”,避免误称底层完全不支持。
+
+首期不提供从 Studio 代发群消息、导入机器人入群前的飞书历史、跨群共享上下文。网页聊天不依赖飞书配置完成。
+
+## 2. 页面结构
+
+```text
+VikingBot Bot 运行正常
+ 对话 | 渠道
+
+对话页
+┌──────────────────┬──────────────────────────────────┐
+│ 新建对话 │ 项目讨论群 · 飞书 │
+│ 搜索对话 │ 机器人收到的消息与回复 │
+│ 全部 / 网页 / 飞书 │ 姓名、时间、正文、发送状态 │
+│ │ │
+│ 今天 │ 工具调用默认折叠 │
+│ 需求分析 · 网页 │ │
+│ 项目讨论群 · 飞书 │ 此会话来自飞书,请前往飞书继续对话 │
+└──────────────────┴──────────────────────────────────┘
+```
+
+“对话”默认选中最近一次打开且仍有权限的会话,否则显示欢迎页。窄屏先显示列表,选择后进入详情,提供返回列表操作。
+
+列表显示标题、来源、最后消息摘要和时间;飞书话题显示“群名 / 话题摘要”。不向普通用户暴露群 ID、消息 ID 或内部 SessionKey。名称暂不可用时显示“飞书群聊(名称待同步)”,技术 ID 仅在管理员诊断详情中展示。
+
+“渠道”页包含网页渠道、已连接的飞书应用、添加飞书应用按钮,以及其他 IM 的开发中卡片。一个应用可以服务多个群;应用连接和群会话分别展示,不把一个群建成一个渠道。
+
+## 3. 首次启用与网页对话
+
+### 3.1 进入页面
+
+页面分别检测 Bot 服务、模型配置和当前身份权限:
+
+| 状态 | 页面文案与操作 |
+|---|---|
+| Bot 未启用 | “先启用 VikingBot”;管理员看到 `openviking-server --with-bot` 与部署说明,普通用户看到“请联系管理员启用” |
+| 服务不可达 | “暂时无法连接 VikingBot”;显示重试与管理员诊断入口,不清除已有历史 |
+| 模型未配置 | “配置对话模型后即可开始”;链接现有模型配置说明,说明默认继承根级 `vlm` |
+| 可以使用 | “开始与 VikingBot 对话”;主按钮“新建对话”,次按钮“连接飞书” |
+
+读取配置只代表模型已配置,不代表调用成功。首次正常对话成功后记录模型可用;模型调用失败保留输入并提供重试。
+
+### 3.2 开始与继续对话
+
+1. 点击“新建对话”,输入问题。
+2. 首次发送时建立持久会话;提交接受前保留输入、阻止重复发送。
+3. 流式展示回答,工具调用折叠展示,支持停止生成。
+4. 左侧立即出现新会话,标题取首条问题,可重命名。
+5. 刷新、重新登录或服务重启后,可重新打开历史继续对话。
+
+切换会话、取消或卸载页面时,旧请求不能覆盖新会话内容。停止浏览器流不自动表示服务端任务已取消;产品只有在服务端确认取消后才显示“已停止”,否则显示“已停止接收,任务可能仍在运行”。
+
+## 4. 飞书接入流程
+
+### 默认:扫码自动配置
+
+1. 选择当前账户的普通用户,填写机器人名称(默认 VikingBot),点击生成二维码。页面事先说明将创建应用及申请的权限。
+2. 用飞书扫码并在手机确认。服务端用该次登录会话创建应用、开启机器人和长连接,申请 `im:message.group_at_msg:readonly`、`im:message:send_as_bot`、`im:chat:readonly`,订阅 `im.message.receive_v1`,创建并提交首个版本。
+3. 读取版本状态:已上线后展示加群指引;审核中则等待管理员审批。添加到群后生成测试消息,分别确认收到消息、飞书接受回复以及用户在群内看到回复。
+
+初始应用可用范围仅包含扫码创建者。扩大群成员可用范围需要在开放平台调整并发布。
+
+扫码登录参考 Botmux 的 Web 会话路径,使用飞书开放平台控制台接口,不是第三方 OAuth 安装接口。平台契约集中在飞书适配器,变更时可回退手动接入。不会使用开发机已有 Botmux 或浏览器登录凭证。
+
+任务和创建/发布检查点保存在 SQLite;Cookie、二维码 token 和 flow key 仅存在服务端任务内存中。二维码两分钟过期,等待审批最长保留会话十分钟。超时、服务重启后重新扫码,必须匹配原账号和企业。创建、创建版本与发布请求不自动重放;结果未知时引导检查开放平台。页面刷新恢复原任务,不重复创建应用。
+
+### 备用:已有应用或手动恢复
+
+以下六步仅用于手动接入。
+
+
+入口:“渠道 → 添加飞书应用”。采用独立页面式向导,左侧步骤,右侧操作与说明。每步可返回;退出后保留服务端草稿并支持“继续配置”。密钥不写入浏览器本地存储。
+
+首次说明:“将 VikingBot 加入飞书群,在群里 @机器人即可对话。你需要飞书企业自建应用的管理权限,以及目标群添加机器人的权限。”首期引导面向企业内部群,外部群不承诺支持。
+
+### 第一步:创建应用
+
+1. 点击“打开飞书开放平台”:https://open.feishu.cn/app 。
+2. 创建企业自建应用,设置名称和头像。
+3. 在应用能力中添加“机器人”。
+4. 返回 Studio,点击“下一步:连接应用”。
+
+说明这是支持接收消息的应用机器人;仅有群 Webhook 地址不能完成此流程。
+
+### 第二步:连接应用
+
+填写 App ID 与 App Secret,提供“在哪里找到?”说明:进入应用的“凭证与基础信息”。Secret 默认隐藏,保存后仅显示“已配置”,支持替换。
+
+点击“验证并建立连接”:服务端验证凭证,尝试获取机器人名称和身份,保存草稿并启动长连接。成功后展示机器人名称及头像;无法自动获取时说明缺失条件,名称允许补填,但不能用名称匹配替代可靠的机器人身份识别。
+
+状态依次展示“验证凭证 → 建立长连接”。凭证通过但连接失败时分别显示结果。SDK 初始化成功不算连接成功,需要实际连接证据。
+
+建立长连接后再引导配置事件,避免用户在飞书选择长连接时因为服务尚未启动而无法继续。
+
+### 第三步:配置权限与事件
+
+提供逐条可复制的权限/事件说明及官方链接,默认只配置“群内 @机器人回复”所需能力:接收群 @消息、以机器人身份发送消息;启用单聊时增加接收单聊消息能力。群名称、成员名称、图片相关权限按使用功能补充。
+
+实现时维护经过官方核验的权限清单及批量导入内容,不能直接把旧文档中的笼统 `im:message` 当成完整权限模板。平台权限标识与展示名称应同时列出。
+
+事件订阅选择“使用长连接接收事件”,添加 `im.message.receive_v1`。首期不要求填写公网回调 URL、Encrypt Key 或 Verification Token。
+
+提供“检查配置”按钮。可由 API 检测的项目显示结果;无法读取的订阅/发布状态显示“待群内验证”,用户勾选只表示已完成操作,不显示自动检测通过。
+
+### 第四步:发布应用
+
+引导前往“版本管理与发布”,创建版本,设置适当的可用范围并提交发布。需审批时显示“等待管理员审批”,允许保存退出。权限或事件调整后,提示检查是否需要重新发布。
+
+“我已发布,继续”进入下一步,但不改变技术验证结果。
+
+### 第五步:添加到群并验证
+
+1. 在飞书打开目标群,通过群设置中的机器人入口添加刚创建的应用机器人。
+2. Studio 生成一条带短期随机验证码的测试消息,例如 `@VikingBot 连接测试 7K2P`,提供复制按钮;提示在飞书使用真正的 @ 选择机器人,复制的纯文本不等于 mention。
+3. 用户在目标群发送测试消息,Studio 等待该应用收到匹配验证码的事件。
+4. Bot 返回固定测试确认,不调用模型、不执行工具、不写入长期记忆。随后更新验证状态。
+
+验证拆成三项:“收到群消息”“回复已被飞书接受”“群内可见”。前两项使用入站事件与发送 API 回执验证,最后一项由用户确认或后续已验证的平台能力确认。发送 API 成功不声称消息已读。
+
+只把当前草稿应用、有效期内、匹配验证码的事件绑定为本次验证;重复事件不重复建群、不重复回复。超时后可生成新验证码重试。
+
+完成页显示群名、机器人名、“仅 @时回复”,操作为“查看该群会话”“再连接一个群”“完成”。增加其他群复用当前应用,从本步骤开始。
+
+未收到消息时提供按顺序排查:应用是否已发布且可用范围正确、机器人是否已入群、是否使用真正的 @、事件与权限是否生效、长连接是否正常。收到消息但发不出去时,定位发送权限、机器人是否仍在群中及飞书返回错误。
+
+### 第六步:正常使用
+
+提示用户在群里 @机器人提出一个真实问题。该步骤验证模型对话链路;固定测试通过但模型失败时显示“飞书已接通,对话模型调用失败”,不要求用户重做渠道配置。
+
+## 5. 飞书历史与日常管理
+
+飞书历史展示 VikingBot 实际收到、持久化的消息以及自身回复。首次显示提示:“仅展示机器人接入后收到的消息,不包含完整群历史。”未授权接收的非 @消息不会凭空出现在列表里。
+
+普通群按群组织,话题群按话题组织。飞书单聊独立展示。消息包含发送人、时间、正文及已支持的附件;不支持的消息类型显示明确占位,不丢弃整条记录。生成失败、发送失败和发送成功分开标识。
+
+飞书会话详情首期只读,底部固定提示“请前往飞书继续对话”。有可靠平台链接时提供“在飞书打开”;没有时展示群名和操作说明,不拼造跳转链接。
+
+应用详情展示:连接状态、最近收消息时间、最近成功回复时间、最近错误、已发现的群、接入向导进度。明确“已发现的群”为收到过消息的群,不声称枚举了全部已加入群。
+
+支持更新凭证、重新检测、暂停与恢复;暂停停止接收新任务,已有任务按明确的排空策略结束,保留历史。删除连接需要二次确认,并说明不会自动删除飞书应用或历史。凭证更新失败保留原连接,不能破坏其他渠道。
+
+首期固定推荐“仅 @机器人时回复”。不开放“所有群消息自动回复”,避免额外权限、消息量和话题规则使首次引导复杂化。
+
+## 6. 身份、权限和上下文
+
+- 渠道配置及密钥修改仅管理员可用;服务端逐接口鉴权,不能仅隐藏按钮。
+- 首期群历史仅对该连接所属管理范围内的管理员开放。普通 Studio 用户只查看自己的网页会话;后续另行实现飞书成员身份绑定与按群授权。
+- 外部应用必须绑定明确的 OpenViking account/workspace 与运行身份;无绑定或无权限时拒绝启用,不回退 root 身份。
+- 群会话不得继承管理员私人网页会话或个人记忆。群可访问资源与记忆范围使用受限的渠道身份配置。
+- 列表、搜索、详情、附件、流事件均使用同一服务端权限过滤;禁止先全量返回再由前端过滤。
+- 群历史中的文字只是消息内容,不作为 Studio 管理指令执行。
+
+## 7. 当前可复用能力与需要补齐的能力
+
+基于当前仓库代码核对:
+
+| 能力 | 现状 | 实现工作 |
+|---|---|---|
+| 网页聊天 | Studio 已有 `useChat`、Composer、MessageList,Server 代理 Bot 流式接口 | 复用组件与请求生命周期,增加独立入口 |
+| 网页历史 | Studio 当前读取 OpenViking Session 与归档 | 复用持久历史,避免另建重复会话 |
+| Bot 历史 | Bot SessionManager 持久化并可列举;OpenAPI `/sessions` 使用运行时内存索引 | 新增持久化的统一会话索引和权限过滤 |
+| 飞书群 | 已有长连接、普通群与话题群处理 | 增加向导、配置 API、身份检测、验证回执 |
+| @识别 | 当前基于 `bot_name` 匹配 mention 名称 | 改为机器人稳定身份匹配,兼容已配置名称 |
+| 渠道生命周期 | 配置加载与启动已有;文档要求修改配置后重启 | 新增单渠道受控应用配置、替换、暂停、恢复与回滚 |
+| 运行状态 | `_running` 与启动日志不能证明连接和消息收发正常 | 增加实际连接、入站、出站的独立状态与时间戳 |
+
+## 8. 建议接口与数据契约
+
+以下均为拟新增能力,不代表现有 API 已提供。Studio 统一访问 OpenViking Server,由 Server 进行鉴权并调用受管 Bot。
+
+| 接口 | 用途 |
+|---|---|
+| `GET /bot/v1/capabilities` | 当前用户权限、Bot 状态、支持的渠道与管理能力 |
+| `GET /bot/v1/conversations` | 按来源、关键词及游标列出有权限的持久会话 |
+| `GET /bot/v1/conversations/{id}/messages` | 分页读取统一时间线 |
+| 当前管理接口 | 以本文“接口范围与复用依据”的表格为准;不存在独立的 validate/apply/status HTTP 接口。 |
+
+网页发送继续复用现有 chat/stream 接口;统一 conversation ID 必须能映射到原 Session ID。飞书会话不提供网页发送接口。
+
+Conversation 索引保存:权限作用域、来源、连接、原始会话引用、群/话题显示信息、最近活动时间。原始身份标识仅服务端保存。历史正文沿用现有存储,索引不复制两份消息;同一 Bot 会话关联的 OpenViking 会话必须去重映射。
+
+历史消息区分 generated、send_failed、sent 等状态;不能把模型输出视为已发送。旧历史缺少发送证据时标注“发送状态未知”。已有会话迁移时不能推测拥有者;无法确定权限归属的记录暂不对普通用户开放。
+
+连接使用 draft、connecting、connected、degraded、paused、error 等运行状态;配置验证、群内测试另设独立结果。刷新页面和服务重启不丢失引导步骤,但运行状态须重新探测。
+
+首期管理能力限定为 Server 受管 Bot。外置 Gateway 未实现管理协议时显示“当前部署暂不支持在 Studio 配置渠道”,仍可使用已授权的网页聊天,并提供配置文件说明;不显示注定失败的表单。
+
+密钥只在写请求中提交,响应、日志及诊断导出均不回显。沿用服务端配置位置,采用严格文件权限、原子写入与版本校验,保留不相关配置。只读配置部署返回明确原因与管理员操作指引。
+
+## 9. 实施顺序与验收
+
+第一阶段:独立入口和网页闭环。复用聊天组件、完成可持久的会话索引与身份契约。验证首条发送失败可恢复、切换无串话、重启后历史可读、多身份隔离。
+
+第二阶段:飞书向导和连接管理。完成配置草稿、凭证校验、单渠道应用、身份匹配、真实连接状态、群内验证码收发。验证错误密钥、未发布、未订阅、断网、重复事件、配置失败回滚与刷新续接。
+
+第三阶段:飞书历史与完整验收。展示群名、成员名、话题、附件占位、回复结果;新增其他 IM 开发中卡片。通过真实飞书群完成一次正常 @问答,核对 Studio 历史和平台回复一致。
+
+首期发布必须同时满足:
+
+1. 新用户能从服务未启用状态沿引导走到一次网页成功对话。
+2. 管理员可从零完成飞书应用连接、发布、入群和真实问答;中断后可继续。
+3. 改名后的机器人仍可正确识别 @;普通群与不同话题不串上下文。
+4. 页面重载及 Bot 重启后历史和配置仍可恢复;无内存索引依赖导致的历史消失。
+5. 群消息发送失败不会显示成功;凭证正确不会直接显示“接入完成”。
+6. 无权限用户无法通过接口枚举群历史或读取密钥;群问答无法读取管理员私人记忆。
+7. 其他渠道清楚显示“Studio 接入管理开发中”,不提供虚假可用入口。
+
+## 10. 依据
+
+- 仓库:`web-studio/src/lib/sessions/api.ts`、`web-studio/src/routes/playground/-components/agent-panel.tsx`。
+- 仓库:`bot/vikingbot/channels/openapi.py`、`bot/vikingbot/session/manager.py`、`openviking/server/routers/bot.py`。
+- 仓库:`bot/vikingbot/channels/feishu.py`、`bot/vikingbot/channels/manager.py`、`bot/vikingbot/config/schema.py`、`bot/docs/zh/concepts/05-channel.md`。
+- [飞书开放平台:事件订阅方式](https://open.feishu.cn/document/server-docs/event-subscription-guide/event-subscription-configure-/request-url-configuration-case)与[接收消息事件](https://open.feishu.cn/document/server-docs/im-v1/message/events/receive):实现时核对最新权限与事件要求;本次抓取页面未返回正文,不据此宣称精确权限模板已验证。
+- [飞书官方:配置机器人能力与发布应用](https://www.feishu.cn/content/425524486655):用于机器人能力和发布步骤参考。
+
+
+## 多 IM 目录边界
+
+- `bot/vikingbot/studio/service.py`:账号隔离、持久化、版本冲突和连接生命周期。
+- `bot/vikingbot/studio/providers/registry.py`:按连接 `type` 选择平台适配器;旧记录默认飞书,未知类型拒绝接入。
+- `bot/vikingbot/studio/providers/feishu/`:凭证校验、引导动作、消息接收和长连接协议。扫码会话、控制台协议和自动配置也集中在此目录。
+- `web-studio/src/routes/vikingbot/-providers/registry.ts`:注册各平台的引导和凭证组件。
+- `web-studio/src/routes/vikingbot/-providers/feishu/`:飞书专属界面和测试。
+- 公共会话、历史记录和渠道列表保留在 `-components/`。
+
+新增 Slack 等平台时,新增对应 provider 目录并注册,复用连接生命周期和历史存储。平台特有权限、扫码或 OAuth 状态不进入公共服务。当前仅飞书可接入,其他平台保持“开发中”。扫码初始化已通过真实飞书接口验证;登录后建应用、审批和群收发仍需真实账号验收。
+
+
+### 扫码任务与回复配置
+
+浏览器使用 `/api/v1/admin/accounts/{account_id}/bot` 下的 `onboarding-runs` 创建任务,`onboarding-runs/current?type=feishu` 恢复任务,`onboarding-runs/{id}` 查询状态,以及 `POST onboarding-runs/{id}/actions`(`action` 为 `retry`、`cancel`、`manual`)。所有接口复用 root 管理认证和 account 隔离;返回状态白名单不含凭证、Cookie 或原始上游错误。
+
+扫码和手动创建均提供“群聊回复方式”,通过已有创建接口的 `settings.thread_require_mention` 保存,默认为 `true`。已创建连接通过已有 `PATCH connections/{id}` 提交 `settings` 和 `revision` 修改;一次请求只能修改 `enabled` 或 `settings` 之一。设置立即更新运行中的渠道,并持久化供重启或恢复时加载,旧记录保持原默认行为。
+
+关闭该设置后,普通群消息无需 @;话题首条消息无需 @,后续话题回复仍需 @(DEBUG 模式例外),私聊不受影响。扫码创建按选项申请 `im:message.group_msg` 权限;手动接入或创建后切换时,用户需在飞书开放平台补充接收未 @ 群消息的权限并发布应用。保存本地设置不代表飞书权限已生效。
+
+`settings` 由对应平台 provider 校验和应用,飞书仅接受布尔型 `thread_require_mention`。未来钉钉等平台可扩展自己的设置而无需增加平台专属路由。
diff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.md
index f333f3939..b5de72d82 100644
--- a/docs/en/api/08-admin.md
+++ b/docs/en/api/08-admin.md
@@ -976,6 +976,7 @@ List active users in a workspace. Users with deletion in progress are omitted.
| account_id | str | Yes | - | Workspace ID |
| name | str | No | null | Filter by user ID (wildcard `*` and `?` matching) |
| role | str | No | null | Filter by role |
+| include_credentials | bool | No | true | HTTP-only. Set false to return `user_id`, `role`, and `api_key_available` without credentials or key prefixes. The default preserves the existing mode-dependent response. |
| limit | int | No | null | Page size (≥1). Omit to return all matches |
| page | int | No | 1 | 1-based page number; only applies when `limit` is set |
diff --git a/docs/scripts/check-api-reference.mjs b/docs/scripts/check-api-reference.mjs
index 29f20b7c3..6a1a4432e 100644
--- a/docs/scripts/check-api-reference.mjs
+++ b/docs/scripts/check-api-reference.mjs
@@ -75,7 +75,14 @@ function splitTopLevel(source) {
const routes = new Map()
const middlewareQueryParameters = new Set(['profile'])
-const internalRouterFiles = new Set(['console.py', 'debug.py', 'stats.py', 'user_settings.py'])
+// Studio management routes are internal UI APIs, not part of the public HTTP reference.
+const internalRouterFiles = new Set([
+ 'bot_studio.py',
+ 'console.py',
+ 'debug.py',
+ 'stats.py',
+ 'user_settings.py',
+])
for (const file of fs.readdirSync(routerDir).filter((name) => name.endsWith('.py'))) {
if (internalRouterFiles.has(file)) continue
const source = fs.readFileSync(path.join(routerDir, file), 'utf8')
diff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.md
index 04208cb26..e34e58103 100644
--- a/docs/zh/api/08-admin.md
+++ b/docs/zh/api/08-admin.md
@@ -920,6 +920,7 @@ ov admin register-user acme bob-private --role user \
| account_id | str | 是 | - | 工作区 ID |
| name | str | 否 | null | 按用户 ID 过滤(通配符 `*` 和 `?` 匹配) |
| role | str | 否 | null | 按角色过滤 |
+| include_credentials | bool | 否 | true | 仅 HTTP。设为 false 时仅返回 `user_id`、`role` 和 `api_key_available`,不返回密钥或前缀;默认保持现有按鉴权模式返回字段的行为。 |
| limit | int | 否 | null | 每页数量(≥1)。省略则返回所有匹配项 |
| page | int | 否 | 1 | 从 1 开始的页码;仅在设置了 `limit` 时生效 |
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 3b422d39f..0acdf0e6b 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -36,6 +36,7 @@ from openviking.server.routers import (
admin_router,
agent_evolution_router,
bot_router,
+ bot_studio_router,
compile_router,
console_router,
content_router,
@@ -667,6 +668,7 @@ def create_app(
app.include_router(watches_router)
app.include_router(webdav_router)
app.include_router(bot_router, prefix="/bot/v1")
+ app.include_router(bot_studio_router)
# OAuth 2.1: when enabled, mount the official MCP SDK auth routes
# (DCR / authorize / token / metadata) plus our authorize page + consent /
diff --git a/openviking/server/bootstrap.py b/openviking/server/bootstrap.py
index 61d16f2e9..6b857a4fa 100644
--- a/openviking/server/bootstrap.py
+++ b/openviking/server/bootstrap.py
@@ -2,8 +2,8 @@
# SPDX-License-Identifier: AGPL-3.0
"""Bootstrap script for OpenViking HTTP Server."""
-import asyncio
import argparse
+import asyncio
import json
import os
import shutil
@@ -276,6 +276,10 @@ def main():
bot_process: Optional[BotProcess] = None
if config.with_bot:
+ import secrets
+
+ # Shared only by this server and its managed child, never returned to Studio.
+ os.environ["OPENVIKING_BOT_STUDIO_TOKEN"] = secrets.token_urlsafe(32)
bot_port = args.bot_port
config.bot_api_url = f"http://{VIKINGBOT_DEFAULT_HOST}:{bot_port}"
_abort_if_port_in_use(bot_port, "vikingbot gateway")
diff --git a/openviking/server/routers/__init__.py b/openviking/server/routers/__init__.py
index 79abd75c4..1c4186d24 100644
--- a/openviking/server/routers/__init__.py
+++ b/openviking/server/routers/__init__.py
@@ -6,6 +6,7 @@ from openviking.server.routers.acl import router as acl_router
from openviking.server.routers.admin import router as admin_router
from openviking.server.routers.agent_evolution import router as agent_evolution_router
from openviking.server.routers.bot import router as bot_router
+from openviking.server.routers.bot_studio import router as bot_studio_router
from openviking.server.routers.compile import router as compile_router
from openviking.server.routers.console import router as console_router
from openviking.server.routers.content import router as content_router
@@ -33,6 +34,7 @@ __all__ = [
"admin_router",
"agent_evolution_router",
"bot_router",
+ "bot_studio_router",
"compile_router",
"system_router",
"resources_router",
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index a29af961e..3ed9444be 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -255,9 +255,7 @@ async def _write_initial_user_config(
await write_user_config(service.viking_fs, user_ctx, user_config)
-async def _check_user_exists(
- request: Request, account_id: str, user_id: str, manager=None
-) -> None:
+async def _check_user_exists(request: Request, account_id: str, user_id: str, manager=None) -> None:
manager = manager or _get_api_key_manager(request)
if not manager.has_user(account_id, user_id):
raise NotFoundError(user_id, "user")
@@ -617,6 +615,10 @@ async def list_users(
request: Request,
account_id: str = Path(..., description="Account ID"),
limit: int | None = Query(None, ge=1, description="Page size; omit to return all"),
+ include_credentials: bool = Query(
+ True,
+ description="Include credentials when permitted; false returns only credential availability",
+ ),
name: str | None = None,
role: str | None = None,
page: int = Query(1, ge=1, description="1-based page number (requires limit)"),
@@ -637,10 +639,19 @@ async def list_users(
limit=limit,
name_filter=name,
role_filter=role,
- expose_key=expose_key,
+ expose_key=expose_key or not include_credentials,
page=page,
query_filter=query,
)
+ if not include_credentials:
+ users["users"] = [
+ {
+ "user_id": user["user_id"],
+ "role": user["role"],
+ "api_key_available": bool(user.get("api_key")),
+ }
+ for user in users["users"]
+ ]
return Response(status="ok", result=users if include_summary else users["users"])
@@ -838,9 +849,7 @@ async def add_group_member(
ctx: RequestContext = Depends(get_request_context),
):
_check_account_access(ctx, account_id)
- added = await _get_api_key_manager(request).add_group_member(
- account_id, group_id, user_id
- )
+ added = await _get_api_key_manager(request).add_group_member(account_id, group_id, user_id)
return Response(status="ok", result={"added": added})
@@ -854,7 +863,5 @@ async def remove_group_member(
ctx: RequestContext = Depends(get_request_context),
):
_check_account_access(ctx, account_id)
- removed = await _get_api_key_manager(request).remove_group_member(
- account_id, group_id, user_id
- )
+ removed = await _get_api_key_manager(request).remove_group_member(account_id, group_id, user_id)
return Response(status="ok", result={"removed": removed})
diff --git a/openviking/server/routers/bot_studio.py b/openviking/server/routers/bot_studio.py
new file mode 100644
index 000000000..087baec2e
--- /dev/null
+++ b/openviking/server/routers/bot_studio.py
@@ -0,0 +1,252 @@
+"""Root-managed, account-scoped Studio bot administration."""
+
+import os
+from dataclasses import replace
+from typing import Literal
+
+import httpx
+from fastapi import APIRouter, Depends, HTTPException, Query, Request
+from pydantic import BaseModel, ConfigDict, Field, model_validator
+
+from openviking.server.auth import get_api_key_manager_or_raise, get_request_context
+from openviking.server.config import get_server_url_from_server_data
+from openviking.server.identity import RequestContext, Role
+from openviking.server.routers import bot
+from openviking_cli.session.user_id import UserIdentifier
+
+# Studio's internal UI contract is not part of the public OpenAPI schema.
+router = APIRouter(prefix="/api/v1/admin", tags=["admin"], include_in_schema=False)
+ACCOUNT_BOT = "/accounts/{account_id}/bot"
+
+
+class RevisionRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ revision: int = Field(ge=1)
+
+
+class UpdateConnectionRequest(RevisionRequest):
+ enabled: bool | None = None
+ settings: dict | None = None
+
+ @model_validator(mode="after")
+ def one_change(self):
+ if (self.enabled is None) == (self.settings is None):
+ raise ValueError("Provide either enabled or settings")
+ return self
+
+
+class CredentialsRequest(RevisionRequest):
+ credentials: dict[str, str]
+ user_id: str
+
+
+class CreateConnectionRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ type: str
+ user_id: str
+ credentials: dict[str, str]
+ settings: dict = Field(default_factory=dict)
+
+
+class OnboardingActionRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ action: Literal["retry", "cancel", "manual"]
+
+
+class StartOnboardingRequest(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ type: str
+ user_id: str
+ name: str = "VikingBot"
+ request_id: str
+ settings: dict = Field(default_factory=dict)
+
+
+async def manager(
+ account_id: str,
+ ctx: RequestContext = Depends(get_request_context),
+):
+ # App installations are process-wide. Account admins cannot mutate host credentials.
+ if ctx.role != Role.ROOT:
+ raise HTTPException(403, "Only the server administrator can manage Bot connections")
+ try:
+ return replace(ctx, user=UserIdentifier(account_id, ctx.user.user_id))
+ except ValueError as exc:
+ raise HTTPException(400, "Invalid account ID") from exc
+
+
+async def dispatch(ctx, action, payload=None, connection_id=None, identity=None):
+ token = os.environ.get("OPENVIKING_BOT_STUDIO_TOKEN") or bot.BOT_API_KEY
+ if not token:
+ raise HTTPException(503, "Managed Bot gateway authentication is unavailable")
+ try:
+ async with bot._create_bot_proxy_client() as client:
+ result = await client.post(
+ bot.get_bot_url() + "/bot/v1/studio/dispatch",
+ headers={"X-Gateway-Token": token},
+ timeout=25,
+ json={
+ "account": ctx.account_id,
+ "action": action,
+ "payload": payload or {},
+ "connection_id": connection_id,
+ "identity": identity,
+ },
+ )
+ data = result.json()
+ if result.is_error:
+ raise HTTPException(result.status_code, data.get("detail", "Bot operation failed"))
+ return {"status": "ok", "result": data}
+ except (httpx.HTTPError, ValueError) as exc:
+ raise HTTPException(502, "Cannot reach the managed Bot gateway") from exc
+
+
[email protected]("/bot/capabilities")
+async def capabilities(ctx: RequestContext = Depends(get_request_context)):
+ return {
+ "status": "ok",
+ "result": {
+ "enabled": bot.BOT_API_URL is not None,
+ "can_manage": ctx.role == Role.ROOT
+ and bool(os.environ.get("OPENVIKING_BOT_STUDIO_TOKEN") or bot.BOT_API_KEY),
+ },
+ }
+
+
[email protected](ACCOUNT_BOT + "/connections")
+async def connections(ctx: RequestContext = Depends(manager)):
+ return await dispatch(ctx, "list")
+
+
+async def account_users(request, ctx):
+ registry = get_api_key_manager_or_raise(request)
+ await registry.refresh_account_users_from_store(ctx.account_id)
+ return registry.get_users(ctx.account_id, limit=None, role_filter="user", expose_key=True)
+
+
+async def selected_identity(request, ctx, user_id):
+ rows = await account_users(request, ctx)
+ row = next((row for row in rows if row["user_id"] == user_id), None)
+ if row is None:
+ raise HTTPException(400, "Select an ordinary user in the current account")
+ if not row.get("api_key"):
+ raise HTTPException(409, "This user's credential cannot be bound automatically")
+ return {
+ "account_id": ctx.account_id,
+ "user_id": row["user_id"],
+ "role": "user",
+ "api_key_type": "user",
+ "api_key": row["api_key"],
+ "agent_id": "vikingbot",
+ "server_url": get_server_url_from_server_data(getattr(request.app.state, "config", None)),
+ }
+
+
[email protected](ACCOUNT_BOT + "/connections")
+async def create(
+ request: Request, body: CreateConnectionRequest, ctx: RequestContext = Depends(manager)
+):
+ connection = await selected_identity(request, ctx, body.user_id)
+ return await dispatch(ctx, "create", body.model_dump(), identity=connection)
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}")
+async def update(
+ connection_id: str, body: UpdateConnectionRequest, ctx: RequestContext = Depends(manager)
+):
+ return await dispatch(
+ ctx,
+ "update",
+ {
+ "action": "settings"
+ if body.settings is not None
+ else ("resume" if body.enabled else "pause"),
+ "revision": body.revision,
+ **({"settings": body.settings} if body.settings is not None else {}),
+ },
+ connection_id,
+ )
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}")
+async def delete_connection(
+ connection_id: str,
+ revision: int = Query(..., ge=1),
+ ctx: RequestContext = Depends(manager),
+):
+ return await dispatch(ctx, "update", {"action": "delete", "revision": revision}, connection_id)
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}/credentials")
+async def update_credentials(
+ connection_id: str,
+ body: CredentialsRequest,
+ request: Request,
+ ctx: RequestContext = Depends(manager),
+):
+ identity = await selected_identity(request, ctx, body.user_id)
+ return await dispatch(
+ ctx,
+ "update",
+ {
+ "action": "credentials",
+ "revision": body.revision,
+ "credentials": body.credentials,
+ "identity": identity,
+ },
+ connection_id,
+ )
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}/verifications")
+async def verify_connection(
+ connection_id: str, body: RevisionRequest, ctx: RequestContext = Depends(manager)
+):
+ return await dispatch(
+ ctx,
+ "update",
+ {
+ "action": "verify",
+ "revision": body.revision,
+ },
+ connection_id,
+ )
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}/conversations")
+async def conversations(connection_id: str, ctx: RequestContext = Depends(manager)):
+ return await dispatch(ctx, "conversations", connection_id=connection_id)
+
+
[email protected](ACCOUNT_BOT + "/connections/{connection_id}/messages")
+async def messages(
+ connection_id: str, conversation: str, before: int = 0, ctx: RequestContext = Depends(manager)
+):
+ return await dispatch(
+ ctx, "messages", {"conversation": conversation, "before": before}, connection_id
+ )
+
+
[email protected](ACCOUNT_BOT + "/onboarding-runs")
+async def start_onboarding(
+ request: Request, body: StartOnboardingRequest, ctx: RequestContext = Depends(manager)
+):
+ identity = await selected_identity(request, ctx, body.user_id)
+ return await dispatch(ctx, "onboarding_start", body.model_dump(), identity=identity)
+
+
[email protected](ACCOUNT_BOT + "/onboarding-runs/current")
+async def current_onboarding(type: str, ctx: RequestContext = Depends(manager)):
+ return await dispatch(ctx, "onboarding_current", {"type": type})
+
+
[email protected](ACCOUNT_BOT + "/onboarding-runs/{identifier}")
+async def get_onboarding(identifier: str, ctx: RequestContext = Depends(manager)):
+ return await dispatch(ctx, "onboarding_get", {"id": identifier})
+
+
[email protected](ACCOUNT_BOT + "/onboarding-runs/{identifier}/actions")
+async def update_onboarding(
+ identifier: str, body: OnboardingActionRequest, ctx: RequestContext = Depends(manager)
+):
+ return await dispatch(ctx, "onboarding_update", {"id": identifier, "action": body.action})
diff --git a/pyproject.toml b/pyproject.toml
index caa2f4241..33ee5bcc6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -212,6 +212,7 @@ include = ["openviking*", "vikingbot*"]
exclude = ["tests*", "docs*", "examples*"]
[tool.setuptools.package-data]
+"vikingbot.studio.providers.feishu" = ["icon.png"]
openviking = [
"prompts/templates/**/*.yaml",
"server/static/**/*",
diff --git a/tests/api_test/filesystem/test_fs_cp.py b/tests/api_test/filesystem/test_fs_cp.py
index 48ce879c6..233a51db1 100644
--- a/tests/api_test/filesystem/test_fs_cp.py
+++ b/tests/api_test/filesystem/test_fs_cp.py
@@ -12,7 +12,7 @@ class TestFsCp:
content = f"copy payload {suffix}"
try:
write = api_client.fs_write(source, content, mode="create", wait=True)
- assert write.status_code == 200
+ assert write.status_code == 200, write.text
copied = api_client.fs_cp(source, target)
assert copied.status_code == 200, copied.text
@@ -29,10 +29,22 @@ class TestFsCp:
assert content in read.json().get("result", "")
if os.getenv("HAS_SECRETS", "true").lower() == "true":
- found = api_client.find(query=suffix, target_uri=target, limit=5)
- assert found.status_code == 200
- resources = found.json().get("result", {}).get("resources", [])
- assert any(item.get("uri") == target for item in resources)
+ vectors = result.get("vectors", {})
+ assert vectors.get("scanned", 0) > 0, copied.text
+ assert vectors.get("written") == vectors["scanned"], copied.text
+ # This contract checks index copying, not the embedding model's
+ # similarity score for a random UUID. Filter-only find still
+ # reads the vector store and preserves tenant/access scoping.
+ for uri in (source, target):
+ found = api_client.find(
+ query="",
+ target_uri=uri,
+ filter={"op": "must", "field": "uri", "conds": [uri]},
+ limit=5,
+ )
+ assert found.status_code == 200, found.text
+ resources = found.json().get("result", {}).get("resources", [])
+ assert any(item.get("uri") == uri for item in resources), found.text
assert api_client.fs_rm(source).status_code == 200
assert api_client.fs_read(target).status_code == 200
diff --git a/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py b/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py
index 6c36ca798..d33157eca 100644
--- a/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py
+++ b/tests/api_test/scenarios/resources_retrieval/test_build_error_handling.py
@@ -51,9 +51,10 @@ class TestBuildErrorHandling:
assert (
"resolve" in error_msg
or "hostname" in error_msg
+ or "host does not exist" in error_msg
or "dns" in error_msg
or "error" in error_msg
- ), f"DNS失败错误信息应包含 resolve/hostname/dns/error, 实际: {error_msg}"
+ ), f"DNS失败错误信息应包含 resolve/hostname/host does not exist/dns/error, 实际: {error_msg}"
print("✓ TC-E08 DNS解析失败处理通过(返回error)")
return
diff --git a/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py b/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py
index e9139011b..8836fa5f1 100644
--- a/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py
+++ b/tests/api_test/scenarios/resources_retrieval_slow/test_build_error_handling_slow.py
@@ -295,10 +295,11 @@ class TestBuildErrorHandlingSlow:
assert (
"resolve" in error_msg
or "hostname" in error_msg
+ or "host does not exist" in error_msg
or "dns" in error_msg
or "error" in error_msg
or "connect" in error_msg
- ), f"DNS失败错误信息应包含 resolve/hostname/dns/error/connect, 实际: {error_msg}"
+ ), f"DNS失败错误信息应包含 resolve/hostname/host does not exist/dns/error/connect, 实际: {error_msg}"
print("✓ TC-E08 DNS解析失败处理通过(返回error)")
return
@@ -310,11 +311,12 @@ class TestBuildErrorHandlingSlow:
assert (
"resolve" in inner_msg
or "hostname" in inner_msg
+ or "host does not exist" in inner_msg
or "dns" in inner_msg
or "connect" in inner_msg
or "failed" in inner_msg
or "error" in inner_msg
- ), f"DNS内层错误应包含 resolve/hostname/dns/connect/failed/error, 实际: {inner_msg}"
+ ), f"DNS内层错误应包含 resolve/hostname/host does not exist/dns/connect/failed/error, 实际: {inner_msg}"
print(f"✓ TC-E08 DNS解析失败处理通过(内层错误): {inner_msg[:80]}")
return
diff --git a/tests/server/test_bot_studio.py b/tests/server/test_bot_studio.py
new file mode 100644
index 000000000..90c27b131
--- /dev/null
+++ b/tests/server/test_bot_studio.py
@@ -0,0 +1,372 @@
+"""The browser cannot elevate or cross accounts through Studio management."""
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from openviking.server.auth import get_request_context
+from openviking.server.identity import RequestContext, Role
+from openviking.server.routers import admin, bot_studio
+from openviking_cli.session.user_id import UserIdentifier
+
+
+def app():
+ app = FastAPI()
+ app.include_router(bot_studio.router)
+ app.include_router(admin.router)
+ return app
+
+
[email protected]("role", ["user", "admin"])
+async def test_management_rejects_non_root(app, role, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: SimpleNamespace(
+ role=role, account_id="a"
+ )
+ dispatch = AsyncMock()
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ for method, url in [
+ ("GET", "/api/v1/admin/accounts/a/bot/connections"),
+ ("POST", "/api/v1/admin/accounts/a/bot/connections"),
+ ("POST", "/api/v1/admin/accounts/a/bot/onboarding-runs"),
+ ("GET", "/api/v1/admin/accounts/a/bot/onboarding-runs/current?type=feishu"),
+ ("GET", "/api/v1/admin/accounts/a/bot/onboarding-runs/job"),
+ ("POST", "/api/v1/admin/accounts/a/bot/onboarding-runs/job/actions"),
+ ("DELETE", "/api/v1/admin/accounts/a/bot/connections/x?revision=1"),
+ ("POST", "/api/v1/admin/accounts/a/bot/connections/x/credentials"),
+ ("POST", "/api/v1/admin/accounts/a/bot/connections/x/verifications"),
+ ("GET", "/api/v1/admin/accounts/a/bot/connections/x/messages?conversation=y"),
+ ]:
+ result = await client.request(method, url, json={})
+ assert result.status_code == 403
+ dispatch.assert_not_called()
+
+
+async def test_update_scope_comes_from_authenticated_context(app, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"), role=Role.ROOT
+ )
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {}})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ result = await client.patch(
+ "/api/v1/admin/accounts/a/bot/connections/id", json={"revision": 1, "enabled": False}
+ )
+ assert result.status_code == 200
+ assert dispatch.call_args.args[0].account_id == "a"
+
+
[email protected]("include_summary", [True, False])
[email protected]("include_credentials", [True, False])
+async def test_reused_admin_users_support_safe_credential_status(
+ app, monkeypatch, include_credentials, include_summary
+):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"),
+ role=Role.ROOT,
+ )
+ registry = SimpleNamespace(
+ refresh_account_users_from_store=AsyncMock(),
+ get_users_page=lambda *args, **kwargs: {
+ "users": [
+ {"user_id": "bot", "role": "user", "api_key": "private"},
+ {"user_id": "hashed", "role": "user", "key_prefix": "prefix"},
+ ],
+ "total": 2,
+ "account_total": 2,
+ "manager_count": 0,
+ "key_count": 2,
+ },
+ )
+ app.state.api_key_manager = registry
+ monkeypatch.setattr(admin, "_get_api_key_manager", lambda request: registry)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.get(
+ "/api/v1/admin/accounts/a/users",
+ params={
+ "role": "user",
+ "include_credentials": str(include_credentials).lower(),
+ "include_summary": str(include_summary).lower(),
+ },
+ )
+ assert response.status_code == 200
+ result = response.json()["result"]
+ if include_summary:
+ assert result["total"] == result["account_total"] == 2
+ assert result["manager_count"] == 0
+ result = result["users"]
+ if include_credentials:
+ assert result[0]["api_key"] == "private"
+ else:
+ assert "private" not in response.text and "prefix" not in response.text
+ assert result == [
+ {"user_id": "bot", "role": "user", "api_key_available": True},
+ {"user_id": "hashed", "role": "user", "api_key_available": False},
+ ]
+
+
[email protected]("user_id,accepted", [("missing", False), ("root", False), ("bot", True)])
+async def test_selection_uses_current_account_registry(monkeypatch, user_id, accepted):
+ from fastapi import HTTPException
+
+ registry = SimpleNamespace(
+ refresh_account_users_from_store=AsyncMock(),
+ get_users=lambda *a, **kw: [{"user_id": "bot", "api_key": "internal-key"}],
+ )
+ monkeypatch.setattr(bot_studio, "get_api_key_manager_or_raise", lambda request: registry)
+ monkeypatch.setattr(
+ bot_studio, "get_server_url_from_server_data", lambda config: "http://localhost"
+ )
+ request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(config=None)))
+ ctx = SimpleNamespace(account_id="a")
+ if accepted:
+ result = await bot_studio.selected_identity(request, ctx, user_id)
+ assert result["api_key"] == "internal-key"
+ assert result["role"] == "user"
+ assert result["account_id"] == "a"
+ else:
+ with pytest.raises(HTTPException) as exc:
+ await bot_studio.selected_identity(request, ctx, user_id)
+ assert exc.value.status_code == 400
+ registry.refresh_account_users_from_store.assert_awaited_with("a")
+
+
+async def test_hashed_key_is_not_treated_as_a_usable_credential(monkeypatch):
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(
+ bot_studio,
+ "account_users",
+ AsyncMock(return_value=[{"user_id": "bot", "key_prefix": "prefix"}]),
+ )
+ with pytest.raises(HTTPException) as exc:
+ await bot_studio.selected_identity(None, SimpleNamespace(account_id="a"), "bot")
+ assert exc.value.status_code == 409
+
+
+async def test_onboarding_identity_is_selected_server_side(app, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"), role=Role.ROOT
+ )
+ identity = {"user_id": "bot", "account_id": "a", "api_key": "server-key"}
+ select = AsyncMock(return_value=identity)
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {"id": "job"}})
+ monkeypatch.setattr(bot_studio, "selected_identity", select)
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ result = await client.post(
+ "/api/v1/admin/accounts/a/bot/onboarding-runs",
+ json={
+ "user_id": "bot",
+ "type": "feishu",
+ "request_id": "e232e744-f13a-44f3-8fda-4e82ad1b58b4",
+ },
+ )
+ assert result.status_code == 200
+ assert dispatch.call_args.args[0].account_id == "a"
+ assert dispatch.call_args.kwargs["identity"] == identity
+ assert "server-key" not in result.text
+
+
+ "path,allowed",
+ [
+ ("/api/v1/admin/bot/capabilities", True),
+ ("/api/v1/admin/accounts/a/users", True),
+ ("/api/v1/admin/accounts/a/bot/onboarding-runs", True),
+ ("/bot/v1/chat", False),
+ ("/bot/v1/studio-other", False),
+ ("/bot/v1/studio/connections", False),
+ ],
+)
+def test_real_root_policy_allows_only_studio_control_plane(path, allowed):
+ from openviking.server.auth.plugins.api_key import ApiKeyAuthPlugin
+ from openviking.server.identity import ResolvedIdentity
+ from openviking_cli.exceptions import PermissionDeniedError
+
+ identity = ResolvedIdentity(role="root", account_id="default", user_id="default")
+ if allowed:
+ ApiKeyAuthPlugin().get_request_context_checks(path, identity)
+ else:
+ with pytest.raises(PermissionDeniedError):
+ ApiKeyAuthPlugin().get_request_context_checks(path, identity)
+
+
+async def test_root_management_scope_comes_from_account_path(app, monkeypatch):
+ from openviking.server.identity import RequestContext
+ from openviking_cli.session.user_id import UserIdentifier
+
+ ctx = RequestContext(user=UserIdentifier("default", "default"), role="root")
+ app.dependency_overrides[get_request_context] = lambda: ctx
+ dispatch = AsyncMock(return_value={"status": "ok", "result": []})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ result = await client.get(
+ "/api/v1/admin/accounts/team/bot/connections",
+ headers={"X-OpenViking-Studio-Account": "ignored"},
+ )
+ assert result.status_code == 200
+ assert dispatch.call_args.args[0].account_id == "team"
+ assert ctx.account_id == "default"
+
+
+async def test_removed_scheduler_endpoint_is_not_exposed(app, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"), role=Role.ROOT
+ )
+ dispatch = AsyncMock()
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.get("/studio/schedules")
+ assert response.status_code == 404
+ dispatch.assert_not_called()
+
+
+ "method,suffix,body,action",
+ [
+ ("PATCH", "", {"revision": 3, "enabled": True}, "resume"),
+ ("DELETE", "?revision=3", None, "delete"),
+ ("POST", "/verifications", {"revision": 3}, "verify"),
+ ],
+)
+async def test_connection_http_methods_map_to_lifecycle(
+ app, monkeypatch, method, suffix, body, action
+):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("default", "root"),
+ role=Role.ROOT,
+ )
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {}})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.request(
+ method, "/api/v1/admin/accounts/team/bot/connections/id" + suffix, json=body
+ )
+ assert response.status_code == 200
+ assert dispatch.call_args.args[0].account_id == "team"
+ assert dispatch.call_args.args[2] == {"action": action, "revision": 3}
+
+
+async def test_platform_credentials_are_opaque_to_http_router(app, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"),
+ role=Role.ROOT,
+ )
+ identity = {"user_id": "bot", "api_key": "server-only"}
+ monkeypatch.setattr(bot_studio, "selected_identity", AsyncMock(return_value=identity))
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {"id": "new"}})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.post(
+ "/api/v1/admin/accounts/a/bot/connections",
+ json={
+ "type": "future-platform",
+ "user_id": "bot",
+ "credentials": {"client_id": "client", "client_secret": "secret"},
+ },
+ )
+ assert response.status_code == 200
+ assert dispatch.call_args.args[2]["type"] == "future-platform"
+ assert dispatch.call_args.args[2]["credentials"] == {
+ "client_id": "client",
+ "client_secret": "secret",
+ }
+ assert dispatch.call_args.kwargs["identity"] == identity
+ response = await client.patch(
+ "/api/v1/admin/accounts/a/bot/connections/new",
+ json={
+ "revision": 1,
+ "enabled": True,
+ "identity": {"api_key": "forged"},
+ },
+ )
+ assert response.status_code == 422
+
+
+async def test_settings_patch_reuses_connection_endpoint(app, monkeypatch):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("a", "root"),
+ role=Role.ROOT,
+ )
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {}})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.patch(
+ "/api/v1/admin/accounts/a/bot/connections/id",
+ json={
+ "revision": 2,
+ "settings": {"thread_require_mention": False},
+ },
+ )
+ assert response.status_code == 200
+ assert dispatch.call_args.args[2] == {
+ "action": "settings",
+ "revision": 2,
+ "settings": {"thread_require_mention": False},
+ }
+ response = await client.patch(
+ "/api/v1/admin/accounts/a/bot/connections/id",
+ json={
+ "revision": 2,
+ "enabled": True,
+ "settings": {},
+ },
+ )
+ assert response.status_code == 422
+
+
[email protected]("action", ["retry", "cancel", "manual"])
+async def test_onboarding_actions_preserve_account_and_validate_body(app, monkeypatch, action):
+ app.dependency_overrides[get_request_context] = lambda: RequestContext(
+ user=UserIdentifier("default", "root"), role=Role.ROOT
+ )
+ dispatch = AsyncMock(return_value={"status": "ok", "result": {}})
+ monkeypatch.setattr(bot_studio, "dispatch", dispatch)
+ base = "/api/v1/admin/accounts/team/bot/onboarding-runs/job"
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ response = await client.post(base + "/actions", json={"action": action})
+ assert response.status_code == 200
+ assert dispatch.call_args.args[0].account_id == "team"
+ assert dispatch.call_args.args[1:] == ("onboarding_update", {"id": "job", "action": action})
+ dispatch.reset_mock()
+ for body in ({}, {"action": "unknown"}, {"action": action, "account": "other"}):
+ response = await client.post(base + "/actions", json=body)
+ assert response.status_code == 422
+ response = await client.post(base + "/" + action)
+ assert response.status_code == 404
+ dispatch.assert_not_called()
+
+
+def test_studio_routes_are_registered_but_excluded_from_public_schema(app):
+ paths = app.openapi()["paths"]
+ assert all(route.path not in paths for route in bot_studio.router.routes)
+ assert all(
+ route in app.routes or any(r.path == route.path for r in app.routes)
+ for route in bot_studio.router.routes
+ )
+ assert "/api/v1/admin/accounts/{account_id}/users" in paths
diff --git a/web-studio/package-lock.json b/web-studio/package-lock.json
index d74dbc25e..a9cda3d0f 100644
--- a/web-studio/package-lock.json
+++ b/web-studio/package-lock.json
@@ -50,6 +50,7 @@
"lucide-react": "^0.545.0",
"next-themes": "^0.4.6",
"postprocessing": "^6.39.0",
+ "qrcode.react": "^4.2.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-dropzone": "^15.0.0",
@@ -12403,6 +12404,15 @@
"node": ">=6"
}
},
+ "node_modules/qrcode.react": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
+ "integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/qs": {
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.0.tgz",
diff --git a/web-studio/package.json b/web-studio/package.json
index 13ef1d129..247325924 100644
--- a/web-studio/package.json
+++ b/web-studio/package.json
@@ -60,6 +60,7 @@
"lucide-react": "^0.545.0",
"next-themes": "^0.4.6",
"postprocessing": "^6.39.0",
+ "qrcode.react": "^4.2.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-dropzone": "^15.0.0",
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 333a72096..71030819a 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -14,6 +14,7 @@ import {
MoonIcon,
ActivityIcon,
BotIcon,
+ PanelsTopLeftIcon,
CableIcon,
ScrollTextIcon,
SearchIcon,
@@ -91,12 +92,19 @@ const NAV_ITEMS: readonly NavItem[] = [
to: '/home',
},
{
- icon: BotIcon,
+ icon: PanelsTopLeftIcon,
id: 'playground',
section: 'workspace',
titleKey: 'navigation.playground.title',
to: '/playground',
},
+ {
+ icon: BotIcon,
+ id: 'vikingbot',
+ section: 'workspace',
+ titleKey: 'vikingbot:title',
+ to: '/vikingbot',
+ },
{
icon: SearchIcon,
id: 'retrieval',
diff --git a/web-studio/src/components/sessions/delete-conversation.test.tsx b/web-studio/src/components/sessions/delete-conversation.test.tsx
new file mode 100644
index 000000000..3042d66fc
--- /dev/null
+++ b/web-studio/src/components/sessions/delete-conversation.test.tsx
@@ -0,0 +1,62 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { DeleteConversation } from './delete-conversation'
+
+const remove = vi.hoisted(() => vi.fn())
+vi.mock('#/lib/sessions/use-sessions', () => ({
+ useDeleteSession: () => ({
+ mutateAsync: remove,
+ reset: vi.fn(),
+ isPending: false,
+ error: null,
+ }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+it('requires confirmation and does not delete on cancel', async () => {
+ const onDeleted = vi.fn()
+ remove.mockResolvedValue(undefined)
+ render(<DeleteConversation id="session" title="Chat" onDeleted={onDeleted} />)
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.deleteSession' }),
+ )
+ expect(remove).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'threadList.cancel' }))
+ expect(remove).not.toHaveBeenCalled()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.deleteSession' }),
+ )
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.confirmDelete' }),
+ )
+ await waitFor(() => expect(onDeleted).toHaveBeenCalledOnce())
+ expect(remove).toHaveBeenCalledExactlyOnceWith('session')
+})
+
+it('does not dismiss the conversation when deletion fails', async () => {
+ const onDeleted = vi.fn()
+ remove.mockRejectedValue(new Error('failed'))
+ render(<DeleteConversation id="session" title="Chat" onDeleted={onDeleted} />)
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.deleteSession' }),
+ )
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.confirmDelete' }),
+ )
+ await waitFor(() => expect(remove).toHaveBeenCalledOnce())
+ expect(onDeleted).not.toHaveBeenCalled()
+ expect(screen.getByRole('alertdialog')).toBeTruthy()
+})
diff --git a/web-studio/src/components/sessions/delete-conversation.tsx b/web-studio/src/components/sessions/delete-conversation.tsx
new file mode 100644
index 000000000..544f2ef28
--- /dev/null
+++ b/web-studio/src/components/sessions/delete-conversation.tsx
@@ -0,0 +1,93 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Trash2Icon } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '#/components/ui/alert-dialog'
+import { useDeleteSession } from '#/lib/sessions/use-sessions'
+
+export function DeleteConversation({
+ id,
+ title,
+ onDeleted,
+}: {
+ id: string
+ title: string
+ onDeleted: () => void
+}) {
+ const { t } = useTranslation('sessions')
+ const [open, setOpen] = useState(false)
+ const mutation = useDeleteSession()
+ return (
+ <>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="mr-1 shrink-0 text-muted-foreground hover:text-destructive [@media(hover:hover)]:opacity-0 group-hover/conversation:opacity-100 group-focus-within/conversation:opacity-100 focus-visible:opacity-100 transition-opacity"
+ aria-label={t('threadList.deleteSession', { title })}
+ onClick={() => {
+ mutation.reset()
+ setOpen(true)
+ }}
+ >
+ <Trash2Icon className="size-4" />
+ </Button>
+ <AlertDialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!mutation.isPending) setOpen(value)
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t('threadList.deleteConfirmTitle')}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t('threadList.deleteConfirmDescription', { title })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('threadList.deleteFailed', { error: mutation.error.message })}
+ </p>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={mutation.isPending}>
+ {t('threadList.cancel')}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-white hover:bg-destructive/90"
+ disabled={mutation.isPending}
+ onClick={async (event) => {
+ event.preventDefault()
+ if (mutation.isPending) return
+ try {
+ await mutation.mutateAsync(id)
+ setOpen(false)
+ onDeleted()
+ } catch {
+ // Keep the dialog and error visible so the user can retry.
+ }
+ }}
+ >
+ {t(
+ mutation.isPending
+ ? 'threadList.deleting'
+ : 'threadList.confirmDelete',
+ )}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 4fdcca575..1ab55e12e 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -1,3 +1,4 @@
+import vikingbot from './en/vikingbot'
import compile from './en/compile'
import memoryPolicy from './en/user-memory-policy'
import workspace from './en/workspace'
@@ -6,6 +7,7 @@ import activity from './en/activity'
const en = {
compile,
+ vikingbot,
...workspace,
...resources,
...activity,
diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.ts
index 8b7fd49b9..ca2966123 100644
--- a/web-studio/src/i18n/locales/en/activity.ts
+++ b/web-studio/src/i18n/locales/en/activity.ts
@@ -186,7 +186,7 @@ const activity = {
botDisabledFooter: 'Enable bot mode to chat with the Agent',
historyTitle: 'Agent session history',
historyDescription:
- 'Only sessions used by the Agent panel are shown here; a new session opens a blank Agent context.',
+ 'Conversations are shared with VikingBot, including legacy Agent sessions saved in this browser.',
loadingSessions: 'Loading sessions...',
noSessions: 'No session history yet',
createTimeout:
diff --git a/web-studio/src/i18n/locales/en/vikingbot.ts b/web-studio/src/i18n/locales/en/vikingbot.ts
new file mode 100644
index 000000000..382f75e46
--- /dev/null
+++ b/web-studio/src/i18n/locales/en/vikingbot.ts
@@ -0,0 +1,231 @@
+export default {
+ replyMode: 'Group reply mode',
+ withoutMention: 'Reply without @mention',
+ mentionModeHint:
+ 'Reply only when mentioned in group chats. Direct messages are unaffected.',
+ withoutMentionHint:
+ 'No mention required in regular groups or the first message of a topic. Later topic replies still require a mention, except in DEBUG mode. Direct messages are unaffected.',
+ groupMessagePermission:
+ 'Requires Feishu permission to receive all group messages. QR setup requests it automatically; for manual connections or later changes, enable the permission and publish the app in the Feishu developer console.',
+ saveReplyMode: 'Save reply mode',
+ savingReplyMode: 'Saving…',
+
+ operationFailed:
+ 'The operation could not be completed. Please retry. Details:',
+ viewSetup: 'View configuration',
+ chooseBotChannel: 'Choose a platform for your bot.',
+ searchBots: 'Search bots or runtime users',
+ botCount: '{{count}} bots',
+ noMatchingBots: 'No bots match your filters.',
+ channelFilter: 'Channel',
+ addBot: 'Add bot',
+ botsHint: 'Manage your bots and filter by channel.',
+ platformReady: 'Scan to connect, then add your bot to Feishu groups.',
+ connectedBots: 'Connected bots',
+ noConnectedBots: 'No bots yet. Select “Add bot” to get started.',
+ dingtalk: 'DingTalk',
+
+ qr: {
+ manualRecovery: 'Continue with manual setup',
+ intro:
+ 'Choose a runtime user, scan with Feishu to configure your bot, then add it to a group.',
+ choose: 'Choose user',
+ scan: 'Scan with Feishu',
+ addGroup: 'Add to group',
+ close: 'Close',
+ botName: 'Bot name',
+ start: 'Generate Feishu QR code',
+ manual: 'Already have an app? Connect manually',
+ consent:
+ 'Confirming the scan creates an app in your Feishu organization, configures group mentions, message sending and chat information permissions, and submits a release.',
+ scanHint:
+ 'Scan with the Feishu app and confirm on your phone. The code expires in about 2 minutes. App creation and configuration follow automatically.',
+ approvalHint:
+ 'The release is awaiting your organization’s approval. You can close this page and return later.',
+ retryScan: 'Scan again and continue',
+ cancel: 'Cancel scan',
+ copyFailed: 'Copy failed. Select and copy the text above manually.',
+ visibilityHint:
+ 'The initial app audience is the person who scanned. To make it available to other group members, update app availability in Feishu and publish.',
+ resumeFirst:
+ 'This connection is paused. Resume it from the channel list before testing.',
+ states: {
+ initializing: 'Preparing QR code…',
+ waiting_for_scan: 'Waiting for Feishu scan',
+ scanned: 'Scanned — confirm on your phone',
+ creating: 'Creating app…',
+ configuring: 'Configuring permissions and messaging…',
+ publishing: 'Submitting release…',
+ awaiting_approval: 'Awaiting administrator approval',
+ ready: 'App published — add it to a group',
+ failed: 'Automatic setup is incomplete',
+ expired: 'QR code expired',
+ interrupted: 'Setup interrupted — resume when ready',
+ cancelled: 'Scan cancelled',
+ },
+ errors: {
+ expired: 'The QR code expired. Scan a new code.',
+ interrupted:
+ 'The service restarted. Scan again to resume from the saved progress.',
+ identity_changed:
+ 'The account or organization differs from the app creator. Scan with the original account.',
+ creation_uncertain:
+ 'The creation result is unknown. Check Feishu for an app with this name before creating another.',
+ publication_uncertain:
+ 'The release result is unknown. Check the version in Feishu. No version will be created or submitted again automatically.',
+ approval_pending:
+ 'Approval is still pending. Once approved, scan again to check the release without creating another app.',
+ permissions_unavailable:
+ 'Required permissions could not be matched in the Feishu catalog. Scan again to retry, or use manual setup if it persists.',
+ events_not_ready:
+ 'Message events are not ready. Scan again to continue configuration.',
+ connection_unavailable:
+ 'The bot connection is not ready. Check the server network and scan again.',
+ platform_request_failed: 'The Feishu request failed. Try again later.',
+ platform_rejected:
+ 'Feishu rejected this operation. Check your app management permissions and organization policies.',
+ session_expired: 'The Feishu session expired. Scan again.',
+ identity_unavailable:
+ 'The account and organization could not be verified. No app was created.',
+ untrusted_redirect:
+ 'This Feishu login redirect is not supported. Setup stopped.',
+ login_unavailable: 'A QR code could not be generated. Try again later.',
+ icon_upload_failed: 'Bot icon upload failed. Please retry.',
+ credentials_unavailable:
+ 'The app exists, but its credentials could not be read. Scan again to resume.',
+ setup_failed:
+ 'Setup is incomplete. Scan again to resume from saved progress. If it fails again, check the app in Feishu.',
+ },
+ },
+ runtimeUser: 'Run as user',
+ selectUser: 'Select a user',
+ runtimeUserHint:
+ 'Select an ordinary user in this account. The bot uses their resource and memory permissions. Credentials are bound by the server; no API key copying is needed.',
+ userUnavailable: 'Credential unavailable',
+ noUsers: 'No ordinary users yet. Create a user, then refresh this list.',
+ manageUsers: 'Manage users',
+ rotateHint:
+ 'Leave the application secret empty to keep it unchanged. The server refreshes the bound user credential automatically. Failed validation keeps the existing connection.',
+ rotate: 'Update credentials',
+ cancelEdit: 'Cancel',
+
+ saveCredentials: 'Validate and save',
+ credentialsSaved: 'Credentials updated',
+ title: 'VikingBot',
+ conversations: 'Conversations',
+ channels: 'Bots',
+ intro: 'Talk to VikingBot here, or bring it into your team’s Feishu groups.',
+ newChat: 'New conversation',
+ web: 'Web',
+ feishu: 'Feishu',
+ all: 'All',
+ search: 'Search conversations',
+ empty: 'Start a conversation',
+ emptyHint: 'Ask a question, explore your resources, or connect Feishu.',
+ enable: 'Enable VikingBot to begin',
+ enableHint:
+ 'Ask your administrator to start OpenViking with Bot support and configure a conversation model.',
+ modelHint: 'VikingBot inherits the root vlm model configuration by default.',
+ retry: 'Retry',
+ loading: 'Loading…',
+ error: 'Something went wrong: {{error}}',
+ addFeishu: 'Connect Feishu',
+ comingSoon: 'Coming soon',
+ adminOnly:
+ 'Only the server administrator can manage connections and view Feishu history.',
+ webReady: 'Web conversations use your current OpenViking identity.',
+ manageHint:
+ 'Connect an application once, then add its bot to multiple groups.',
+ steps: [
+ 'Create application',
+ 'Connect application',
+ 'Permissions & events',
+ 'Publish application',
+ 'Add to group & verify',
+ 'Start chatting',
+ ],
+ setupTitle: 'Connect VikingBot to Feishu',
+ setupHint:
+ 'You need permission to manage a Feishu enterprise application and add its bot to an internal group.',
+ createHint:
+ 'Create an enterprise custom application in Feishu Open Platform, set its name and avatar, then add the Bot capability. A group webhook cannot receive conversations.',
+ openPlatform: 'Open Feishu Open Platform',
+ next: 'Continue',
+ back: 'Back',
+ close: 'Save and close',
+ credentialsHint:
+ 'Find App ID and App Secret under Credentials & Basic Info. Studio validates them and starts the long connection before you configure events.',
+ appId: 'App ID',
+ appSecret: 'App Secret',
+ userKey: 'Dedicated OpenViking user API key',
+ userKeyHint:
+ 'Create an ordinary user specifically for this bot in the current account. Do not reuse your personal key. Root and admin keys are rejected. Grant this user access only to resources intended for group members.',
+ connect: 'Validate and connect',
+ connectedAs: 'Bot identity: {{name}} · OpenViking user: {{user}}',
+ permissionsHint:
+ 'Enable receiving group @bot messages and sending messages as the bot. Add receiving direct messages if you need private chat. Enable im:chat.members:read and publish a new version to display member names.',
+ eventsHint:
+ 'Under Events & Callbacks, choose long connection and subscribe to im.message.receive_v1. No public callback URL is needed. Wait for the connection before saving the subscription.',
+ officialDocs: 'Open official event documentation',
+ permissionsNote:
+ 'Permissions and publication cannot be fully inspected here. The group test below verifies actual message reception and delivery.',
+ publishHint:
+ 'Create a version in Version Management & Release, set the availability range, and submit it. If approval is required, return after the administrator approves it. Changes to permissions may require a new release.',
+ publishDone: 'I have published the application',
+ groupHint:
+ 'In Feishu, open your group settings and add this application bot. Generate a test message, then use Feishu’s @ picker to mention the bot and send it. Copied plain text is not a real mention.',
+ test: 'Generate connection test',
+ testText: 'VikingBot connection test {{code}}',
+ copy: 'Copy',
+ copied: 'Copied',
+ received: 'Group message received',
+ sent: 'Reply accepted by Feishu',
+ waiting: 'Waiting',
+ verified: 'Verified',
+ visible: 'I can see the test reply in the group',
+ expired: 'Test expired. Generate a new test message.',
+ troubleshoot:
+ 'No reply? Check publication and availability, bot membership, a real @mention, message permissions, event subscription, and the long connection. If a message was received, check sending permissions.',
+ done: 'Feishu is connected',
+ doneHint:
+ 'Now @ the bot with a real question. The connection test does not call the model. If normal chat fails, check the model configuration.',
+ setupComplete: 'Feishu setup complete',
+ startUsingHint:
+ 'Add this app in your Feishu group settings, then @mention it to start chatting. No test code is required.',
+ noActivity: 'No activity yet',
+ connectionHelp: 'Troubleshoot connection (optional)',
+ deleteConnection: 'Delete connection',
+ deleteConnectionHint:
+ 'Delete the connection for “{{title}}”? This stops the bot connection and permanently removes its Studio chat history. The Feishu app and group messages remain unchanged.',
+ deleteFailed: 'Deletion failed: {{error}}',
+ cancelDelete: 'Cancel',
+ deletingConnection: 'Deleting…',
+ confirmDeleteConnection: 'Delete',
+ manualTitle: 'Connect an existing app',
+ manualHint: 'Enter your Feishu app credentials and select its runtime user.',
+ manualInstructions: 'Configuration: permissions, events and publication',
+ manualConnected: 'App credentials verified',
+ manualConnectedHint:
+ 'Connection saved. Configure message permissions and long-connection events, then publish the app before using it in a group.',
+ finish: 'Done',
+ continueSetup: 'Continue setup',
+ pause: 'Pause',
+ resume: 'Resume',
+ state: { connected: 'Connected', connecting: 'Connecting', paused: 'Paused' },
+ onlyMention: 'Responds when @mentioned',
+ historyHint:
+ 'Only messages received since this connection was set up are shown. This is not the complete Feishu group history.',
+ readonly: 'This is a Feishu conversation. Continue chatting in Feishu.',
+ group: 'Feishu conversation',
+ unknownSender: 'Group member',
+ noHistory: 'No received messages yet',
+ earlier: 'Load earlier messages',
+ delivery: {
+ received: 'Received',
+ sent: 'Accepted by Feishu',
+ send_failed: 'Sending failed',
+ },
+ connectionError: 'Bot service is unavailable. Check the service and retry.',
+ lastReceived: 'Last received',
+ lastSent: 'Last successful reply',
+} as const
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 2493e278a..23a5c8be5 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -1,3 +1,4 @@
+import vikingbot from './zh-CN/vikingbot'
import compile from './zh-CN/compile'
import memoryPolicy from './zh-CN/user-memory-policy'
import workspace from './zh-CN/workspace'
@@ -6,6 +7,7 @@ import activity from './zh-CN/activity'
const zhCN = {
compile,
+ vikingbot,
...workspace,
...resources,
...activity,
diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.ts
index b4e718f50..02b9dcf6d 100644
--- a/web-studio/src/i18n/locales/zh-CN/activity.ts
+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts
@@ -178,7 +178,7 @@ const activity = {
botDisabledFooter: '启用 VikingBot 后即可与 Agent 对话',
historyTitle: 'Agent 会话历史',
historyDescription:
- '这里只显示 Agent 面板使用过的会话。新建会话会创建一段空白的 Agent 上下文。',
+ '工作台与 VikingBot 共用对话记录,也包含当前浏览器保存的旧 Agent 会话。',
loadingSessions: '正在加载会话...',
noSessions: '暂无历史会话',
createTimeout: '创建工作台会话超时,请检查连接设置后重试。',
diff --git a/web-studio/src/i18n/locales/zh-CN/vikingbot.ts b/web-studio/src/i18n/locales/zh-CN/vikingbot.ts
new file mode 100644
index 000000000..0d259d758
--- /dev/null
+++ b/web-studio/src/i18n/locales/zh-CN/vikingbot.ts
@@ -0,0 +1,214 @@
+export default {
+ replyMode: '群聊回复方式',
+ withoutMention: '无需 @ 即可回复',
+ mentionModeHint: '群聊中仅在被 @ 时回复,私聊不受影响。',
+ withoutMentionHint:
+ '普通群无需 @;话题群首条消息无需 @,后续回复仍需 @(DEBUG 模式除外)。私聊不受影响。',
+ groupMessagePermission:
+ '需要飞书“获取群组中所有消息”权限。扫码新建时会申请;手动接入或后续切换时,请在飞书开放平台补充权限并发布应用。',
+ saveReplyMode: '保存回复方式',
+ savingReplyMode: '保存中…',
+
+ operationFailed: '操作未完成,请重试。错误详情:',
+ viewSetup: '查看配置',
+ chooseBotChannel: '选择机器人接入的平台。',
+ searchBots: '搜索机器人或运行用户',
+ botCount: '{{count}} 个机器人',
+ noMatchingBots: '没有符合筛选条件的机器人',
+ channelFilter: '渠道',
+ addBot: '添加机器人',
+ botsHint: '管理已添加的机器人,按渠道筛选。',
+ platformReady: '扫码连接,将机器人添加到飞书群。',
+ connectedBots: '已连接的机器人',
+ noConnectedBots: '暂无机器人,点击“添加机器人”开始。',
+ dingtalk: '钉钉',
+
+ qr: {
+ manualRecovery: '改用手动配置',
+ intro: '选择运行用户,用飞书扫码后自动配置机器人,最后添加到群。',
+ choose: '选择用户',
+ scan: '飞书扫码',
+ addGroup: '添加到群',
+ close: '关闭',
+ botName: '机器人名称',
+ start: '生成飞书二维码',
+ manual: '已有应用?手动连接',
+ consent:
+ '扫码确认后,将在扫码账号所属企业创建应用,配置群聊 @消息、发送消息和群信息读取权限,并提交发布。',
+ scanHint:
+ '请用飞书 App 扫码并在手机确认。二维码约 2 分钟有效;确认后将自动创建并配置应用。',
+ approvalHint:
+ '发布已提交,正在等待企业管理员审批。可以关闭页面,稍后从此处继续。',
+ retryScan: '重新扫码并继续',
+ cancel: '取消扫码',
+ copyFailed: '复制失败,请选择上方文本手动复制。',
+ visibilityHint:
+ '初始可用范围为扫码创建者。若群内其他成员无法使用,请在飞书开放平台调整应用可用范围并发布。',
+ resumeFirst: '连接已暂停,请回到渠道列表恢复后再测试。',
+ states: {
+ initializing: '正在准备二维码…',
+ waiting_for_scan: '等待飞书扫码',
+ scanned: '已扫码,请在手机确认',
+ creating: '正在创建应用…',
+ configuring: '正在配置权限和消息接收…',
+ publishing: '正在提交发布…',
+ awaiting_approval: '等待企业管理员审批',
+ ready: '应用已发布,准备添加到群',
+ failed: '自动配置暂未完成',
+ expired: '二维码已过期',
+ interrupted: '配置任务已中断,可继续恢复',
+ cancelled: '扫码已取消',
+ },
+ errors: {
+ expired: '二维码已过期,请重新扫码。',
+ interrupted: '服务已重启。重新扫码后将从已保存的进度继续。',
+ identity_changed: '扫码账号或企业与创建时不一致,请使用原账号重新扫码。',
+ creation_uncertain:
+ '创建请求的结果尚未确认。请先在开放平台检查同名应用,避免重复创建。',
+ publication_uncertain:
+ '发布结果尚未确认。请在开放平台检查当前版本;流程不会重复创建或提交版本。',
+ approval_pending:
+ '企业审批尚未完成。审批后重新扫码检查发布状态,不会重复创建应用。',
+ permissions_unavailable:
+ '未能从飞书权限目录匹配所需权限。请重新扫码重试;若仍失败,可改用手动配置。',
+ events_not_ready: '消息事件尚未配置成功,请重新扫码继续配置。',
+ connection_unavailable:
+ '机器人长连接尚未建立,请检查服务器网络后重新扫码。',
+ platform_request_failed: '飞书请求失败,请稍后重试。',
+ platform_rejected:
+ '飞书拒绝了当前操作,请检查账号的应用管理权限或企业策略。',
+ session_expired: '飞书登录已失效,请重新扫码。',
+ identity_unavailable: '无法确认扫码账号和企业,尚未创建应用。',
+ untrusted_redirect: '飞书登录跳转地址不受支持,已停止操作。',
+ login_unavailable: '暂时无法生成二维码,请稍后重试。',
+ icon_upload_failed: '机器人图标上传失败,请重试。',
+ credentials_unavailable:
+ '应用已创建,但暂时无法读取凭证,请重新扫码继续。',
+ setup_failed:
+ '自动配置未完成。可重新扫码从已保存的进度继续;若仍失败,请在飞书开放平台检查应用。',
+ },
+ },
+ runtimeUser: '运行用户',
+ selectUser: '选择用户',
+ runtimeUserHint:
+ '选择当前账户下的普通用户,机器人将使用该用户的资源和记忆权限。凭证由服务端自动绑定,无需复制 API Key。',
+ userUnavailable: '凭证不可自动绑定',
+ noUsers: '暂无普通用户,请先创建用户,再刷新列表。',
+ manageUsers: '管理用户',
+ rotateHint:
+ '应用密钥不变时可留空。运行用户的凭证由服务端自动同步,验证失败会保留原连接。',
+ rotate: '更新凭证',
+ cancelEdit: '取消',
+
+ saveCredentials: '验证并保存',
+ credentialsSaved: '凭证已更新',
+ title: 'VikingBot',
+ conversations: '对话',
+ channels: '机器人',
+ intro: '在这里与 VikingBot 对话,也可以将它加入团队的飞书群。',
+ newChat: '新建对话',
+ web: '网页',
+ feishu: '飞书',
+ all: '全部',
+ search: '搜索对话',
+ empty: '开始与 VikingBot 对话',
+ emptyHint: '提出问题、探索资源,或将机器人连接到飞书。',
+ enable: '先启用 VikingBot',
+ enableHint: '请管理员以 Bot 模式启动 OpenViking,并配置对话模型。',
+ modelHint: 'VikingBot 默认继承根级 vlm 模型配置。',
+ retry: '重试',
+ loading: '加载中…',
+ error: '操作失败:{{error}}',
+ addFeishu: '连接飞书',
+ comingSoon: '开发中',
+ adminOnly: '仅服务管理员可以管理连接和查看飞书历史。',
+ webReady: '网页对话使用当前 OpenViking 身份。',
+ manageHint: '连接一个应用后,可将它的机器人加入多个群。',
+ steps: [
+ '创建应用',
+ '连接应用',
+ '权限与事件',
+ '发布应用',
+ '添加到群并验证',
+ '开始对话',
+ ],
+ setupTitle: '将 VikingBot 连接到飞书',
+ setupHint:
+ '你需要飞书企业自建应用的管理权限,以及向企业内部群添加机器人的权限。',
+ createHint:
+ '在飞书开放平台创建企业自建应用,设置名称与头像,然后添加「机器人」能力。群 Webhook 无法完成对话接入。',
+ openPlatform: '打开飞书开放平台',
+ next: '下一步',
+ back: '上一步',
+ close: '保存并关闭',
+ credentialsHint:
+ '在「凭证与基础信息」找到 App ID 与 App Secret。验证成功后先建立长连接,再配置事件订阅。',
+ appId: 'App ID',
+ appSecret: 'App Secret',
+ userKey: '专用 OpenViking 用户 API Key',
+ userKeyHint:
+ '在当前账户下为机器人创建专用普通用户,不要复用个人密钥。Root 和管理员密钥不可用。仅向该用户授权允许群成员使用的资源。',
+ connect: '验证并建立连接',
+ connectedAs: '机器人:{{name}} · OpenViking 用户:{{user}}',
+ permissionsHint:
+ '开启接收群聊 @机器人消息、以机器人身份发送消息的权限。如需私聊,再开启接收单聊消息权限。显示成员姓名需开启 im:chat.members:read(获取群成员列表),并重新发布应用。',
+ eventsHint:
+ '在「事件与回调」中选择长连接,订阅 im.message.receive_v1。无需公网回调地址,请等待连接建立后再保存订阅。',
+ officialDocs: '查看官方事件说明',
+ permissionsNote:
+ '此处无法完整读取权限与发布状态,后续群内测试将验证实际收发能力。',
+ publishHint:
+ '前往「版本管理与发布」创建版本,设置可用范围并提交发布。如需审批,等待管理员审批后继续。修改权限后可能需要重新发布。',
+ publishDone: '我已发布应用',
+ groupHint:
+ '打开飞书目标群的群设置,添加此应用机器人。生成测试消息后,在飞书使用 @选择器选中机器人并发送。复制的普通文本不等于真正的 @。',
+ test: '生成连接测试消息',
+ testText: 'VikingBot connection test {{code}}',
+ copy: '复制',
+ copied: '已复制',
+ received: '收到群消息',
+ sent: '回复已被飞书接受',
+ waiting: '等待中',
+ verified: '已验证',
+ visible: '我已在群里看到测试回复',
+ expired: '测试已过期,请重新生成测试消息。',
+ troubleshoot:
+ '没有回复?依次检查发布与可用范围、机器人是否入群、是否真正 @机器人、消息权限、事件订阅与长连接。已收到消息时,请检查发送权限。',
+ done: '飞书已接通',
+ doneHint:
+ '现在可以在群里 @机器人提出真实问题。连接测试不会调用模型;若正常对话失败,请检查模型配置。',
+ setupComplete: '飞书配置已完成',
+ startUsingHint:
+ '在飞书群设置中添加此应用,然后在群里 @它即可开始对话。无需发送测试码。',
+ noActivity: '暂无记录',
+ connectionHelp: '排查连接问题(可选)',
+ deleteConnection: '删除连接',
+ deleteConnectionHint:
+ '确定删除“{{title}}”的连接吗?这将停止机器人连接,并删除此连接在 Studio 中的聊天记录,无法恢复。飞书平台上的应用和群消息不会删除。',
+ deleteFailed: '删除失败:{{error}}',
+ cancelDelete: '取消',
+ deletingConnection: '删除中…',
+ confirmDeleteConnection: '确认删除',
+ manualTitle: '连接已有应用',
+ manualHint: '填写已有飞书应用的凭证,绑定运行用户。',
+ manualInstructions: '配置说明:权限、事件与发布',
+ manualConnected: '应用凭证已验证',
+ manualConnectedHint:
+ '连接已保存。请确保已在飞书配置消息权限、长连接事件并发布应用,即可添加到群使用。',
+ finish: '完成',
+ continueSetup: '继续配置',
+ pause: '暂停',
+ resume: '恢复',
+ state: { connected: '已连接', connecting: '连接中', paused: '已暂停' },
+ onlyMention: '仅 @机器人时回复',
+ historyHint: '仅展示此连接建立后机器人收到的消息,不包含完整飞书群历史。',
+ readonly: '此会话来自飞书,请前往飞书继续对话。',
+ group: '飞书会话',
+ unknownSender: '群成员',
+ noHistory: '暂无收到的消息',
+ earlier: '加载更早消息',
+ delivery: { received: '已收到', sent: '飞书已接受', send_failed: '发送失败' },
+ connectionError: '暂时无法连接 Bot 服务,请检查服务后重试。',
+ lastReceived: '最近收消息',
+ lastSent: '最近成功回复',
+} as const
diff --git a/web-studio/src/lib/ov-client/client.test.ts b/web-studio/src/lib/ov-client/client.test.ts
index d2dbe37a9..417a43c95 100644
--- a/web-studio/src/lib/ov-client/client.test.ts
+++ b/web-studio/src/lib/ov-client/client.test.ts
@@ -137,3 +137,27 @@ describe('createOvClient API key selection', () => {
expect(readRequestHeader(requests[0], 'X-OpenViking-User')).toBe('bob')
})
})
+
+it('uses the control credential for Studio bot management only', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({ adminApiKey: 'admin-key', apiKey: 'user-key' })
+ await client.instance.get('/api/v1/admin/accounts/team/bot/connections')
+ await client.instance.post('/bot/v1/chat/stream')
+ expect(readRequestHeader(requests[0], 'X-API-Key')).toBe('admin-key')
+ expect(readRequestHeader(requests[1], 'X-API-Key')).toBe('user-key')
+})
+
+it('scopes Studio root management to the selected account without asserting a data identity', async () => {
+ const { client, requests } = createRecordingClient()
+ client.setConnection({
+ adminApiKey: 'root-key',
+ apiKey: 'user-key',
+ accountId: 'team',
+ identityHeaders: false,
+ })
+ await client.instance.get('/api/v1/admin/accounts/team/bot/connections')
+ await client.instance.get('/bot/v1/chat')
+ expect(readRequestHeader(requests[0], 'X-OpenViking-Studio-Account')).toBe('')
+ expect(readRequestHeader(requests[0], 'X-OpenViking-Account')).toBe('')
+ expect(readRequestHeader(requests[1], 'X-OpenViking-Studio-Account')).toBe('')
+})
diff --git a/web-studio/src/lib/sessions/api.test.ts b/web-studio/src/lib/sessions/api.test.ts
index 02a7029f5..6f682926f 100644
--- a/web-studio/src/lib/sessions/api.test.ts
+++ b/web-studio/src/lib/sessions/api.test.ts
@@ -2,7 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import { OvClientError } from '#/lib/ov-client'
-import { fetchSessionMessages, serializeParts } from './api'
+import {
+ fetchSessionFirstTitle,
+ fetchSessionMessages,
+ serializeParts,
+} from './api'
const {
getSessionBySessionIdMock,
@@ -156,3 +160,48 @@ describe('serializeParts', () => {
])
})
})
+
+describe('fetchSessionFirstTitle', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('stops at the first archived user message without reading later history', async () => {
+ getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 20 }))
+ getSessionIdArchiveByArchiveIdMock.mockReturnValue(
+ response({ messages: [message('first', 'First\n question')] }),
+ )
+ expect(await fetchSessionFirstTitle('s')).toBe('First question')
+ expect(getSessionIdArchiveByArchiveIdMock).toHaveBeenCalledExactlyOnceWith({
+ path: { session_id: 's', archive_id: 'archive_001' },
+ })
+ expect(getSessionIdContextMock).not.toHaveBeenCalled()
+ })
+
+ it('reads current context when there are no archives', async () => {
+ getSessionBySessionIdMock.mockReturnValue(response({ commit_count: 0 }))
+ getSessionIdContextMock.mockReturnValue(
+ response({ messages: [message('1', 'Hello')] }),
+ )
+ expect(await fetchSessionFirstTitle('s')).toBe('Hello')
+ expect(getSessionIdArchiveByArchiveIdMock).not.toHaveBeenCalled()
+ })
+
+ it('limits simultaneous title lookups to four and releases slots after errors', async () => {
+ let active = 0
+ let peak = 0
+ getSessionBySessionIdMock.mockImplementation(async () => {
+ active += 1
+ peak = Math.max(peak, active)
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ active -= 1
+ throw new Error('unavailable')
+ })
+ const results = await Promise.allSettled(
+ Array.from({ length: 12 }, (_, i) => fetchSessionFirstTitle(String(i))),
+ )
+ expect(peak).toBe(4)
+ expect(results.every((result) => result.status === 'rejected')).toBe(true)
+ expect(getSessionBySessionIdMock).toHaveBeenCalledTimes(12)
+ })
+})
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index b27c67d36..3b10f8146 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -204,6 +204,57 @@ export async function fetchSessionMessages(
])
}
+// Share four slots across title backfills from both conversation entry points.
+let activeTitleRequests = 0
+const titleWaiters: Array<() => void> = []
+
+export async function fetchSessionFirstTitle(
+ sessionId: string,
+): Promise<string> {
+ if (activeTitleRequests >= 4) {
+ await new Promise<void>((resolve) => titleWaiters.push(resolve))
+ } else {
+ activeTitleRequests += 1
+ }
+ try {
+ const session = await fetchSession(sessionId)
+ const count = Math.max(0, Math.floor(session.commit_count || 0))
+ for (let index = 1; index <= count; index += 1) {
+ try {
+ const archive = await fetchSessionArchive(
+ sessionId,
+ `archive_${String(index).padStart(3, '0')}`,
+ )
+ const title = firstUserTitle(archive.messages)
+ if (title) return title
+ } catch (error) {
+ if (!isMissingArchive(error)) throw error
+ }
+ }
+ return firstUserTitle((await fetchSessionContext(sessionId)).messages)
+ } finally {
+ const next = titleWaiters.shift()
+ if (next) next()
+ else activeTitleRequests -= 1
+ }
+}
+
+function firstUserTitle(value: unknown): string {
+ const first = getMessages(value).find(
+ (message) =>
+ message.role === 'user' &&
+ message.parts.some((part) => part.type === 'text' && part.text.trim()),
+ )
+ return (
+ first?.parts
+ .flatMap((part) => (part.type === 'text' ? [part.text] : []))
+ .join(' ')
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, 60) || ''
+ )
+}
+
export async function fetchSessionMemoryDiffs(
session: SessionMeta,
): Promise<SessionMemoryDiff[]> {
diff --git a/web-studio/src/lib/sessions/use-default-conversation-titles.test.tsx b/web-studio/src/lib/sessions/use-default-conversation-titles.test.tsx
new file mode 100644
index 000000000..62100d668
--- /dev/null
+++ b/web-studio/src/lib/sessions/use-default-conversation-titles.test.tsx
@@ -0,0 +1,34 @@
+// @vitest-environment jsdom
+import { cleanup, renderHook, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { useDefaultConversationTitles } from './use-default-conversation-titles'
+
+const mocks = vi.hoisted(() => ({ fetch: vi.fn(), save: vi.fn() }))
+vi.mock('./api', () => ({ fetchSessionFirstTitle: mocks.fetch }))
+vi.mock('./use-session-titles', () => ({
+ useSessionTitles: () => ({
+ getTitle: (id: string) => (id === 'custom' ? 'My title' : id),
+ setTitle: mocks.save,
+ }),
+}))
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+it('backfills the first user text without fetching or replacing a custom title', async () => {
+ mocks.fetch.mockResolvedValue('First question')
+ const client = new QueryClient()
+ renderHook(
+ () => useDefaultConversationTitles('account', ['missing', 'custom']),
+ {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ },
+ )
+ await waitFor(() =>
+ expect(mocks.save).toHaveBeenCalledWith('missing', 'First question'),
+ )
+ expect(mocks.fetch).toHaveBeenCalledExactlyOnceWith('missing')
+})
diff --git a/web-studio/src/lib/sessions/use-default-conversation-titles.ts b/web-studio/src/lib/sessions/use-default-conversation-titles.ts
new file mode 100644
index 000000000..a8813224a
--- /dev/null
+++ b/web-studio/src/lib/sessions/use-default-conversation-titles.ts
@@ -0,0 +1,31 @@
+import { useEffect } from 'react'
+import { useQueries } from '@tanstack/react-query'
+import { fetchSessionFirstTitle } from './api'
+import { useSessionTitles } from './use-session-titles'
+
+const PLACEHOLDERS = new Set([
+ '新建对话',
+ '新建工作台会话',
+ 'New conversation',
+ 'New session',
+])
+
+export function useDefaultConversationTitles(scope: string, ids: string[]) {
+ const { getTitle, setTitle } = useSessionTitles(scope)
+ const missing = ids.filter(
+ (id) => getTitle(id) === id || PLACEHOLDERS.has(getTitle(id)),
+ )
+ const queries = useQueries({
+ queries: missing.map((id) => ({
+ queryKey: ['conversation-first-message', scope, id],
+ queryFn: () => fetchSessionFirstTitle(id),
+ staleTime: 60_000,
+ retry: false,
+ })),
+ })
+ useEffect(() => {
+ queries.forEach((query, index) => {
+ if (query.data) setTitle(missing[index], query.data)
+ })
+ }, [queries, missing, setTitle])
+}
diff --git a/web-studio/src/lib/sessions/vikingbot-sessions.ts b/web-studio/src/lib/sessions/vikingbot-sessions.ts
new file mode 100644
index 000000000..fd1794e47
--- /dev/null
+++ b/web-studio/src/lib/sessions/vikingbot-sessions.ts
@@ -0,0 +1,21 @@
+import { createRandomUuid } from '#/lib/browser-crypto'
+
+// Persist ownership in the session ID: the generic session API has no source field.
+// Legacy IDs are accepted only from the identity-scoped Playground Agent history.
+const WEB_SESSION_PREFIX = 'vikingbot-web-'
+const WEB_SESSION_PATTERN =
+ /^vikingbot-web-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
+
+export function createVikingBotWebSessionId() {
+ return `${WEB_SESSION_PREFIX}${createRandomUuid()}`
+}
+
+export function isVikingBotWebSession(
+ session: { session_id: string },
+ legacyPlaygroundIds: readonly string[] = [],
+) {
+ return (
+ WEB_SESSION_PATTERN.test(session.session_id) ||
+ legacyPlaygroundIds.includes(session.session_id)
+ )
+}
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index 19ba845fa..51a5de85e 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -10,6 +10,7 @@
import { Route as rootRouteImport } from './routes/__root'
import { Route as WatchesRouteRouteImport } from './routes/watches/route'
+import { Route as VikingbotRouteRouteImport } from './routes/vikingbot/route'
import { Route as UsersRouteRouteImport } from './routes/users/route'
import { Route as TasksRouteRouteImport } from './routes/tasks/route'
import { Route as SkillsRouteRouteImport } from './routes/skills/route'
@@ -22,6 +23,7 @@ import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'
import { Route as HomeRouteRouteImport } from './routes/home/route'
import { Route as AgentExperienceRouteRouteImport } from './routes/agent-experience/route'
import { Route as IndexRouteImport } from './routes/index'
+import { Route as VikingbotIndexRouteImport } from './routes/vikingbot/index'
import { Route as SessionsIndexRouteImport } from './routes/sessions/index'
import { Route as CompileIndexRouteImport } from './routes/compile/index'
import { Route as AgentExperienceIndexRouteImport } from './routes/agent-experience/index'
@@ -36,6 +38,11 @@ const WatchesRouteRoute = WatchesRouteRouteImport.update({
path: '/watches',
getParentRoute: () => rootRouteImport,
} as any)
+const VikingbotRouteRoute = VikingbotRouteRouteImport.update({
+ id: '/vikingbot',
+ path: '/vikingbot',
+ getParentRoute: () => rootRouteImport,
+} as any)
const UsersRouteRoute = UsersRouteRouteImport.update({
id: '/users',
path: '/users',
@@ -96,6 +103,11 @@ const IndexRoute = IndexRouteImport.update({
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
+const VikingbotIndexRoute = VikingbotIndexRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () => VikingbotRouteRoute,
+} as any)
const SessionsIndexRoute = SessionsIndexRouteImport.update({
id: '/',
path: '/',
@@ -151,6 +163,7 @@ export interface FileRoutesByFullPath {
'/skills': typeof SkillsRouteRoute
'/tasks': typeof TasksRouteRoute
'/users': typeof UsersRouteRoute
+ '/vikingbot': typeof VikingbotRouteRouteWithChildren
'/watches': typeof WatchesRouteRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
'/compile/new': typeof CompileNewRoute
@@ -159,6 +172,7 @@ export interface FileRoutesByFullPath {
'/agent-experience/': typeof AgentExperienceIndexRoute
'/compile/': typeof CompileIndexRoute
'/sessions/': typeof SessionsIndexRoute
+ '/vikingbot/': typeof VikingbotIndexRoute
'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRoutesByTo {
@@ -180,6 +194,7 @@ export interface FileRoutesByTo {
'/agent-experience': typeof AgentExperienceIndexRoute
'/compile': typeof CompileIndexRoute
'/sessions': typeof SessionsIndexRoute
+ '/vikingbot': typeof VikingbotIndexRoute
'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRoutesById {
@@ -196,6 +211,7 @@ export interface FileRoutesById {
'/skills': typeof SkillsRouteRoute
'/tasks': typeof TasksRouteRoute
'/users': typeof UsersRouteRoute
+ '/vikingbot': typeof VikingbotRouteRouteWithChildren
'/watches': typeof WatchesRouteRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
'/compile/new': typeof CompileNewRoute
@@ -204,6 +220,7 @@ export interface FileRoutesById {
'/agent-experience/': typeof AgentExperienceIndexRoute
'/compile/': typeof CompileIndexRoute
'/sessions/': typeof SessionsIndexRoute
+ '/vikingbot/': typeof VikingbotIndexRoute
'/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRouteTypes {
@@ -221,6 +238,7 @@ export interface FileRouteTypes {
| '/skills'
| '/tasks'
| '/users'
+ | '/vikingbot'
| '/watches'
| '/agent-experience/$experienceUri'
| '/compile/new'
@@ -229,6 +247,7 @@ export interface FileRouteTypes {
| '/agent-experience/'
| '/compile/'
| '/sessions/'
+ | '/vikingbot/'
| '/compile/tasks/$taskId'
fileRoutesByTo: FileRoutesByTo
to:
@@ -250,6 +269,7 @@ export interface FileRouteTypes {
| '/agent-experience'
| '/compile'
| '/sessions'
+ | '/vikingbot'
| '/compile/tasks/$taskId'
id:
| '__root__'
@@ -265,6 +285,7 @@ export interface FileRouteTypes {
| '/skills'
| '/tasks'
| '/users'
+ | '/vikingbot'
| '/watches'
| '/agent-experience/$experienceUri'
| '/compile/new'
@@ -273,6 +294,7 @@ export interface FileRouteTypes {
| '/agent-experience/'
| '/compile/'
| '/sessions/'
+ | '/vikingbot/'
| '/compile/tasks/$taskId'
fileRoutesById: FileRoutesById
}
@@ -289,6 +311,7 @@ export interface RootRouteChildren {
SkillsRouteRoute: typeof SkillsRouteRoute
TasksRouteRoute: typeof TasksRouteRoute
UsersRouteRoute: typeof UsersRouteRoute
+ VikingbotRouteRoute: typeof VikingbotRouteRouteWithChildren
WatchesRouteRoute: typeof WatchesRouteRoute
CompileNewRoute: typeof CompileNewRoute
OauthConsentRoute: typeof OauthConsentRoute
@@ -306,6 +329,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof WatchesRouteRouteImport
parentRoute: typeof rootRouteImport
}
+ '/vikingbot': {
+ id: '/vikingbot'
+ path: '/vikingbot'
+ fullPath: '/vikingbot'
+ preLoaderRoute: typeof VikingbotRouteRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/users': {
id: '/users'
path: '/users'
@@ -390,6 +420,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
+ '/vikingbot/': {
+ id: '/vikingbot/'
+ path: '/'
+ fullPath: '/vikingbot/'
+ preLoaderRoute: typeof VikingbotIndexRouteImport
+ parentRoute: typeof VikingbotRouteRoute
+ }
'/sessions/': {
id: '/sessions/'
path: '/'
@@ -474,6 +511,18 @@ const SessionsRouteRouteWithChildren = SessionsRouteRoute._addFileChildren(
SessionsRouteRouteChildren,
)
+interface VikingbotRouteRouteChildren {
+ VikingbotIndexRoute: typeof VikingbotIndexRoute
+}
+
+const VikingbotRouteRouteChildren: VikingbotRouteRouteChildren = {
+ VikingbotIndexRoute: VikingbotIndexRoute,
+}
+
+const VikingbotRouteRouteWithChildren = VikingbotRouteRoute._addFileChildren(
+ VikingbotRouteRouteChildren,
+)
+
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
AgentExperienceRouteRoute: AgentExperienceRouteRouteWithChildren,
@@ -487,6 +536,7 @@ const rootRouteChildren: RootRouteChildren = {
SkillsRouteRoute: SkillsRouteRoute,
TasksRouteRoute: TasksRouteRoute,
UsersRouteRoute: UsersRouteRoute,
+ VikingbotRouteRoute: VikingbotRouteRouteWithChildren,
WatchesRouteRoute: WatchesRouteRoute,
CompileNewRoute: CompileNewRoute,
OauthConsentRoute: OauthConsentRoute,
diff --git a/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx b/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx
index 5f1573b64..0ca41d3e7 100644
--- a/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel-initialization.test.tsx
@@ -9,6 +9,9 @@ const mocks = vi.hoisted(() => ({
send: vi.fn(),
onSend: undefined as undefined | ((message: string) => Promise<void>),
}))
+vi.mock('#/lib/sessions/use-default-conversation-titles', () => ({
+ useDefaultConversationTitles: vi.fn(),
+}))
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
@@ -99,6 +102,7 @@ it('creates the draft before sending and publishes only the persisted ID', async
expect(mocks.send).not.toHaveBeenCalled()
expect(onSessionChange).not.toHaveBeenCalled()
const id = mocks.create.mock.calls[0][0]
+ expect(id).toMatch(/^vikingbot-web-/)
await act(async () => {
resolveCreation({ session_id: id })
await sending
diff --git a/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx b/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx
index ed9cf7428..839bdac77 100644
--- a/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel-submission.test.tsx
@@ -6,9 +6,13 @@ import { registerPlaygroundAgentSessionId } from '../-lib/utils'
const m = vi.hoisted(() => ({
create: vi.fn(),
+ remove: vi.fn(),
stream: vi.fn(),
history: vi.fn(),
}))
+vi.mock('#/lib/sessions/use-default-conversation-titles', () => ({
+ useDefaultConversationTitles: vi.fn(),
+}))
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}))
@@ -16,11 +20,20 @@ vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({ identityScopeKey: 'test' }),
}))
vi.mock('#/lib/sessions/use-session-titles', () => ({
- useSessionTitles: () => ({ getTitle: (id: string) => id, setTitle: vi.fn() }),
+ useSessionTitles: () => ({
+ getTitle: (id: string) => id,
+ setTitle: vi.fn(),
+ removeTitle: vi.fn(),
+ }),
setSessionTitle: vi.fn(),
}))
vi.mock('#/lib/sessions/use-sessions', () => ({
useBotHealth: () => ({ isLoading: true }),
+ useDeleteSession: () => ({
+ mutateAsync: m.remove,
+ reset: vi.fn(),
+ isPending: false,
+ }),
useCreateSession: () => ({ mutateAsync: m.create }),
useSessionListByRecency: () => ({
data: [{ session_id: 'B' }],
@@ -36,6 +49,7 @@ vi.mock('#/lib/sessions/api', () => ({
beforeEach(() => {
Element.prototype.scrollIntoView = vi.fn()
window.localStorage.clear()
+ m.remove.mockReset().mockResolvedValue(undefined)
m.create.mockReset()
m.history.mockReset().mockReturnValue({ data: undefined })
m.stream.mockReset().mockImplementation(() => new Promise(() => {}))
@@ -139,3 +153,30 @@ it('does not send or publish after the panel unmounts', async () => {
expect(pending.url).not.toHaveBeenCalled()
expect(m.stream).not.toHaveBeenCalled()
})
+
+it('deletes the active history session only after confirmation and returns to a draft', async () => {
+ const pending = setup()
+ fireEvent.click(screen.getByRole('button', { name: 'agent.history' }))
+ fireEvent.click(screen.getByRole('button', { name: 'BB' }))
+ fireEvent.click(screen.getByRole('button', { name: 'agent.history' }))
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.deleteSession' }),
+ )
+ expect(m.remove).not.toHaveBeenCalled()
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole('button', { name: 'threadList.confirmDelete' }),
+ )
+ })
+ expect(m.remove).toHaveBeenCalledWith('B')
+ expect(pending.url).toHaveBeenLastCalledWith('')
+ expect(m.create).not.toHaveBeenCalled()
+})
+
+it('opens a new draft without persisting an empty conversation', () => {
+ const pending = setup()
+ fireEvent.click(screen.getByTitle('agent.newSession'))
+ expect(m.create).not.toHaveBeenCalled()
+ expect(m.history).toHaveBeenLastCalledWith(undefined)
+ expect(pending.url).toHaveBeenCalledWith('')
+})
diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsx
index 6b494d038..b2a02509d 100644
--- a/web-studio/src/routes/playground/-components/agent-panel.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx
@@ -1,3 +1,4 @@
+import { useDefaultConversationTitles } from '#/lib/sessions/use-default-conversation-titles'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
@@ -10,6 +11,7 @@ import {
SquarePenIcon,
} from 'lucide-react'
+import { DeleteConversation } from '#/components/sessions/delete-conversation'
import { Button } from '#/components/ui/button'
import {
Dialog,
@@ -20,7 +22,10 @@ import {
} from '#/components/ui/dialog'
import { cn } from '#/lib/utils'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { createRandomUuid } from '#/lib/browser-crypto'
+import {
+ createVikingBotWebSessionId,
+ isVikingBotWebSession,
+} from '#/lib/sessions/vikingbot-sessions'
import { useChat } from '#/lib/sessions/use-chat'
import {
useBotHealth,
@@ -37,7 +42,6 @@ import {
getErrorMessage,
readPlaygroundAgentSessionIds,
registerPlaygroundAgentSessionId,
- withTimeout,
} from '../-lib/utils'
export function AgentPanel({
@@ -54,7 +58,7 @@ export function AgentPanel({
const { t } = useTranslation('playground')
const { identityScopeKey } = useAppConnection()
const [sessionId, setSessionId] = useState(
- initialSessionId ?? createRandomUuid(),
+ initialSessionId ?? createVikingBotWebSessionId(),
)
const [historyOpen, setHistoryOpen] = useState(false)
const [sessionError, setSessionError] = useState<string | null>(null)
@@ -73,10 +77,16 @@ export function AgentPanel({
const createSession = useCreateSession()
const { data: sessions, isLoading: isLoadingSessions } =
useSessionListByRecency()
- const { getTitle, setTitle } = useSessionTitles(identityScopeKey)
+ const { getTitle, removeTitle } = useSessionTitles(identityScopeKey)
const [playgroundSessionIds, setPlaygroundSessionIds] = useState<string[]>(
() => readPlaygroundAgentSessionIds(identityScopeKey),
)
+ useDefaultConversationTitles(
+ identityScopeKey,
+ sessions
+ .filter((session) => isVikingBotWebSession(session, playgroundSessionIds))
+ .map((session) => session.session_id),
+ )
const { data: historyMessages } = useSessionMessages(historySessionId)
const chat = useChat({
identityScopeKey,
@@ -87,51 +97,19 @@ export function AgentPanel({
const scrollRef = useRef<HTMLDivElement>(null)
const bottomRef = useRef<HTMLDivElement>(null)
- const handleNewSession = useCallback(async () => {
+ const handleNewSession = useCallback(() => {
if (isCreatingSession) return
-
- const generation = ++creationGenerationRef.current
+ creationGenerationRef.current += 1
chat.abort()
chat.setMessages([])
- creationStartedRef.current = true
- setIsCreatingSession(true)
+ creationStartedRef.current = false
setSessionError(null)
-
- try {
- const result = await withTimeout(
- createSession.mutateAsync(undefined),
- 12_000,
- t('agent.createTimeout'),
- )
- if (generation !== creationGenerationRef.current) return
- setPlaygroundSessionIds(
- registerPlaygroundAgentSessionId(result.session_id, identityScopeKey),
- )
- setTitle(result.session_id, t('agent.newSessionTitle'))
- setHistorySessionId(undefined)
- setPersistedSessionId(result.session_id)
- setSessionId(result.session_id)
- onSessionChange(result.session_id)
- setHistoryOpen(false)
- } catch (error) {
- if (generation !== creationGenerationRef.current) return
- creationStartedRef.current = false
- setSessionError(error instanceof Error ? error.message : String(error))
- } finally {
- if (generation === creationGenerationRef.current) {
- creationStartedRef.current = false
- setIsCreatingSession(false)
- }
- }
- }, [
- chat,
- createSession,
- identityScopeKey,
- isCreatingSession,
- onSessionChange,
- setTitle,
- t,
- ])
+ setHistorySessionId(undefined)
+ setPersistedSessionId(undefined)
+ setSessionId(createVikingBotWebSessionId())
+ onSessionChange('')
+ setHistoryOpen(false)
+ }, [chat, isCreatingSession, onSessionChange])
const handleSwitchSession = useCallback(
(nextSessionId: string) => {
@@ -207,17 +185,9 @@ export function AgentPanel({
const displayedSessionTitle =
sessionTitle === sessionId ? t('agent.newSessionTitle') : sessionTitle
const reversedSessions = useMemo(() => {
- // `sessions` is already sorted by recency (newest first). Filter to
- // sessions that were opened in this playground, preserving recency order.
- const sessionById = new Map(
- sessions.map((session) => [session.session_id, session]),
+ return sessions.filter((session) =>
+ isVikingBotWebSession(session, playgroundSessionIds),
)
-
- return playgroundSessionIds
- .map((playgroundSessionId) => sessionById.get(playgroundSessionId))
- .filter((session): session is NonNullable<typeof session> =>
- Boolean(session),
- )
}, [sessions, playgroundSessionIds])
return (
@@ -324,30 +294,57 @@ export function AgentPanel({
const title = getTitle(session.session_id)
return (
- <button
+ <div
key={session.session_id}
- type="button"
- className={cn(
- 'flex min-w-0 items-center gap-3 rounded-lg border px-3 py-2 text-left transition-colors hover:border-primary/45 hover:bg-muted/45',
- active
- ? 'border-primary/60 bg-primary/10'
- : 'border-border bg-background',
- )}
- onClick={() => handleSwitchSession(session.session_id)}
+ className="group/conversation flex items-center gap-1"
>
- <HistoryIcon className="size-4 shrink-0 text-muted-foreground" />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium text-foreground">
- {title}
- </span>
- <span className="block truncate font-mono text-[11px] text-muted-foreground">
- {session.session_id}
+ <button
+ type="button"
+ className={cn(
+ 'flex min-w-0 flex-1 items-center gap-3 rounded-lg border px-3 py-2 text-left transition-colors hover:border-primary/45 hover:bg-muted/45',
+ active
+ ? 'border-primary/60 bg-primary/10'
+ : 'border-border bg-background',
+ )}
+ onClick={() => handleSwitchSession(session.session_id)}
+ >
+ <HistoryIcon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-sm font-medium text-foreground">
+ {title}
+ </span>
+ <span className="block truncate font-mono text-[11px] text-muted-foreground">
+ {session.session_id}
+ </span>
</span>
- </span>
- {active ? (
- <CheckCircle2Icon className="size-4 shrink-0 text-primary" />
- ) : null}
- </button>
+ {active ? (
+ <CheckCircle2Icon className="size-4 shrink-0 text-primary" />
+ ) : null}
+ </button>
+ <DeleteConversation
+ id={session.session_id}
+ title={title}
+ onDeleted={() => {
+ removeTitle(session.session_id)
+ setPlaygroundSessionIds((ids) =>
+ ids.filter((id) => id !== session.session_id),
+ )
+ if (session.session_id === sessionId) {
+ creationGenerationRef.current += 1
+ chat.abort()
+ chat.setMessages([])
+ creationStartedRef.current = false
+ setIsCreatingSession(false)
+ setSessionError(null)
+ setHistorySessionId(undefined)
+ setPersistedSessionId(undefined)
+ setSessionId(createVikingBotWebSessionId())
+ onSessionChange('')
+ setHistoryOpen(false)
+ }
+ }}
+ />
+ </div>
)
})}
</div>
diff --git a/web-studio/src/routes/sessions/-components/thread-draft.test.tsx b/web-studio/src/routes/sessions/-components/thread-draft.test.tsx
new file mode 100644
index 000000000..f0bd85865
--- /dev/null
+++ b/web-studio/src/routes/sessions/-components/thread-draft.test.tsx
@@ -0,0 +1,128 @@
+// @vitest-environment jsdom
+import { useState } from 'react'
+import { act, cleanup, render } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { Thread } from './thread'
+
+const m = vi.hoisted(() => ({
+ create: vi.fn(),
+ history: vi.fn(),
+ send: vi.fn(),
+ onSend: undefined as undefined | ((text: string) => Promise<boolean>),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'test' }),
+}))
+vi.mock('#/lib/sessions/use-session-titles', () => ({
+ useSessionTitles: () => ({ getTitle: (id: string) => id }),
+}))
+vi.mock('#/lib/sessions/use-sessions', () => ({
+ useCreateSession: () => ({ mutateAsync: m.create }),
+ useSession: () => ({}),
+ useSessionMessages: m.history,
+}))
+vi.mock('#/lib/sessions/use-chat', () => ({
+ useChat: () => ({ messages: [], status: 'idle', send: m.send }),
+}))
+vi.mock('./memory-impact', () => ({ MemoryImpact: () => null }))
+vi.mock('./composer', () => ({
+ Composer: ({ onSend }: { onSend: typeof m.onSend }) => {
+ m.onSend = onSend
+ return null
+ },
+}))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ m.history.mockReturnValue({ isPending: true })
+ Element.prototype.scrollIntoView = vi.fn()
+})
+afterEach(cleanup)
+
+it('does not request draft history and persists only once on first send', async () => {
+ m.create.mockResolvedValue({ session_id: 'draft' })
+ render(<Thread sessionId="draft" draft />)
+ expect(m.create).not.toHaveBeenCalled()
+ expect(m.history).toHaveBeenLastCalledWith(undefined)
+ await act(async () => {
+ expect(await m.onSend!('first')).toBe(true)
+ })
+ await act(async () => {
+ await m.onSend!('second')
+ })
+ expect(m.create).toHaveBeenCalledExactlyOnceWith('draft')
+ expect(m.send).toHaveBeenCalledWith('first')
+ expect(m.history).toHaveBeenLastCalledWith(undefined)
+})
+
+it('rejects failed creation so the composer can retain input', async () => {
+ m.create.mockRejectedValue(new Error('unavailable'))
+ render(<Thread sessionId="draft" draft />)
+ await act(async () => {
+ expect(await m.onSend!('first')).toBe(false)
+ })
+ expect(m.send).not.toHaveBeenCalled()
+})
+
+it('does not send after leaving a draft during creation', async () => {
+ let resolve!: (value: unknown) => void
+ m.create.mockImplementation(
+ () =>
+ new Promise((done) => {
+ resolve = done
+ }),
+ )
+ const view = render(<Thread sessionId="draft" draft />)
+ let pending!: Promise<boolean>
+ act(() => {
+ pending = m.onSend!('first')
+ })
+ expect(await m.onSend!('duplicate')).toBe(false)
+ view.unmount()
+ resolve({ session_id: 'draft' })
+ expect(await pending).toBe(false)
+ expect(m.send).not.toHaveBeenCalled()
+ expect(m.create).toHaveBeenCalledTimes(1)
+})
+
+it('loads the correct history when switching existing sessions', () => {
+ const view = render(<Thread sessionId="first" />)
+ expect(m.history).toHaveBeenLastCalledWith('first')
+ view.rerender(<Thread sessionId="second" />)
+ expect(m.history).toHaveBeenLastCalledWith('second')
+ expect(m.create).not.toHaveBeenCalled()
+})
+
+it('loads persisted history and continues after switching tabs', async () => {
+ let showThread!: (visible: boolean) => void
+ function Workspace() {
+ const [draft, setDraft] = useState(true)
+ const [visible, setVisible] = useState(true)
+ showThread = setVisible
+ return visible ? (
+ <Thread
+ sessionId="draft"
+ draft={draft}
+ onPersisted={() => setDraft(false)}
+ />
+ ) : null
+ }
+ m.create
+ .mockResolvedValueOnce({ session_id: 'draft' })
+ .mockRejectedValue(new Error('Session already exists'))
+ render(<Workspace />)
+ await act(async () => {
+ expect(await m.onSend!('first')).toBe(true)
+ })
+ act(() => showThread(false))
+ act(() => showThread(true))
+ expect(m.history).toHaveBeenLastCalledWith('draft')
+ await act(async () => {
+ expect(await m.onSend!('second')).toBe(true)
+ })
+ expect(m.create).toHaveBeenCalledExactlyOnceWith('draft')
+ expect(m.send).toHaveBeenLastCalledWith('second')
+})
diff --git a/web-studio/src/routes/sessions/-components/thread.tsx b/web-studio/src/routes/sessions/-components/thread.tsx
index 77aea7434..a49f84a40 100644
--- a/web-studio/src/routes/sessions/-components/thread.tsx
+++ b/web-studio/src/routes/sessions/-components/thread.tsx
@@ -4,7 +4,11 @@ import { useTranslation } from 'react-i18next'
import { useAppConnection } from '#/hooks/use-app-connection'
import { useChat } from '#/lib/sessions/use-chat'
-import { useSession, useSessionMessages } from '#/lib/sessions/use-sessions'
+import {
+ useCreateSession,
+ useSession,
+ useSessionMessages,
+} from '#/lib/sessions/use-sessions'
import { useSessionTitles } from '#/lib/sessions/use-session-titles'
import { MessageList } from './message-list'
import { MemoryImpact } from './memory-impact'
@@ -15,20 +19,41 @@ const PRODUCT_NAME = 'OpenViking'
interface ThreadProps {
sessionId: string
+ draft?: boolean
+ onPersisted?: () => void
}
-export function Thread({ sessionId }: ThreadProps) {
+export function Thread(props: ThreadProps) {
+ const { identityScopeKey } = useAppConnection()
+ return (
+ <SessionThread key={`${identityScopeKey}:${props.sessionId}`} {...props} />
+ )
+}
+
+function SessionThread({ sessionId, draft = false, onPersisted }: ThreadProps) {
const { t } = useTranslation('sessions')
const { identityScopeKey } = useAppConnection()
const { getTitle } = useSessionTitles(identityScopeKey)
const title = getTitle(sessionId)
- const { data: session } = useSession(sessionId)
+ const [historyId] = useState(draft ? undefined : sessionId)
+ const persisted = useRef(!draft)
+ const creating = useRef(false)
+ const mounted = useRef(false)
+ const [creationError, setCreationError] = useState<string>()
+ const createSession = useCreateSession()
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
+ const { data: session } = useSession(historyId)
const {
data: historyMessages,
isPending: historyLoading,
error: historyError,
- } = useSessionMessages(sessionId)
+ } = useSessionMessages(historyId)
const chat = useChat({
identityScopeKey,
@@ -40,10 +65,30 @@ export function Thread({ sessionId }: ThreadProps) {
const isStreaming = chat.status === 'streaming'
const handleSend = useCallback(
- (message: string) => {
- if (message.trim()) chat.send(message)
+ async (message: string) => {
+ if (!message.trim() || creating.current) return false
+ if (!persisted.current) {
+ creating.current = true
+ setCreationError(undefined)
+ try {
+ await createSession.mutateAsync(sessionId)
+ onPersisted?.()
+ if (!mounted.current) return false
+ persisted.current = true
+ } catch (error) {
+ if (mounted.current)
+ setCreationError(
+ error instanceof Error ? error.message : String(error),
+ )
+ return false
+ } finally {
+ creating.current = false
+ }
+ }
+ void chat.send(message)
+ return true
},
- [chat],
+ [chat, createSession, sessionId, onPersisted],
)
// ---- Auto-scroll ----
@@ -102,7 +147,9 @@ export function Thread({ sessionId }: ThreadProps) {
<div className="relative z-10 flex h-12 items-center justify-between gap-4 border-b border-border/50 bg-background/95 px-6">
<h2 className="truncate text-sm font-medium text-foreground">
- {title || sessionId}
+ {draft && title === sessionId
+ ? t('threadList.newSession')
+ : title || sessionId}
</h2>
<MemoryImpact session={session} />
</div>
@@ -112,7 +159,7 @@ export function Thread({ sessionId }: ThreadProps) {
onScroll={handleScroll}
className="relative z-10 flex flex-1 flex-col items-center overflow-y-auto px-4 pt-6 pb-6"
>
- {historyLoading ? (
+ {historyId && historyLoading ? (
<div role="status" className="py-6 text-sm text-muted-foreground">
{t('threadList.loading')}
</div>
@@ -138,12 +185,12 @@ export function Thread({ sessionId }: ThreadProps) {
<div ref={bottomRef} />
</div>
- {chat.error && (
+ {(creationError || chat.error) && (
<div
role="alert"
className="relative z-10 mx-auto w-full max-w-4xl px-4 py-2 text-sm text-destructive"
>
- {t('chat.sendFailed', { error: chat.error })}
+ {t('chat.sendFailed', { error: creationError || chat.error })}
</div>
)}
<div className="relative z-10">
diff --git a/web-studio/src/routes/vikingbot/-api.test.ts b/web-studio/src/routes/vikingbot/-api.test.ts
new file mode 100644
index 000000000..5c026f8ad
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-api.test.ts
@@ -0,0 +1,91 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+import {
+ createConnection,
+ deleteConnection,
+ getBotUsers,
+ getMessages,
+ rotateCredentials,
+ updateConnection,
+ verifyConnection,
+} from './-api'
+import { currentOnboarding, updateOnboarding } from './-providers/feishu/api'
+import type { Connection } from './-api'
+
+const transport = vi.hoisted(() => ({
+ get: vi.fn(),
+ post: vi.fn(),
+ patch: vi.fn(),
+ delete: vi.fn(),
+ accountId: 'team',
+}))
+vi.mock('#/lib/ov-client', () => ({
+ ovClient: {
+ client: transport,
+ getConnection: () => ({ accountId: transport.accountId }),
+ },
+ getOvResult: (result: unknown) => result,
+}))
+const connection = { id: 'connection', revision: 3 } as Connection
+const base = '/api/v1/admin/accounts/team/bot'
+beforeEach(() => {
+ vi.clearAllMocks()
+ transport.accountId = 'team'
+})
+it('uses explicit lifecycle methods and preserves revision checks', () => {
+ updateConnection(connection, 'pause')
+ expect(transport.patch).toHaveBeenCalledWith({
+ url: `${base}/connections/connection`,
+ body: { enabled: false, revision: 3 },
+ })
+ deleteConnection(connection)
+ expect(transport.delete).toHaveBeenCalledWith({
+ url: `${base}/connections/connection`,
+ query: { revision: 3 },
+ })
+ verifyConnection(connection)
+ expect(transport.post).toHaveBeenCalledWith({
+ url: `${base}/connections/connection/verifications`,
+ body: { revision: 3 },
+ })
+})
+it('keeps provider credential fields inside a generic envelope', () => {
+ const credentials = { client_id: 'id', client_secret: 'secret' }
+ createConnection({ type: 'future-platform', user_id: 'bot', credentials })
+ expect(transport.post).toHaveBeenCalledWith({
+ url: `${base}/connections`,
+ body: { type: 'future-platform', user_id: 'bot', credentials },
+ })
+ rotateCredentials(connection, credentials, 'bot')
+ expect(transport.post).toHaveBeenLastCalledWith({
+ url: `${base}/connections/connection/credentials`,
+ body: { revision: 3, credentials, user_id: 'bot' },
+ })
+})
+it('reuses the safe admin-user projection', async () => {
+ transport.get.mockResolvedValue([{ user_id: 'bot', api_key_available: true }])
+ expect(await getBotUsers()).toEqual([{ user_id: 'bot', available: true }])
+ expect(transport.get).toHaveBeenCalledWith({
+ url: '/api/v1/admin/accounts/team/users',
+ query: { role: 'user', include_credentials: false },
+ })
+})
+it('uses current account and encodes identifiers without moving conversation keys into paths', () => {
+ transport.accountId = 'team two'
+ getMessages('app/id', 'group/thread:topic', 7)
+ expect(transport.get).toHaveBeenCalledWith({
+ url: '/api/v1/admin/accounts/team%20two/bot/connections/app%2Fid/messages',
+ query: { conversation: 'group/thread:topic', before: 7 },
+ })
+})
+it('uses provider selection for current setup and explicit job actions', () => {
+ currentOnboarding()
+ expect(transport.get).toHaveBeenCalledWith({
+ url: `${base}/onboarding-runs/current`,
+ query: { type: 'feishu' },
+ })
+ updateOnboarding('job', 'retry')
+ expect(transport.post).toHaveBeenCalledWith({
+ url: `${base}/onboarding-runs/job/actions`,
+ body: { action: 'retry' },
+ })
+})
diff --git a/web-studio/src/routes/vikingbot/-api.ts b/web-studio/src/routes/vikingbot/-api.ts
new file mode 100644
index 000000000..c7ae02b6f
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-api.ts
@@ -0,0 +1,158 @@
+import { getOvResult, ovClient } from '#/lib/ov-client'
+
+export type Connection = {
+ id: string
+ type?: string
+ setup_mode?: string
+ onboarding_id?: string
+ app_id: string
+ bot_name: string
+ enabled: boolean
+ step: number
+ revision: number
+ settings?: Record<string, unknown>
+ identity_user: string
+ status: {
+ state: string
+ last_received?: string
+ last_sent?: string
+ verification?: {
+ code: string
+ expires_at: number
+ received: boolean
+ sent: boolean
+ conversation?: string
+ }
+ }
+}
+export type PlatformMessage = {
+ id: number
+ role: string
+ content: string
+ sender: string
+ time: string
+ status: string
+ conversation: string
+}
+export function botAccountBase() {
+ const { accountId } = ovClient.getConnection()
+ if (!accountId) throw new Error('Select an account before managing bots')
+ return `/api/v1/admin/accounts/${encodeURIComponent(accountId)}/bot`
+}
+export function getCapabilities() {
+ return getOvResult<{ enabled: boolean; can_manage: boolean }>(
+ ovClient.client.get({ url: '/api/v1/admin/bot/capabilities' }),
+ )
+}
+export function getConnections() {
+ return getOvResult<Connection[]>(
+ ovClient.client.get({ url: `${botAccountBase()}/connections` }),
+ )
+}
+export function createConnection(body: {
+ type: string
+ credentials: Record<string, string>
+ settings?: Record<string, unknown>
+ user_id: string
+}) {
+ return getOvResult<Connection>(
+ ovClient.client.post({ url: `${botAccountBase()}/connections`, body }),
+ )
+}
+export function updateConnection(
+ connection: Connection,
+ action: 'pause' | 'resume',
+) {
+ return getOvResult<Connection>(
+ ovClient.client.patch({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(connection.id)}`,
+ body: { enabled: action === 'resume', revision: connection.revision },
+ }),
+ )
+}
+export function deleteConnection(connection: Connection) {
+ return getOvResult<{ deleted: boolean }>(
+ ovClient.client.delete({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(connection.id)}`,
+ query: { revision: connection.revision },
+ }),
+ )
+}
+export function verifyConnection(connection: Connection) {
+ return getOvResult<Connection>(
+ ovClient.client.post({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(connection.id)}/verifications`,
+ body: { revision: connection.revision },
+ }),
+ )
+}
+export function getConversations(id: string) {
+ return getOvResult<
+ Array<{
+ conversation: string
+ latest: number
+ title: string
+ group_name?: string
+ preview?: string
+ time?: string
+ }>
+ >(
+ ovClient.client.get({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(id)}/conversations`,
+ }),
+ )
+}
+export function getMessages(id: string, conversation: string, before = 0) {
+ return getOvResult<PlatformMessage[]>(
+ ovClient.client.get({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(id)}/messages`,
+ query: { conversation, before },
+ }),
+ )
+}
+
+export function rotateCredentials(
+ connection: Connection,
+ credentials: Record<string, string>,
+ userId: string,
+) {
+ return getOvResult<Connection>(
+ ovClient.client.post({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(connection.id)}/credentials`,
+ body: {
+ revision: connection.revision,
+ credentials,
+ user_id: userId,
+ },
+ }),
+ )
+}
+
+export async function getBotUsers() {
+ const { accountId } = ovClient.getConnection()
+ if (!accountId) throw new Error('Select an account before managing bots')
+ const users = await getOvResult<
+ Array<{ user_id: string; api_key_available: boolean }>
+ >(
+ ovClient.client.get({
+ url: `/api/v1/admin/accounts/${encodeURIComponent(accountId)}/users`,
+ query: { role: 'user', include_credentials: false },
+ }),
+ )
+ return users.map((user) => ({
+ user_id: user.user_id,
+ available: user.api_key_available,
+ }))
+}
+
+export function updateConnectionSettings(
+ connection: Connection,
+ settings: Record<string, unknown>,
+) {
+ return getOvResult<Connection>(
+ ovClient.client.patch({
+ url: `${botAccountBase()}/connections/${encodeURIComponent(connection.id)}`,
+ body: { settings, revision: connection.revision },
+ }),
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-components/channels.tsx b/web-studio/src/routes/vikingbot/-components/channels.tsx
new file mode 100644
index 000000000..a08bd1da8
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-components/channels.tsx
@@ -0,0 +1,323 @@
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from '#/components/ui/dialog'
+import {
+ getProvider,
+ providers,
+ upcomingProviders,
+} from '../-providers/registry'
+import { DeleteConnection } from './delete-connection'
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { BotIcon, PlusIcon, SearchIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { getConnections, updateConnection } from '../-api'
+import type { Connection } from '../-api'
+
+export function Channels({
+ canManage,
+ scope,
+}: {
+ canManage: boolean
+ scope: string
+}) {
+ const { t } = useTranslation('vikingbot')
+ const client = useQueryClient()
+ const key = ['vikingbot', scope, 'connections']
+ const connections = useQuery({
+ queryKey: key,
+ queryFn: getConnections,
+ enabled: canManage,
+ refetchInterval: 4000,
+ })
+ const [choosing, setChoosing] = useState(false)
+ const [channelFilter, setChannelFilter] = useState('all')
+ const [search, setSearch] = useState('')
+ const visibleConnections = (connections.data ?? []).filter(
+ (connection) =>
+ (channelFilter === 'all' ||
+ (connection.type ?? 'feishu') === channelFilter) &&
+ `${connection.bot_name} ${connection.identity_user}`
+ .toLowerCase()
+ .includes(search.trim().toLowerCase()),
+ )
+ const [editing, setEditing] = useState<string>()
+ const [newType, setNewType] = useState('feishu')
+ const selected = connections.data?.find((c) => c.id === editing)
+ function changed(value: Connection) {
+ client.setQueryData<Connection[]>(key, (old) => [
+ ...(old ?? []).filter((c) => c.id !== value.id),
+ value,
+ ])
+ setEditing(value.id)
+ void client.invalidateQueries({ queryKey: key })
+ }
+ const mutation = useMutation({
+ mutationFn: ({
+ connection,
+ action,
+ }: {
+ connection: Connection
+ action: 'pause' | 'resume'
+ }) => updateConnection(connection, action),
+ onSuccess: () => client.invalidateQueries({ queryKey: key }),
+ })
+ const provider = getProvider(editing === 'new' ? newType : selected?.type)
+ const Setup = provider?.Setup
+ if (canManage && editing && Setup)
+ return (
+ <Setup
+ key={editing === 'new' ? 'setup' : editing}
+ connection={selected}
+ onChange={changed}
+ onClose={() => setEditing(undefined)}
+ />
+ )
+ return (
+ <div className="mx-auto w-full min-w-0 max-w-7xl space-y-5 p-4 md:p-6 lg:p-8">
+ <div className="flex flex-wrap items-center justify-between gap-4">
+ <div>
+ <h2 className="text-lg font-semibold">{t('channels')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">{t('botsHint')}</p>
+ </div>
+ {canManage && (
+ <Button onClick={() => setChoosing(true)}>
+ <PlusIcon className="size-4" />
+ {t('addBot')}
+ </Button>
+ )}
+ </div>
+ {canManage && (
+ <div className="flex flex-wrap items-center gap-3 rounded-lg border bg-muted/20 p-3">
+ <div className="relative min-w-48 flex-1 sm:max-w-sm">
+ <SearchIcon className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ className="pl-9"
+ aria-label={t('searchBots')}
+ placeholder={t('searchBots')}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ </div>
+ <label className="flex items-center gap-2 text-sm text-muted-foreground">
+ {t('channelFilter')}
+ <select
+ className="h-9 rounded-md border bg-background px-3 text-foreground"
+ value={channelFilter}
+ onChange={(event) => setChannelFilter(event.target.value)}
+ >
+ <option value="all">{t('all')}</option>
+ {Object.entries(providers).map(([type, entry]) => (
+ <option key={type} value={type}>
+ {t(entry.label)}
+ </option>
+ ))}
+ </select>
+ </label>
+ <span className="ml-auto text-xs tabular-nums text-muted-foreground">
+ {t('botCount', { count: visibleConnections.length })}
+ </span>
+ </div>
+ )}
+ {!canManage && (
+ <p className="rounded-lg bg-muted p-4 text-sm">{t('adminOnly')}</p>
+ )}
+ {(connections.error || mutation.error) && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('error', {
+ error: (connections.error || mutation.error)?.message,
+ })}
+ </p>
+ )}
+ <Dialog open={choosing} onOpenChange={setChoosing}>
+ <DialogContent className="max-h-[85svh] overflow-y-auto sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{t('addBot')}</DialogTitle>
+ <DialogDescription>{t('chooseBotChannel')}</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-2">
+ {Object.entries(providers).map(([type, entry]) => (
+ <div
+ key={type}
+ className="flex min-h-16 items-center justify-between gap-4 rounded-lg border px-4 py-3"
+ >
+ <h3 className="text-sm font-medium">{t(entry.label)}</h3>
+ <Button
+ size="sm"
+ disabled={!canManage}
+ onClick={() => {
+ setChoosing(false)
+ setNewType(type)
+ setEditing('new')
+ }}
+ >
+ <PlusIcon className="size-4" />
+ {t(entry.addLabel)}
+ </Button>
+ </div>
+ ))}
+ {upcomingProviders.map((name) => (
+ <div
+ key={name}
+ className="flex min-h-16 items-center justify-between gap-4 rounded-lg border px-4 py-3"
+ >
+ <h3 className="text-sm font-medium text-muted-foreground">
+ {name === 'DingTalk' ? t('dingtalk') : name}
+ </h3>
+ <span className="rounded-full bg-muted px-3 py-1 text-xs text-muted-foreground">
+ {t('comingSoon')}
+ </span>
+ </div>
+ ))}
+ </div>
+ </DialogContent>
+ </Dialog>
+ {canManage && (
+ <div className="space-y-2">
+ {connections.isPending ? (
+ <p role="status" className="text-sm text-muted-foreground">
+ {t('loading')}
+ </p>
+ ) : !connections.error && visibleConnections.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t(
+ search || channelFilter !== 'all'
+ ? 'noMatchingBots'
+ : 'noConnectedBots',
+ )}
+ </p>
+ ) : null}
+ </div>
+ )}
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,28rem),1fr))] items-start gap-4">
+ {visibleConnections.map((connection) => {
+ const entry = getProvider(connection.type)
+ const Credentials = entry?.Credentials
+ return (
+ <div
+ key={connection.id}
+ className="min-w-0 rounded-xl border bg-card p-4 transition-colors hover:border-primary/30 sm:p-5"
+ >
+ <div className="flex items-start gap-3">
+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
+ <BotIcon className="size-5" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="truncate font-medium">
+ {connection.bot_name}
+ </h3>
+ <span
+ className={`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs ${connection.enabled && connection.status.state === 'connected' ? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-400' : 'bg-muted text-muted-foreground'}`}
+ >
+ <span className="size-1.5 rounded-full bg-current" />
+ {t(
+ `state.${connection.enabled ? (connection.status.state as 'connected' | 'connecting') : 'paused'}`,
+ )}
+ </span>
+ </div>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {entry ? t(entry.label) : connection.type}
+ {entry && <> · {t(entry.summary(connection))}</>}
+ </p>
+ <dl className="mt-3 flex flex-wrap gap-x-6 gap-y-2 text-xs">
+ <div className="flex min-w-0 gap-2">
+ <dt className="text-muted-foreground">
+ {t('runtimeUser')}
+ </dt>
+ <dd className="truncate">{connection.identity_user}</dd>
+ </div>
+ {connection.status.last_received && (
+ <div className="flex gap-2">
+ <dt className="text-muted-foreground">
+ {t('lastReceived')}
+ </dt>
+ <dd>
+ {new Date(
+ connection.status.last_received,
+ ).toLocaleString()}
+ </dd>
+ </div>
+ )}
+ {connection.status.last_sent && (
+ <div className="flex gap-2">
+ <dt className="text-muted-foreground">
+ {t('lastSent')}
+ </dt>
+ <dd>
+ {new Date(
+ connection.status.last_sent,
+ ).toLocaleString()}
+ </dd>
+ </div>
+ )}
+ </dl>
+ </div>
+ </div>
+ <div className="mt-4 flex flex-wrap items-center gap-1">
+ <Button
+ variant="outline"
+ onClick={() => setEditing(connection.id)}
+ >
+ {t(
+ connection.setup_mode !== 'qr' ||
+ connection.step >= 5 ||
+ connection.step === 4
+ ? 'viewSetup'
+ : 'continueSetup',
+ )}
+ </Button>
+ <Button
+ variant="ghost"
+ disabled={mutation.isPending}
+ onClick={() =>
+ mutation.mutate({
+ connection,
+ action: connection.enabled ? 'pause' : 'resume',
+ })
+ }
+ >
+ {t(connection.enabled ? 'pause' : 'resume')}
+ </Button>
+ {entry && (
+ <entry.Settings
+ connection={connection}
+ onSaved={() => {
+ void client.invalidateQueries({ queryKey: key })
+ }}
+ />
+ )}
+ {Credentials && (
+ <Credentials
+ connection={connection}
+ onSaved={() => {
+ void client.invalidateQueries({ queryKey: key })
+ }}
+ />
+ )}
+ <DeleteConnection
+ connection={connection}
+ title={connection.bot_name}
+ onDeleted={() => {
+ client.setQueryData<Connection[]>(key, (old) =>
+ (old ?? []).filter((item) => item.id !== connection.id),
+ )
+ void client.invalidateQueries({
+ queryKey: ['vikingbot', scope],
+ })
+ }}
+ />
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-components/conversation-row.tsx b/web-studio/src/routes/vikingbot/-components/conversation-row.tsx
new file mode 100644
index 000000000..a882a8df3
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-components/conversation-row.tsx
@@ -0,0 +1,59 @@
+import type { ReactNode } from 'react'
+
+export function ConversationRow({
+ title,
+ subtitle,
+ time,
+ icon,
+ selected,
+ onSelect,
+ action,
+}: {
+ title: string
+ subtitle: string
+ time?: string
+ icon: ReactNode
+ selected: boolean
+ onSelect: () => void
+ action?: ReactNode
+}) {
+ const date =
+ time && !Number.isNaN(Date.parse(time)) ? new Date(time) : undefined
+ return (
+ <div
+ className={`group/conversation relative mt-1 rounded-lg hover:bg-muted ${selected ? 'bg-muted' : ''}`}
+ >
+ <button
+ type="button"
+ onClick={onSelect}
+ aria-pressed={selected}
+ className="block w-full min-w-0 p-3 text-left text-sm"
+ >
+ <span className="flex h-5 items-center gap-2 pr-9">
+ <span className="shrink-0 text-muted-foreground">{icon}</span>
+ <span className="min-w-0 flex-1 truncate font-medium">{title}</span>
+ </span>
+ <span className="mt-1.5 flex h-4 items-center justify-between gap-2 text-xs text-muted-foreground">
+ <span className="truncate rounded bg-muted px-1.5 py-0.5 text-[11px]">
+ {subtitle}
+ </span>
+ {date && (
+ <time
+ className="shrink-0"
+ dateTime={time}
+ title={date.toLocaleString()}
+ >
+ {date.toLocaleString(undefined, {
+ month: 'numeric',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit',
+ })}
+ </time>
+ )}
+ </span>
+ </button>
+ {action && <div className="absolute right-1 top-1">{action}</div>}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-components/delete-connection.tsx b/web-studio/src/routes/vikingbot/-components/delete-connection.tsx
new file mode 100644
index 000000000..cb2eae479
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-components/delete-connection.tsx
@@ -0,0 +1,95 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Trash2Icon } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '#/components/ui/alert-dialog'
+import { useMutation } from '@tanstack/react-query'
+import { deleteConnection } from '../-api'
+import type { Connection } from '../-api'
+
+export function DeleteConnection({
+ connection,
+ title,
+ onDeleted,
+}: {
+ connection: Connection
+ title: string
+ onDeleted: () => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const [open, setOpen] = useState(false)
+ const mutation = useMutation({
+ mutationFn: () => deleteConnection(connection),
+ })
+ return (
+ <>
+ <Button
+ variant="ghost"
+ className="mr-1 shrink-0 text-muted-foreground hover:text-destructive"
+ aria-label={t('deleteConnection', { title })}
+ onClick={() => {
+ mutation.reset()
+ setOpen(true)
+ }}
+ >
+ <Trash2Icon className="size-4" />
+ {t('deleteConnection')}
+ </Button>
+ <AlertDialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!mutation.isPending) setOpen(value)
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t('deleteConnection')}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t('deleteConnectionHint', { title })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('deleteFailed', { error: mutation.error.message })}
+ </p>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={mutation.isPending}>
+ {t('cancelDelete')}
+ </AlertDialogCancel>
+ <AlertDialogAction
+ className="bg-destructive text-white hover:bg-destructive/90"
+ disabled={mutation.isPending}
+ onClick={async (event) => {
+ event.preventDefault()
+ if (mutation.isPending) return
+ try {
+ await mutation.mutateAsync()
+ setOpen(false)
+ onDeleted()
+ } catch {
+ // Keep the dialog and error visible so the user can retry.
+ }
+ }}
+ >
+ {t(
+ mutation.isPending
+ ? 'deletingConnection'
+ : 'confirmDeleteConnection',
+ )}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-components/platform-history.tsx b/web-studio/src/routes/vikingbot/-components/platform-history.tsx
new file mode 100644
index 000000000..181150aa8
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-components/platform-history.tsx
@@ -0,0 +1,91 @@
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
+import { UsersIcon } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { getConversations, getMessages } from '../-api'
+
+export function PlatformHistory({
+ connection,
+ conversation,
+ scope,
+}: {
+ connection: string
+ conversation: string
+ scope: string
+}) {
+ const { t } = useTranslation('vikingbot')
+ const conversations = useQuery({
+ queryKey: ['vikingbot', scope, connection, 'conversations'],
+ queryFn: () => getConversations(connection),
+ refetchInterval: 5000,
+ })
+ const title = conversations.data?.find(
+ (item) => item.conversation === conversation,
+ )?.title
+ const query = useInfiniteQuery({
+ queryKey: ['vikingbot', scope, connection, conversation, 'messages'],
+ initialPageParam: 0,
+ queryFn: ({ pageParam }) =>
+ getMessages(connection, conversation, pageParam),
+ getNextPageParam: (page) => (page.length > 100 ? page[99].id : undefined),
+ refetchInterval: 5000,
+ })
+ const messages = [
+ ...(query.data?.pages.flatMap((page) => page.slice(0, 100)) ?? []),
+ ].reverse()
+ return (
+ <section className="flex h-full flex-col">
+ <div className="border-b p-4">
+ <h2 className="flex items-center gap-2 font-medium">
+ <UsersIcon className="size-4 shrink-0 text-muted-foreground" />
+ <span className="truncate">{title || t('newChat')}</span>
+ </h2>
+ <p className="mt-1 text-xs text-muted-foreground">{t('historyHint')}</p>
+ </div>
+ <div className="flex-1 space-y-5 overflow-auto p-4 md:p-8">
+ {query.hasNextPage && (
+ <Button
+ variant="outline"
+ disabled={query.isFetchingNextPage}
+ onClick={() => void query.fetchNextPage()}
+ >
+ {t('earlier')}
+ </Button>
+ )}
+ {query.isPending && <p role="status">{t('loading')}</p>}
+ {query.error && (
+ <p role="alert" className="text-destructive">
+ {t('operationFailed')} {query.error.message}
+ </p>
+ )}
+ {!query.isPending && !messages.length && (
+ <p className="text-sm text-muted-foreground">{t('noHistory')}</p>
+ )}
+ {messages.map((message) => (
+ <article
+ key={message.id}
+ className="mx-auto max-w-3xl rounded-xl border p-4"
+ >
+ <div className="mb-2 flex flex-wrap justify-between gap-2 text-xs text-muted-foreground">
+ <span>{message.sender || t('unknownSender')}</span>
+ <time>{new Date(message.time).toLocaleString()}</time>
+ </div>
+ <p className="whitespace-pre-wrap break-words text-sm leading-7">
+ {message.content}
+ </p>
+ <p
+ className={`mt-2 text-xs ${message.status === 'send_failed' ? 'text-destructive' : 'text-muted-foreground'}`}
+ >
+ {t(
+ `delivery.${message.status as 'received' | 'sent' | 'send_failed'}`,
+ )}
+ </p>
+ </article>
+ ))}
+ </div>
+ <p className="border-t p-4 text-center text-sm text-muted-foreground">
+ {t('readonly')}
+ </p>
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-components/runtime-user-select.tsx b/web-studio/src/routes/vikingbot/-components/runtime-user-select.tsx
new file mode 100644
index 000000000..c8c6d0541
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-components/runtime-user-select.tsx
@@ -0,0 +1,96 @@
+import { useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { getBotUsers } from '../-api'
+
+export function useRuntimeUserSelection(enabled: boolean) {
+ const { identityScopeKey } = useAppConnection()
+ const [userId, setUserId] = useState('')
+ const users = useQuery({
+ queryKey: ['vikingbot', identityScopeKey, 'users'],
+ queryFn: getBotUsers,
+ enabled,
+ retry: false,
+ })
+ const available = users.isSuccess
+ ? users.data.filter((user) => user.available)
+ : []
+ const selectedUser = available.some((user) => user.user_id === userId)
+ ? userId
+ : available.length === 1
+ ? available[0].user_id
+ : ''
+ return { users, available, selectedUser, setUserId }
+}
+
+export function RuntimeUserSelect({
+ selection,
+ disabled = false,
+}: {
+ selection: ReturnType<typeof useRuntimeUserSelection>
+ disabled?: boolean
+}) {
+ const { t } = useTranslation('vikingbot')
+ const { users, available, selectedUser, setUserId } = selection
+ return (
+ <div className="space-y-3">
+ <label className="grid gap-3 text-sm">
+ <span>{t('runtimeUser')}</span>
+ <select
+ aria-label={t('runtimeUser')}
+ className="h-9 w-full rounded-md border bg-background px-3 text-sm"
+ value={selectedUser}
+ disabled={disabled || users.isPending || users.isError}
+ onChange={(event) => setUserId(event.target.value)}
+ >
+ <option value="">
+ {t(users.isPending ? 'loading' : 'selectUser')}
+ </option>
+ {users.data?.map((user) => (
+ <option
+ key={user.user_id}
+ value={user.user_id}
+ disabled={!user.available}
+ >
+ {user.user_id}
+ {user.available ? '' : ` — ${t('userUnavailable')}`}
+ </option>
+ ))}
+ </select>
+ </label>
+ <p className="text-xs leading-6 text-muted-foreground">
+ {t('runtimeUserHint')}
+ </p>
+ {users.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('operationFailed')} {users.error.message}
+ </p>
+ )}
+ {users.isSuccess && available.length === 0 && (
+ <p className="text-sm text-muted-foreground">
+ {t('noUsers')}{' '}
+ <a
+ href="/users"
+ target="_blank"
+ rel="noreferrer"
+ className="text-primary underline"
+ >
+ {t('manageUsers')}
+ </a>
+ </p>
+ )}
+ {(users.isError || (users.isSuccess && available.length === 0)) && (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={disabled || users.isFetching}
+ onClick={() => void users.refetch()}
+ >
+ {t('retry')}
+ </Button>
+ )}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/api.ts b/web-studio/src/routes/vikingbot/-providers/feishu/api.ts
new file mode 100644
index 000000000..e4fa684b2
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/api.ts
@@ -0,0 +1,64 @@
+import { getOvResult, ovClient } from '#/lib/ov-client'
+import { botAccountBase } from '../../-api'
+
+export type OnboardingRun = {
+ id: string
+ type: string
+ state:
+ | 'initializing'
+ | 'waiting_for_scan'
+ | 'scanned'
+ | 'creating'
+ | 'configuring'
+ | 'publishing'
+ | 'awaiting_approval'
+ | 'ready'
+ | 'failed'
+ | 'expired'
+ | 'interrupted'
+ | 'cancelled'
+ name: string
+ user_id: string
+ qr?: string
+ expires_at?: number
+ error?: string
+ can_retry: boolean
+ app_id?: string
+ connection_id?: string
+ owner?: { user_name: string; tenant_name: string }
+}
+const base = () => `${botAccountBase()}/onboarding-runs`
+export function currentOnboarding() {
+ return getOvResult<OnboardingRun | null>(
+ ovClient.client.get({
+ url: `${base()}/current`,
+ query: { type: 'feishu' },
+ }),
+ )
+}
+export function getOnboarding(id: string) {
+ return getOvResult<OnboardingRun>(
+ ovClient.client.get({ url: `${base()}/${encodeURIComponent(id)}` }),
+ )
+}
+export function startOnboarding(body: {
+ user_id: string
+ name: string
+ request_id: string
+ settings: { thread_require_mention: boolean }
+}) {
+ return getOvResult<OnboardingRun>(
+ ovClient.client.post({ url: base(), body: { ...body, type: 'feishu' } }),
+ )
+}
+export function updateOnboarding(
+ id: string,
+ action: 'retry' | 'cancel' | 'manual',
+) {
+ return getOvResult<OnboardingRun>(
+ ovClient.client.post({
+ url: `${base()}/${encodeURIComponent(id)}/actions`,
+ body: { action },
+ }),
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/connect.test.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/connect.test.tsx
new file mode 100644
index 000000000..caaf0b691
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/connect.test.tsx
@@ -0,0 +1,204 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { FeishuConnect } from './connect'
+import zh from '#/i18n/locales/zh-CN/vikingbot'
+
+const api = vi.hoisted(() => ({
+ current: vi.fn(),
+ get: vi.fn(),
+ start: vi.fn(),
+ update: vi.fn(),
+ users: vi.fn(),
+ connections: vi.fn(),
+}))
+vi.mock('./api', () => ({
+ currentOnboarding: api.current,
+ getOnboarding: api.get,
+ startOnboarding: api.start,
+ updateOnboarding: api.update,
+}))
+vi.mock('../../-api', () => ({
+ getBotUsers: api.users,
+ getConnections: api.connections,
+ verifyConnection: vi.fn(),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'a' }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) =>
+ key.split('.').reduce<any>((value, part) => value?.[part], zh) || key,
+ }),
+}))
+const run = {
+ id: 'job',
+ type: 'feishu',
+ state: 'waiting_for_scan',
+ name: 'VikingBot',
+ user_id: 'bot',
+ qr: '{"qrlogin":{"token":"test-only"}}',
+ can_retry: false,
+}
+beforeEach(() => {
+ api.current.mockResolvedValue(null)
+ api.get.mockResolvedValue(run)
+ api.start.mockResolvedValue(run)
+ api.users.mockResolvedValue([{ user_id: 'bot', available: true }])
+ api.connections.mockResolvedValue([])
+})
+afterEach(() => {
+ cleanup()
+ vi.resetAllMocks()
+ vi.unstubAllGlobals()
+})
+function show() {
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+ }
+ >
+ <FeishuConnect onChange={vi.fn()} onClose={vi.fn()} />
+ </QueryClientProvider>,
+ )
+}
+it('selects the sole user and starts without app credentials', async () => {
+ show()
+ const button = await screen.findByRole('button', { name: zh.qr.start })
+ await waitFor(() =>
+ expect((button as HTMLButtonElement).disabled).toBe(false),
+ )
+ expect(screen.queryByLabelText('App Secret')).toBeNull()
+ fireEvent.click(button)
+ await screen.findByText(zh.qr.states.waiting_for_scan)
+ expect(api.start).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user_id: 'bot',
+ name: 'VikingBot',
+ request_id: expect.any(String),
+ settings: { thread_require_mention: true },
+ }),
+ )
+ expect(screen.getByTitle(zh.qr.scan)).toBeTruthy()
+})
+it('restores active tasks instead of creating another app', async () => {
+ api.current.mockResolvedValue(run)
+ show()
+ await screen.findByText(zh.qr.states.waiting_for_scan)
+ expect(api.start).not.toHaveBeenCalled()
+ expect(screen.queryByRole('button', { name: zh.qr.start })).toBeNull()
+})
+it('locks duplicate start requests', async () => {
+ api.start.mockReturnValue(new Promise(() => {}))
+ show()
+ const button = await screen.findByRole('button', { name: zh.qr.start })
+ await waitFor(() =>
+ expect((button as HTMLButtonElement).disabled).toBe(false),
+ )
+ fireEvent.click(button)
+ fireEvent.click(button)
+ await waitFor(() => expect(api.start).toHaveBeenCalledTimes(1))
+})
+it('hides expired QR and offers explicit retry', async () => {
+ const expired = { ...run, state: 'expired', can_retry: true }
+ api.current.mockResolvedValue(expired)
+ api.get.mockResolvedValue(expired)
+ show()
+ await screen.findByText(zh.qr.states.expired)
+ expect(screen.queryByTitle(zh.qr.scan)).toBeNull()
+ expect(screen.getByRole('button', { name: zh.qr.retryScan })).toBeTruthy()
+})
+it('does not offer group completion while awaiting approval', async () => {
+ const approval = { ...run, qr: undefined, state: 'awaiting_approval' }
+ api.current.mockResolvedValue(approval)
+ api.get.mockResolvedValue(approval)
+ show()
+ await screen.findByText(zh.qr.states.awaiting_approval)
+ expect(screen.queryByRole('button', { name: zh.test })).toBeNull()
+})
+it('does not retry uncertain creation', async () => {
+ const failed = {
+ ...run,
+ qr: undefined,
+ state: 'failed',
+ error: 'creation_uncertain',
+ can_retry: false,
+ }
+ api.current.mockResolvedValue(failed)
+ api.get.mockResolvedValue(failed)
+ show()
+ await screen.findByText(zh.qr.errors.creation_uncertain)
+ expect(screen.queryByRole('button', { name: zh.qr.retryScan })).toBeNull()
+})
+
+it('works on HTTP dev hosts without crypto.randomUUID', async () => {
+ vi.stubGlobal('crypto', {
+ getRandomValues: crypto.getRandomValues.bind(crypto),
+ })
+ show()
+ const button = await screen.findByRole('button', { name: zh.qr.start })
+ await waitFor(() =>
+ expect((button as HTMLButtonElement).disabled).toBe(false),
+ )
+ fireEvent.click(button)
+ await waitFor(() => expect(api.start).toHaveBeenCalledTimes(1))
+ expect(api.start.mock.calls[0][0].request_id).toMatch(
+ /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,
+ )
+})
+
+it('passes the selected group reply mode to QR onboarding', async () => {
+ show()
+ const button = await screen.findByRole('button', { name: zh.qr.start })
+ await waitFor(() =>
+ expect((button as HTMLButtonElement).disabled).toBe(false),
+ )
+ fireEvent.change(screen.getByLabelText(zh.replyMode), {
+ target: { value: 'false' },
+ })
+ fireEvent.click(button)
+ await waitFor(() =>
+ expect(api.start).toHaveBeenCalledWith(
+ expect.objectContaining({ settings: { thread_require_mention: false } }),
+ ),
+ )
+})
+
+it.each([
+ { users: [] },
+ { users: [{ user_id: 'unavailable', available: false }] },
+])(
+ 'offers user management and recovers after refreshing unavailable users: %j',
+ async ({ users }) => {
+ api.users.mockResolvedValueOnce(users)
+ show()
+ await screen.findByRole('link', { name: zh.manageUsers })
+ const submit = screen.getByRole<HTMLButtonElement>('button', {
+ name: zh.qr.start,
+ })
+ expect(submit.disabled).toBe(true)
+ api.users.mockResolvedValueOnce([{ user_id: 'recovered', available: true }])
+ fireEvent.click(screen.getByRole('button', { name: zh.retry }))
+ await waitFor(() =>
+ expect(
+ screen.getByLabelText<HTMLSelectElement>(zh.runtimeUser).value,
+ ).toBe('recovered'),
+ )
+ expect(submit.disabled).toBe(false)
+ expect(screen.queryByRole('link', { name: zh.manageUsers })).toBeNull()
+ },
+)
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/connect.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/connect.tsx
new file mode 100644
index 000000000..5f9bd9396
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/connect.tsx
@@ -0,0 +1,322 @@
+import {
+ RuntimeUserSelect,
+ useRuntimeUserSelection,
+} from '../../-components/runtime-user-select'
+import { ReplyMode } from './reply-settings'
+import { useRef, useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { QRCodeSVG } from 'qrcode.react'
+import { Loader2Icon } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { createRandomUuid } from '#/lib/browser-crypto'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { getConnections } from '../../-api'
+import { FeishuSetup } from './feishu-setup'
+import { GroupSetup } from './group-setup'
+import {
+ currentOnboarding,
+ getOnboarding,
+ startOnboarding,
+ updateOnboarding,
+} from './api'
+import type { OnboardingRun } from './api'
+import type { Connection } from '../../-api'
+
+const STEP_LABELS = ['choose', 'scan', 'addGroup'] as const
+const finished = new Set([
+ 'ready',
+ 'failed',
+ 'expired',
+ 'interrupted',
+ 'cancelled',
+])
+const cancellable = new Set([
+ 'initializing',
+ 'waiting_for_scan',
+ 'scanned',
+ 'expired',
+])
+
+export function FeishuConnect(props: {
+ connection?: Connection
+ onChange: (connection: Connection) => void
+ onClose: () => void
+}) {
+ const [manual, setManual] = useState<Connection | boolean>(false)
+ if (manual || (props.connection && props.connection.setup_mode !== 'qr')) {
+ return (
+ <FeishuSetup
+ {...props}
+ connection={typeof manual === 'object' ? manual : props.connection}
+ />
+ )
+ }
+ return <ScanSetup {...props} onManual={(value) => setManual(value ?? true)} />
+}
+
+function ScanSetup({
+ connection,
+ onChange,
+ onClose,
+ onManual,
+}: {
+ connection?: Connection
+ onChange: (connection: Connection) => void
+ onClose: () => void
+ onManual: (connection?: Connection) => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const { identityScopeKey: scope } = useAppConnection()
+ const client = useQueryClient()
+ const [requireMention, setRequireMention] = useState(true)
+ const [name, setName] = useState('VikingBot')
+ const [jobId, setJobId] = useState(connection?.onboarding_id)
+ const busy = useRef(false)
+ const requestId = useRef(createRandomUuid())
+ const currentKey = ['vikingbot', scope, 'onboarding', 'current']
+ const current = useQuery({
+ queryKey: currentKey,
+ queryFn: currentOnboarding,
+ enabled: !jobId,
+ retry: false,
+ staleTime: 0,
+ })
+ const id = jobId ?? current.data?.id
+ const jobKey = ['vikingbot', scope, 'onboarding', id]
+ const job = useQuery({
+ queryKey: jobKey,
+ queryFn: () => getOnboarding(id!),
+ enabled: Boolean(id),
+ retry: false,
+ refetchInterval: (query) =>
+ query.state.data && finished.has(query.state.data.state) ? false : 1500,
+ })
+ const run = job.data ?? (current.data?.id === id ? current.data : undefined)
+ const userSelection = useRuntimeUserSelection(!id)
+ const { selectedUser } = userSelection
+ const connections = useQuery({
+ queryKey: ['vikingbot', scope, 'connections'],
+ queryFn: getConnections,
+ enabled: Boolean(run?.connection_id),
+ refetchInterval: run?.state === 'ready' ? 4000 : false,
+ })
+ const linked =
+ connection ??
+ connections.data?.find((item) => item.id === run?.connection_id)
+ const mutation = useMutation({
+ mutationFn: (action: 'start' | 'retry' | 'cancel' | 'manual') =>
+ action === 'start'
+ ? startOnboarding({
+ user_id: selectedUser,
+ settings: { thread_require_mention: requireMention },
+ name,
+ request_id: requestId.current,
+ })
+ : updateOnboarding(id!, action),
+ onSuccess: (value: OnboardingRun, action) => {
+ if (action === 'manual') {
+ client.setQueryData(currentKey, null)
+ onManual(linked)
+ return
+ }
+ if (value.state === 'cancelled') {
+ client.setQueryData(currentKey, null)
+ setJobId(undefined)
+ requestId.current = createRandomUuid()
+ } else {
+ client.setQueryData(['vikingbot', scope, 'onboarding', value.id], value)
+ setJobId(value.id)
+ }
+ },
+ })
+ function submit(action: 'start' | 'retry' | 'cancel' | 'manual') {
+ if (busy.current) return
+ busy.current = true
+ mutation.mutate(action, {
+ onSettled: () => {
+ busy.current = false
+ },
+ })
+ }
+ const error =
+ mutation.error || current.error || job.error || connections.error
+ const step = run?.state === 'ready' ? 2 : id ? 1 : 0
+ return (
+ <section className="mx-auto w-full min-w-0 max-w-4xl space-y-8 px-6 py-8 sm:px-8 lg:px-12 lg:py-10">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-xl font-semibold">{t('setupTitle')}</h2>
+ <p className="mt-2 text-sm text-muted-foreground">{t('qr.intro')}</p>
+ </div>
+ <Button variant="ghost" onClick={onClose}>
+ {t('qr.close')}
+ </Button>
+ </div>
+ <ol className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-3">
+ {STEP_LABELS.map((label, index) => (
+ <li
+ key={label}
+ aria-current={step === index ? 'step' : undefined}
+ className={`rounded-lg px-4 py-3 ${step === index ? 'bg-primary/10 font-medium text-primary' : 'text-muted-foreground'}`}
+ >
+ {index + 1}. {t(`qr.${label}`)}
+ </li>
+ ))}
+ </ol>
+ <div className="rounded-xl border p-6 sm:p-8">
+ {!id && current.isPending ? (
+ <p role="status">{t('loading')}</p>
+ ) : !id && !current.error ? (
+ <div className="space-y-6">
+ <RuntimeUserSelect
+ selection={userSelection}
+ disabled={mutation.isPending}
+ />
+ <ReplyMode
+ value={requireMention}
+ onChange={setRequireMention}
+ disabled={mutation.isPending}
+ />
+ <label className="grid gap-3 text-sm">
+ <span>{t('qr.botName')}</span>
+ <Input
+ className="h-11 px-4"
+ value={name}
+ maxLength={50}
+ onChange={(event) => setName(event.target.value)}
+ />
+ </label>
+ <p className="text-xs leading-6 text-muted-foreground">
+ {t('qr.consent')}
+ </p>
+ <Button
+ disabled={
+ !selectedUser ||
+ !name.trim() ||
+ mutation.isPending ||
+ current.isPending
+ }
+ onClick={() => submit('start')}
+ >
+ {mutation.isPending && (
+ <Loader2Icon className="size-4 animate-spin" />
+ )}
+ {t('qr.start')}
+ </Button>
+ </div>
+ ) : run?.state === 'ready' && linked ? (
+ <GroupSetup
+ connection={linked}
+ onChange={onChange}
+ onClose={onClose}
+ />
+ ) : (
+ <div className="space-y-4">
+ <p role="status" className="font-medium">
+ {run ? t(`qr.states.${run.state}`) : t('loading')}
+ </p>
+ {run?.qr && !finished.has(run.state) && (
+ <div className="w-fit rounded-xl bg-white p-4">
+ <QRCodeSVG
+ value={run.qr}
+ size={208}
+ marginSize={2}
+ title={t('qr.scan')}
+ />
+ </div>
+ )}
+ {run?.qr && (
+ <p className="text-sm text-muted-foreground">
+ {t('qr.scanHint')}
+ </p>
+ )}
+ {run && (
+ <p className="text-sm text-muted-foreground">
+ {t('runtimeUser')}: {run.user_id}
+ </p>
+ )}
+ {run?.owner && (
+ <p className="text-sm text-muted-foreground">
+ {run.owner.user_name} · {run.owner.tenant_name}
+ </p>
+ )}
+ {run?.state === 'awaiting_approval' && (
+ <p className="text-sm text-muted-foreground">
+ {t('qr.approvalHint')}
+ </p>
+ )}
+ {run?.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t(`qr.errors.${run.error}`, {
+ defaultValue: t('qr.errors.setup_failed'),
+ })}
+ </p>
+ )}
+ {run?.app_id && (
+ <a
+ className="inline-block text-sm underline"
+ target="_blank"
+ rel="noreferrer"
+ href={`https://open.feishu.cn/app/${encodeURIComponent(run.app_id)}`}
+ >
+ {t('openPlatform')}
+ </a>
+ )}
+ <div className="flex flex-wrap gap-3">
+ {run &&
+ ['failed', 'expired', 'interrupted'].includes(run.state) && (
+ <Button
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() => submit('manual')}
+ >
+ {t('qr.manualRecovery')}
+ </Button>
+ )}
+ {run?.can_retry && (
+ <Button
+ disabled={mutation.isPending}
+ onClick={() => submit('retry')}
+ >
+ {t('qr.retryScan')}
+ </Button>
+ )}
+ {run && cancellable.has(run.state) && (
+ <Button
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() => submit('cancel')}
+ >
+ {t('qr.cancel')}
+ </Button>
+ )}
+ </div>
+ </div>
+ )}
+ {error && (
+ <div className="mt-4 space-y-2">
+ <p role="alert" className="text-sm text-destructive">
+ {t('error', { error: error.message })}
+ </p>
+ <Button
+ variant="outline"
+ onClick={() => {
+ void current.refetch()
+ if (id) void job.refetch()
+ }}
+ >
+ {t('retry')}
+ </Button>
+ </div>
+ )}
+ </div>
+ {!id && (
+ <Button variant="link" onClick={() => onManual()}>
+ {t('qr.manual')}
+ </Button>
+ )}
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/connection-credentials.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/connection-credentials.tsx
new file mode 100644
index 000000000..caf4d8651
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/connection-credentials.tsx
@@ -0,0 +1,105 @@
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import {
+ Dialog,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from '#/components/ui/dialog'
+import { rotateCredentials } from '../../-api'
+import type { Connection } from '../../-api'
+
+export function ConnectionCredentials({
+ connection,
+ onSaved,
+}: {
+ connection: Connection
+ onSaved: () => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const [secret, setSecret] = useState('')
+ const [open, setOpen] = useState(false)
+ const mutation = useMutation({
+ mutationFn: () =>
+ rotateCredentials(
+ connection,
+ { app_secret: secret },
+ connection.identity_user,
+ ),
+ onSuccess: () => {
+ setSecret('')
+ setOpen(false)
+ onSaved()
+ },
+ })
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (mutation.isPending) return
+ setSecret('')
+ mutation.reset()
+ setOpen(value)
+ }}
+ >
+ <DialogTrigger render={<Button variant="ghost" />}>
+ {t('rotate')}
+ </DialogTrigger>
+ <DialogContent showCloseButton={!mutation.isPending}>
+ <DialogHeader>
+ <DialogTitle>{t('rotate')}</DialogTitle>
+ <DialogDescription>{t('rotateHint')}</DialogDescription>
+ </DialogHeader>
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (!mutation.isPending) mutation.mutate()
+ }}
+ >
+ <label className="block space-y-1 text-sm">
+ <span>{t('appSecret')}</span>
+ <Input
+ autoComplete="new-password"
+ type="password"
+ disabled={mutation.isPending}
+ value={secret}
+ onChange={(e) => setSecret(e.target.value)}
+ />
+ </label>
+ <p className="text-sm text-muted-foreground">
+ {t('runtimeUser')}: {connection.identity_user}
+ </p>
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('operationFailed')} {mutation.error.message}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() => {
+ setOpen(false)
+ setSecret('')
+ mutation.reset()
+ }}
+ >
+ {t('cancelEdit')}
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {t('saveCredentials')}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.test.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.test.tsx
new file mode 100644
index 000000000..f76b04cb0
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.test.tsx
@@ -0,0 +1,174 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { FeishuSetup } from './feishu-setup'
+import zh from '#/i18n/locales/zh-CN/vikingbot'
+import type { Connection } from '../../-api'
+
+const api = vi.hoisted(() => ({
+ create: vi.fn(),
+ update: vi.fn(),
+ users: vi.fn().mockResolvedValue([{ user_id: 'bot-user', available: true }]),
+}))
+vi.mock('../../-api', () => ({
+ createConnection: api.create,
+ verifyConnection: api.update,
+ getBotUsers: api.users,
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'test' }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => (zh as Record<string, unknown>)[key] || key,
+ }),
+}))
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+function show(connection?: Connection) {
+ const change = vi.fn()
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { mutations: { retry: false } } })
+ }
+ >
+ <FeishuSetup
+ connection={connection}
+ onChange={change}
+ onClose={vi.fn()}
+ />
+ </QueryClientProvider>,
+ )
+ return change
+}
+const connection: Connection = {
+ id: 'id',
+ app_id: 'cli_test',
+ bot_name: 'Bot',
+ enabled: true,
+ step: 4,
+ revision: 1,
+ identity_user: 'bot',
+ status: { state: 'connected' },
+}
+it('allows closing a saved connection without claiming publication', () => {
+ show(connection)
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.finish }).disabled,
+ ).toBe(false)
+})
+it('does not require outbound verification to close setup', () => {
+ show({
+ ...connection,
+ status: {
+ ...connection.status,
+ verification: {
+ code: 'ABC',
+ expires_at: Date.now() / 1000 + 60,
+ received: true,
+ sent: false,
+ },
+ },
+ })
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.finish }).disabled,
+ ).toBe(false)
+})
+it('keeps completion available after successful delivery', () => {
+ show({
+ ...connection,
+ status: {
+ ...connection.status,
+ verification: {
+ code: 'ABC',
+ expires_at: Date.now() / 1000 + 60,
+ received: true,
+ sent: true,
+ },
+ },
+ })
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.finish }).disabled,
+ ).toBe(false)
+})
+it('preserves credentials after validation failure and blocks duplicate submission', async () => {
+ let reject!: (error: Error) => void
+ api.create.mockImplementation(
+ () =>
+ new Promise((_resolve, rejectPromise) => {
+ reject = rejectPromise
+ }),
+ )
+ const changed = show()
+ fireEvent.change(screen.getByLabelText<HTMLInputElement>(zh.appId), {
+ target: { value: 'cli_test' },
+ })
+ fireEvent.change(screen.getByLabelText<HTMLInputElement>(zh.appSecret), {
+ target: { value: 'secret' },
+ })
+ await screen.findByRole('option', { name: 'bot-user' })
+ fireEvent.change(screen.getByLabelText<HTMLSelectElement>(zh.runtimeUser), {
+ target: { value: 'bot-user' },
+ })
+ fireEvent.change(screen.getByLabelText(zh.replyMode), {
+ target: { value: 'false' },
+ })
+ fireEvent.click(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.connect }),
+ )
+ await waitFor(() => expect(api.create).toHaveBeenCalledTimes(1))
+ expect(api.create).toHaveBeenCalledWith(
+ expect.objectContaining({ settings: { thread_require_mention: false } }),
+ )
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.connect })
+ .disabled,
+ ).toBe(true)
+ reject(new Error('Rejected'))
+ await screen.findByRole('alert')
+ expect(screen.getByLabelText<HTMLInputElement>(zh.appSecret).value).toBe(
+ 'secret',
+ )
+ expect(changed).not.toHaveBeenCalled()
+})
+
+it.each([
+ { users: [] },
+ { users: [{ user_id: 'unavailable', available: false }] },
+])(
+ 'offers user management and recovers after refreshing unavailable users: %j',
+ async ({ users }) => {
+ api.users.mockResolvedValueOnce(users)
+ show()
+ await screen.findByRole('link', { name: zh.manageUsers })
+ fireEvent.change(screen.getByLabelText(zh.appId), {
+ target: { value: 'cli_test' },
+ })
+ fireEvent.change(screen.getByLabelText(zh.appSecret), {
+ target: { value: 'secret' },
+ })
+ const submit = screen.getByRole<HTMLButtonElement>('button', {
+ name: zh.connect,
+ })
+ expect(submit.disabled).toBe(true)
+ api.users.mockResolvedValueOnce([{ user_id: 'recovered', available: true }])
+ fireEvent.click(screen.getByRole('button', { name: zh.retry }))
+ await waitFor(() =>
+ expect(
+ screen.getByLabelText<HTMLSelectElement>(zh.runtimeUser).value,
+ ).toBe('recovered'),
+ )
+ expect(submit.disabled).toBe(false)
+ expect(screen.queryByRole('link', { name: zh.manageUsers })).toBeNull()
+ },
+)
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.tsx
new file mode 100644
index 000000000..d21186626
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/feishu-setup.tsx
@@ -0,0 +1,141 @@
+import {
+ RuntimeUserSelect,
+ useRuntimeUserSelection,
+} from '../../-components/runtime-user-select'
+import { ReplyMode } from './reply-settings'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { ExternalLinkIcon, Loader2Icon } from 'lucide-react'
+import { useMutation } from '@tanstack/react-query'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { createConnection } from '../../-api'
+import { GroupSetup } from './group-setup'
+import type { Connection } from '../../-api'
+
+export function FeishuSetup({
+ connection,
+ onChange,
+ onClose,
+}: {
+ connection?: Connection
+ onChange: (connection: Connection) => void
+ onClose: () => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const [appId, setAppId] = useState('')
+ const [secret, setSecret] = useState('')
+ const [requireMention, setRequireMention] = useState(true)
+ const [created, setCreated] = useState<Connection>()
+ const current = connection ?? created
+ const userSelection = useRuntimeUserSelection(!current)
+ const { selectedUser } = userSelection
+ const mutation = useMutation({
+ mutationFn: () =>
+ createConnection({
+ type: 'feishu',
+ credentials: { app_id: appId.trim(), app_secret: secret.trim() },
+ user_id: selectedUser,
+ settings: { thread_require_mention: requireMention },
+ }),
+ onSuccess: (value) => {
+ setSecret('')
+ setCreated(value)
+ onChange(value)
+ },
+ })
+ return (
+ <section className="mx-auto w-full min-w-0 max-w-3xl space-y-6 px-6 py-8 sm:px-8">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h2 className="text-xl font-semibold">{t('manualTitle')}</h2>
+ <p className="mt-2 text-sm text-muted-foreground">
+ {t('manualHint')}
+ </p>
+ </div>
+ <Button variant="ghost" onClick={onClose}>
+ {t('qr.close')}
+ </Button>
+ </div>
+ {current ? (
+ <div className="rounded-xl border p-6 sm:p-8">
+ <GroupSetup
+ connection={current}
+ onChange={onChange}
+ onClose={onClose}
+ manual
+ />
+ </div>
+ ) : (
+ <div className="space-y-6 rounded-xl border p-6 sm:p-8">
+ <p className="text-sm leading-7">{t('credentialsHint')}</p>
+ <label className="grid gap-3 text-sm">
+ <span>{t('appId')}</span>
+ <Input
+ value={appId}
+ onChange={(e) => setAppId(e.target.value)}
+ autoComplete="off"
+ />
+ </label>
+ <label className="grid gap-3 text-sm">
+ <span>{t('appSecret')}</span>
+ <Input
+ type="password"
+ value={secret}
+ onChange={(e) => setSecret(e.target.value)}
+ autoComplete="new-password"
+ />
+ </label>
+ <RuntimeUserSelect
+ selection={userSelection}
+ disabled={mutation.isPending}
+ />
+
+ <ReplyMode
+ value={requireMention}
+ onChange={setRequireMention}
+ disabled={mutation.isPending}
+ />
+ <details className="rounded-lg border p-4">
+ <summary className="cursor-pointer text-sm font-medium">
+ {t('manualInstructions')}
+ </summary>
+ <div className="mt-4 space-y-3 text-sm leading-7 text-muted-foreground">
+ <p>{t('permissionsHint')}</p>
+ <p>{t('eventsHint')}</p>
+ <p>{t('publishHint')}</p>
+ <a
+ className="inline-flex items-center gap-2 text-primary underline"
+ href="https://open.feishu.cn/app"
+ target="_blank"
+ rel="noreferrer"
+ >
+ {t('openPlatform')}
+ <ExternalLinkIcon className="size-4" />
+ </a>
+ </div>
+ </details>
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('operationFailed')} {mutation.error.message}
+ </p>
+ )}
+ <Button
+ disabled={
+ !appId.trim() ||
+ !secret.trim() ||
+ !selectedUser ||
+ mutation.isPending
+ }
+ onClick={() => mutation.mutate()}
+ >
+ {mutation.isPending && (
+ <Loader2Icon className="size-4 animate-spin" />
+ )}
+ {t('connect')}
+ </Button>
+ </div>
+ )}
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.test.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.test.tsx
new file mode 100644
index 000000000..4dcd8f363
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.test.tsx
@@ -0,0 +1,41 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { GroupSetup } from './group-setup'
+import { verifyConnection } from '../../-api'
+
+vi.mock('../../-api', () => ({ verifyConnection: vi.fn() }))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+afterEach(cleanup)
+
+it('finishes published setup without a test or a verification mutation', () => {
+ const close = vi.fn()
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <GroupSetup
+ connection={{
+ id: 'bot',
+ app_id: 'app',
+ bot_name: 'Bot',
+ enabled: true,
+ step: 4,
+ revision: 1,
+ identity_user: 'default',
+ status: { state: 'connected' },
+ }}
+ onChange={vi.fn()}
+ onClose={close}
+ />
+ </QueryClientProvider>,
+ )
+ expect(screen.getByText('setupComplete')).toBeTruthy()
+ expect(screen.getByText('connectionHelp').closest('details')?.open).toBe(
+ false,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'finish' }))
+ expect(close).toHaveBeenCalledOnce()
+ expect(verifyConnection).not.toHaveBeenCalled()
+})
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx
new file mode 100644
index 000000000..2523df753
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/group-setup.tsx
@@ -0,0 +1,125 @@
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { CheckCircle2Icon } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { copyTextToClipboard } from '#/lib/clipboard'
+import { verifyConnection } from '../../-api'
+import type { Connection } from '../../-api'
+
+const ACTIVITY_FIELDS = ['last_received', 'last_sent'] as const
+const VERIFICATION_STAGES = ['received', 'sent'] as const
+
+export function GroupSetup({
+ connection,
+ onChange,
+ onClose,
+ manual = false,
+}: {
+ manual?: boolean
+ connection: Connection
+ onChange: (connection: Connection) => void
+ onClose: () => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const [copied, setCopied] = useState(false)
+ const [copyError, setCopyError] = useState(false)
+ const mutation = useMutation({
+ mutationFn: () => verifyConnection(connection),
+ onSuccess: onChange,
+ })
+ const verification = connection.status.verification
+
+ return (
+ <div className="space-y-4">
+ <CheckCircle2Icon className="size-9 text-green-600" />
+ <h3 className="font-semibold">
+ {t(manual ? 'manualConnected' : 'setupComplete')}
+ </h3>
+ {manual && (
+ <p className="text-sm text-muted-foreground">
+ {t('manualConnectedHint')}
+ </p>
+ )}
+ <p className="text-sm">
+ {t('connectedAs', {
+ name: connection.bot_name,
+ user: connection.identity_user,
+ })}
+ </p>
+ <p className="text-sm leading-7 text-muted-foreground">
+ {t('startUsingHint')}
+ </p>
+ <p className="text-xs text-muted-foreground">{t('qr.visibilityHint')}</p>
+ {!connection.enabled && <p role="alert">{t('qr.resumeFirst')}</p>}
+ <dl className="grid gap-4 rounded-lg bg-muted/50 p-4 sm:grid-cols-2">
+ {ACTIVITY_FIELDS.map((key) => (
+ <div key={key} className="space-y-1">
+ <dt className="text-xs text-muted-foreground">
+ {t(key === 'last_received' ? 'lastReceived' : 'sent')}
+ </dt>
+ <dd className="text-sm">
+ {connection.status[key]
+ ? new Date(connection.status[key]).toLocaleString()
+ : t('noActivity')}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <Button onClick={onClose}>{t('finish')}</Button>
+ <details className="rounded-lg border p-4">
+ <summary className="cursor-pointer text-sm font-medium">
+ {t('connectionHelp')}
+ </summary>
+ <div className="mt-4 space-y-4">
+ <p className="text-sm text-muted-foreground">{t('troubleshoot')}</p>
+ <p className="text-sm text-muted-foreground">{t('groupHint')}</p>
+ <Button
+ variant="outline"
+ disabled={mutation.isPending || !connection.enabled}
+ onClick={() => mutation.mutate()}
+ >
+ {t('test')}
+ </Button>
+ {verification && (
+ <div className="space-y-3 rounded-lg bg-muted p-4">
+ <p className="break-words font-mono text-sm">
+ {t('testText', { code: verification.code })}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={async () => {
+ try {
+ await copyTextToClipboard(
+ t('testText', { code: verification.code }),
+ )
+ setCopied(true)
+ setCopyError(false)
+ } catch {
+ setCopyError(true)
+ }
+ }}
+ >
+ {t(copied ? 'copied' : 'copy')}
+ </Button>
+ {copyError && <p role="alert">{t('qr.copyFailed')}</p>}
+ {VERIFICATION_STAGES.map((stage) => (
+ <p key={stage} role="status" className="text-sm">
+ {t(stage)} · {t(verification[stage] ? 'verified' : 'waiting')}
+ </p>
+ ))}
+ {verification.expires_at * 1000 < Date.now() &&
+ !verification.sent && <p role="alert">{t('expired')}</p>}
+ </div>
+ )}
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('operationFailed')} {mutation.error.message}
+ </p>
+ )}
+ </div>
+ </details>
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.test.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.test.tsx
new file mode 100644
index 000000000..8d6ca37f8
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.test.tsx
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { afterEach, expect, it, vi } from 'vitest'
+import { ReplySettings } from './reply-settings'
+import type { Connection } from '../../-api'
+import zh from '#/i18n/locales/zh-CN/vikingbot'
+
+const update = vi.hoisted(() => vi.fn())
+vi.mock('../../-api', () => ({ updateConnectionSettings: update }))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: keyof typeof zh) => zh[key] }),
+}))
+afterEach(() => {
+ cleanup()
+ vi.resetAllMocks()
+})
+it('keeps a failed selection for retry and saves against the connection revision', async () => {
+ const connection: Connection = {
+ id: 'c',
+ app_id: 'cli_test',
+ bot_name: 'Bot',
+ enabled: true,
+ step: 4,
+ revision: 3,
+ identity_user: 'bot',
+ status: { state: 'connected' },
+ }
+ const saved = vi.fn()
+ update.mockRejectedValueOnce(new Error('Rejected')).mockResolvedValueOnce({})
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { mutations: { retry: false } } })
+ }
+ >
+ <ReplySettings connection={connection} onSaved={saved} />
+ </QueryClientProvider>,
+ )
+ fireEvent.click(screen.getByRole('button', { name: zh.replyMode }))
+ const select = screen.getByRole<HTMLSelectElement>('combobox', {
+ name: zh.replyMode,
+ })
+ expect(select.value).toBe('true')
+ expect(
+ screen.getByRole<HTMLButtonElement>('button', { name: zh.saveReplyMode })
+ .disabled,
+ ).toBe(true)
+ fireEvent.change(select, { target: { value: 'false' } })
+ fireEvent.click(screen.getByRole('button', { name: zh.saveReplyMode }))
+ await screen.findByRole('alert')
+ expect(select.value).toBe('false')
+ expect(saved).not.toHaveBeenCalled()
+ expect(update).toHaveBeenCalledWith(connection, {
+ thread_require_mention: false,
+ })
+ fireEvent.click(screen.getByRole('button', { name: zh.saveReplyMode }))
+ await waitFor(() => expect(saved).toHaveBeenCalledTimes(1))
+})
diff --git a/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.tsx b/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.tsx
new file mode 100644
index 000000000..096e6482a
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/feishu/reply-settings.tsx
@@ -0,0 +1,120 @@
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import {
+ Dialog,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+ DialogFooter,
+} from '#/components/ui/dialog'
+import { updateConnectionSettings } from '../../-api'
+import type { Connection } from '../../-api'
+
+export function ReplyMode({
+ value,
+ onChange,
+ disabled = false,
+}: {
+ value: boolean
+ onChange: (value: boolean) => void
+ disabled?: boolean
+}) {
+ const { t } = useTranslation('vikingbot')
+ return (
+ <div className="space-y-2">
+ <label className="grid gap-2 text-sm">
+ <span>{t('replyMode')}</span>
+ <select
+ className="h-9 rounded-md border bg-background px-3"
+ value={String(value)}
+ disabled={disabled}
+ onChange={(event) => onChange(event.target.value === 'true')}
+ >
+ <option value="true">{t('onlyMention')}</option>
+ <option value="false">{t('withoutMention')}</option>
+ </select>
+ </label>
+ <p className="text-xs leading-6 text-muted-foreground">
+ {t(value ? 'mentionModeHint' : 'withoutMentionHint')}
+ </p>
+ {!value && (
+ <p className="text-xs leading-6 text-muted-foreground">
+ {t('groupMessagePermission')}
+ </p>
+ )}
+ </div>
+ )
+}
+
+export function ReplySettings({
+ connection,
+ onSaved,
+}: {
+ connection: Connection
+ onSaved: () => void
+}) {
+ const { t } = useTranslation('vikingbot')
+ const saved = connection.settings?.thread_require_mention !== false
+ const [required, setRequired] = useState(saved)
+ const [open, setOpen] = useState(false)
+ const mutation = useMutation({
+ mutationFn: () =>
+ updateConnectionSettings(connection, {
+ thread_require_mention: required,
+ }),
+ onSuccess: () => {
+ setOpen(false)
+ onSaved()
+ },
+ })
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (mutation.isPending) return
+ setRequired(saved)
+ mutation.reset()
+ setOpen(value)
+ }}
+ >
+ <DialogTrigger render={<Button variant="ghost" />}>
+ {t('replyMode')}
+ </DialogTrigger>
+ <DialogContent showCloseButton={!mutation.isPending}>
+ <DialogHeader>
+ <DialogTitle>{t('replyMode')}</DialogTitle>
+ <DialogDescription>{connection.bot_name}</DialogDescription>
+ </DialogHeader>
+ <ReplyMode
+ value={required}
+ onChange={setRequired}
+ disabled={mutation.isPending}
+ />
+ {mutation.error && (
+ <p role="alert" className="text-sm text-destructive">
+ {t('operationFailed')} {mutation.error.message}
+ </p>
+ )}
+ <DialogFooter>
+ <Button
+ variant="outline"
+ disabled={mutation.isPending}
+ onClick={() => setOpen(false)}
+ >
+ {t('cancelEdit')}
+ </Button>
+ <Button
+ disabled={required === saved || mutation.isPending}
+ onClick={() => mutation.mutate()}
+ >
+ {t(mutation.isPending ? 'savingReplyMode' : 'saveReplyMode')}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/-providers/registry.ts b/web-studio/src/routes/vikingbot/-providers/registry.ts
new file mode 100644
index 000000000..5a10a6d69
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-providers/registry.ts
@@ -0,0 +1,26 @@
+import { ReplySettings } from './feishu/reply-settings'
+import type { Connection } from '../-api'
+import { FeishuConnect } from './feishu/connect'
+import { ConnectionCredentials } from './feishu/connection-credentials'
+
+// Each supported platform owns its setup and credential UI.
+export const providers = {
+ feishu: {
+ label: 'feishu' as const,
+ addLabel: 'addFeishu' as const,
+ Setup: FeishuConnect,
+ Credentials: ConnectionCredentials,
+ Settings: ReplySettings,
+ summary: (connection: Connection) =>
+ connection.settings?.thread_require_mention === false
+ ? ('withoutMention' as const)
+ : ('onlyMention' as const),
+ },
+}
+export const upcomingProviders = ['Slack', 'DingTalk', 'Discord', 'Telegram']
+export function getProvider(type?: string) {
+ const key = type ?? 'feishu'
+ return Object.hasOwn(providers, key)
+ ? providers[key as keyof typeof providers]
+ : undefined
+}
diff --git a/web-studio/src/routes/vikingbot/-web-sessions.test.ts b/web-studio/src/routes/vikingbot/-web-sessions.test.ts
new file mode 100644
index 000000000..576ac5c49
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/-web-sessions.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest'
+import {
+ createVikingBotWebSessionId,
+ isVikingBotWebSession,
+} from '#/lib/sessions/vikingbot-sessions'
+
+describe('VikingBot web session ownership', () => {
+ it.each([
+ 'cx-01a098bf-0500-7ee2-9178-460fa176331f',
+ 'chatcrew-group-f23e11e8036f79be',
+ 'cli__default__7b3e8760',
+ '__openviking_resource_reason__',
+ '01a098bf-0500-7ee2-9178-460fa176331f',
+ 'vikingbot-web-unknown',
+ ])('does not relabel external or unclassified session %s', (session_id) => {
+ expect(isVikingBotWebSession({ session_id })).toBe(false)
+ })
+
+ it('recognizes persisted ownership independently of browser state', () => {
+ expect(
+ isVikingBotWebSession({
+ session_id: 'vikingbot-web-63507b10-0000-4000-8000-000000000001',
+ }),
+ ).toBe(true)
+ const first = createVikingBotWebSessionId()
+ expect(isVikingBotWebSession({ session_id: first })).toBe(true)
+ expect(createVikingBotWebSessionId()).not.toBe(first)
+ })
+})
+
+it('includes only explicitly registered legacy playground sessions', () => {
+ const legacy = 'f5216b16-cd10-4e9a-b542-a29576f2260c'
+ expect(isVikingBotWebSession({ session_id: legacy }, [legacy])).toBe(true)
+ expect(isVikingBotWebSession({ session_id: legacy }, [])).toBe(false)
+ expect(isVikingBotWebSession({ session_id: 'cx-other' }, [legacy])).toBe(
+ false,
+ )
+})
diff --git a/web-studio/src/routes/vikingbot/index.tsx b/web-studio/src/routes/vikingbot/index.tsx
new file mode 100644
index 000000000..b24cfb9e0
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/index.tsx
@@ -0,0 +1,354 @@
+import { useDefaultConversationTitles } from '#/lib/sessions/use-default-conversation-titles'
+import { ConversationRow } from './-components/conversation-row'
+import { readPlaygroundAgentSessionIds } from '#/routes/playground/-lib/utils'
+import { useState } from 'react'
+import { createFileRoute } from '@tanstack/react-router'
+import { useQueries, useQuery } from '@tanstack/react-query'
+import {
+ ArrowLeftIcon,
+ BotIcon,
+ PlusIcon,
+ MessageSquareIcon,
+ UsersIcon,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import {
+ useBotHealth,
+ useSessionListByRecency,
+} from '#/lib/sessions/use-sessions'
+import { useSessionTitles } from '#/lib/sessions/use-session-titles'
+import { Thread } from '#/routes/sessions/-components/thread'
+import { getCapabilities, getConnections, getConversations } from './-api'
+import {
+ createVikingBotWebSessionId,
+ isVikingBotWebSession,
+} from '#/lib/sessions/vikingbot-sessions'
+import { DeleteConversation } from '#/components/sessions/delete-conversation'
+import { Channels } from './-components/channels'
+import { PlatformHistory } from './-components/platform-history'
+
+const PAGE_TABS = ['conversations', 'channels'] as const
+const START_COMMAND = 'openviking-server --with-bot'
+
+export const Route = createFileRoute('/vikingbot/')({
+ component: VikingBotPage,
+})
+
+function VikingBotPage() {
+ const { identityScopeKey } = useAppConnection()
+ return <VikingBotWorkspace key={identityScopeKey} scope={identityScopeKey} />
+}
+
+function VikingBotWorkspace({ scope }: { scope: string }) {
+ const { t } = useTranslation('vikingbot')
+ const [tab, setTab] = useState<(typeof PAGE_TABS)[number]>('conversations')
+ const [selected, setSelected] = useState<{
+ id: string
+ connection?: string
+ draft?: boolean
+ }>()
+ const [filter, setFilter] = useState('all')
+ const [search, setSearch] = useState('')
+ const capabilities = useQuery({
+ queryKey: ['vikingbot', scope, 'capabilities'],
+ queryFn: getCapabilities,
+ retry: false,
+ })
+ const canManage = capabilities.data?.can_manage ?? false
+ const health = useBotHealth()
+ const connections = useQuery({
+ queryKey: ['vikingbot', scope, 'connections'],
+ queryFn: getConnections,
+ enabled: canManage,
+ })
+ const hasFeishu =
+ canManage &&
+ connections.data?.some(
+ (connection) => (connection.type ?? 'feishu') === 'feishu',
+ )
+ const sourceFilters = hasFeishu ? (['all', 'web', 'feishu'] as const) : []
+ const activeFilter = hasFeishu ? filter : 'all'
+ const sessions = useSessionListByRecency()
+ const { getTitle, removeTitle } = useSessionTitles(scope)
+ useDefaultConversationTitles(
+ scope,
+ sessions.data
+ .filter((session) =>
+ isVikingBotWebSession(session, readPlaygroundAgentSessionIds(scope)),
+ )
+ .map((session) => session.session_id),
+ )
+ const platformQueries = useQueries({
+ queries: (connections.data ?? []).map((connection) => ({
+ queryKey: ['vikingbot', scope, connection.id, 'conversations'],
+ queryFn: () => getConversations(connection.id),
+ refetchInterval: 5000,
+ enabled: canManage,
+ })),
+ })
+ const rows = [
+ ...sessions.data
+ .filter((session) =>
+ isVikingBotWebSession(session, readPlaygroundAgentSessionIds(scope)),
+ )
+ .map((session) => ({
+ id: session.session_id,
+ connection: undefined as string | undefined,
+ title:
+ getTitle(session.session_id) === session.session_id
+ ? t('newChat')
+ : getTitle(session.session_id),
+ time: session.mod_time,
+ channel: 'web',
+ groupName: '',
+ })),
+ ...platformQueries.flatMap((query, index) =>
+ (query.data ?? []).map((item) => ({
+ id: item.conversation,
+ connection: connections.data![index].id,
+ title: item.title || t('newChat'),
+ time: item.time,
+ channel: connections.data![index].type ?? 'feishu',
+ groupName: item.group_name ?? '',
+ })),
+ ),
+ ]
+ .filter(
+ (row) =>
+ (activeFilter === 'all' || row.channel === activeFilter) &&
+ `${row.title} ${row.groupName}`
+ .toLowerCase()
+ .includes(search.toLowerCase()),
+ )
+ .sort(
+ (a, b) =>
+ (Date.parse(b.time ?? '') || 0) - (Date.parse(a.time ?? '') || 0),
+ )
+ function create() {
+ setSelected({ id: createVikingBotWebSessionId(), draft: true })
+ }
+ function select(id: string, connection?: string) {
+ setSelected({ id, connection })
+ }
+ return (
+ <div className="-mx-4 -my-6 flex h-[calc(100svh-3rem)] min-w-0 flex-col overflow-hidden md:-mx-6">
+ <header className="flex shrink-0 flex-col items-start gap-4 border-b px-4 pt-4 md:px-6">
+ <h1 className="flex items-center gap-2 font-semibold">
+ <BotIcon className="size-5 text-primary" />
+ {t('title')}
+ </h1>
+ <div role="tablist" aria-label={t('title')} className="flex gap-6">
+ {PAGE_TABS.map((value) => (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === value}
+ key={value}
+ className={`-mb-px border-b-2 px-1 pb-3 text-sm font-medium transition-colors ${tab === value ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
+ onClick={() => setTab(value)}
+ >
+ {t(value)}
+ </button>
+ ))}
+ </div>
+ </header>
+ {capabilities.isPending ? (
+ <p role="status" className="p-8">
+ {t('loading')}
+ </p>
+ ) : capabilities.error ? (
+ <div role="alert" className="p-8">
+ <p>
+ {t('operationFailed')} {capabilities.error.message}
+ </p>
+ <Button onClick={() => void capabilities.refetch()}>
+ {t('retry')}
+ </Button>
+ </div>
+ ) : !capabilities.data.enabled ? (
+ <div className="m-auto max-w-xl space-y-4 p-8">
+ <h2 className="text-xl font-semibold">{t('enable')}</h2>
+ <p>{t('enableHint')}</p>
+ <code className="block rounded-lg bg-muted p-4">{START_COMMAND}</code>
+ <p className="text-sm text-muted-foreground">{t('modelHint')}</p>
+ <Button
+ onClick={() => {
+ void capabilities.refetch()
+ void health.refetch()
+ }}
+ >
+ {t('retry')}
+ </Button>
+ </div>
+ ) : tab === 'channels' ? (
+ <div className="flex-1 overflow-auto">
+ <Channels canManage={canManage} scope={scope} />
+ </div>
+ ) : (
+ <div className="flex min-h-0 flex-1">
+ <aside
+ className={`${selected ? 'hidden md:flex' : 'flex'} w-full shrink-0 flex-col border-r md:w-72`}
+ >
+ <div className="space-y-3 border-b p-3">
+ <Button
+ className="w-full"
+ disabled={health.isError}
+ onClick={() => void create()}
+ >
+ <PlusIcon className="size-4" />
+ {t('newChat')}
+ </Button>
+ <Input
+ aria-label={t('search')}
+ placeholder={t('search')}
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ {sourceFilters.length > 0 && (
+ <div className="flex gap-1">
+ {sourceFilters.map((value) => (
+ <Button
+ size="sm"
+ variant={activeFilter === value ? 'secondary' : 'ghost'}
+ key={value}
+ onClick={() => setFilter(value)}
+ >
+ {t(value)}
+ </Button>
+ ))}
+ </div>
+ )}
+ </div>
+ <div className="flex-1 overflow-auto p-2">
+ {platformQueries.map(
+ (query, index) =>
+ query.error && (
+ <p
+ key={index}
+ role="alert"
+ className="p-2 text-sm text-destructive"
+ >
+ {t('operationFailed')} {query.error.message}
+ </p>
+ ),
+ )}
+ {rows.map((row) => (
+ <ConversationRow
+ key={`${row.connection ?? 'web'}:${row.id}`}
+ title={row.title}
+ subtitle={
+ row.groupName
+ ? `${t(row.channel)}-${row.groupName}`
+ : t(row.channel)
+ }
+ time={row.time}
+ icon={
+ row.connection ? (
+ <UsersIcon className="size-4" />
+ ) : (
+ <MessageSquareIcon className="size-4" />
+ )
+ }
+ selected={
+ selected?.id === row.id &&
+ selected.connection === row.connection
+ }
+ onSelect={() => select(row.id, row.connection)}
+ action={
+ !row.connection ? (
+ <DeleteConversation
+ id={row.id}
+ title={row.title}
+ onDeleted={() => {
+ removeTitle(row.id)
+ setSelected((current) =>
+ current?.id === row.id && !current.connection
+ ? undefined
+ : current,
+ )
+ }}
+ />
+ ) : undefined
+ }
+ />
+ ))}
+ {activeFilter === 'feishu' && !canManage && (
+ <p className="p-3 text-sm text-muted-foreground">
+ {t('adminOnly')}
+ </p>
+ )}
+ </div>
+ </aside>
+ <main
+ className={`${selected ? 'flex' : 'hidden md:flex'} min-w-0 flex-1 flex-col`}
+ >
+ {selected && (
+ <Button
+ variant="ghost"
+ className="self-start md:hidden"
+ onClick={() => setSelected(undefined)}
+ >
+ <ArrowLeftIcon className="size-4" />
+ {t('back')}
+ </Button>
+ )}
+ {health.isError && (
+ <div
+ role="alert"
+ className="flex items-center justify-between gap-3 border-b p-3 text-sm text-destructive"
+ >
+ {t('connectionError')}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void health.refetch()}
+ >
+ {t('retry')}
+ </Button>
+ </div>
+ )}
+ <div className="min-h-0 flex-1">
+ {selected ? (
+ selected.connection ? (
+ <PlatformHistory
+ key={`${selected.connection}:${selected.id}`}
+ scope={scope}
+ connection={selected.connection}
+ conversation={selected.id}
+ />
+ ) : (
+ <Thread
+ key={selected.id}
+ sessionId={selected.id}
+ draft={selected.draft}
+ onPersisted={() =>
+ setSelected((current) =>
+ current?.id === selected.id && !current.connection
+ ? { ...current, draft: false }
+ : current,
+ )
+ }
+ />
+ )
+ ) : (
+ <div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
+ <BotIcon className="size-12 text-primary" />
+ <h2 className="text-xl font-semibold">{t('empty')}</h2>
+ <p className="max-w-md text-sm text-muted-foreground">
+ {t('emptyHint')}
+ </p>
+ <Button variant="outline" onClick={() => setTab('channels')}>
+ {t('addFeishu')}
+ </Button>
+ </div>
+ )}
+ </div>
+ </main>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/vikingbot/route.tsx b/web-studio/src/routes/vikingbot/route.tsx
new file mode 100644
index 000000000..f522504ee
--- /dev/null
+++ b/web-studio/src/routes/vikingbot/route.tsx
@@ -0,0 +1,3 @@
+import { createFileRoute, Outlet } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/vikingbot')({ component: Outlet })