Compare commits

..

1 Commits

Author SHA1 Message Date
TyperBody 9fe80eaf64 newplatfrom 2026-09-09 23:37:51 +08:00
11 changed files with 735 additions and 623 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

+587
View File
@@ -0,0 +1,587 @@
"""ESPL V3 adapter — WebSocket server for E-SP-Line2's Adapter Gateway (接入器).
LangBot acts as a server-mode WebSocket endpoint. E-SP-Line2's adapter (接入器)
in **client mode** connects to this endpoint (or a reverse proxy forwards it)
and exchanges e-commerce messages:
* **Inbound** — E-SP-Line2 broadcasts ``message.received`` envelopes to every
connected adapter client. This adapter converts each envelope into a LangBot
``FriendMessage`` / ``GroupMessage`` event (the ``conversation_id`` maps to
the LangBot launcher/session id) and fires it into the normal pipeline.
* **Outbound** — every ``reply_message`` / ``reply_message_chunk`` the pipeline
emits is converted into an ESPL v3 outbound ``message`` frame
(``command_type: send_text``) and sent back over the WebSocket that carries
the matching conversation.
Design notes:
* Listens on ``ws://<host>:<port>/ws`` (default ``ws://127.0.0.1:8000/ws``).
In E-SP-Line2 create a **client-mode** 接入器 with ``ws_url`` pointing here.
* Supports multiple simultaneous E-SP-Line2 connections. Each connection is
identified by its ``adapter_id`` (from the ``key``/path) so outbound replies
route back to the correct connection.
* Heartbeats: responds to ``ping`` frames with ``pong``; the E-SP-Line2
gateway also sends server pings that we answer automatically via the
websockets library.
* The ``conversation_id`` from the inbound envelope is used as the LangBot
launcher id so each e-commerce conversation maps 1:1 to an isolated LangBot
session. Replies are routed back to the same ``conversation_id``.
* ``instance_id`` is captured from the inbound envelope and stashed on the
event's ``source_platform_object``.
See docs/user-guide/adapter-gateway.md in the E-SP-Line2 repo for the full
ESPL v3 protocol reference.
"""
from __future__ import annotations
import asyncio
import json
import logging
import time
import typing
import uuid
from datetime import datetime
import pydantic
import websockets
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
import langbot_plugin.api.entities.builtin.platform.message as platform_message
import langbot_plugin.api.entities.builtin.platform.events as platform_events
import langbot_plugin.api.entities.builtin.platform.entities as platform_entities
import langbot_plugin.api.definition.abstract.platform.event_logger as abstract_platform_logger
logger = logging.getLogger(__name__)
# Default listen host / port (E-SP-Line2 client-mode 接入器 connects here).
_DEFAULT_HOST = '127.0.0.1'
_DEFAULT_PORT = 8000
# Default heartbeat ping interval (seconds).
_DEFAULT_HEARTBEAT_INTERVAL = 30
# Max inbound frame size (1MB, matches E-SP-Line2 gateway).
_MAX_MESSAGE_SIZE = 1 * 1024 * 1024
class _EsplConnection:
"""A single connected E-SP-Line2 adapter gateway client.
Holds the WebSocket plus the routing info needed to reply.
"""
def __init__(self, ws, adapter_id: str = ''):
self.ws = ws
self.adapter_id = adapter_id
self.send_lock = asyncio.Lock()
async def send_frame(self, frame: dict) -> None:
async with self.send_lock:
await self.ws.send(json.dumps(frame, ensure_ascii=False))
class EsplAdapter(abstract_platform_adapter.AbstractMessagePlatformAdapter):
"""ESPL V3 WebSocket server adapter (LangBot is the server)."""
bot_uuid: str = pydantic.Field(default='', exclude=True)
listeners: dict[
typing.Type[platform_events.Event],
typing.Callable[[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], None],
] = pydantic.Field(default_factory=dict, exclude=True)
# WebSocket server state (excluded from pydantic serialization).
server: typing.Any = pydantic.Field(default=None, exclude=True)
running: bool = pydantic.Field(default=False, exclude=True)
connections: dict[str, '_EsplConnection'] = pydantic.Field(default_factory=dict, exclude=True)
inbound_tasks: set[asyncio.Task] = pydantic.Field(default_factory=set, exclude=True)
heartbeat_task: asyncio.Task | None = pydantic.Field(default=None, exclude=True)
model_config = pydantic.ConfigDict(arbitrary_types_allowed=True)
def __init__(self, config: dict, logger: abstract_platform_logger.AbstractEventLogger, **kwargs):
super().__init__(config=config, logger=logger, **kwargs)
self.bot_account_id = 'espl'
self.listeners = {}
self.server = None
self.running = False
self.connections = {}
self.inbound_tasks = set()
self.heartbeat_task = None
# -- framework hooks ------------------------------------------------------
def set_bot_uuid(self, bot_uuid: str) -> None:
"""Called by the bot manager so the adapter knows its own bot uuid."""
object.__setattr__(self, 'bot_uuid', bot_uuid)
def get_launcher_id(self, event: platform_events.MessageEvent) -> str:
"""Map an inbound event to a LangBot launcher id.
We use the e-commerce ``conversation_id`` (stashed on the sender id at
inbound time) so each conversation maps 1:1 to an isolated LangBot
session.
"""
if isinstance(event, platform_events.GroupMessage):
return str(event.sender.group.id)
return str(event.sender.id)
def register_listener(
self,
event_type: typing.Type[platform_events.Event],
func: typing.Callable[
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], typing.Awaitable[None]
],
):
self.listeners[event_type] = func
def unregister_listener(
self,
event_type: typing.Type[platform_events.Event],
func: typing.Callable[
[platform_events.Event, abstract_platform_adapter.AbstractMessagePlatformAdapter], typing.Awaitable[None]
],
):
self.listeners.pop(event_type, None)
async def is_muted(self, group_id: int) -> bool:
return False
async def is_stream_output_supported(self) -> bool:
return False
# -- server lifecycle -----------------------------------------------------
async def run_async(self):
"""Start the WebSocket server and serve forever."""
host = str(self.config.get('host', _DEFAULT_HOST))
port = int(self.config.get('port', _DEFAULT_PORT))
self.running = True
self.server = await websockets.serve(
self._handle_connection,
host,
port,
ping_interval=None, # we manage heartbeats ourselves
max_size=_MAX_MESSAGE_SIZE,
)
await self.logger.info(f'ESPL adapter listening on ws://{host}:{port}/ws')
self.heartbeat_task = asyncio.create_task(self._heartbeat_loop())
try:
# Serve forever; run_async is expected to stay alive.
while self.running:
await asyncio.sleep(3600)
except asyncio.CancelledError:
raise
finally:
if self.server is not None:
self.server.close()
await self.server.wait_closed()
self.server = None
async def kill(self) -> bool:
"""Stop the server and close all connections."""
self.running = False
if self.heartbeat_task is not None and not self.heartbeat_task.done():
self.heartbeat_task.cancel()
self.heartbeat_task = None
for task in list(self.inbound_tasks):
if not task.done():
task.cancel()
self.inbound_tasks.clear()
for conn in list(self.connections.values()):
try:
await conn.ws.close()
except Exception:
pass
self.connections.clear()
return True
# -- connection handler ---------------------------------------------------
async def _handle_connection(self, ws):
"""Handle a new WebSocket connection from an E-SP-Line2 gateway client.
The E-SP-Line2 client-mode adapter connects with ``?key=<KEY>`` in the
query string. If the adapter has been configured with a non-empty
``key``, this method **rejects** connections that do not present a
matching key (close code 1008 — policy violation).
Note: websockets >= 14 removed the ``path`` / ``query_string``
attributes from the connection object. The request path (including
the query string) is available via ``ws.request.path``.
"""
# In websockets >= 14 the request path (with query string) lives on
# ``ws.request.path`` (e.g. ``/ws?key=abc``). Fall back to the legacy
# ``ws.path`` / ``ws.query_string`` attributes for older versions.
request = getattr(ws, 'request', None)
if request is not None:
raw_path = str(getattr(request, 'path', '') or '')
else:
raw_path = str(getattr(ws, 'path', '') or '')
path, _, query = raw_path.partition('?')
# ── Key authentication ──────────────────────────────────────────
expected_key = str(self.config.get('key') or '')
provided_key = self._extract_key(query)
if expected_key:
if not provided_key:
await self.logger.warning(
f'ESPL adapter key missing; closing connection from {raw_path}'
)
await ws.close(1008, 'Unauthorized: key missing')
return
if provided_key != expected_key:
await self.logger.warning(
f'ESPL adapter key mismatch; closing connection from {raw_path}'
)
await ws.close(1008, 'Unauthorized: invalid key')
return
# ── Identify the connection for routing ─────────────────────────
adapter_id = self._extract_adapter_id(path, query)
conn = _EsplConnection(ws, adapter_id=adapter_id)
conn_key = adapter_id or ('conn_' + uuid.uuid4().hex)
self.connections[conn_key] = conn
await self.logger.info(
f'ESPL adapter client connected: adapter_id={adapter_id or "(client-mode, no adapter-id in path)"} '
f'path={raw_path}'
)
# ── Send the connected handshake ────────────────────────────────
try:
await conn.send_frame(
{
'type': 'connected',
'id': uuid.uuid4().hex,
'timestamp': int(time.time() * 1000),
'adapter_id': adapter_id or '',
'gateway_version': 'v3',
'session_id': conn_key,
'adapter_name': self.config.get('name', 'ESPL'),
'platform': self.config.get('platform', ''),
}
)
except Exception as e:
await self.logger.warning(f'ESPL adapter handshake failed: {e}')
self.connections.pop(conn_key, None)
return
# ── Read loop ───────────────────────────────────────────────────
try:
async for raw in ws:
try:
frame = json.loads(raw)
except (json.JSONDecodeError, ValueError):
await self.logger.warning(f'ESPL adapter received non-JSON frame: {raw[:200]}')
continue
await self._handle_frame(conn, frame)
except websockets.exceptions.ConnectionClosed as e:
await self.logger.info(f'ESPL adapter client disconnected: {e.code} {e.reason}')
except asyncio.CancelledError:
raise
except Exception as e:
await self.logger.warning(f'ESPL adapter connection error: {e}')
finally:
self.connections.pop(conn_key, None)
@staticmethod
def _extract_adapter_id(path: str, query: str) -> str:
"""Extract the adapter id from the connection path.
E-SP-Line2 client mode may connect to /ws/adapter-gateway/<id>?key=...
or a custom path /custom?key=... The adapter id is extracted from the
path segment, NOT from the key query parameter.
"""
path_part = path.split('?', 1)[0]
if '/ws/adapter-gateway/' in path_part:
maybe_id = path_part.rsplit('/', 1)[-1]
if maybe_id and maybe_id not in ('ws', 'adapter-gateway'):
return maybe_id
# No adapter id in the path; return empty string (anonymous connection).
return ''
@staticmethod
def _extract_key(query: str) -> str:
"""Extract the ``key`` query parameter from the WebSocket query string.
E-SP-Line2 client-mode adapter passes the access key as
``?key=<KEY>`` in the WebSocket URL (see ``client_connector.go``
line 172-177).
"""
for pair in query.split('&'):
if '=' in pair:
k, v = pair.split('=', 1)
if k == 'key':
return v
return ''
async def _handle_frame(self, conn: _EsplConnection, frame: dict) -> None:
"""Handle a single inbound frame from an E-SP-Line2 gateway client."""
msg_type = frame.get('type', '')
if msg_type == 'ping':
await conn.send_frame({'type': 'pong', 'timestamp': int(time.time() * 1000)})
return
if msg_type == 'pong':
return
if msg_type == 'ack':
return
if msg_type == 'error':
await self.logger.warning(f'ESPL adapter gateway error: {frame.get("code")} {frame.get("message")}')
return
# Inbound message envelope (message.received).
if frame.get('event_type') == 'message.received':
await self._handle_inbound_message(conn, frame)
return
await self.logger.debug(f'ESPL adapter unhandled frame type: {msg_type}')
def _start_inbound_task(self, coro) -> asyncio.Task | None:
self.inbound_tasks = {task for task in self.inbound_tasks if not task.done()}
task = asyncio.create_task(coro)
self.inbound_tasks.add(task)
def task_done(done_task: asyncio.Task) -> None:
self.inbound_tasks.discard(done_task)
if not done_task.cancelled():
done_task.exception()
task.add_done_callback(task_done)
return task
async def _handle_inbound_message(self, conn: _EsplConnection, envelope: dict) -> None:
"""Convert a message.received envelope into a LangBot event and fire it."""
payload = envelope.get('payload') or {}
if not isinstance(payload, dict):
await self.logger.warning('ESPL adapter inbound payload is not an object')
return
conversation_id = str(payload.get('conversation_id') or '')
sender_id = str(payload.get('sender_id') or '')
sender_name = str(payload.get('sender_name') or 'User')
message_content = str(payload.get('message_content') or '')
instance_id = str(payload.get('instance') or payload.get('instance_id') or '')
platform = str(payload.get('platform_id') or envelope.get('platform') or '')
if not conversation_id:
await self.logger.warning('ESPL adapter inbound message missing conversation_id')
return
chain = self._build_message_chain(payload.get('message_chain'), message_content)
# Stash routing context (instance_id, conversation_id, conn_key) on the
# event so outbound replies route back to the correct connection.
source_platform_object = {
'instance_id': instance_id,
'conversation_id': conversation_id,
'platform': platform,
'sender_id': sender_id,
'_conn': conn,
}
session_type = str(payload.get('session_type') or 'person')
if session_type == 'group':
group = platform_entities.Group(
id=conversation_id,
name=str(payload.get('group_name') or conversation_id),
permission=platform_entities.Permission.Member,
)
sender = platform_entities.GroupMember(
id=sender_id or conversation_id,
member_name=sender_name,
group=group,
permission=platform_entities.Permission.Member,
)
event = platform_events.GroupMessage(
sender=sender,
message_chain=chain,
time=datetime.now().timestamp(),
source_platform_object=source_platform_object,
)
else:
sender = platform_entities.Friend(
id=conversation_id,
nickname=sender_name,
remark=sender_name,
)
event = platform_events.FriendMessage(
sender=sender,
message_chain=chain,
time=datetime.now().timestamp(),
source_platform_object=source_platform_object,
)
listener = self.listeners.get(type(event))
if listener is None:
await self.logger.warning(f'ESPL adapter no listener for {type(event).__name__}')
return
await self.logger.info(
f'ESPL adapter inbound: conversation={conversation_id} sender={sender_name} '
f'content={message_content[:100]}'
)
self._start_inbound_task(listener(event, self))
def _build_message_chain(
self,
message_chain: typing.Any,
fallback_text: str,
) -> platform_message.MessageChain:
"""Convert an ESPL message_chain into a LangBot MessageChain."""
components: list[platform_message.MessageComponent] = []
if isinstance(message_chain, list):
for elem in message_chain:
if not isinstance(elem, dict):
continue
elem_type = elem.get('type', '')
content = elem.get('content')
if elem_type == 'text':
text = ''
if isinstance(content, dict):
text = str(content.get('text', ''))
elif isinstance(content, str):
text = content
else:
text = str(elem.get('text', ''))
if text:
components.append(platform_message.Plain(text=text))
elif elem_type == 'image':
url = ''
if isinstance(content, dict):
url = str(content.get('url', ''))
elif isinstance(content, str):
url = content
else:
url = str(elem.get('url', ''))
if url:
components.append(platform_message.Image(url=url))
elif elem_type in ('item', 'product', 'goods'):
# E-commerce product card (e.g. 闲鱼 itemInfo).
# Render as a plain-text description so the product info
# (title/price) is not dropped downstream.
title = ''
price = ''
if isinstance(content, dict):
title = str(content.get('title') or '')
price = str(content.get('price') or '')
elif isinstance(content, str):
title = content
else:
title = str(elem.get('title') or '')
price = str(elem.get('price') or '')
product_text = title
if price:
product_text = f'{title} [价格: {price}]' if title else f'价格: {price}'
if product_text:
components.append(platform_message.Plain(text=product_text))
if not components and fallback_text:
components.append(platform_message.Plain(text=fallback_text))
return platform_message.MessageChain(components)
# -- outbound -------------------------------------------------------------
async def send_message(self, target_type: str, target_id: str, message: platform_message.MessageChain) -> dict:
"""Proactively push a message to a conversation (target_id == conversation_id)."""
return await self._emit_outbound(target_id, message)
async def reply_message(
self,
message_source: platform_events.MessageEvent,
message: platform_message.MessageChain,
quote_origin: bool = False,
) -> dict:
return await self._emit_outbound_from_event(message_source, message)
async def reply_message_chunk(
self,
message_source: platform_events.MessageEvent,
bot_message,
message: platform_message.MessageChain,
quote_origin: bool = False,
is_final: bool = False,
) -> dict:
# ESPL v3 has no streaming; send the whole chunk as a final message.
return await self._emit_outbound_from_event(message_source, message)
async def _emit_outbound_from_event(
self,
message_source: platform_events.MessageEvent,
message: platform_message.MessageChain,
) -> dict:
"""Send a reply, routing back to the connection captured at inbound."""
source = getattr(message_source, 'source_platform_object', None) or {}
conn = source.get('_conn')
conversation_id = str(source.get('conversation_id') or '')
instance_id = str(source.get('instance_id') or '')
sender_id = str(source.get('sender_id') or '')
if not conversation_id:
conversation_id = str(self.get_launcher_id(message_source))
return await self._emit_outbound(
conversation_id,
message,
instance_id=instance_id,
sender_id=sender_id,
conn=conn,
)
async def _emit_outbound(
self,
conversation_id: str,
message: platform_message.MessageChain,
instance_id: str = '',
sender_id: str = '',
conn: _EsplConnection | None = None,
) -> dict:
"""Build and send an ESPL v3 outbound message frame."""
if conn is None:
# Try to find a connection for this conversation by scanning.
if not self.connections:
await self.logger.warning('ESPL adapter no connections; dropping outbound message')
return {}
conn = next(iter(self.connections.values()))
# Convert the LangBot message chain to ESPL chain elements.
chain = []
for component in message:
if isinstance(component, platform_message.Plain):
chain.append({'type': 'text', 'content': {'text': component.text}})
elif isinstance(component, platform_message.Image):
chain.append({'type': 'image', 'content': {'url': component.url or ''}})
frame = {
'type': 'message',
'id': 'out_' + uuid.uuid4().hex,
'timestamp': int(time.time() * 1000),
'payload': {
'instance_id': instance_id,
'command_type': 'send_text',
'conversation_id': conversation_id,
'target_id': sender_id or conversation_id,
'sender_id': sender_id,
'message_chain': chain,
},
}
try:
await conn.send_frame(frame)
except Exception as e:
await self.logger.error(f'ESPL adapter failed to send outbound: {e}')
return {}
await self.logger.info(f'ESPL adapter outbound: conversation={conversation_id} chain={chain}')
return frame
# -- heartbeat ------------------------------------------------------------
async def _heartbeat_loop(self) -> None:
"""Periodically ping all connected clients to keep connections alive."""
interval = int(self.config.get('heartbeat_interval', _DEFAULT_HEARTBEAT_INTERVAL))
while self.running:
await asyncio.sleep(interval)
for conn in list(self.connections.values()):
try:
await conn.send_frame({'type': 'ping', 'timestamp': int(time.time() * 1000)})
except Exception as e:
await self.logger.warning(f'ESPL adapter heartbeat to client failed: {e}')
@@ -0,0 +1,83 @@
apiVersion: v1
kind: MessagePlatformAdapter
metadata:
name: espl
label:
en_US: ESPL V3
zh_Hans: ESPL V3
zh_Hant: ESPL V3
ja_JP: ESPL V3
description:
en_US: "LangBot acts as a WebSocket server. E-SP-Line2 creates a client-mode adapter (接入器) pointing its ws_url to this endpoint. Receives e-commerce messages (Taobao / Xianyu) as inbound events and sends AI replies back to the platform."
zh_Hans: "LangBot 作为 WebSocket 服务端。在 E-SP-Line2 中创建客户端模式接入器,将 ws_url 指向本端点即可接入。接收电商平台(淘宝/闲鱼)消息作为入站事件,并将 AI 回复发回平台。"
zh_Hant: "LangBot 作為 WebSocket 服務端。在 E-SP-Line2 中建立用戶端模式接入器,將 ws_url 指向本端點即可接入。接收電商平台(淘寶/閒魚)訊息作為入站事件,並將 AI 回覆發回平台。"
ja_JP: "LangBot が WebSocket サーバーとして動作します。E-SP-Line2 でクライアントモードのアダプター(接入器)を作成し、ws_url をこのエンドポイントに向けます。EC プラットフォーム(Taobao / Xianyu)のメッセージをインバウンドイベントとして受信し、AI 返信をプラットフォームに送り返します。"
icon: espl.png
spec:
categories:
- global
help_links:
zh: https://docs.langbot.app/zh/platforms/espl
en: https://docs.langbot.app/en/platforms/espl
ja: https://docs.langbot.app/ja/platforms/espl
config:
- name: host
label:
en_US: Listen Host
zh_Hans: 监听主机
zh_Hant: 監聽主機
ja_JP: リッスンホスト
description:
en_US: "Host to bind the WebSocket server. Set 0.0.0.0 when E-SP-Line2 is on another machine."
zh_Hans: "WebSocket 服务端绑定的主机。E-SP-Line2 在其他机器时设为 0.0.0.0。"
zh_Hant: "WebSocket 服務端綁定的主機。E-SP-Line2 在其他機器時設為 0.0.0.0。"
ja_JP: "WebSocket サーバーをバインドするホスト。E-SP-Line2 が別マシンの場合は 0.0.0.0 を設定します。"
type: string
required: true
default: "127.0.0.1"
- name: port
label:
en_US: Listen Port
zh_Hans: 监听端口
zh_Hant: 監聽連接埠
ja_JP: リッスンポート
description:
en_US: "Port to bind the WebSocket server. E-SP-Line2 client-mode adapter connects to ws://<host>:<port>/ws."
zh_Hans: "WebSocket 服务端绑定的端口。E-SP-Line2 客户端模式接入器连接 ws://<host>:<port>/ws。"
zh_Hant: "WebSocket 服務端綁定的連接埠。E-SP-Line2 用戶端模式接入器連接 ws://<host>:<port>/ws。"
ja_JP: "WebSocket サーバーをバインドするポート。E-SP-Line2 クライアントモードアダプターは ws://<host>:<port>/ws に接続します。"
type: integer
required: false
default: 8000
- name: key
label:
en_US: Access Key
zh_Hans: 访问密钥
zh_Hant: 訪問密鑰
ja_JP: アクセスキー
description:
en_US: "Access key for authentication. E-SP-Line2 client-mode adapter passes this key as ?key=<KEY> in the WebSocket URL. Leave empty to disable key validation (not recommended)."
zh_Hans: "访问密钥用于认证。E-SP-Line2 客户端模式接入器在 WebSocket URL 中携带 ?key=<KEY> 传递此密钥。留空表示不验证密钥(不推荐)。"
zh_Hant: "訪問密鑰用於認證。E-SP-Line2 用戶端模式接入器在 WebSocket URL 中攜帶 ?key=<KEY> 傳遞此密鑰。留空表示不驗證密鑰(不推薦)。"
ja_JP: "認証用のアクセスキー。E-SP-Line2 クライアントモードアダプターは WebSocket URL に ?key=<KEY> としてこのキーを渡します。空の場合はキー検証を無効にします(非推奨)。"
type: string
required: false
default: ""
- name: heartbeat_interval
label:
en_US: Heartbeat Interval (seconds)
zh_Hans: 心跳间隔(秒)
zh_Hant: 心跳間隔(秒)
ja_JP: ハートビート間隔(秒)
description:
en_US: "How often to ping connected clients to keep the connection alive."
zh_Hans: "发送 ping 帧保持连接的间隔。"
zh_Hant: "發送 ping 幀保持連線的間隔。"
ja_JP: "接続を維持するためにクライアントに ping を送信する間隔。"
type: integer
required: false
default: 30
execution:
python:
path: ./espl.py
attr: EsplAdapter
+12 -35
View File
@@ -143,41 +143,18 @@ stages:
operator: eq
value: false
disabled_tooltip:
en_US: "Sandbox is unavailable. Enable Box and check its connection before changing the scope."
zh_Hans: "沙箱未启用,请启用 Box 并确认连接正常后再修改作用域。"
zh_Hant: "沙箱未啟用,請啟用 Box 並確認連線正常後再修改作用域。"
ja_JP: "サンドボックスは利用できません。Box を有効にし、接続を確認してからスコープを変更してください。"
vi_VN: "Sandbox không khả dụng. Hãy bật Box và kiểm tra kết nối trước khi thay đổi phạm vi."
th_TH: "Sandbox ไม่พร้อมใช้งาน โปรดเปิดใช้งาน Box และตรวจสอบการเชื่อมต่อก่อนเปลี่ยนขอบเขต"
es_ES: "El sandbox no está disponible. Active Box y compruebe su conexión antes de cambiar el alcance."
ru_RU: "Песочница недоступна. Включите Box и проверьте подключение, прежде чем менять область."
disabled_tooltip_overrides:
- when:
field: __system.box_scope_forced_global
operator: eq
value: true
tooltip:
en_US: "A global sandbox is enforced; the scope cannot be changed."
zh_Hans: "已强制使用全局沙箱,无法修改作用域。"
zh_Hant: "已強制使用全域沙箱,無法修改作用域。"
ja_JP: "グローバルサンドボックスの使用が強制されているため、スコープを変更できません。"
vi_VN: "Bắt buộc sử dụng sandbox toàn cục; không thể thay đổi phạm vi."
th_TH: "ระบบบังคับใช้ Sandbox ส่วนกลาง จึงไม่สามารถเปลี่ยนขอบเขตได้"
es_ES: "Se impone un sandbox global; no se puede cambiar el alcance."
ru_RU: "Принудительно используется глобальная песочница; изменить область нельзя."
- when:
field: __system.box_scope_forced
operator: eq
value: true
tooltip:
en_US: "A fixed sandbox scope is enforced; the scope cannot be changed."
zh_Hans: "已强制使用固定沙箱作用域,无法修改作用域。"
zh_Hant: "已強制使用固定沙箱作用域,無法修改作用域。"
ja_JP: "固定のサンドボックススコープが強制されているため、スコープを変更できません。"
vi_VN: "Phạm vi sandbox đã được cố định bắt buộc; không thể thay đổi phạm vi."
th_TH: "ระบบบังคับใช้ขอบเขต Sandbox แบบตายตัว จึงไม่สามารถเปลี่ยนขอบเขตได้"
es_ES: "Se impone un alcance fijo del sandbox; no se puede cambiar el alcance."
ru_RU: "Принудительно задана фиксированная область песочницы; изменить её нельзя."
en_US: >-
Sandbox scope can't be changed: either the Box sandbox is disabled
or unavailable (enable it in config.yaml with box.enabled = true and
ensure the runtime is reachable), or this deployment pins all
pipelines to a fixed scope.
zh_Hans: "无法修改沙箱作用域:Box 沙箱已禁用或不可用(请在配置中启用 box.enabled = true 并确认运行时连接正常),或本部署已将所有流水线固定为统一作用域。"
zh_Hant: "無法修改沙箱作用域:Box 沙箱已停用或無法使用(請在設定中啟用 box.enabled = true 並確認執行時連線正常),或本部署已將所有流水線固定為統一作用域。"
ja_JP: "サンドボックススコープを変更できません:Box サンドボックスが無効/利用不可(設定で box.enabled = true にしてランタイム接続を確認)、またはこのデプロイがすべてのパイプラインを固定スコープに制限しています。"
vi_VN: "Không thể thay đổi phạm vi sandboxBox sandbox bị tắt hoặc không khả dụng (bật box.enabled = true và đảm bảo runtime hoạt động), hoặc bản triển khai này cố định mọi pipeline về một phạm vi."
th_TH: "ไม่สามารถเปลี่ยนขอบเขต Sandbox:Box sandbox ถูกปิดหรือไม่พร้อมใช้งาน (เปิด box.enabled = true และตรวจสอบรันไทม์) หรือการ deploy นี้ล็อกทุก pipeline ไว้ที่ขอบเขตเดียว"
es_ES: "No se puede cambiar el alcance del sandbox: el sandbox de Box está desactivado o no disponible (actívelo con box.enabled = true y verifique el runtime), o este despliegue fija todas las pipelines a un alcance único."
ru_RU: "Невозможно изменить область песочницы: песочница Box отключена или недоступна (включите box.enabled = true и проверьте среду выполнения), либо это развёртывание фиксирует единую область для всех конвейеров."
type: select
required: false
default: "{launcher_type}_{launcher_id}"
@@ -46,10 +46,30 @@ import {
} from '@/components/ui/tooltip';
import { systemInfo } from '@/app/infra/http';
import { getAdapterDocUrl } from '@/app/infra/entities/adapter-docs';
import {
resolveDisabledState,
resolveShowIfValue,
} from './DynamicFormConditions';
/**
* Resolve the value referenced by a `show_if.field` string.
*
* Fields prefixed with `__system.` are looked up in the caller-supplied
* `systemContext` dictionary (e.g. `__system.is_wizard` → `systemContext.is_wizard`).
* All other field names are resolved from the live form values first, then
* fall back to `externalDependentValues`.
*/
function resolveShowIfValue(
field: string,
watchedValues: Record<string, unknown>,
externalDependentValues?: Record<string, unknown>,
systemContext?: Record<string, unknown>,
): unknown {
if (field.startsWith(SYSTEM_FIELD_PREFIX)) {
const key = field.slice(SYSTEM_FIELD_PREFIX.length);
return systemContext?.[key];
}
if (watchedValues[field] !== undefined) {
return watchedValues[field];
}
return externalDependentValues?.[field];
}
type DynamicFormValueSpec = Pick<
IDynamicFormItemSchema,
@@ -655,19 +675,40 @@ export default function DynamicFormComponent({
}
}
// Keep locked fields visible and resolve only the applicable reason.
const { isDisabledByCondition, disabledTooltip: tooltip } =
resolveDisabledState(
config,
// ``disable_if`` mirrors ``show_if``'s evaluator but instead of
// hiding the field, leaves it visible and inert. Use it when the
// operator needs to see that the field exists yet cannot edit it
// under the current runtime state (e.g. sandbox-bound fields when
// Box is disabled).
let isDisabledByCondition = false;
if (config.disable_if) {
const dependValue = resolveShowIfValue(
config.disable_if.field,
watchedValues as Record<string, unknown>,
externalDependentValues,
systemContext,
);
const cond = config.disable_if;
if (cond.operator === 'eq' && dependValue === cond.value) {
isDisabledByCondition = true;
} else if (cond.operator === 'neq' && dependValue !== cond.value) {
isDisabledByCondition = true;
} else if (
cond.operator === 'in' &&
Array.isArray(cond.value) &&
cond.value.includes(dependValue)
) {
isDisabledByCondition = true;
}
}
// All fields are disabled when editing (creation_settings are
// immutable) or when ``disable_if`` matches.
const isFieldDisabled = !!isEditing || isDisabledByCondition;
const disabledTooltip = tooltip ? extractI18nObject(tooltip) : '';
const disabledTooltip =
isDisabledByCondition && config.disabled_tooltip
? extractI18nObject(config.disabled_tooltip)
: '';
const renderDisabledTooltipIcon = () =>
disabledTooltip ? (
<DisabledTooltipIcon text={disabledTooltip} />
@@ -1,71 +0,0 @@
import {
SYSTEM_FIELD_PREFIX,
type IDynamicFormItemSchema,
type IShowIfCondition,
} from '@/app/infra/entities/form/dynamic';
/** System references use caller context; other fields prefer live form values. */
export function resolveShowIfValue(
field: string,
watchedValues: Record<string, unknown>,
externalDependentValues?: Record<string, unknown>,
systemContext?: Record<string, unknown>,
): unknown {
if (field.startsWith(SYSTEM_FIELD_PREFIX)) {
return systemContext?.[field.slice(SYSTEM_FIELD_PREFIX.length)];
}
if (watchedValues[field] !== undefined) {
return watchedValues[field];
}
return externalDependentValues?.[field];
}
export function matchesFormCondition(
condition: IShowIfCondition,
watchedValues: Record<string, unknown>,
externalDependentValues?: Record<string, unknown>,
systemContext?: Record<string, unknown>,
): boolean {
const value = resolveShowIfValue(
condition.field,
watchedValues,
externalDependentValues,
systemContext,
);
switch (condition.operator) {
case 'eq':
return value === condition.value;
case 'neq':
return value !== condition.value;
case 'in':
return Array.isArray(condition.value) && condition.value.includes(value);
default:
return false;
}
}
export function resolveDisabledState(
config: Pick<
IDynamicFormItemSchema,
'disable_if' | 'disabled_tooltip' | 'disabled_tooltip_overrides'
>,
watchedValues: Record<string, unknown>,
externalDependentValues?: Record<string, unknown>,
systemContext?: Record<string, unknown>,
) {
const matches = (condition: IShowIfCondition) =>
matchesFormCondition(
condition,
watchedValues,
externalDependentValues,
systemContext,
);
const isDisabledByCondition =
!!config.disable_if && matches(config.disable_if);
const disabledTooltip = isDisabledByCondition
? (config.disabled_tooltip_overrides?.find((override) =>
matches(override.when),
)?.tooltip ?? config.disabled_tooltip)
: undefined;
return { isDisabledByCondition, disabledTooltip };
}
@@ -1,14 +0,0 @@
/** Unavailability takes priority over the deployment's scope restriction. */
export function getBoxScopeContext(
boxAvailable: boolean,
forcedTemplate?: string,
) {
forcedTemplate = forcedTemplate?.trim();
return {
box_available: boxAvailable,
box_scope_editable: boxAvailable && !forcedTemplate,
// Only expose forced-scope reasons when the sandbox is available.
box_scope_forced: boxAvailable && !!forcedTemplate,
box_scope_forced_global: boxAvailable && forcedTemplate === '{global}',
};
}
@@ -8,7 +8,6 @@ import {
import DynamicFormComponent from '@/app/home/components/dynamic-form/DynamicFormComponent';
import N8nAuthFormComponent from '@/app/home/components/dynamic-form/N8nAuthFormComponent';
import { useBoxStatus } from '@/app/infra/hooks/useBoxStatus';
import { getBoxScopeContext } from './BoxScopeContext';
import { systemInfo } from '@/app/infra/http';
import { Button } from '@/components/ui/button';
import { useForm } from 'react-hook-form';
@@ -426,12 +425,13 @@ export default function PipelineFormComponent({
// 2. the deployment pins all pipelines to a fixed scope via
// ``system.limitation.force_box_session_id_template`` (SaaS).
const forcedBoxTemplate =
systemInfo.limitation?.force_box_session_id_template?.trim() || '';
systemInfo.limitation?.force_box_session_id_template || '';
const boxScopeForced = !!forcedBoxTemplate;
const isLocalAgentStage = formName === 'ai' && stage.name === 'local-agent';
const stageSystemContext = isLocalAgentStage
? {
...getBoxScopeContext(boxAvailable, forcedBoxTemplate),
box_available: boxAvailable,
box_scope_editable: boxAvailable && !boxScopeForced,
pipeline_id: pipelineId,
}
: undefined;
@@ -39,13 +39,6 @@ export interface IDynamicFormItemSchema {
disable_if?: IShowIfCondition;
/** Tooltip shown next to the field label when ``disable_if`` is active. */
disabled_tooltip?: I18nObject;
/** Optional overrides evaluated in order when ``disable_if`` matches.
* The first matching ``when`` wins; otherwise use ``disabled_tooltip``.
* Conditions use the same operators and value lookup as ``disable_if``. */
disabled_tooltip_overrides?: {
when: IShowIfCondition;
tooltip: I18nObject;
}[];
/** when type is PLUGIN_SELECTOR, the scopes is the scopes of components(plugin contains), the default is all */
scopes?: string[];
-232
View File
@@ -1,232 +0,0 @@
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { resolve } from 'node:path';
import { expect, test, type Page } from '@playwright/test';
import { installLangBotApiMocks } from './fixtures/langbot-api';
// UI fixtures only: real app/components, intercepted APIs, no production Box.
// Load the shipped metadata rather than reproducing its tooltip conditions.
const requireFromTest = createRequire(__filename);
const { load } = createRequire(requireFromTest.resolve('eslint'))(
'js-yaml',
) as {
load: (source: string) => unknown;
};
const aiMetadata = load(
readFileSync(
resolve(
__dirname,
'../../../src/langbot/templates/metadata/pipeline/ai.yaml',
),
'utf8',
),
);
const unavailableHint = '沙箱未启用,请启用 Box 并确认连接正常后再修改作用域。';
const forcedHint = '已强制使用全局沙箱,无法修改作用域。';
interface BoxState {
enabled: boolean;
available: boolean;
}
async function openPipeline(page: Page, box: BoxState, forced = '') {
await installLangBotApiMocks(page, {
authenticated: true,
storage: { langbot_language: 'zh-Hans' },
});
await page.route('**/api/v1/system/info', (route) =>
route.fulfill({
json: {
code: 0,
data: {
debug: false,
version: 'sandbox-scope-ui-fixture',
edition: 'community',
cloud_service_url: 'https://space.langbot.app',
enable_marketplace: true,
allow_modify_login_info: true,
disable_models_service: false,
limitation: {
max_bots: -1,
max_pipelines: -1,
max_extensions: -1,
force_box_session_id_template: forced,
},
outbound_ips: [],
wizard_status: 'completed',
wizard_progress: null,
},
},
}),
);
await page.route('**/api/v1/box/status', (route) =>
route.fulfill({
json: {
code: 0,
data: {
...box,
profile: 'UI fixture only',
recent_error_count: 0,
active_sessions: 0,
managed_processes: 0,
session_ttl_sec: 3600,
backend: { name: 'ui-fixture', available: box.available },
},
},
}),
);
await page.route(/\/api\/v1\/tools(?:\?.*)?$/, (route) =>
route.fulfill({ json: { code: 0, data: { tools: [] } } }),
);
await page.route('**/api/v1/pipelines/_/metadata', (route) =>
route.fulfill({ json: { code: 0, data: { configs: [aiMetadata] } } }),
);
await page.route('**/api/v1/pipelines/sandbox-scope-fixture', (route) =>
route.fulfill({
json: {
code: 0,
data: {
pipeline: {
uuid: 'sandbox-scope-fixture',
name: 'Sandbox scope — UI fixture only',
description: '',
emoji: '⚙️',
is_default: false,
config: {
ai: {
runner: { runner: 'local-agent' },
'local-agent': {
'box-session-id-template': '{launcher_type}_{launcher_id}',
},
},
trigger: {},
safety: {},
output: {},
},
},
},
},
}),
);
await page.goto('/home/pipelines?id=sandbox-scope-fixture');
await page.getByRole('button', { name: 'AI 能力', exact: true }).click();
// DynamicForm gates this control through its wrapper's pointer-events,
// and its label targets that wrapper rather than the nested select.
const scope = page
.locator('[data-slot="form-item"]')
.filter({ has: page.getByText('沙箱作用域', { exact: true }) })
.getByRole('combobox');
await expect(scope).toBeVisible();
return scope;
}
async function expectWarning(page: Page, hint: string) {
const warning = page.getByRole('button', { name: hint, exact: true });
await expect(warning).toBeVisible();
await warning.hover();
await expect(page.getByRole('tooltip')).toHaveText(hint);
}
async function expectNoWarning(page: Page) {
await expect(page.getByRole('button', { name: unavailableHint })).toHaveCount(
0,
);
await expect(page.getByRole('button', { name: forcedHint })).toHaveCount(0);
await expect(page.getByRole('tooltip')).toHaveCount(0);
}
test.describe('sandbox scope disabled reason (UI fixtures only)', () => {
for (const scenario of [
{ name: 'Box disabled', enabled: false, available: false, forced: '' },
{ name: 'Box disconnected', enabled: true, available: false, forced: '' },
{
name: 'unavailable Box takes precedence over forced global',
enabled: true,
available: false,
forced: '{global}',
},
]) {
test(scenario.name, async ({ page }) => {
const scope = await openPipeline(page, scenario, scenario.forced);
await expect(scope).toHaveCSS('pointer-events', 'none');
await expectWarning(page, unavailableHint);
await expect(page.getByRole('tooltip')).not.toContainText('强制');
await expect(page.getByRole('button', { name: forcedHint })).toHaveCount(
0,
);
});
}
for (const forced of ['{global}', ' {global} ']) {
test(`available Box with forced global explains the deployment restriction (${JSON.stringify(forced)})`, async ({
page,
}) => {
const scope = await openPipeline(
page,
{ enabled: true, available: true },
forced,
);
await expect(scope).toHaveCSS('pointer-events', 'none');
await expect(scope).toHaveText('全局(所有人共享)');
await expectWarning(page, forcedHint);
await expect(
page.getByRole('button', { name: unavailableHint }),
).toHaveCount(0);
});
}
for (const forced of ['', ' ']) {
test(`available and unforced Box is editable without a disabled warning (${JSON.stringify(forced)})`, async ({
page,
}) => {
const scope = await openPipeline(
page,
{ enabled: true, available: true },
forced,
);
await expect(scope).toHaveCSS('pointer-events', 'auto');
await expect(scope).toHaveText('每个会话(推荐)');
await expectNoWarning(page);
await scope.click();
await page
.getByRole('option', { name: '全局(所有人共享)', exact: true })
.click();
await expect(scope).toHaveText('全局(所有人共享)');
await expectNoWarning(page);
});
}
for (const forced of ['', '{global}']) {
test(`Box status polls update the warning without remounting (${forced || 'unforced'})`, async ({
page,
}) => {
await page.clock.install();
const box = { enabled: true, available: false };
const scope = await openPipeline(page, box, forced);
await expect(scope).toHaveCSS('pointer-events', 'none');
await expectWarning(page, unavailableHint);
await page.mouse.move(0, 0);
const recovered = page.waitForResponse('**/api/v1/box/status');
box.available = true;
await page.clock.fastForward(31_000);
await recovered;
if (forced) {
await expect(scope).toHaveCSS('pointer-events', 'none');
await expectWarning(page, forcedHint);
} else {
await expect(scope).toHaveCSS('pointer-events', 'auto');
await expectNoWarning(page);
}
await page.mouse.move(0, 0);
const disconnected = page.waitForResponse('**/api/v1/box/status');
box.available = false;
await page.clock.fastForward(31_000);
await disconnected;
await expect(scope).toHaveCSS('pointer-events', 'none');
await expectWarning(page, unavailableHint);
await expect(page.getByRole('tooltip')).not.toContainText('强制');
});
}
});
@@ -1,252 +0,0 @@
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import test from 'node:test';
import ts from 'typescript';
const require = createRequire(import.meta.url);
const { load } = createRequire(require.resolve('eslint'))('js-yaml');
const metadata = load(
fs.readFileSync(
new URL(
'../../../src/langbot/templates/metadata/pipeline/ai.yaml',
import.meta.url,
),
'utf8',
),
);
const scope = metadata.stages
.find((stage) => stage.name === 'local-agent')
.config.find((item) => item.name === 'box-session-id-template');
const unavailable = '沙箱未启用,请启用 Box 并确认连接正常后再修改作用域。';
const globalForced = '已强制使用全局沙箱,无法修改作用域。';
const customForced = '已强制使用固定沙箱作用域,无法修改作用域。';
function loadSource(relativePath) {
const filename = new URL(`../../src/${relativePath}`, import.meta.url);
assert.ok(fs.existsSync(filename), `Missing policy module: ${relativePath}`);
const compiled = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS },
}).outputText;
const loaded = { exports: {} };
new Function('require', 'module', 'exports', compiled)(
(name) => {
if (name === '@/app/infra/entities/form/dynamic')
return loadSource('app/infra/entities/form/dynamic.ts');
throw new Error(`Unexpected runtime import: ${name}`);
},
loaded,
loaded.exports,
);
return loaded.exports;
}
function policies() {
return {
...loadSource('app/home/components/dynamic-form/DynamicFormConditions.ts'),
...loadSource(
'app/home/pipelines/components/pipeline-form/BoxScopeContext.ts',
),
};
}
function scopeState(available, forcedTemplate) {
const { getBoxScopeContext, resolveDisabledState } = policies();
return resolveDisabledState(
scope,
{},
undefined,
getBoxScopeContext(available, forcedTemplate),
);
}
test('sandbox default tooltip explains only unavailability', () => {
assert.equal(scope.disabled_tooltip.zh_Hans, unavailable);
});
for (const [name, available, template, expected] of [
['Box disabled', false, '', unavailable],
['Box disconnected', false, undefined, unavailable],
[
'unavailable takes precedence over forced global',
false,
'{global}',
unavailable,
],
[
'unavailable takes precedence over forced custom',
false,
'{pipeline_id}',
unavailable,
],
['available forced global', true, '{global}', globalForced],
['available padded forced global', true, ' {global} ', globalForced],
['available whitespace-only editable', true, ' ', undefined],
['available forced custom', true, '{pipeline_id}', customForced],
['available forced literal', true, 'tenant-sandbox', customForced],
['available editable', true, '', undefined],
['available without limitation', true, undefined, undefined],
]) {
test(name, () => {
const state = scopeState(available, template);
assert.equal(state.isDisabledByCondition, expected !== undefined);
assert.equal(state.disabledTooltip?.zh_Hans, expected);
});
}
test('reason follows availability and forced-scope transitions without mutating metadata', () => {
const snapshot = structuredClone(scope);
for (const [available, template, expected] of [
[false, '{global}', unavailable],
[true, '{global}', globalForced],
[true, '{pipeline_id}', customForced],
[true, '', undefined],
[false, '', unavailable],
[true, '', undefined],
]) {
assert.equal(
scopeState(available, template).disabledTooltip?.zh_Hans,
expected,
);
}
assert.deepEqual(scope, snapshot);
});
test('all sandbox reason variants preserve the eight metadata locales', () => {
const locales = [
'en_US',
'zh_Hans',
'zh_Hant',
'ja_JP',
'vi_VN',
'th_TH',
'es_ES',
'ru_RU',
].sort();
assert.equal(scope.disabled_tooltip_overrides?.length, 2);
const messages = [
scope.disabled_tooltip,
...scope.disabled_tooltip_overrides.map((entry) => entry.tooltip),
];
for (const message of messages) {
assert.deepEqual(Object.keys(message).sort(), locales);
for (const locale of locales) assert.ok(message[locale].trim(), locale);
}
for (const locale of locales) {
assert.equal(
new Set(messages.map((message) => message[locale])).size,
3,
locale,
);
assert.equal(
scopeState(false, '{global}').disabledTooltip[locale],
messages[0][locale],
);
assert.equal(
scopeState(true, '{global}').disabledTooltip[locale],
messages[1][locale],
);
assert.equal(
scopeState(true, '{pipeline_id}').disabledTooltip[locale],
messages[2][locale],
);
}
});
test('ordinary static disabled tooltip remains compatible', () => {
const { resolveDisabledState } = policies();
const tooltip = { en_US: 'Read only' };
const config = {
disable_if: { field: 'locked', operator: 'eq', value: true },
disabled_tooltip: tooltip,
};
assert.deepEqual(resolveDisabledState(config, { locked: true }), {
isDisabledByCondition: true,
disabledTooltip: tooltip,
});
assert.deepEqual(resolveDisabledState(config, { locked: false }), {
isDisabledByCondition: false,
disabledTooltip: undefined,
});
assert.equal(
resolveDisabledState({ disabled_tooltip: tooltip }, {}).disabledTooltip,
undefined,
);
assert.equal(
resolveDisabledState({ disable_if: config.disable_if }, { locked: true })
.disabledTooltip,
undefined,
);
});
test('conditional overrides reuse eq, neq, in and live/external/system resolution', () => {
const { matchesFormCondition, resolveDisabledState } = policies();
const watched = { mode: 'live', empty: null, '__system.locked': false };
const external = { mode: 'external', fallback: 3, empty: 'external' };
const system = { locked: true };
for (const [condition, expected] of [
[{ field: 'mode', operator: 'eq', value: 'live' }, true],
[{ field: 'mode', operator: 'eq', value: 'external' }, false],
[{ field: 'fallback', operator: 'neq', value: 4 }, true],
[{ field: 'fallback', operator: 'in', value: [2, 3] }, true],
[{ field: 'fallback', operator: 'in', value: '3' }, false],
[{ field: 'fallback', operator: 'eq', value: '3' }, false],
[{ field: 'empty', operator: 'eq', value: null }, true],
[{ field: '__system.locked', operator: 'eq', value: true }, true],
[{ field: 'absent', operator: 'eq', value: true }, false],
])
assert.equal(
matchesFormCondition(condition, watched, external, system),
expected,
);
const config = {
disable_if: { field: '__system.locked', operator: 'eq', value: true },
disabled_tooltip: { en_US: 'Default' },
disabled_tooltip_overrides: [
{
when: { field: 'mode', operator: 'eq', value: 'external' },
tooltip: { en_US: 'Wrong' },
},
{
when: { field: 'fallback', operator: 'in', value: [3] },
tooltip: { en_US: 'First match' },
},
{
when: { field: 'mode', operator: 'neq', value: 'external' },
tooltip: { en_US: 'Later match' },
},
],
};
assert.equal(
resolveDisabledState(config, watched, external, system).disabledTooltip
.en_US,
'First match',
);
assert.equal(
resolveDisabledState(config, {}, {}, system).disabledTooltip.en_US,
'Later match',
);
assert.equal(
resolveDisabledState(config, watched, external, { locked: false })
.disabledTooltip,
undefined,
);
assert.equal(
resolveDisabledState(
{ ...config, disabled_tooltip_overrides: [] },
watched,
external,
system,
).disabledTooltip.en_US,
'Default',
);
const unmatched = {
...config,
disabled_tooltip_overrides: [config.disabled_tooltip_overrides[0]],
};
assert.equal(
resolveDisabledState(unmatched, watched, external, system).disabledTooltip
.en_US,
'Default',
);
});